PYTHON: sum of two numbers - python-2.7

I'm trying to find, for a list of numbers from 1 to 50, what numbers within that range are the sums of two other specific numbers from another list. The other list is 1, 2, 4, 6, 18, 26.
I'm basically trying to run a "for x in range(1,50):" type program that then lists all the numbers from 1 to 50 and next to them says "TRUE" if they are the sum of any two of the numbers in that list (e.g. 1 + 1, 1 + 4, 1 + 26, 4 + 18, 18 + 26 etc etc).
Any ideas??
Thank you!!
Matt

Iterate over all possible pairs of numbers:
sums = []
for n1 in numbers:
for n2 in numbers:
# Add them together and store the result in `sums`
And then check to see if every number from range(50) is in your list of sums:
for n in range(50):
if n in sums:
# `n` is the sum of two numbers from your list

def solveMeFirst(a,b):
# Hint: Type return a+b below
return a+b
num1 = int(input())
num2 = int(input())
res = solveMeFirst(num1,num2)
print(res)

Related

How can I write this algorithm that returns the count between x and y in a list?

I am given this algorithmic problem, and need to find a way to return the count in a list S and another list L that is between some variable x and some variable y, inclusive, that runs in O(1) time:
I've issued a challenge against Jack. He will submit a list of his favorite years (from 0 to 2020). If Jack really likes a year,
he may list it multiple times. Since Jack comes up with this list on the fly, it is in no
particular order. Specifically, the list is not sorted, nor do years that appear in the list
multiple times appear next to each other in the list.
I will also submit such a list of years.
I then will ask Jack to pick a random year between 0 and 2020. Suppose Jack picks the year x.
At the same time, I will also then pick a random year between 0 and 2020. Suppose I
pick the year y. Without loss of generality, suppose that x ≤ y.
Once x and y are picked, Jack and I get a very short amount of time (perhaps 5
seconds) to decide if we want to re-do the process of selecting x and y.
If no one asks for a re-do, then we count the number of entries in Jack's list that are
between x and y inclusively and the number of entries in my list that are between x and
y inclusively.
More technically, here is the situation. You are given lists S and L of m and n integers,
respectively, in the range [0, k], representing the collections of years selected by Jack and
I. You may preprocess S and L in O(m+n+k) time. You must then give an algorithm
that runs in O(1) time – so that I can decide if I need to ask for a re-do – that solves the
following problem:
Input: Two integers, x as a member of [0,k] and y as a member of [0,k]
Output: the number of entries in S in the range [x, y], and the number of entries in L in [x, y].
For example, suppose S = {3, 1, 9, 2, 2, 3, 4}. Given x = 2 and y = 3, the returned count
would be 4.
I would prefer pseudocode; it helps me understand the problem a bit easier.
Implementing the approach of user3386109 taking care of edge case of x = 0.
user3386109 : Make a histogram, and then compute the accumulated sum for each entry in the histogram. Suppose S={3,1,9,2,2,3,4} and k is 9. The histogram is H={0,1,2,2,1,0,0,0,0,1}. After accumulating, H={0,1,3,5,6,6,6,6,6,7}. Given x=2 and y=3, the count is H[y] - H[x-1] = H[3] - H[1] = 5 - 1 = 4. Of course, x=0 is a corner case that has to be handled.
# INPUT
S = [3, 1, 9, 2, 2, 3, 4]
L = [2, 9, 4, 6, 8, 5, 3]
k = 9
x = 2
y = 3
# Histogram for S
S_hist = [0]*(k+1)
for element in S:
S_hist[element] = S_hist[element] + 1
# Storing prefix sum in S_hist
sum = S_hist[0]
for index in range(1,k+1):
sum = sum + S_hist[index]
S_hist[index] = sum
# Similar approach for L
# Histogram for L
L_hist = [0] * (k+1)
for element in L:
L_hist[element] = L_hist[element] + 1
# Stroing prefix sum in L_hist
sum = L_hist[0]
for index in range(1,k+1):
sum = sum + L_hist[index]
L_hist[index] = sum
# Finding number of elements between x and y (inclusive) in S
print("number of elements between x and y (inclusive) in S:")
if(x == 0):
print(S_hist[y])
else:
print(S_hist[y] - S_hist[x-1])
# Finding number of elements between x and y (inclusive) in S
print("number of elements between x and y (inclusive) in L:")
if(x == 0):
print(L_hist[y])
else:
print(L_hist[y] - L_hist[x-1])

Python replace every 3rd value with previous 2 items sum when not equal

A given list is n=[3,1,5,9,6,14] , replace 5 with 3+1 and 14 with 9+6. The output will look like [3,1,4,9,6,15]
My approach was using a range and assign value
i+ [i+1]==[i+2]
I tried 2 ways but in both cases I am getting out of bound exception
#Approach 1
for idx,item in enumerate(n):
if (idx + (idx+1))!=(idx+2):
n[idx+2]=(idx + (idx+1))
#Approach2
for i in range(len(n)):
if n[i]+n[i+1]!=n[i+2]:
n[i + 2]==n[i]+n[i+1]
print(n)
Even doing a len(n)-1 does not solve the problem. Some directions will be helpful. Thank You.
You could use the mod (%) operator to check for every third item:
items = [3, 1, 5, 9, 6, 14]
for i, item in enumerate(items):
if ((i+1) % 3 == 0):
items[i] = items[i-1] + items[i-2]
print(items)
Or to be more efficient, use range as mentioned in the comments:
for i in range(2, len(items), 3):
items[i] = items[i-1] + items[i-2]
print(items)

Increment list index in a while loop

I'm trying to print the first 12 numbers in the Fibonacci. My idea is to increment the two list index numbers.
list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers
listint = list[0] #sets the list variable I want to incremented
list2int = list[1] #set the other list variable to be incremented
while len(list) < 13: #sets my loop to stop when it has 12 numbers in it
x = listint + list2int #calculates number at index 2
list.append(x) #appends new number to list
listint += 1 #here is where it is supposed to be incrementing the index
list2int +=1
print list
My output is:
[0, 1, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
I want:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
Please note I am a beginner, and I'm trying to do this without using an built in functions. (I'm sure there is some sort of fibonacci sequence generator).
Thanks in advance for your help!
The problem is in the two last lines of the while loop. You are adding 1 each time instead of using the last two elements of the list that are the previous fibonacci numbers:
list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers
listint = list[0] #sets the list variable I want to incremented
list2int = list[1] #set the other list variable to be incremented
while len(list) < 13: #sets my loop to stop when it has 12 numbers in it
x = listint + list2int #calculates number at index 2
list.append(x) #appends new number to list
listint = list[-2] #here is where it is supposed to be incrementing the index
list2int = list[-1]
print list
list = [0,1]
while len(list) < 12:
list.append(list[len(list)-1]+list[len(list)-2])
print list
Not very performant, but quick and dirty.
use < 12 because in 11th loop you'll add the 12th entry to the list.
With list[x] you access the x number of entry starting with 0 for the first entry.
edit:
output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
change the first line of the while loop:
list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers
listint = list[0] #sets the list variable I want to incremented
list2int = list[1] #set the other list variable to be incremented
while len(list) < 12: #sets my loop to stop when it has 12 numbers in it
x = list[listint] + list[list2int] #calculates number at index 2
list.append(x) #appends new number to list
listint += 1 #here is where it is supposed to be incrementing the index
list2int +=1
print list
Also to get the 1st 12 numbers you can set your while loop condition to < 12 because Python list indices start from 0.

List all combinations of 'select 10 different numbers from 1-100'

It is known that there exists C(100,10) possibilities of selecting 10 different numbers from 1 to 100. each possibility is a combination like [1, 2,..., 10] or [2,3,...,11], or [11, 22, 33, .., 99, 100], as long as the 10 numbers are different.
How to list all the combinations by programming??
I don't want to write 10 Loops, python or c preferred
Using python and itertools.combinations.
Warning - Printing will take a long time
for i in itertools.combinations(xrange(1,101),10):
print i
My friend, Yujie Liu came up this idea. Using pure iteration.
# select n diff numbers from min - max
def traceArr(arr, min, max, n):
if n > 0:
for i in range(min, max-n+2):
arr1 = arr[:]
arr1.append(i)
traceArr(arr1, i+1, max, n-1)
elif n == 0:
print arr
# Demo, select 5 diff numbers from 1-10
traceArr([], 1, 10, 5);

Ranking and unranking of permutations with duplicates

I'm reading about permutations and I'm interested in ranking/unranking methods.
From the abstract of a paper:
A ranking function for the permutations on n symbols assigns a unique
integer in the range [0, n! - 1] to each of the n! permutations. The corresponding
unranking function is the inverse: given an integer between 0 and n! - 1, the
value of the function is the permutation having this rank.
I made a ranking and an unranking function in C++ using next_permutation. But this isn't practical for n>8. I'm looking for a faster method and factoradics seem to be quite popular.
But I'm not sure if this also works with duplicates. So what would be a good way to rank/unrank permutations with duplicates?
I will cover one half of your question in this answer - 'unranking'. The goal is to find the lexicographically 'K'th permutation of an ordered string [abcd...] efficiently.
We need to understand Factorial Number System (factoradics) for this. A factorial number system uses factorial values instead of powers of numbers (binary system uses powers of 2, decimal uses powers of 10) to denote place-values (or base).
The place values (base) are –
5!= 120 4!= 24 3!=6 2!= 2 1!=1 0!=1 etc..
The digit in the zeroth place is always 0. The digit in the first place (with base = 1!) can be 0 or 1. The digit in the second place (with base 2!) can be 0,1 or 2 and so on. Generally speaking, the digit at nth place can take any value between 0-n.
First few numbers represented as factoradics-
0 -> 0 = 0*0!
1 -> 10 = 1*1! + 0*0!
2 -> 100 = 1*2! + 0*1! + 0*0!
3 -> 110 = 1*2! + 1*1! + 0*0!
4 -> 200 = 2*2! + 0*1! + 0*0!
5 -> 210 = 2*2! + 1*1! + 0*0!
6 -> 1000 = 1*3! + 0*2! + 0*1! + 0*0!
7 -> 1010 = 1*3! + 0*2! + 1*1! + 0*0!
8 -> 1100 = 1*3! + 1*2! + 0*1! + 0*0!
9 -> 1110
10-> 1200
There is a direct relationship between n-th lexicographical permutation of a string and its factoradic representation.
For example, here are the permutations of the string “abcd”.
0 abcd 6 bacd 12 cabd 18 dabc
1 abdc 7 badc 13 cadb 19 dacb
2 acbd 8 bcad 14 cbad 20 dbac
3 acdb 9 bcda 15 cbda 21 dbca
4 adbc 10 bdac 16 cdab 22 dcab
5 adcb 11 bdca 17 cdba 23 dcba
We can see a pattern here, if observed carefully. The first letter changes after every 6-th (3!) permutation. The second letter changes after 2(2!) permutation. The third letter changed after every (1!) permutation and the fourth letter changes after every (0!) permutation. We can use this relation to directly find the n-th permutation.
Once we represent n in factoradic representation, we consider each digit in it and add a character from the given string to the output. If we need to find the 14-th permutation of ‘abcd’. 14 in factoradics -> 2100.
Start with the first digit ->2, String is ‘abcd’. Assuming the index starts at 0, take the element at position 2, from the string and add it to the Output.
Output String
c abd
2 012
The next digit -> 1.String is now ‘abd’. Again, pluck the character at position 1 and add it to the Output.
Output String
cb ad
21 01
Next digit -> 0. String is ‘ad’. Add the character at position 1 to the Output.
Output String
cba d
210 0
Next digit -> 0. String is ‘d’. Add the character at position 0 to the Output.
Output String
cbad ''
2100
To convert a given number to Factorial Number System,successively divide the number by 1,2,3,4,5 and so on until the quotient becomes zero. The reminders at each step forms the factoradic representation.
For eg, to convert 349 to factoradic,
Quotient Reminder Factorial Representation
349/1 349 0 0
349/2 174 1 10
174/3 58 0 010
58/4 14 2 2010
14/5 2 4 42010
2/6 0 2 242010
Factoradic representation of 349 is 242010.
One way is to rank and unrank the choice of indices by a particular group of equal numbers, e.g.,
def choose(n, k):
c = 1
for f in xrange(1, k + 1):
c = (c * (n - f + 1)) // f
return c
def rank_choice(S):
k = len(S)
r = 0
j = k - 1
for n in S:
for i in xrange(j, n):
r += choose(i, j)
j -= 1
return r
def unrank_choice(k, r):
S = []
for j in xrange(k - 1, -1, -1):
n = j
while r >= choose(n, j):
r -= choose(n, j)
n += 1
S.append(n)
return S
def rank_perm(P):
P = list(P)
r = 0
for n in xrange(max(P), -1, -1):
S = []
for i, p in enumerate(P):
if p == n:
S.append(i)
S.reverse()
for i in S:
del P[i]
r *= choose(len(P) + len(S), len(S))
r += rank_choice(S)
return r
def unrank_perm(M, r):
P = []
for n, m in enumerate(M):
S = unrank_choice(m, r % choose(len(P) + m, m))
r //= choose(len(P) + m, m)
S.reverse()
for i in S:
P.insert(i, n)
return tuple(P)
if __name__ == '__main__':
for i in xrange(60):
print rank_perm(unrank_perm([2, 3, 1], i))
For large n-s you need arbitrary precision library like GMP.
this is my previous post for an unranking function written in python, I think it's readable, almost like a pseudocode, there is also some explanation in the comments: Given a list of elements in lexicographical order (i.e. ['a', 'b', 'c', 'd']), find the nth permutation - Average time to solve?
based on this you should be able to figure out the ranking function, it's basically the same logic ;)
Java, from https://github.com/timtiemens/permute/blob/master/src/main/java/permute/PermuteUtil.java (my public domain code, minus the error checking):
public class PermuteUtil {
public <T> List<T> nthPermutation(List<T> original, final BigInteger permutationNumber) {
final int size = original.size();
// the return list:
List<T> ret = new ArrayList<>();
// local mutable copy of the original list:
List<T> numbers = new ArrayList<>(original);
// Our input permutationNumber is [1,N!], but array indexes are [0,N!-1], so subtract one:
BigInteger permNum = permutationNumber.subtract(BigInteger.ONE);
for (int i = 1; i <= size; i++) {
BigInteger factorialNminusI = factorial(size - i);
// casting to integer is ok here, because even though permNum _could_ be big,
// the factorialNminusI is _always_ big
int j = permNum.divide(factorialNminusI).intValue();
permNum = permNum.mod(factorialNminusI);
// remove item at index j, and put it in the return list at the end
T item = numbers.remove(j);
ret.add(item);
}
return ret;
}
}