I need to write a function printMultiples(lst) that takes a list of numbers and PRINTS the number if it is a multiple of 8
>>> printMultiples([2, 3, 4, 5, 6, 7, 8, 9])
So whenever I run this I don't get any output just a blank line. I'm told I need to call the function printMultiples, but I am clueless how to do that.
printMultiples = [(2, 3 ,4, 5, 6, 7, 8, 9)]
def printMultiples(lst):
for i in lst[0]:
if (i%8==0):
print (i)
I should see the number 8 print out but I seem to be missing a step or a line.
The function is well defined, and it does what you want it to do. The problem is that you are naming a variable with the same name as your function, so it gets overriden, use the following:
multiples = [(2, 3 ,4, 5, 6, 7, 8, 9)]
def printMultiples(lst):
for i in lst[0]:
if (i%8==0):
print (i)
printMultiples(multiples)
Output:
8
As #roganjosh has suggested, you can improve your code by following PEP-8:
multiples = [(2, 3 ,4, 5, 6, 7, 8, 9)]
def print_multiples(lst):
for number in lst[0]:
if number % 8 == 0:
print(number)
print_multiples(multiples)
Your first line of code shows how to call the function:
>>> printMultiples([2, 3, 4, 5, 6, 7, 8, 9])
Node that the >>> signals that you can anything following it in the Python REPL. If you are saving this in a file, you don't need to type the >>>.
The problem with the rest of the code is that you assign a list to the same name that you give to your function. If you want to put the list in a variable, you should give it a different name:
multiples = [2, 3 ,4, 5, 6, 7, 8, 9]
Note that I also removed the parentheses. When you call the function by directly passing the array in, you need parentheses () around the brackets []. But when you assign a list to a variable, you don't need the parentheses at all.
Now to call the function with this variable, you put the variable name in parentheses after the function name:
printMultiples(multiples)
Add this line at the end of your program. Be sure that it is not indented.
Others have stated that your list containing the multiples cannot be the same name as your function. Also, why not just store the multiples as list, like this:
lst = [2, 3 ,4, 5, 6, 7, 8, 9]
def printMultiples(lst):
for i in lst:
if i%8==0:
print(i)
printMultiples(lst)
Related
This works..
indices = [1, 2, 3, 5, 8]
sample_reviews = reviews.loc[indices]
But... this does not works the same way, instead shows an error
sample_reviews = reviews.loc[1, 2, 3, 5, 8]
In the first case your are passing a list called indicies to the function, which is correct. In the second, you are passing 5 ints, which is incorrect. You need to change the second to:
sample_reviews = reviews.loc[[1, 2, 3, 5, 8]]
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.
Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:
a = [1, 2, 3, 4, 5, 6, 7, 8]
and the output needs to be:
1-2
3-4
5-6
7-8
Now I have gotten as far as this, but have no idea what to do next:
a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]
duos = zip(a1, a2)
print(list(duos))
And this only gives me this as result:
[(1, 2), (3, 4), (5, 6), (7, 8)]
I feel like I am close and just missing one tiny step.
Build a lazy iterator:
>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> it = iter(a)
>>> print([f"{x}-{y}" for x,y in zip(it,it)])
['1-2', '3-4', '5-6', '7-8']
Yep, very close indeed.
You can use a generator expression to form the pair strings without the intermediate variables, then "\n".join to make a single string out of the formatted pairs.
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> print("\n".join(f"{a}-{b}" for (a, b) in zip(numbers[::2], numbers[1::2])))
1-2
3-4
5-6
7-8
The more procedural version (that's functionally equivalent, but doesn't form a list, but just prints each pair) would be
for (a, b) in zip(numbers[::2], numbers[1::2]):
print(f"{a}-{b}")
Completing your work:
for x, y in duos:
print(f'{x}-{y}')
(Note you need to do this instead of your print(list(duos)), otherwise that consumes the zip iterator and there's nothing left.)
You're indeed very close. Now just print each pair in duos on a separate line with a dash as separator:
for a,b in duos: print(a,b,sep="-")
Or you could do it all in one line using a combination of map, zip and join:
print(*map("-".join,zip(*[map(str,a)]*2)),sep="\n")
A somewhat fun[*] alternative, easily adapts to similar cases just by altering the string of ends:
from itertools import cycle
a = [1, 2, 3, 4, 5, 6, 7, 8]
for x, end in zip(a, cycle('-\n')):
print(x, end=end)
For example with cycle('+-*\n'), it would instead print this:
1+2-3*4
5+6-7*8
[*] Everything itertools is fun for me :-)
I have a list:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
There are multiple if usages that check a number is in the a list.
while True:
if 3 in a:
some_work1 #(different)
if 4 in a:
some_work2 #(different)
if 8 in a:
some_work3 #(different)
if 11 in a:
some_work4 #(different)
if 12 in a:
some_work5 #(different)
Are there any faster (less cpu usage) methods for these multiple if usages? (List a is always same. Also it does not change over iterations.). There is no dublicated items in the a list. Works do not overlap.
Python 3.8.7
Use a set which has constant insert and retrieve times. In comparison, the in operator performs a linear search in your a every check.
I'm not exactly sure what your use-case is without seeing your larger code. I'm assuming your use-case treats a as a list of flags. As such, a set fits the bill.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9 10, 11, 12]
a = set(a) # pass an iterable
# or simply
a = {1, 2, 3, 4, 5, 6, 7, 8, 9 10, 11, 12}
# or built at runtime
a = set()
a.add(1)
a.add(2)
if 3 in a:
some_work1
If you want a more efficient switch statement, you have already found it. Python uses if..elif for this. This ensures each is evaluated in sequence with short-circuit. If you could match multiple outcomes, use a dict (e.g. {3: functor3, 4: functor4, ...}. A functor is a callable, ie it has a __call__() method defined. A lambda also satisfies this.
A set is an unordered collection that does not allow duplicates. It's like a dictionary but with the values removed, leaving just keys. As you know, dictionary keys are unique, and likewise members of a set are unique. Here we just want a set for performance.
option 1
You could use a dictionary whose keys are the number in a and values the corresponding function. Then you loop over them once and store the needed functions in an array (to_call). In the while loop you simply iterate over this array and call its members.
def some_work1():
print("work1")
def some_work2():
print("work2");
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
func = {3:some_work1,4:some_work2}
to_call = []
for k in func:
if k in a:
to_call.append(func[k])
while 1:
for f in to_call:
f();
Option 2
Write some kind of code generator that reads a and generates a .py file containing the function calls.
I'm still pretty new to this website and to python. So, please forgive my question possibly not being specific enough and the possibility of there already being an answer that I haven't found yet.
Basically, I am having trouble with for loops in python.
I want to create lists using the in range() function. Each successive list should set with the next number. For example
[1,2,3,4,5]
[2,3,4,5,6]
[3,4,5,6,7]
I want also the lists that are produced to be of equal length: for example, 5 numbers, 6 numbers or 7 numbers, etc.
l=[]
for i in range (1,10):
for a in range (i):
l.append (i)
print (l[:5])
result is:
[1]
[1, 2]
[1, 2, 2]
[1, 2, 2, 3]
[1, 2, 2, 3, 3]
and then it just repeats with 3. However, I want the next line two start with a new number, so 2 then the next line 3, etc.
I would greatly appreciate your help or at least a hint in the right direction !
If this question has already been answered, I would also appreciate having the link for the respective article.
Start over. Code one or two lines at a time. Print out variables to trace their values. Do not write more code until you know that the current code does what you need. A significant portion of your problem is that you tried to write too much code in one pass, more than you (yet) know how to handle.
Let's start here:
l=[]
for i in range (1,10):
...
Although you clearly state that you want a new starting point at each iteration, you initialize l only once. This means that it will accumulate all of the values you append to it for the entire run of the program, rather than giving you a new list each time.
for a in range (i):
How does this support anything that you're trying to do? You will iterate once, then twice, then 3 times ... what part of your program is repeated in this fashion? You clearly state that you want each list to be of the same length, but then you go out of your way to ensure that you accumulate an ever-increasing list on each completion of this inner loop.
Does this get you moving?
Hey Christopher try this.
for i in range (0,4):
l=[]
for j in range (1+i,6+i):
l.append (j)
print(l)
I think what you're trying to do probably looks something like this:
my_lists = []
for i in range(10):
some_list = []
for j in range(5):
some_list.append(i + j)
print(some_list)
my_lists.append(some_list)
# or if you're being fancy,
# my_lists = [list(range(i, i + 5)) for i in range(10)]
I wouldn't worry too much about the ways to shorten and/or optimise the various
bits of it for now. This gives you a nice list my_lists of all the smaller
lists generated. Does that help you? I'd make sure you understand what's going
on in each loop, and why everything's structured the way it is.
(side note: the sum of the first three values of each list
is given by a fairly straightforward arithmetic progression, so if you need to
calculate it efficiently you'd be better off looking for an algebraic closed
form.)
You could write a function like this one:
def makelists(start, end, n):
sequence = [i for i in range(start, end + 1)]
if n == 1:
print(sequence)
else:
print(sequence)
for i in range(1, n):
sequence = list(map(lambda x: x + 1, sequence))
print(sequence)
makelists(1, 5, 3)
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
For other inputs:
makelists(3, 10, 7)
[3, 4, 5, 6, 7, 8, 9, 10]
[4, 5, 6, 7, 8, 9, 10, 11]
[5, 6, 7, 8, 9, 10, 11, 12]
[6, 7, 8, 9, 10, 11, 12, 13]
[7, 8, 9, 10, 11, 12, 13, 14]
[8, 9, 10, 11, 12, 13, 14, 15]
[9, 10, 11, 12, 13, 14, 15, 16]
I have recently created a GUI, which contents tables. User can insert values in cells. As shown figur below.
I want to use values to make some calculation based on values given by user. Rows can be added and removed based on choice of user. with other word, the data I get from user could come from just one row or several rows.
I manage to obtain all values from tables automatically and assign them to python list. Each row gives 5 elements in the list.
I have achieved that. Data in python list have to be processed and organised. This is exactly I want to have help. Because few dags I have been thinking, and I can not figure out, how to continue...
Python data as list from table. as an example.
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, '', 11, 12, 13, 14]
What I want to achieve!
I want to split list into 3 times len(data).
I have also achieved this.
def split_seq(seq, num_pieces):
start = 0
for i in range(num_pieces):
stop = start + len(seq[i::num_pieces])
yield seq[start:stop]
start = stop
for data in split_seq(data, int(len(data)/5)):
print(data)
Output would be:
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
['', 11, 12, 13, 14]
The difficulty part starts here.
I want to take each splitted list and throw them into an if condition and store values as variables and message those values to an external function.
Something like this below:
for i in range(len(splitted_list1)):
if splitted_list1[0] == '':
do nothing
else:
x_+str(i)= splitted_list1[i]
externalfunc(x_1,x_2,x_3,x_4,x_5)
for i in range(len(splitted_list2)):
if splitted_list2[0] == '':
do nothing
else:
x_+str(i)= splitted_list2[i]
externalfunc(x_1,x_2,x_3,x_4,x_5)
continues depending on number of splitted_lists
..............
I appreciate any help and you are welcome to come with another idea to come around this.
Use one single list and pass that to externalfunc.
The line x_+str(i)= ... is going to be interpreted as x_"0"= ... or whatever number eventually. The function is going to take in a possibly unknown number of variables. You can just group each "variable" into one list and index them based on the number instead. Which you already have. Each one would be in splitted_list0, splitted_list1, etc.
However, you do not need to asynchronously return the different lists. Instead, you can split the lists and put them in one larger list. This is a two-dimensional array. Seems scary but it's just some lists inside another list.
Now to pass each number to the externalfunc you can use each split list and pass it as an argument. Basically resulting in externalfunc(splitted_list0) and so on.
The final code ends up something like the following:
# Split the data into seperate lists:
split_lists = [data[i*(len(data)/3):(i+1)*(len(data)/3)] for i in range(3)]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, '', 11, 12, 13, 14] becomes
# [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ['', 11, 12, 13, 14]]
# Pass each list to the external function:
for i in range(split_lists):
externalfunc(split_lists[i])
# split_lists[i] will be [1, 2, 3, 4, 5] or [6, 7, 8, 9, 10], etc.
Note that the 3 in the first line of code can be changed to be any number smaller than the length of the list data. This is just the number of lists to split the data into. Remember to change every 3 if it's hardcoded or just add a variable. Finally, the function externalfunc will have the list of 5 numbers as the first and only argument of the function.
def externalfunc(nums):
for n in nums:
# n = each number in the list
# do something with n, write it somewhere, store it, print it.
print(n)