This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
return statement in for loops [duplicate]
(6 answers)
Closed 1 year ago.
Please see the below code
def common_letters(string_one,string_two):
letters_in_common = []
for letter in string_one:
for letter2 in string_two:
if letter == letter2:
letters_in_common.append(letter)
return letters_in_common
returned = common_letters("hello", "loha")
print(returned)
The above code works, but only on the first iteration of the outer loop, hence my letters_in_common list only returns ['h'] when it should return ['h','l','l'], In JS the syntax is different and the loop works incrementally.
Am I misunderstanding how loops work in Python or is there a syntax level step I have not included?
p.s. I am aware that I could use the 'in' keyword etc but I wanted to try it with a loop first.
Your return is indented so that it is inside if. Presumably you want to return after you check every letter against every letter, which means return has to be outside the loops:
def common_letters(string_one, string_two):
letters_in_common = []
for letter in string_one:
for letter2 in string_two:
if letter == letter2:
letters_in_common.append(letter)
return letters_in_common
Sidenote: This will give a somewhat surprising result if there are multiples of a shared letter in both strings. If I wanted to find out just the shared letters, I would use set intersection:
def common_letters(string_one, string_two):
return list(set(string_one) & set(string_two))
Related
This question already has answers here:
Is it possible to use 'else' in a list comprehension? [duplicate]
(6 answers)
Closed 2 years ago.
Learning list comprehensions and discovered that if/if-else statement can be placed in different order of apperance in expression.
In example, starting understanding list comprehension construction from for loop schema:
positive = []
for number in numbers:
if int(number) >= 0:
positive.append(int(number))
else:
positive.append(0 - int(number))
can be evaluated to:
positive = [int(number) if int(number) >= 0 else 0 - int(number) for number in numbers]
But
positive = []
for number in number:
if int(number) >= 0:
positive.append(int(number))
goes to:
positive = [int(number) for number in numbers if int(number) >= 0]
I know that one of useful technique for creating list comprehension is to read for loop from top to down and put them in one line (a little shortcut of course).
But why those 2 examples put if / if-else statement once in front and secondly in the end of construction?
In the first case, you're choosing between two options; but in either choice, you're adding to the list. Whatever comes before the for is added to the list.
In the second case, you're only adding to the result list in one option. Whatever comes after the for construct on the right decides if something is added at all.
If you want to pick what's added between (usually two) options, use the first. If you what to pick if something is added at all, use the second.
This question already has answers here:
How can I invert (swap) the case of each letter in a string?
(8 answers)
Closed 6 months ago.
this script is supposed to swap case in words but the result is really weird and doesn't make sense
def swap_case(s):
for i in range(len(s)):
if s[i].islower():
s= s.replace(s[i],s[i].upper())
elif s[i].isupper():
s= s.replace(s[i],s[i].lower())
else:
pass
example
First of all consider using inbuild swapcase function
Otherwise, you can use join function
E.g.
s = "hELLO wORLD"
# inbuilt
print(s.swapcase())
# join
print(''.join([ss.lower() if ss.isupper() else ss.upper() for ss in s]))
which gives you
You're going through each letter in the string, then replacing all instances of that letter. That means that if there's an even amount of a letter, the case won't be changed.
Also, a method, swapcase, already exists for this.
>>> 'Hello World!'.swapcase()
'hELLO wORLD!'
Here is the solution for your problem-->
def swap_case(s):
k=''
for i in range(len(s)):
if s[i].islower():
k+=s[i].upper()
elif s[i].isupper():
k+=s[i].lower()
else:
pass
print(k)
Solution with Python
Case Swapping can be achieve using a python built-in function called swapcase if you want to do this manually then here is the code.
result = ''
for element in (s):
if element.isupper():
result += element.lower()
else:
result += element.upper()
print(result)
This question already has answers here:
Appending to list with loop
(2 answers)
Closed 3 years ago.
I am trying to create a cartesian product of the alphabet with loops. I have for loops that create the desired output but i in my while loop is never reached for some reason.
This loop is running forever in a jupyter lab notebook.
lower_az = [chr(ord('a') + i) for i in range(26)]
i=0
n=2
lst = lower_az.copy()
final_list = []
while i < n:
for let in lst:
for j in range(26):
strng = let + lower_az[j]
lst.append(strng)
i += 1
final_list.append(lst)
Unless I am missing something obvious the variable i should increment until it reaches n and stop the while loop at the desired length of strings.
You are changing the list you are iterating over. The problem is not the while-loop, it's the lst.append(strng) while iterating for let in lst.
#blue_note is correct - Python doesn't behave well when you change a list you're iterating over.
It looks like this is just a typo, though: you've got final_list all ready to receive the elements. To fix this, change:
lst.append(strng)
to
final_list.append(strng)
and drop final_list.append(lst) and your program appears to work fine.
This question already has answers here:
Convert from "For-loops" to "While-loops"
(3 answers)
Closed 4 years ago.
For a school work, we have to create a function that determines if a list is injective, which returns True or False. 2 ways of doing the job are recommended : with 'for' loops and with 'while' loops. I managed to program with 'for' loops, but I'm having issues with 'while' loops, as i cannot figure out why mine is infinite.
I'll put my code below. I already tried getting rid of few variables that where needless, and as I modify the value of 'a' within the loop, it seems to me there is nothing wrong on paper.
def injective(x):
i=0
k=i+1
a=True
while i<len(L)-1 : #L is the name of the list
while k<len(L) :
if L[i]==L[k] :
a=False
else :
a=True
i+=1
return a
I expect to get True when the list is injective and False when not
It is because the value of k in the inner loop is not changing, I think you are missing k+=1 somewhere.
Code
def injective(x):
i=0
k=i+1
while i<len(L)-1 : #L is the name of the list
while k<len(L) :
if L[i]==L[k] :
return False
k+=1
i+=1
return True
I have taken the liberty to optimize the code a bit (it will decrease your iterations drastically for a non-injective function). You can use the same in your other program with the for loop.
This question already has answers here:
Python Variable Declaration
(6 answers)
Understanding for loops in Python
(4 answers)
Closed 4 years ago.
I came across code like this:
s1 = "mit u rock"
s2 = "i rule mit"
if len(s1) == len(s2):
for char1 in s1:
for char2 in s2:
if char1 == char2:
print("common letter")
break
I notice there are no previous defines for the variable like char1 or char2, so how does this work? I think it might be some "keyword for a variable" that Python understands. If so, could you tell me what's it called, and what are other common variables like this?
What that for loop does is loop over s1. For every iteration it assigns an element of iterable container s1 to variable char1.
Therefore, on the first iteration of the loop for char1 in s1, char1 will have the string value 'm', on the second iteration string value 'i'.
Note that even after the loop has finished executing, char1 will still have a value assigned (the last iteration means it will have value 'k').
What your iterating over doesn't have to be a string, it can be any object that defines __iter__ and __next__ methods. So some examples are a list [1,2,3] or a generator like what is returned by function invokation range(5).