+ 2
how can i make the code better?
word = input() word = word.lower() itog = None for i in range(len(word)): x = word.count(word[i]) if x > 1 : itog = ("false") break else: itog = ("true") print(itog)
7 Antworten
+ 9
Санчик Мигноу ,
a general improvement would be to use proper *indentation* as described in the python styleguide pep-0008:
https://peps.python.org/pep-0008/#indentation
> indentation should be done as 4 spaces per level. this improves readability of the code.
so the code as close as possible to your version could be:
word = input().lower()
#word = word.lower() # can be done in one expression see line above
#itog = True # not required to declare and initialize variable *itog* here
#for i in range(len(word)): # better to use for loop without indexes like:
for char in word: # use meaningful variable names. *char* instead of *i*
#amount = word.count(char) # combine counting of character with if conditional
if word.count(char) > 1:
itog = "false" #no need to use parenthesis
break
else:
itog = "true" #no need to use parenthesis
print(itog)
+ 8
It would be useful if you also described what your program is supposed to do. That can help others to judge, how it should be improved. :)
It seems you are trying to check that there are no duplicate characters in a string.
You can also use a trick here, compare the size of the string, with the size of a set made from the same letters. A set already eliminates duplicates, so if these two are the same, then there are no duplicate letters.
word = input() or "Sololearn"
no_reps = len(word) == len(set(word))
print(no_reps)
An additional improvement would be to put your code inside a function (def block) - then you can test multiple cases with a single run.
+ 5
word = input() or "SoloLearn"
w = word.lower()
for c in w:
if w.count(c)>1:
print("false")
break
else:
print("true")
+ 4
I agree with Tibor Santa
print(str(no_reps).lower()) # if you want the result to be uncapitalized
+ 4
If we follow the general pattern of your code, I'd first eliminate unnecessary assignments.
You don't need the reassignment for word, and you don't need x.
Also you don't need i, that you then use to index each letter - you can take each letter directly.
word = input().lower()
for letter in word:
if word.count(letter) > 1 :
itog = ("false")
break
else:
itog = ("true")
print(itog)
If you don't use itog anywhere else, you can get rid of that variable as well, just printing 'true' or 'false' in place.
Tibor already showed another version with the set - possibly the shortest way.
Another relatively short way that still explicitly expresses the letter counting:
print(all(word.count(letter)==1 for letter in word))
0
# How about we start with comment ?
0
name="comment"()