Calculate the product from a list of multiples - python

I have a Python assignment where it asks me to create a function that returns a list of numbers that are multiples. Then, write another function that takes the list of numbers and calculates the product of all the items in the list. For loop must be used in your function.
The output should be like:
Enter multiple of: 2
Enter an upper limit: 10
[2, 4, 6, 8, 10]
product is 3840
but I cannot get the second function to work, it prints 0.
#from functools import reduce # Valid in Python 2.6+, required in Python 3
#import operator
a = []
def func_list(multi,upper,a):
for i in range (upper):
if i % multi == 0:
a.append(i) #DOESNT INCLUDE THE UPPER LIMIT
multi = int(input("Enter multiple of: "))
upper = int(input("Enter an upper limit: "))
func_list(multi,upper,a)
print(a)
#b
#input = list of number (param)
#output = calculates the product of all the list (sum)
def prod(a):
prod1 = 1
for i in a:
prod1 *= i
return prod1
#return reduce(operator.mul, a, 1)
#func_list(multi,upper)
prod(a)
print (prod(a))
The output I get is:
Enter multiple of: 2
Enter an upper limit: 10
[0, 2, 4, 6, 8] I don't know how to inc. the limiter, but it's not my concern yet.
0 not right
I tried using reduce as suggested on here, but I don't know if I did something incorrect, because it didn't work.

Python's range() already has this functionality built in: range(start, stop, increment)
Simply:
def func_list(multi,upper,a):
a = list(range(multi, upper+1, a))
If you need to use a for loop:
def func_list(multi,upper,inc):
for i in range(multi, upper+1, inc):
a.append(i)
Your second product function does actually work. The reason why it is printing 0 is because of this line: for i in range (upper):. This results in 0 getting appended to your list, making the product 0.

import numpy as np
def multiples_list(numbers, upper):
'''
Create a function that returns a list of multiples
with a upper limit of 10.
'''
numbers_list = []
for number in numbers:
if number <= upper and number % 2 == 0:
numbers_list.append(number)
return numbers_list
def product_of_multiples(numbers):
new_numbers = []
for num in numbers:
new_numbers.append(num)
numbers_array = np.array(new_numbers)
product = np.product(numbers_array)
return product
#numbers_list = list(int(input('Please enter a series of numbers: ')))
numbers_list = [2, 4, 6, 8, 10]
print(multiples_list(numbers_list, 10))
print(product_of_multiples(numbers_list))
Here is the output:
[2, 4, 6, 8, 10]
3840
What I did here in your product function is create a new list from the list that you pass as the argument. We use a for loop to append to the new list. We can pass the new list to np.array() to create an array from the list after the for loop. We can use the np.product() function and pass the array of the list and return a fully formatted version of the product.

Related

How to find the unique sets of each element where difference is 1 in Python?

I have an array of integers. I want to find how all unique sets where the difference is 1 and separate them into unique sets.
example input: [3,4,5,8,9,11]
example output: [{3,4,5}, {8,9}, {11}]
What's the simplest way to do this with Python?
Catch the begin of the chain and add all the elements of the chain in a set.
Here is the super simple code for this idea:
def f(arr):
res = []
st = set(arr)
for num in st:
if num - 1 not in st: #begin of chain
temp = []
while num in st:
temp.append(num)
num += 1
res.append(temp)
return res
print(f([3,4,5,8,9,11]))
Output: [[3, 4, 5], [8, 9], [11]]
Time complexity: O(n)
Space complexity: O(n)
I guess this is the best complexity we can achieve. (Don't mind the variable names in the code 😁)
I'm assuming you input list contains no duplicates. If input is [3,4,5,8,9,11,8,9,10] do we want unique sets as [[3,4,5],[8,9,10,11],[8,9]]? If yes, then I leave it to you as an exercise. Hint: Use counter/dictionary instead of set above and it's easy.
Perhaps not the most efficient, but you can sort, then split on the difference. Here's a solution using numpy:
example_input = [3, 4, 5, 8, 9, 11]
output = np.split(np.sort(example_input),
np.where(np.diff(np.sort(example_input)) > 1)[0] + 1)
What this is doing is finding where the difference between elements of the sorted array is greater than one, then splitting the input on that. We add one to the element to split on the next set.
You can then map the arrays to sets if you prefer that.
sets = [set(x) for x in output]
# [{3, 4, 5}, {8, 9}, {11}]
You can start with the first number and keep incrementing it by 1 until the new value you get is not in the original list anymore.
Remove the values which were in the original list.
Repeat the same process for the remaining values.
This should get your started
import typing
def find_unique(elems: list[int]) -> set[int]:
... # fill in your code here
def find_all_unique(elems: list[int]) -> typing.Iterator[set[int]]:
while (elems):
yield find_unique(elems)
if __name__ == '__main__':
my_list = [3,4,5,8,9,11]
print list(find_all_unique(my_list))
You can sort the input list first, and initialize a set s with the first element.
Then go through the sorted list for the second to the last element, compare the number num with its previous number prev_num.
If num == prev_num (if the input list contains duplicates), then we just ignore it.
If num == prev_num + 1, then we add num to the same set s
Otherwise, we know that we need to create a new set. We add the current set to the output list and create a new set.
def find_unique_sets(input_list):
output_list = []
if not input_list:
return output_list
input_list.sort()
s = {input_list[0]}
prev_num = input_list[0]
for i in range(1, len(input_list)):
num = input_list[i]
if num == prev_num:
continue
elif num == prev_num + 1:
s.add(num)
else:
output_list.append(s)
s = {num}
prev_num = num
output_list.append(s)
return output_list
print(find_unique_sets([3,4,5,8,9,11]))

Print harmonic series for the given series in Python 3

I want to print harmonic series in python as follow but I don't understand how to do it, pls help and it would be nice if you could maybe explain how you did it. I have not tried any code and was not able to find it on the web
The problem
We want to iterate n (1, 2, 3, 4, 5, ...) and pass it in the formula nx/n!, for example user ill define x by this line of code x = int(input("What's the value of x? ")), so image user types number 5, so we need to get: 1*5/1!, 2*5/2!, 3*5/3!, 4*5/4!.
Here is another problem: Python's ! symbol means boolean invert, so !true is equal to false, not factorial.
factorial function in Python
So we need to define function factorial:
def factorial(number):
fact = 1
for n in range(1, number+1):
fact *= n # The same as fact = fact * n
return fact
# TEST OF THE FACTORIAL FUNCTION
# print(f'factorial(3) == 1*2*3 => { factorial(3) == 1*2*3 }')
Limit of the sequence
We actually need to get the nlim number from the user that tells the loop when to stop.
nlim = int(input("What's the limit of the sequence? "))
The sequence
So, we need to get Python evaluate this (if x is equal to 5 and n is increasing from 1 by step 1 to limit nlim): 1*5/factorial(1), 2*5/factorial(2), 3*5/factorial(3) and so on.
results = [] # in this list all the results will be stored
for n in range(1, nlim+1):
results.append((n*x) / factorial(n)) # here comes the formula!
Read sequence
for i, result in enumerate(results):
# enumerate([7, 8, 9]) will give us 2D list with indexes [[0, 7], [1, 8], [2, 9]]
# Then we will iterate this, so on each loop cycle we get [0, 7], then [1, 8] and so on
# if we do following: a, b = [1, 2] then variable a will be 1 and variable b will be 2
print(f'result[{ i }]: { result }')
All the code
def factorial(number):
fact = 1
for n in range(1, number+1):
fact *= n
return fact
x = int(input("What's the value of x? "))
nlim = int(input("What's the limit of the sequence? "))
results = []
for n in range(1, nlim+1):
results.append((n*x) / factorial(n))
for i, result in enumerate(results):
print(f'result[{ i }]: { result }')

Trying to find the first missing positive by using the in-loop variable

Given a list of integers, I want to find the first missing positive. My idea was to do it using the variable within the for loop to avoid clutter. Here is what I did:
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
sort_list = sorted(nums)
holder = 0
item = 1
for item in range(len(sort_list)):
if sort_list[item] != item:
holder = item
return holder
So here is what I did. First, I sorted the list in ascending order. Then I initialized 2 variables holder = 0 and item = 1. Because the given list is suppose to start at 1, I tried to start the for-loop at 1 as well. The reason is that if I was given a list like [7, 8, 9, 5, 5, 3], the first missing positive has to be one. Anyways, then I tried to loop through every item in the list to see if it compares item and if not, I assigned holder = item and returned holder. However, it ended up returning 0 when my input was [1, 2, 0] when it should've returned 3.
Add all the numbers to a set then check successively 1, 2, 3, etc. to see if they are in the set:
def first_missing_positive(number_list):
number_set = set(number_list)
for n in range(1, len(number_list) + 1):
if n not in number_set:
return n
return None
print(first_missing_positive([7, 6, 5, 3, 2, 1, 8]))
Prints:
4
Another approach:
All the numbers 1, 2, ... len(input list) are added to a set. Then the numbers in the passed list are removed from this set and the smallest number in the set remaining is returned. This could be an improvement over the first solution, especially when the first positive number missing is towards the end (high positive value) since looping in Python might be slower than the set calculations done in its C-language implementation.
def first_missing_positive(number_list):
return min(set(range(1, len(number_list) + 1)) - set(number_list))
I tried it in a little different way:
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
max = len(nums)
for i in range(1,max+2):
if i not in nums:
return i
you can just check if the current number from a iteration is in the list, it doesn't have to be sorted.
range is from 1 to max+2, because if you got a list like [1,2,3,4] it has to count from 1 to 5, to find the 5 as missing number.
Your problem is that you give holder a value (0) in the beginning, so if you don't find any missing value, it will return 0. That'd solve your problem:
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
sort_list = sorted(nums)
holder = None
for item in range(len(sort_list)):
if sort_list[item] != item:
holder = item
return holder if holder is not None else item+1
This is a little simplified, though if inputs are large lists, you should ignore this answer
from operator import eq
def firstMissingPositive(nums):
l = list(map(eq, nums, range(1, len(nums)+1)))
return l.index(False) + 1 if False in l else -1
You can try set:
def missingPos(x):
y = set(range(1,max(x)+2))
return min(y-set(x))
print(missingPos([7, 8, 9, 5, 5, 3]))
print(missingPos([1,2,0]))
Output:
1
3
A better solution would be to use iterators, that will be memory efficient for calculation with large lists:
def missingPos(x):
generator = (i for i in range(1,max(x)+2) if i not in x)
print(next(generator))
missingPos([1,2,0])
missingPos([7, 8, 9, 5, 5, 3])
Output:
3
1

dict does not contain the expected number of items

I'm writing a program to iterate through a long number, converting it into a string, and then using an index list to pick out 10 individual consecutive numbers from the long number, then multiplying those ten numbers together and adding the numbers and the result to a dictionary. Then I am increasing the index list values by 1, and repeating the process until I have run through the whole number.
Then I am trying to find the largest value in the dictionary, and have the program tell me that value.
The problem I am having is that I have an error checking mechanism in the program, which tells me how many key/value pairs I have in the dictionary. It should be 990, but instead I have 53.
If anyone can identify what the problem is, I will be eternally grateful.
Code to follow:
from functools import reduce
#define the number to test
testno = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
#declare initial variables
index=[]
products = {}
count = 0
#define functions
def product(x):
return reduce((lambda a,b: a*b),x)
def increm(y):
return [x+1 for x in y]
#def runproduct(x):
# return product
def testnos(x):
return [int(str(x)[y]) for y in index]
#define the initial index
for x in range(10):
index = index+[x]
runtime = len(str(testno))-10
#start the while loop
while count < runtime:
products[str(testnos(testno))] = product(testnos(testno))
index = increm(index)
count+=1
print("[+] Number of results: "+str(len(str(products.values))))
print("[+] The numbers with the largest product are: "+str(max(products.keys(),key=(lambda k:products[k]))))
You have a problem in your first print statement. You are currently converting your products into a string, which returns to you something like this
{'[0, 8, 1, 3, 5, 3, 3, 6, 2, 7]': 0, ..., '[7, 8, 4, 6, 8, 6, 2, 2, 4, 8]': 8257536}
Applying the len built-in over it will return the result 53. What you really want here is calling len directly over you products variable.
>>> print("[+] Number of results: {}".format(len(products)))
[+] Number of results: 990
Consider using the format function when building your string. You can use PyFormat website as reference.

Summing consecutive third numbers in python

How would I solve this?
The program should contain the definition for the function sumTri(cutOff). The function adds Tri numbers into the sum.
Tri numbers are every third number: 1, 4, 7, 10, .... The function adds consecutive Tri numbers 1, 4, 7, ... into the sum so long as the Tri number is less than the cutOff. The function returns the sum of these numbers.
It's simple:
def sumTri(cutOff):
return sum(range(1,cutOff,3))
Or, when you need it lowlevel:
def sumTri(cutOff):
sum = 0
tri = 1
while tri < cutOff:
sum += tri
tri += 3
return sum
I'll try to explain both soultions a little bit.
In the first case you use two "highlevel" functions of Python, that make all work for you: sum and range. The range(a,b,c) function generates a list of numbers from a to b with the step c between. E.g.:
In [1]: range(1,10,3)
Out[1]: [1, 4, 7]
In [2]: range(1,22,3)
Out[2]: [1, 4, 7, 10, 13, 16, 19]
You must note here that range generates numbers until the number in the list is less than b, not less-or-equal. Exactly what you need for your task.
And sum obviously calculates and returns the sum of the numbers in the list that it has as its argument:
In [3]: sum([1])
Out[3]: 1
In [4]: sum([1,2])
Out[4]: 3
In [5]: sum([1,2,3])
Out[5]: 6
Now you need just to combine these two functions:
return sum(range(1,cutOff,3))
The second solution is more "lowlevel" and "algorithmic". You use no special python functions here and do everything yourself.
You use two variable to calculate the sum:
sum -- the variable where you store your sum
tri -- the variable with the current value of number that you add step by step
When you write something like:
a = a + 5
that means: "Now I want a to be equal to what a was before plus 5" or "increase a by 5". You can write it shorter:
a += 5
These two forms are equivalent.
But you need not simple add something. You need to do it for many times until something is happened. In python you do it using while:
while someting-is-true:
do-something
Every time while checks the something-is-true condition, and when it's True, it makes commands that are under while (indented) i.e. do-something.
Now you know all necessary to write the solution:
def sumTri(cutOff):
sum = 0 # we start the sum from 0
tri = 1 # and the first number to add is 1
while tri < cutOff: # next number to add < cutOff?
sum += tri # than add it to sum
tri += 3 # and increase the number by 3
return sum # now you have the result, return it
That was the function that makes the job. Now you can use the function.
How you do this?
def sumTri(cutOff):
...
# anywhere in you program:
# presuming a is the cutOff
print sumTri(a)
when you want to run the function and use its result you just write function_name(args).
This sequence is related to triangular numbers
Here is one that is O(1)
def sumTri(cutoff):
n = (cutoff+1)//3
return (3*n-1)*n//2

Categories

Resources