Finding number from list that respects conditions - python

I need to code a script that chooses a number from a user input (list) depending on two conditions:
Is a multiple of 3
Is the smallest of all numbers
Here is what I've done so far
if a % 3 == 0 and a < b:
print (a)
a = int(input())
r = list(map(int, input().split()))
result(a, r)
The problem is I need to create a loop that keeps verifying these conditions for the (x) number of inputs.

It looks like you want a to be values within r rather than its own input. Here's an example of iterating through r and checking which numbers are multiples of 3, and of finding the minimum of all the numbers (not necessarily only those which are multiples of 3):
r = list(map(int, input().split()))
for a in r:
if a % 3 == 0:
print(f"Multiple of 3: {a}")
print(f"Smallest of numbers: {min(r)}")
1 2 3 4 5 6 7 8 9 0
Multiple of 3: 3
Multiple of 3: 6
Multiple of 3: 9
Multiple of 3: 0
Smallest of numbers: 0

Doing this in one line – or through generators – can improve performance through optimizing memory allocation:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# The following is a generator
# Also: you need to decide if you want 0 to be included
all_threes = (x for x in my_list if x%3==0)
min_number = min(my_list)

Related

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

Google Kickstart Round E 2020 Longest Arithmetic Runtime Error

I tried solving this challenge mentioned below but I got a Run Time error. I used Python
Problem
An arithmetic array is an array that contains at least two integers and the differences between consecutive integers are equal. For example, [9, 10], [3, 3, 3], and [9, 7, 5, 3] are arithmetic arrays, while [1, 3, 3, 7], [2, 1, 2], and [1, 2, 4] are not arithmetic arrays.
Sarasvati has an array of N non-negative integers. The i-th integer of the array is Ai. She wants to choose a contiguous arithmetic subarray from her array that has the maximum length. Please help her to determine the length of the longest contiguous arithmetic subarray.
Input:
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integer N. The second line contains N integers. The i-th integer is Ai.
Output:
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the length of the longest contiguous arithmetic subarray.
Limits
Time limit: 20 seconds per test set.
Memory limit: 1GB.
1 ≤ T ≤ 100.
0 ≤ Ai ≤ 109.
Test Set 1
2 ≤ N ≤ 2000.
Test Set 2
2 ≤ N ≤ 2 × 105 for at most 10 test cases.
For the remaining cases, 2 ≤ N ≤ 2000.
Sample Input
4
7
10 7 4 6 8 10 11
4
9 7 5 3
9
5 5 4 5 5 5 4 5 6
10
5 4 3 2 1 2 3 4 5 6
Output
Case #1: 4
Case #2: 4
Case #3: 3
Case #4: 6
Here's my python3 solution which gives run time error
t = int(input())
for t_case in range(t):
n = int(input())
arr = list(map(int, input().split()))
x = []
for i in range(n - 1) :
x.append((arr[i] - arr[i + 1]))
ans, temp = 1, 1
j = len(x)
for i in range(1,j):
if x[i] == x[i - 1]:
temp = temp + 1
else:
ans = max(ans, temp)
temp = 1
ans = max(ans, temp)
print(f"Case #{t_case+1}: {ans+1}")
Could anyone please help me out.
As of now Kickstart is using Python 3.5 which does not support f-strings (they were added in py3.6). Try to replace them with str.format.
t=int(input())
for test in range(t):
n=int(input())
arr = list(map(int, input().split()))
x = []
for i in range(n - 1) :
x.append((arr[i] - arr[i + 1]))
ans, temp = 1, 1
j = len(x)
for i in range(1,j):
if x[i] == x[i - 1]:
temp = temp + 1
else:
ans = max(ans, temp)
temp = 1
ans = max(ans, temp)
print('Case #{0}: {1}'.format(test+1,ans+1))

Can't delete not last single object [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 6 years ago.
My code should recieve a list of numbers and then output on the screen the only numbers which repeat more then once. I don't know why but it don't work with the numbers in the middle of list. My code:
a = [int(i) for i in (input().split())]
a.sort()
for number in a:
if a.count(number)==1:
a.remove(number)
else:
a.remove(a.count(number)-a.count(number)+number)
for number in a:
print(number, end=' ')
I tried changing if on while on 4th string, but then the last number is left in the list.
It should work like:
Sample Input 1: 4 8 0 3 4 2 0 3 Sample Output 1: 0 3 4
Sample Input 2: 10 Sample Output 2:
Sample Input 3: 1 1 2 2 3 3 Sample Output 3: 1 2 3
Sample Input 4: 1 1 1 1 1 2 2 2 Sample Output 4: 1 2
You could approach this problem using set instead:
a = list(map(int, input().split()))
print(" ".join(map(str, set(i for i in a if a.count(i) > 1))))
Explanation:
Firstly, it looks like you should read up on the map function. Instead of a = [int(i) for i in (input().split())], you can just use list(map(int, input().split())), which is much more Pythonic.
Secondly, the important part of the second line is set(i for i in a if a.count(i) > 1), which just creates a new list containing only the duplicates from a (i.e. [1, 2, 3, 2, 3] becomes [2, 3, 2, 3] and then applies set to it, which converts [2, 3, 2, 3] into {2, 3} (which is a set object).
In case you're wondering what map(str, ...) is for, it's so that you can print each of the elements inside your new set (e.g. {2, 3}).
You can use built-in lib collections to count list items and filter it by a required condition.
import collections
ints = map(int, input().split())
count = collections.Counter(ints)
print filter(lambda x: count[x] > 1, count)

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