Repeat list elements based in another list - python

I would like to repeat elements from one list based in a second list, like this:
i = 0
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for x in j:
while i <= x:
print(x)
i += 1
I've got this result:
1
1
4
4
4
10
10
10
10
10
10
I'd like to get this result:
11.65
11.65
11.69
11.69
11.69
11.71
11.71
11.71
11.71
11.71
11.71

You may iterate on both list together, using zip, then increase i until you reach the bound of the current value
i = 0
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for bound, value in zip(j, z):
while i <= bound:
print(value)
i += 1

j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for i in range(len(j)): #assuming the lenth of both list is always the same
for k in range(j[i]):
print(z[i])
Do you mean something like this?
there is a 1, 4, and 10
so print the first item in z 1 time, second item 4 times and the third 10 times?

Related

Python Count values simultaneously in two columns greater than N

Need help counting the occurrence that values in two columns are greater than a value in the same row. For example, if I want to count the number of times each row is greater than 4 and I have columns X & Y such that:
X Y
2 1
5 5
6 3
5 5
The output variable will be 2 since both numbers are greater than 4 in two rows, row 2 and 4.
Thank you
In [134]: df.gt(4).all(axis="columns").sum()
Out[134]: 2
check if values are greater than 4; gives True/False's (frame)
check if we have all True's per row; gives True/False's again (series)
sum to get the count as True -> 1, False -> 0
What about a comparison like this, in case you're not looking to use any additional packages.
x = [2, 5, 6, 5]
y = [1, 5, 3, 5]
counter = 0 # initialize counter variable
min_value = 4 # initialize min_value to compare
for x, y in zip(x, y):
# print(x, y)
if x > min_value and y > min_value:
counter += 1
print("Row Count: " + str(counter))
If you are using pandas, then you can use something like this:
import pandas as pd
x = [2, 5, 6, 5]
y = [1, 5, 3, 5]
df = pd.DataFrame(list(zip(x, y)), columns=["x", "y"])
min_value = 4 # initialize min_value to compare
counter = df.gt(min_value).all(axis="columns").sum()
print("Row Count: " + str(counter))

How to find how many values are divisible in to certain value in 2d array in python

The following code generate random number of 2d arrays and I want to print how many values in each pair are divisible to 3. For example assume we have an array [[2, 10], [1, 6], [4, 8]].
So the first pair which is [2,10] has 3 ,6 and 9 which are totally 3 and second pair has 3 and 6 which are totally two and last pair[4,8] has just 1 divisible to 3 which is 6. Therefore, The final out put should print sum of total number of divisible values which is 3+2+1=6
a=random.randint(1, 10)
b = np.random.randint(1,10,(a,2))
b = [sorted(i) for i in b]
c = np.array(b)
counter = 0;
for i in range(len(c)):
d=(c[i,0],c[i,1])
if (i % 3 == 0):
counter = counter + 1
print(counter)
One way is to count how many integers in the interval are divisible by 3 by testing each one.
Another way, and this is much more efficient if your intervals are huge, is to use math.
Take the interval [2, 10].
2 / 3 = 0.66; ceil(2 / 3) = 1.
10 / 3 = 3.33; floor(10 / 3) = 3.
Now we need to count how many integers exist between 0.66 and 3.33, or count how many integers exist between 1 and 3. Hey, that sounds an awful lot like subtraction! (and then adding one)
Let's write this as a function
from math import floor, ceil
def numdiv(x, y, div):
return floor(y / div) - ceil(x / div) + 1
So given a list of intervals, we can call it like so:
count = 0
intervals = [[2, 10], [1, 6], [4, 8]]
for interval in intervals:
count += numdiv(interval[0], interval[1], 3)
print(count)
Or using a list comprehension and sum:
count = sum([numdiv(interval[0], interval[1], 3) for interval in intervals])
You can use sum() builtin for the task:
l = [[2, 10], [1, 6], [4, 8]]
print( sum(v % 3 == 0 for a, b in l for v in range(a, b+1)) )
Prints:
6
EDIT: To count number of perfect squares:
def is_square(n):
return (n**.5).is_integer()
print( sum(is_square(v) for a, b in l for v in range(a, b+1)) )
Prints:
5
EDIT 2: To print info about each interval, just combine the two examples above. For example:
def is_square(n):
return (n**.5).is_integer()
for a, b in l:
print('Pair {},{}:'.format(a, b))
print('Number of divisible 3: {}'.format(sum(v % 3 == 0 for v in range(a, b+1))))
print('Number squares: {}'.format(sum(is_square(v) for v in range(a, b+1))))
print()
Prints:
Pair 2,10:
Number of divisible 3: 3
Number squares: 2
Pair 1,6:
Number of divisible 3: 2
Number squares: 2
Pair 4,8:
Number of divisible 3: 1
Number squares: 1

How do I fix this program that adds up all the integers in a list except the one that equals said sum?

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)])

PYTHON: Print X items of a list

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]

Constructing Lists

I'm new to Python and I came across the following query. Can anyone explain why the following:
[ n**2 for n in range(1, 6)]
gives:
[1, 4, 9, 16, 25]
It is called a list comprehension. What is happening is similar to the following:
results = []
for n in range(1,6):
results.append(n**2)
It therefore iterates through a list containing the values [0, 1, 2, 3, 4, 5] and squares each value. The result of the squaring is then added to the results list, and you get back the result you see (which is equivalent to 0**2, 1**2, 2**2, etc., where the **2 means 'raised to the second power').
This structure (populating a list with values based on some other criteria) is a common one in Python, so the list comprehension provides a shorthand syntax for allowing you to do so.
Breaking it down into manageable chunks in the interpreter:
>>> range(1, 6)
[1, 2, 3, 4, 5]
>>> 2 ** 2 # `x ** 2` means `x * x`
4
>>> 3 ** 2
9
>>> for n in range(1, 6):
...   print n
1
2
3
4
5
>>> for n in range(1, 6):
... print n ** 2
1
4
9
16
25
>>> [n ** 2 for n in range(1, 6)]
[1, 4, 9, 16, 25]
So that's a list comprehension.
If you break it down into 3 parts; separated by the words: 'for' and 'in' ..
eg.
[ 1 for 2 in 3 ]
Probably reading it backwards is easiest:
3 - This is the list of input into the whole operation
2 - This is the single item from the big list
1 - This is the operation to do on that item
part 1 and 2 are run multiple times, once for each item in the list that part 3 gives us. The output of part 1 being run over and over, is the output of the whole operation.
So in your example:
3 - Generates a list: [1, 2, 3, 4, 5] -- Range runs from the first param to one before the second param
2 - 'n' represents a single number in that list
1 - Generates a new list of n**2 (n to the power of 2)
So an equivalent code would be:
result = []
for n in range(1, 6):
result.append(n**2)
Finally breaking it all out:
input = [1, 2, 3, 4, 5]
output = []
v = input[0] # value is 1
o = v**2 # 1 to the power of two is 1
output.append(o)
v = input[1] # value is 2
o = v**2 # 2 to the power of two = (2*2) = 4
output.append(o)
v = input[2] # value is 3
o = v**2 # 3 to the power of two is = (3*3) = 9
output.append(o)
v = input[3] # value is 4
o = v**2 # 4 to the power of two is = (4*4) = 16
output.append(o)
v = input[4] # value is 5
o = v**2 # 5 to the power of two is = (5*5) = 25
output.append(o)

Categories