Qual è il mio ID PPCG?


16

Sfida

Dato il nome di un membro PPCG, genera il suo numero ID PPCG. Se l'utente non esiste, è possibile segnalare un errore o restituire qualsiasi numero non positivo. Se ci sono più membri con questo nome, puoi scegliere di generare solo un ID o tutti.

Casi test

"musicman523" -> 69054
"Dennis" -> 12012
"xnor" -> 20260
"Leaky Nun" -> 48934
"fəˈnɛtɪk" -> 64505
"Jörg Hülsermann" -> 59107
"Community" -> -1
"Qualsiasi utente che non esiste" -> 0
"Alex" -> 69198 (questo è un possibile risultato)
"Leaky N" -> 0
"Jorge" -> 3716

1
Caso di prova raccomandato: "Leaky N". Dovrebbe restituire 0.
— Okx,

5
Il nostro programma può comportare comportamenti indefiniti per utenti inesistenti (la mia stampa 48934, ad esempio per un utente inesistente)? Penso che questo dovrebbe essere permesso, poiché gli errori lo sono.
— Mr. Xcoder,

4
@Okx No, non lo so. Chiedo all'OP se questo comportamento è consentito. In caso contrario, eliminerò o risolverò la mia risposta.
— Mr. Xcoder

3
@OliverNi Toxic? Come?
— Okx,

5
@Okx Sta facendo una domanda valida all'OP e tu lo stai abbattendo immediatamente. Lascia che l'OP risponda.
— Oliver Ni

Risposte:


30

Stack Exchange Data Explorer , 56 54 53 51 46 byte

-1 byte grazie a Hyper Neutrino. -5 byte grazie a Giacomo Garabello.

SELECT ID FROM USERS WHERE##S##=DISPLAYNAME--S

Provalo online!

Non sono sicuro che sia completamente valido ma ... L'input deve essere racchiuso tra virgolette singole '.

Inoltre, non capisco ancora perché ai programmatori SQL piace urlare, ma a quanto pare è una buona pratica, quindi ... SELECTTUTTO FROMTUTTO WHERETUTTO LIKETUTTO!

Spiegazione

LASCIATEMI SPIEGARE.

SELECT ID FROM USERS WHERE##S##=DISPLAYNAME--S

                                           --S  -- DECLARE AN INPUT PARAMETER NAMED S
SELECT                                          -- FIND...
       ID                                       -- ID OF THE USERS...
          FROM USERS                            -- IN THE TABLE USERS...
                     WHERE                      -- THAT SATISFIES THE CONDITION...
                          ##S##=DISPLAYNAME     -- S EQUALS THE USERS' DISPLAY NAME

13
-2 BYTES RIMUOVENDO GLI SPAZI INTORNO AL SEGNO
— UGUALE

1
NINJA'D IL TUO NINJA IN CHAT XD
— HyperNeutrino

1
-1 byte invertendo l'ordine degli operandi attorno all'operatore di uguaglianza
— HyperNeutrino

10
+1 per il riferimento ai programmatori SQL che desiderano gridare (e per una buona scelta della lingua per la tua risposta :)
— NH.

4
perché hai inserito i primi 1 in questa query? OP ha detto "Se ci sono più membri con questo nome, puoi scegliere di generare solo un ID o tutti loro" ...
— Giacomo Garabello

5

JavaScript, 155 149 142 135 byte

i=>fetch("//api.stackexchange.com/users?site=codegolf&inname="+i).then(r=>r.json()).then(r=>r.items.find(u=>u.display_name==i).user_id)

f=i=>fetch("//api.stackexchange.com/users?site=codegolf&inname="+i).then(r=>r.json()).then(r=>r.items.find(u=>u.display_name==i).user_id)
<input onchange="f(this.value).then(console.log)"><br>Fill input and press Enter


1
Supporta personaggi speciali come in Jörg Hülsermann?
— Arnauld,

4
Questo è tornato 0per Oliver:(
— Oliver

Salva 7 byte sostituendo r=>r.items[0]).then(rcon ({items:[r]}). Incarico di ristrutturazione ftw!
— kamoroso94

Puoi usare: i=>fetch('//api.stackexchange.com/users?site=codegolf&inname='+i).then(r=>r.json()).then(r=>r.items[0].user_id)poiché restituirà un errore di promessa se fallito. Puoi anche solo fare i=>fetch('/users?site=codegolf&inname='+i).then(r=>r.json()).then(r=>r.items[0].user_id)e dire che deve essere eseguito sul dominio api
— Downgoat

2
@Oliver CHE COSA un altro oliver ???? POSSONO ESSERE SOLO UNO
— Oliver Ni

5

Python 3 + richieste , 196 byte

Grazie @Wondercricket per -6 byte!

from requests import*
x=lambda s:all([print(a['user_id'])if s==a['display_name']else''for a in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']])and d

Utilizza l'API di Exchange Stack. Risolti gli errori Leaky Ne Jorge.

Se ci sono più utenti con lo stesso nome, li stampa tutti, il che è consentito.


Mi dà i dati compressi con gzip.
— Oliver Ni

Errore in inputLeaky N
— Okx,

@Okx risolto. ---
— Oliver Ni

Dal momento che è possibile "segnalare un errore o restituire 0" se l'utente non esiste, l'ultima riga potrebbe essere giusta print a['user_id'], il che genererà un KeyError?
— Daniel,

1
non riesce per "Jorge"
— Felipe Nardi Batista

5

Python 2 + richieste , 187 byte

from requests import*
def f(x):t=get("http://api.stackexchange.com/users?inname="+utils.quote(x)+"&site=codegolf").json()["items"];print[k['user_id']for k in t if k['display_name']==x][0]

Restituisce l'ID utente se esiste un singolo utente, il primo utente che soddisfa i requisiti se ne esistono altri e segnala un errore in caso contrario.


Puoi rimuovere /2.2dall'URL dell'API.
— Kevin Cruijssen,

@KevinCruijssen Grazie mille
— Mr. Xcoder il

Suggerimento : non tentare di eseguirlo fəˈnɛtɪk, utilizzare \u{...}invece, perché Python non tollera la non-ASCII
— Mr. Xcoder

Python 2, comunque.
— totalmente umano il

3
non riesce per "Jorge"
— Felipe Nardi Batista

3

Python 2 + richieste , 173 byte

lambda s:[i['user_id']for i in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']if i['display_name']==s]
from requests import*

Esecuzione del campione

>>> f=\
... lambda s:[i['user_id']for i in get('http://api.stackexchange.com/users?inname=%s&site=codegolf'%utils.quote(s)).json()['items']if i['display_name']==s]
>>> from requests import*
>>>
>>> tests = ['musicman523', 'Dennis', 'xnor', 'Leaky Nun', 'Community', 'Any user that does not exist', 'Alex', 'Leaky N', 'Jorge']
>>> for i in tests: print '%-30r -> %s'%(i, f(i))
... 
'musicman523'                  -> [69054]
'Dennis'                       -> [12012, 13891, 14912, 24937]
'xnor'                         -> [20260]
'Leaky Nun'                    -> [48934]
'Community'                    -> [-1]
'Any user that does not exist' -> []
'Alex'                         -> [21536, 69198, 11192]
'Leaky N'                      -> []
'Jorge'                        -> [3716]

Curiosità: il risultato è ordinato per reputazione, prima il più alto.


Errore di inputLeaky N
— Okx,

Nice trick with %s.
— Mr. Xcoder

@Okx Not for me, it doesn't. >>> f('Leaky N')\n48934
— totallyhuman

@totallyhuman It should return 0. Leaky N does not exist
— Okx

@Okx Fixed. - -
— totallyhuman

3

JavaScript, 128 119 bytes

-9 bytes thanks to Rogem.

n=>fetch("198.252.206.16/users?site=codegolf&inname="+n).then(r=>r.text()).then(t=>t.match(`\\/([^\\/]*)\\/`+n+`"`)[1])

1
Think you'd save some bytes with the IPv4 address. (198.252.206.16 instead of api.stackexchange.com)

-1

JavaScript (ES6) + HTML, 154 152 151 202 179 161 145 bytes

Sacrificed a few bytes to handle special characters.

Needs to be run under the api.stackexchange.com domain. Returns a Promise containing the ID or Throws an error in the Promise if the username can't be found.

s=>fetch(`/users?site=codegolf&inname=`+s).then(r=>r.json()).then(j=>j.items.find(i=>(o.innerHTML=i.display_name,o.innerText==s)).user_id)

<a id=o

Note: This solution was developed independently of Uriel's and its comments; if Uriel decides to use the find method, I'm happy to roll back to my longer, recursive version.


2
I've created a meta discussion on requiring a certain execution domain, since that does save quite a few bytes.
— Birjolaxew

1
@Downvoter, please have the decency to leave a comment.
— Shaggy

@Shaggy I would assume for the same reason as that meta discussion was started.

Downvoter, if you disagree with an established consensus (as @Rogem suggests), please downvote the relevant meta post rather than solutions that adhere to that consensus.
— Shaggy
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.