When I run this through the visualizer it only modifies the first element in the 2d list. How do I make it so that the it runs throught the entire list.
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss)):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
xss = [[1,2,3],[],[4,5]]
make_even(xss)
print(xss)
So first off you need to correct your indentation in your code:
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss)):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
However, because both your loops use len(xss), they expect an array of 3 lists each with 3 elements. If you'd want each list to have variable numbers of elements you should do this instead:
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss[i])):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
Which returns: [[4, 2, 6], [], [4, 8]]
However, there are two obvious changes I would make:
Your if statement should be if xss[i][j] % 2 == 1, since it's more readable.
You can make a number even by adding 1. (If 3 is required for your specs that's fine).
Also, this is totally doable in a single line (any line would work):
# List comprehensions only
xss = [[(x + 3 if x % 2 == 1 else x) for x in row] for row in xss]
# map and lamdbas (returns lists)
xss = list(map(lambda row: list(map((lambda x: x + 3 if x % 2 == 1 else x),row)), xss))
# map and lamdbas (returns iterables)
xss = map(lambda row: map((lambda x: x + 3 if x % 2 == 1 else x),row), xss)
Although personally, I think the list comprehensions is the easiest to read.
Related
I am trying to create a program that takes only even numbers from a range of numbers from 1 to 100 and add all of the even numbers. I am a beginner and I have been trying to get this working since yesterday, and nothing I have tried works. This is my first post, so sorry if the format is wrong but here is my code.
for i in range(1, 100):
if i % 2 == 0:
x = [I]
y = sum(x)
print(y)
The problems with your code has multiple issues that - 1)if you want to get all even numbers from 1 to 100, your range should be (1, 101); 2) the way you build list is wrong (syntax); 3) the sum expect an iterable (list).
There are a few ways to accomplish this sum from 1 to 100 (inclusive), here it will start with yours, and try to show List Comprenshion and Generator Expression way:
lst = [] # to store the build-up list
tot = 0 # to store the answer
for i in range(1, 101):
if i % 2 == 0: # it's a even number
lst.append(i) # store it into lst
tot = sum(lst) # 2550
Generator expression:
all_evens_sum = sum(x for x in range(1, 101) if x % 2 == 0) # 2550
Or List Comprehension:
lst = [x for x in range(1, 101) if x % 2 == 0] # even nums
total = sum(lst) # 2550
I am a beginner too but it looks I can help you some.
for i in range(1, 100):
if(i % 2 == 0):
sum += i
print(sum) // do what you want
So I have a question:
Given an even number (greater than 2), return two prime numbers whose sum will be equal to given number. There are several combinations possible. Print only first such pair
This is for additional reference:
*Input: The first line contains T, the number of test cases. The following T lines consist of a number each, for which we'll find two prime numbers.
Note: The number would always be an even number.
Output: For every test case print two prime numbers space separated, such that the smaller number appears first. Answer for each test case must be in a new line.
Constraints: 1 ≤ T ≤ 70
2 < N ≤ 10000
Example:
Input:
5, 74, 1024, 66, 8, 9990
Output: 3 71, 3 1021, 5 61, 3 5, 17 9973
Here is what I tried:
import math
def prime(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
T = int(input("No of inputs: ")) #T is the no of test cases
input_num = []
for i in range(0,T):
input_num.append(input())
lst2= []
if T in range(1,71):
for i in input_num:
if (i in range(3,1000)) and (i % 2 == 0):
for j in range(0,i):
if prime(j) == True:
lst2.append(j)
for x in lst2:
for y in lst2:
if x + y == j:
print(x,end = ' ')
print(y)
This is only taking inputs but not returning outputs.
Also my code is currently intended for all the combinations but what I want is only the first pair and I am not able to do that
I found a more elegant solution to this problem here. Java, C, C++ etc versions of solution is also present there. I am going to give the python3 solution.
# Python 3 program to find a prime number
# pair whose sum is equal to given number
# Python 3 program to print super primes
# less than or equal to n.
# Generate all prime numbers less than n.
def SieveOfEratosthenes(n, isPrime):
# Initialize all entries of boolean
# array as True. A value in isPrime[i]
# will finally be False if i is Not a
# prime, else True bool isPrime[n+1]
isPrime[0] = isPrime[1] = False
for i in range(2, n+1):
isPrime[i] = True
p = 2
while(p*p <= n):
# If isPrime[p] is not changed,
# then it is a prime
if (isPrime[p] == True):
# Update all multiples of p
i = p*p
while(i <= n):
isPrime[i] = False
i += p
p += 1
# Prints a prime pair with given sum
def findPrimePair(n):
# Generating primes using Sieve
isPrime = [0] * (n+1)
SieveOfEratosthenes(n, isPrime)
# Traversing all numbers to find
# first pair
for i in range(0, n):
if (isPrime[i] and isPrime[n - i]):
print(i,(n - i))
return
# Driven program
n = 74
findPrimePair(n)
I have this list
a = [1,2,3,4,5,6,7,8,9]
I want to find out that how many co-prime pair elements of the list add up to sum=9
Ex, (1+8) = 9 , (2+7) = 9 , (3+6)=9 , (4+5)=9, (5+4)=9 , (6+3)=9, (7+2)=9 , (8+1)=9
Note that i don't want (3+6) as they are prime numbers. And i also don't want (7+2)=9 as it has already occurred (means 2,7 has been already taken in account)
I tried this But it takes repeated values too.
a = [1,2,3,4,5,6,7,8,9]
count=0
for m in a:
for n in a:
total=m+n
if(total==9):
s=str(m) + '+'+ str(n) + "="
print(s , m+n)
count=count+1
print("Count =" ,count)
The result should have count=3
Your mistake is in the way of doing the loops, so you repeat values.
Try this:
#from math import gcd as bltin_gcd
a = [1,2,3,4,5,6,7,8,9]
count = 0
def __gcd(a, b):
# Everything divides 0
if (a == 0 or b == 0): return 0
# base case
if (a == b): return a
# a is greater
if (a > b):
return __gcd(a - b, b)
return __gcd(a, b - a)
# Only python 3
# def coprime(a, b):
# return bltin_gcd(a, b) == 1
for i in range(0,9):
for j in range(i+1,9):
if __gcd(a[i], a[j]) == 1 and a[i] + a[j] == 9:
count += 1
print str(a[i]) + ' ' + str(a[j])
print 'Count = ' + str(count)
In number theory, two integers a and b are said to be relatively prime, mutually prime, or coprime if the only positive integer that divides both of them is 1. Consequently, any prime number that divides one does not divide the other. This is equivalent to their greatest common divisor being 1.
for m in a:
for n in a:
You are not selecting pairs by using this loops, ie. you are picking the first element in both the outer and inner loop during your first iteration.
if(total==9):
You are not checking the condition if the selected pair of numbers are coprime. You are only verifying the sum.
A pythonic solution may be obtained with a one-liner:
from math import gcd
a = [1,2,3,4,5,6,7,8,9]
pairs = [(m,n) for m in a for n in a if n > m and m+n == 9 and gcd(m,n) == 1]
Result :
pairs --> [(1, 8), (2, 7), (4, 5)]
If you are sure to never, never need the pairs but only the number of pairs (as written in the OP), the most efficient solution may be:
count = len([1 for m in a for n in a if n > m and m+n == 9 and gcd(m,n) == 1])
EDIT : I inversed the three conditions in the if statement for improved benefit from lazy boolean evaluation
You can solve this if you have something that calculates your prime factorization in python:
from functools import lru_cache
# cached function results for pime factorization of identical nr
#lru_cache(maxsize=100)
def factors(nr):
# adapted from https://stackoverflow.com/a/43129243/7505395
i = 2
factors = []
while i <= nr:
if (nr % i) == 0:
factors.append(i)
nr = nr / i
else:
i = i + 1
return factors
start_at = 1
end_at = 9
total = 9
r = range(start_at, end_at+1)
# create the tuples we look for, smaller number first - set so no duplicates
tupls = set( (a,b) if a<b else (b,a) for a in r for b in r if a+b == total)
for n in tupls:
a,b = n
f_a = set(factors(a))
f_b = set(factors(b))
# if either set contains the same value, the f_a & f_b will be truthy
# so not coprime - hence skip it
if f_a & f_b:
continue
print(n)
Output:
(2, 7)
(1, 8)
(4, 5)
Basically I'm trying to find 2 elements in a list that adds together to the correct given sum.
Example:
aList = [1,5,6,3,8,9,4] sum = 10
now with the above conditions I will expect 2 results:
[1, 9] and [6, 4]
The answer should be [6, 4] because they are closest to each other. 1 to 9 need to take 4 steps while [6, 4] only need to take 3. Shortest index differences.
My code is below and it doesn't work for the above example:
def sum_pairs(ints, s):
for i in ints:
for b in ints[i:]:
if i + b == s:
return [i,b]
else:
return None
So how would you check between closest index with out writing another loop?
if you want to find numbers with least ammount of steps, loop over the distance and try all tuples with the given distance in between - you should not try pairs with 4 spaces in between when you did not exhaust all tuples with distance 3...
def sum_pairs(ints, s):
for distance in range(1, len(ints)):
for idx in range(len(ints) - distance):
if ints[idx] + ints[idx + distance] == s:
return [ints[idx], ints[idx + distance]]
return None
You weren't really testing at all for the differences between the pairs that you have, simply returning the list of all matches found for the sum you entered.
nums = [1,5,6,3,8,9,4]
def sum_pairs(ints, s):
matches = []
for i in range(len(ints)):
x = ints[i]
for y in ints[i + 1:]:
if x + y == s: matches.append([x, y])
differences = {}
for x, y in matches:
differences[abs(x - y)] = [x, y]
return differences[min(differences.keys())]
>>> sum_pairs(nums, 10)
# [6, 4]
You need to store all possible solutions to the list before returning anything.
a = []
def sum_pairs(ints, s):
for i in ints:
for b in ints[i:]:
if i + b == s:
a.append([i,b])
return a
aList = [1,5,6,3,8,9,4]
print sum_pairs(aList,10)
Output: [[1, 9], [6, 4]]
A "simple" (not most efficient - see another posted answer : adding up a loop to procede by looking at spaces between characters is better) solution :
def sum_pairs(ints, s):
answer = None
distance = 10
for i in ints:
for b in ints[i:]:
if i + b == s and abs(i - b) < distance:
answer = (i, b)
distance = abs(i - b)
return answer
I am new to python and was going through this following code which takes in an integer and outputs the positions of 1's in its binary value.
def L(encoded_set):
print('{', end = '')
i = 0
if encoded_set:
while encoded_set % 2 == 0:
encoded_set //= 2
i += 1
print(i, end = '')
encoded_set //= 2
i += 1
while encoded_set:
if encoded_set % 2:
print(',', i,end = '')
encoded_set //= 2
i += 1
print('}')
For ex: Binary of 54 is 110110 so the code will output: {1, 2, 4, 5}
Now, i need to direct this output to a set so that i can work with the individual set elements. Something like X[0] = 1, X[1] = 2, X[2] = 4
and X[3] = 5. I'm not sure how to do this.
I would go for bit-shifting of value
ones = []
pos = 0
while val:
if val & 1:
ones.append(pos)
pos += 1
val >>= 1
Your solution numbers from first non-0 most-significant bit - which may be meaningless unless the position of MSB is known (yes, you know it, but you'll have to add extra code for that). My solution counts position relative to LSB.
As a more elegant way you can convert your number to binary with bin function and use enumerate and a list comprehension to return the proper positionsm,and return the list of indices:
>>> def pos(num) :
... return [i for i,j in enumerate(bin(num)[2:],1) if j=='1']
...
>>> pos(54)
[1, 2, 4, 5]
NOTE that the result of bin has a 0b on leading of the number so you need to loop over the slice of your binary number (bin(num)[2:]).