I want to create an output that concatenates the list and tuple to give a single output
def conca(names,storey):
for name in names:
i = 0
d = "%s has %d"%(name,storey[i])
print(d)
i = i+1
conca(names=("White house","Burj khalifa",
"Shit"),storey = [3,278,45])
But it gives an output like
White house has 3
Burj khalifa has 3
Shit has 3
But i dont want only 3. I want i to increase. Give output like
White house has 3
Burj khalifa has 278
Shit has 45
Why is i not incrementing. What am i doing wrong
Problem:
You define i inside loop, so you reset to 0 in every iteration resulting in adding first storey every time.
Corrected:
def conca(names, storey):
i = 0
for name in names:
d = "%s has %d"%(name,storey[i])
print(d)
i = i+1
conca(names=("White house","Burj khalifa",
"Shit"), storey=[3,278,45])
You can also use zip() to iterate over lists simultaneously:
def conca(names, storey):
for name, st in zip(names, storey):
print(f'{name} has {st}')
conca(names=("White house","Burj khalifa",
"Shit"), storey=[3,278,45])
Related
names = ["jeremy","johnathon"]
average = 4
def longestNames(names,average):
newlist = []
for i in names:
if len(names) > average:
return newlist.append(len(names))
z = longestNames(names,average)
print(z)
Ive been trying to figure this out but I either get an error or none. I basically want to place all names longer than average the new list.
There is no error. the code returns None because both jack and john has a length smaller than average
Edit :
Use this code:
names = ["veryyyyyyyy","sml"]
average = 4
def longestNames(names,average):
newlist = []
for i in names:
if len(i) > average:
newlist.append(i)
return newlist
z = longestNames(names,average)
print(z)
Note list.append() returns None. You have to return the list itself
The names that you have already selected have the length equal to 4, but you are checking the average bigger than 4. Thus, the returned value would be none. It is better to try other names with the length of 5 or bigger or change the initial average to less than 4.
banks = ["bank1", "bank2", "bank3", "bank4", "bank5", "bank6", "bank7", "bank8", "bank9", "bank10"]
for i, item in enumerate(banks[:5], start=1):
print(i, item)
The output is
1 bank1
2 bank2
3 bank3
4 bank4
5 bank5
How can I save the result of this output in a variable?
You could store the whole thing in another list/ numpy array. It would be basically doubling your memory but you could do something like this:
result = []
for i, item in enumerate(banks[:5], start=1):
result.append([i, item])
i want to count how many pairs of numbers in a list can add to a specific number, this is my code in python but the output is not what it should be
list = [1,2,3,4]
x=3
count = 0
for i in range(len(list)):
for j in range(len(list)):
if i + j == x:
count+=1
print(count)
You could simpilify your code with functions from the built-in itertools module, depending on how you would like to iterate through the list, i.e. combinations, combinations with replacements, or products.
import itertools as itt
in_list = [1,2,3,4]
tgt_num = 3
count = 0
for a,b in itt.combinations(in_list, 2): # returns 1
# for a,b in itt.combinations_with_replacement(in_list, 2): # returns 1
# for a,b in itt.product(in_list, in_list): # returns 2
if a + b == tgt_num:
count += 1
print(count)
Your code has some issues:
One is that it never directly references the items of the list. Because of this, it will only work assuming that the numbers in the list are in ascending order, each is one apart, and that it starts at 1.
Another is that it iterates through the pairs of numbers too many times.
Finally, there are some indentation issues, but I'm guessing those were just lost in the copy-paste. I tried to re-indent it, but when I ran it I got "4", when it should be "1".
Here's a version that incorporates indexing the list, which should resolve the above issues.
list = [1,2,3,4]
x = 3
count = 0
for i in range(0,len(list)):
pair1 = list[i]
pair2 = list[i+1:]
for j in range(0,len(pair2)):
if pair1 + pair2[j] == x:
count += 1
print(count)
Need to remove every third element and return it once the list has only two elements left
def duck_duck_goose(lst: List[str]) -> List[str]:
"""Given an list of names (strings), play 'duck duck goose' with it,
knocking out every third name (wrapping around) until only two names are
left. In other words, when you hit the end of the list, wrap around and keep
counting from where you were.
For example, if given this list ['Nathan', 'Sasha', 'Sara', 'Jennie'], you'd
first knock out Sara. Then first 'duck' on Jennie, wrap around to 'duck' on
Nathan and 'goose' on Sasha - knocking him out and leaving only Nathan and
Jennie.
You may assume the list has 3+ names to start
Args:
lst - a list of names (strings)
Returns:
the resulting list after playing duck duck goose
"""
raise NotImplementedError("duck_duck_goose")
names = ["sasha", "nathan", "jennie", "shane", "will", "sara"]
assert duck_duck_goose(names) == ["sasha", "will"]
Here's a short snippet on how you can do it,
names = ["sasha", "nathan", "jennie", "shane", "will", "sara"]
def removeThirdName(names):
pos = 3 - 1
index = 0
len_list = (len(names))
while len_list > 2:
index = (pos + index) % len_list
print(names.pop(index))
len_list -= 1
removeThirdName(names)
print(names)
Outputs:
['sasha', 'will']
Write the function largestNumber(text) that takes a string of text and returns the largest int value that occurs within that text, or None if no such value occurs.
For example:
largestNumber("I saw 3 dogs, 17 cats, and 14 cows!")
returns 17 (the int value 17, not the string "17").
and
largestNumber("One person ate two hot dogs!")
returns None (the value None, not the string "None").
I tried using isdigit function to separate out integer but how can I compare string?
You can try using a regex, and then max and map functions:
result = [e for e in re.split("[^0-9]", "I saw 3 dogs, 17 cats, and 14 cows!") if e != '']
# list 'result' elements are strings: ['3', '17', '14'], so we use map(int, list) to get integers
print max(map(int, result))
You could also do
def largestNumber(in_str):
l=[int(x) for x in in_str.split() if x.isdigit()]
return max(l) if l else None
First you split in_str based on space () with split() to get a list.
The 'numbers' in this list are identified using isdigit() and converted to integers using int().
These numbers are stored in l as a list.
The expression
max(l) if l else None
will give maximum value in l if l is not empty and otherwise None.
print(largestNumber("I saw 3 dogs, 17 cats, and 14 cows!"))
gives
17
and
print(largestNumber("One person ate two hot dogs!"))
gives
None
Just Another solution:
def findLargestNumber(text):
ls = list()
for w in text.split():
try:
ls.append(int(w))
except:
pass
try:
return max(ls)
except:
return None
print findLargestNumber('I saw 3 dogs, 17 cats, and 14 cows!')
print findLargestNumber('I saw ')
Output:
17
None
def findLargestNumber(text):
front = -1
li = []
for i in range(len(text)):
if front == -1:
if text[i].isdigit():
front = i
else:
continue
else:
if text[i].isdigit():
continue
else:
li.append(int(text[front:i+1]))
front = -1
return max(li)
print findLargestNumber('I saw 3 dogs, 17 cats, and 14 cows!')
import re
def extractmax(str1):
nums=re.findall("\d+",str1)
return max(nums)
\d+ is used to look for a decimal or number with length greater than one, it is appended into the array nums finally maximum value from nums if generated.
The following worked for me, and it works great!
Increment number in the string and then print out the max number in string
import re
import re
Increase number in string
name = "name 1"
number = re.search(r'\d+', str(name))
if number:
rx = r'(?<!\d){}(?!\d)'.format(number.group())
prefix = re.sub(rx, lambda x: str(int(x.group()) + 1), name)
print(prefix)
Instead of just printing this row directly "re.sub(rx, lambda x: str(int(x.group()) + 1), name)"
Store it in a variable, in my case prefix
That's because you will get the updated value in the string and not the original
Store incremented variable "name" into a list
li = [int(prefix[5:])]
print("Largest name", max(li))
Keep in mind that index 5 is where the number is starting, you may need to adjust it depending on the string length
You can try to make 2 variables to see if the max method is working properly