+ 1

How to improve that code?

Hi there, I'm pretty new to python. While taking the course I'm trying to write small scripts for a better understanding of the theorie. What I see is, if my code works or not, but I don't know nearly nothing about it's performance. For example I know that tuples are faster than lists, but that's it with my knowledge so far. Could anybody give me a feedback about this little code: https://code.sololearn.com/cvRkSIn8mrhy ? At which points could the code be improved, e.g. with other methods/functions? What is too complicated and could be written more compact? I hope that will show me some ways to improve my further coding. Thanks a lot!

16th Dec 2018, 4:30 PM
deha
deha - avatar
8 ответов
+ 8
inp = str((input("input some letters: \n"))) => str() not needed, input() is str anyway ~~ a = [] for x in inp: a.append(x) => can be replaced with a = list(inp) ~~ def words(perms): result = "" for y in perms: result += y print(result) return => can be replaced with def words(perms): result = ''.join(perms) print(result)
16th Dec 2018, 4:40 PM
Anna
Anna - avatar
+ 3
In addition to everything Anna said, I hope it's okay if I add that you don't need to make the list "a" of characters from inp. You can directly feed it to permutations(). from itertools import permutations inp = input("input some letters: \n") inp = inp.replace(" ", "").lower() for z in permutations(inp): print(''.join(z))
16th Dec 2018, 5:23 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
Sure! If you have a list of strings, you can use the join method to combine them to a single string. It works like this: l = ['a', 'b', 'c'] # sample list print(''.join(l)) # output: abc Just include the symbol you want to combine the single elements with in the quotation marks: print('+'.join(l)) # output: a+b+c print(', '.join(l)) # output: a, b, c
16th Dec 2018, 5:11 PM
Anna
Anna - avatar
+ 2
Katze war gerade zum ersten Mal im Schnee dieses Jahr :)
16th Dec 2018, 5:22 PM
deha
deha - avatar
+ 1
Kein Problem. Streichel deine Katze mal von mir 😻
16th Dec 2018, 5:18 PM
Anna
Anna - avatar
+ 1
Thanks for that hint, Kishalaya Saha! I don't know intertools very good yet, cause its introduction in the python course was very short.
16th Dec 2018, 5:35 PM
deha
deha - avatar
0
Thank you, Anna! Filling a list this way will save me a lot of time in the future. Could you explain me this part in detail: result = ''.join(perms) ? What is the '' for? Does it mean "empty", like "" and then .join iterates every item in (perm) an appends it to result = ''?
16th Dec 2018, 5:00 PM
deha
deha - avatar
0
Oh right... I slightly remember that lesson now. I think my brain needs an improvement, too :D
16th Dec 2018, 5:17 PM
deha
deha - avatar