I have this code:
U = [1,2,3,4,5,6,7,8,9,10,11,12]
def bla(anzahl):
zaehlwerk = 0
while zaehlwerk < anzahl:
for x in U:
zaehlwerk = zaehlwerk +1
print x
my query:
bla(3)
I hoped that now I would get the first 3 list items, but instead I get the whole list.
1
2
3
4
5
6
7
8
9
10
11
12
I tried to debug because I thought that maybe the counter wouldn't work, but it does. But then where is my error?
use slicing :
>>> U = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> U[:3]
[1, 2, 3]
U[stat-index:end-index], you will get element from start-index to one less end-index, as in above example
>>>U[2:6]
[3, 4, 5, 6]
what you need to do is this using slicing:
def print_list(n):
print "\n".join(map(str,U[:n]))
print_list(3)
output:
1
2
3
for x in U:
is the innermost loop. That is making sure you iterate over everything.
As is you can modify your code to look like
def bla(anzahl):
zaehlwerk = 0
while zaehlwerk < anzahl:
x = U[zaehlwerk]
zaehlwerk = zaehlwerk +1
print x
And that will work for what you want. But more concise would be to to use something like
for index in range(len(anzahl)):
print U[index]
Related
I am trying to solve a problem where I have to enter several integers as an input (seperated by a whitespace), and print the integer that is the sum of all the OTHER integers.
So e.g.:
1 2 3 would give: 3, because 3 = 1 + 2
1 3 5 9 would give: 9, because 5 + 3 + 1 = 9
This is the code I currently have:
x = input().split(" ")
x = [int(c) for c in x]
y = 0
for i in range(len(x)-1):
y += x[i]
del x[i]
z = sum(x)
if y == z:
print(y)
break
else:
x.insert(i,y)
As the output, it just gives nothing no matter what.
Does anyone spot a mistake? I'd be ever greatful as I'm just a beginner who's got a lot to learn :)
(I renamed your strange name x to numbers.)
numbers = input().split()
numbers = [int(i) for i in numbers]
must_be = sum(numbers) / 2
if must_be in numbers:
print(int(must_be))
The explanation:
If there is an element s such that s = (sum of other elements),
then (sum of ALL elements) = s + (sum of other elements) = s + s = 2 * s.
So s = (sum of all elements) / 2.
If the last number entered is always the sum of previous numbers in the input sequence. Your problem lies with the x.insert(i, y) statement. For example take the following input sequence:
'1 2 5 8'
after the first pass through the for loop:
i = 0
z = 15
x = [1, 2, 5, 8]
y = 1
after the second pass through the for loop:
i = 1
z = 14
x = [1, 3, 5, 8]
y = 3
after the third pass through the for loop:
i = 2
z = 12
x = [1, 3, 8, 8]
y = 8
and the for loop completes without printing a result
If it's guaranteed that one of the integers will be the sum of all other integers, can you not just sort the input list and print the last element (assuming positive integers)?
x = input().split(" ")
x = [int(c) for c in x]
print(sorted(x)[-1])
I think this is a tricky question and can be done in quick way by using a trick
i.e create a dictionary with all the keys and store the sum as value like
{1: 18, 3: 18, 5: 18, 9: 18}
now iterate over dictionary and if val - key is in the dictionary then boom that's the number
a = [1, 3, 5, 9]
d = dict(zip(a,[sum(a)]*len(a)))
print([k for k,v in d.items() if d.get(v-k, False)])
Hello am a beginner to python and I have been stuck at this problem for awhile now. I want to start with 2 lists:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [a, b, c]
And write a function that will give me this output:
a
1
2
3
b
4
5
6
c
7
8
9
I have tried using nested for loops and a counter but I am unsure how to obtain the above result.
counter = 0
for i in list2:
print(i)
for j in list1:
print(j)
counter += 1
if counter == 3:
counter = 0
break
Any help would be appreciated!
Here's one possible way, closer to what you intended to write:
j = 0
for i in list2:
print(i)
for _ in range(3):
print(list1[j])
j += 1
Here's an option:
for i, v1 in enumerate(list2):
print(v1)
for v2 in list1[i*3:(i+1)*3]:
print(v2)
You don't need to make and update your own counters here. The built-in enumerate() function generates a counter for you and automatically updates it for each step of the loop. Then you can use list slicing to get the right three values of the inner list.
Try this:
for i in list2:
print(i)
# here you don't have to take it back to 0
counter = 0
for j in range(len(list1)):
# Use range to loop the list so you can cut it off later
# from the position you reach the third element
print(list1[j])
counter += 1
if counter == 3:
list1 = list1[j + 1:]
break
It outputs what you expect:
a
1
2
3
b
4
5
6
c
7
8
9
Everybody,
a =[0, 0, 2, 4, 6]
x=5
This a list (a) and a fix value (x).
I need a loop codes which must add with x every element of list and add this value with previous list elements in every loop ( loop must continue as x value). Other words result should like below:
0
0
2
4
6
0
0
7
9
11
0
0
12
14
16
0
0
15
19
21
0
0
21
24
26
I prepared codes as below but it doesn’t work. Other words produce something as below (incorrect)
i=0
counter=0
while counter < x:
for i in a:
if i >0:
i=i+x
elif i ==0:
i=0
print i
counter=counter+1
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
So, I need to help for this…
Thank you.
I think this does mostly what you want (at least, as I understand the question)...
def make_it_so(a, x):
i = 0
counter=0
while counter < x:
for i in a:
if i == 0:
yield 0
else:
yield i + counter * x
counter = counter + 1
# Demo
for item in make_it_so([0, 0, 2, 4, 6], 5):
print item
Note that I've made it a generator function. You could easily turn it into a regular function that returns a list if you created an output list at the top of the function and swapped yield ... for output_list.append(...) and then return output_list at the end of the function...
The key here is to understand that in the first loop, you are adding 0 to all of the (non-zero) items. In the second loop, you are adding x. In the third loop, you're adding the x + x (since the first loop added x and now you're adding x more). In general, for the Nth loop, you'll be adding (N-1) * x to all of the non-zero items. So, you just need to keep track of N, (or N-1). In fact, your original code was already doing this (with counter), so we just re-purpose that and it's all good.
You need to change the values in a, not just add to the numbers you get out of a (because you'll keep getting the same ones out). Also, you need to print out the original values.
def process(x, memo):
return [n+x if n else n for n in memo]
res = a
memo = a
for _ in range(x - 1):
memo = process(x, memo)
res.extend(memo)
I have written a program that eliminates the items in a list and outputs the other list.
Program :
r = [5,7,2]
for i in range(10):
if i != r:
print i
It outputs
0
1
2
3
4
5
6
7
8
9
But I want the desired output to be
0
1
3
4
6
8
9
What is the method to do so?
When you do - i !=r its always true, because an int and a list are never equal. You want to use the not in operator -
r = [5,7,2]
for i in range(10):
if i not in r:
print i
From python documentation -
The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s .
You are checking if a integer is not equal to to list .which is right so it prints all the value
What you really wanted to do is check if the value is not available in the list .So you need to use not in operator
r = [5,7,2]
for i in range(10):
if i not in r:
print i
You can try like this,
>>> r = [5, 7, 2]
>>> for ix in [item for item in range(10) if item not in r]:
... print ix
...
0
1
3
4
6
8
9
Using set
>>> r = [5,7,2]
>>> for i in set(range(10))-set(r):
... print(i)
...
0
1
3
4
6
8
9
>>>
Is there clean way to get the value at a list index or None if the index is out or range in Python?
The obvious way to do it would be this:
if len(the_list) > i:
return the_list[i]
else:
return None
However, the verbosity reduces code readability. Is there a clean, simple, one-liner that can be used instead?
Try:
try:
return the_list[i]
except IndexError:
return None
Or, one liner:
l[i] if i < len(l) else None
Example:
>>> l=list(range(5))
>>> i=6
>>> print(l[i] if i < len(l) else None)
None
>>> i=2
>>> print(l[i] if i < len(l) else None)
2
I find list slices good for this:
>>> x = [1, 2, 3]
>>> a = x [1:2]
>>> a
[2]
>>> b = x [4:5]
>>> b
[]
So, always access x[i:i+1], if you want x[i]. You'll get a list with the required element if it exists. Otherwise, you get an empty list.
If you are dealing with small lists, you do not need to add an if statement or something of the sorts. An easy solution is to transform the list into a dict. Then you can use dict.get:
table = dict(enumerate(the_list))
return table.get(i)
You can even set another default value than None, using the second argument to dict.get. For example, use table.get(i, 'unknown') to return 'unknown' if the index is out of range.
Note that this method does not work with negative indices.
Combining slicing and iterating
next(iter(the_list[i:i+1]), None)
For your purposes you can exclude the else part as None is return by default if a given condition is not met.
def return_ele(x, i):
if len(x) > i: return x[i]
Result
>>> x = [2,3,4]
>>> b = return_ele(x, 2)
>>> b
4
>>> b = return_ele(x, 5)
>>> b
>>> type(b)
<type 'NoneType'>
return the_list[i] if len(the_list) > i else None
1. if...else...
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
following = l[i + 1] if i + 1 < len(l) else None
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
2. try...except...
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
try:
following = l[i + 1]
except IndexError:
following = None
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
3. dict
suitable for small list
l = [1, 2, 3, 4, 5]
dl = dict(enumerate(l))
for i, current in enumerate(l):
following = dl.get(i + 1)
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
4. List slicing
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
following = next(iter(l[i + 1:i + 2]), None)
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
5. itertools.zip_longest
from itertools import zip_longest
l = [1, 2, 3, 4, 5]
for i, (current, following) in enumerate(zip_longest(l, l[1:])):
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
Using Jupyter magic command of %%timeit
init
from itertools import zip_longest
l = list(range(10000000))
Result
Method
Consume
if...else...
2.62 s
try...except...
1.14 s
dict
2.61 s
List slicing
3.75 s
itertools.zip_longest
1.14 s
Another one-liner:
return((the_list + [None] * i)[i])