Python: Average based on Input of Values and Frequencies - python

I'm trying to write a python function number_pairs which consumes a natural positive number n, and reads in n pairs of natural positive numbers from the user. Each pair represents a value and its frequency. For each pair, the function must prompt the user to input two positive integers the value and its frequency, while indicating the index of the expected pair. The process repeats until all n pairs have been entered. At the end, the function should print the average (of Float type, with the exact string message as in the example) of the n pairs of numbers, and returns the average as well. You may assume that the user only inputs valid data.
I was thinking that maybe writing a helper function that does accumulative recursion but I missed a lot of lectures and I have no idea how to do it. This is what I have so far:
def averge_h(counter):
...
def number_pairs(n):
prompt1 = "Enter value for pair number "
prompt2 = "Enter its frequency:\n"
pn = "{0}: ".format(n)
res="Their average is: "
v = int(input(prompt1+pn))
f = int(input("Enter its frequency: "))
if n = 1:
average = (v*f)/f
else:
v = v+1
print res + str(average)
return average

You can try something like this :
def read_and_avg(sum_,n,left,i): ## left is the number of times the input is to be taken
if left == 0:
print (sum_/float(n))
return (sum_/float(n))
else:
i = i + 1
print "Enter the values for pair number "+str(i)
a = int(input())
b = int(input())
sum_ = sum_ + (a*b) ## Increment the sum
n = n + b ## Increment the total count
print sum_,n,left
return read_and_avg(sum_,n,left-1,i) ## Decrease left by 1,
def func(n):
read_and_avg(0,0,n,0)

Since you said it can only have one argument "n" take a look at this:
def number_pairs(n):
if n == 0:
return 0
else:
average = number_pairs(n-1)
print str(n) + ("st" if n == 1 else ("nd" if n == 2 else ("d" if n == 3 else "th"))) + " pair"
val = input("value: ")
frq = input("frequency: ")
print "" # added for new line
return average + (val * frq)
n = input("Enter the number of pairs: ")
print "" # added for new line
print "The average is: " + str(number_pairs(n) / n)
Output:
Enter the number of pairs: 5
1st pair
value: 1
frequency: 2
2nd pair
value: 2
frequency: 2
3d pair
value: 3
frequency: 2
4th pair
value: 4
frequency: 2
5th pair
value: 5
frequency: 2
The average is: 6

Related

Trying to calculate the arithmetic median

I was just trying to calculate the arithmetic median of a list. Odd list length works but my program has problems with even list length.
here's an example:
The example for the even numbers
Here is what I tried:
#the sorted list
number = int(input('How many numbers do you want to put in? '))
print("")
values = []
for i in range(number):
values.append(int(input('Please enter a value: ')))
print("")
sort = sorted(values)
print("Sorted list:", sort)
#the function
firstMid = int(len(sort)) / 2
secoundMid = (int(len(sort)) / 2) + 1
if isOdd(len(values)) == True:
print("Zentralwert:", values[int(len(sort)/2)]) #odd numbers
else:
print("Zentralwert:", (firstMid + secoundMid) / 2)
It seems you are trying to find median.
For odd numbers, it's the middle number.
[1,2,3,4,5,6,7,8,9] -> Median is 5 at index 4 means index = len(arr) // 2 # // is integer division in python and returns floor value. So 9/2 = 4.5 but 9//2 = 4
Now for even numbers, median would be mean of middle two numbers ie (4+5)/2.
Now here we need to target the correct elements using correct index.
For 8 elements, the correct number would be at index len(arr)//2 8//2 = 4 and len(arr)//2 - 1 8//2 -1 = 4-1=3
Your code should now be this.
#the function
firstMidIndex = int(len(sort)) // 2
secoundMidIndex = (int(len(sort)) // 2) - 1
if isOdd(len(values)) == True:
print("Zentralwert:", sort[firstMidIndex] #odd numbers
else:
print("Zentralwert:", (sort[firstMidIndex] + sort[secoundMidIndex]) / 2)
Probably you want,
#the sorted list
number = int(input('How many numbers do you want to put in? '))
print("")
values = []
for i in range(number):
values.append(int(input('Please enter a value: ')))
print("")
sort = sorted(values)
print("Sorted list:", sort)
#the function
firstMid = int(len(sort)) / 2
secoundMid = (int(len(sort)) / 2) + 1
if isOdd(len(values)) == True:
print("Zentralwert:", sort[int(len(sort)/2)]) #odd numbers
else:
print("Zentralwert:", (sort[firstMid] + sort[secoundMid]) / 2)

Sum of digits untill reach single digit

I set an algorithm which sum a number's digits but I couldn't make it till single digit. It only work for one step.
For example:
a=2, b=8
a^b=256 = 6+5+2 = 13
But I want to reach single digit, like:
a^b=256 = 6+5+2 = 13 = 3+1 = 4
Below you can see my codes.
a = int(input("Enter a value"))
b = int("Enter second value")
number = pow(a, b)
sum= 0
while float(number) / 10 >= .1:
m = number % 10
sum += m
number = number // 10
if float(number) / 10 > .1:
print(m, end=" + ")
else:
print(m, "=", sum)
Here you go:
n = 256
while n > 9:
n = sum(int(i) for i in str(n))
print(n)
So whats going on? str(n) converts n to a string, strings in python can be iterated over so we can access digit by digit. We do this in a generator, converting each digit back to a integer, int(i) for i in str(n), we use sum to sum the elements in the generator. We repeat this process until n is a single digit.
Added a solution that gives the calculation explicitly:
def sum_dig(n):
_sum = sum(int(i) for i in str(n))
explained = "+".join(list(str(n)))
return _sum, explained
n = 256
s = ""
while n > 10:
n, e = sum_dig(n)
s+= f'{e}='
s += str(n)
print(s)
yields:
2+5+6=1+3=4
you can try this.
a = int(input("Enter a value"))
b = int(input("Enter second value"))
number = pow(a, b)
result = str(a)+'^'+str(b) + ' = ' + str(number)
while number > 9:
digit_sum = sum(map(int, str(number)))
result += ' = ' + '+'.join(str(number)) + ' = ' + str(digit_sum)
number = digit_sum
print ( result )
for a=2, b=8 result:
2^8 = 256 = 2+5+6 = 13 = 1+3 = 4
This produces the output in the format OP asked for:
a = int(input("Enter a value: "))
b = int(input("Enter second value: "))
n = pow(a, b)
while n >= 10:
nums = [i for i in str(n)]
op = "+".join(nums)
n = eval(op)
print("{}={}".format(op, n))
Logic:
Store the input in an array of individual numbers as strings.
Create the summation string using "+".join(nums) - for the output print.
Calculate the sum using eval(op) which works on strings (a built-in function) - store in n.
Print the summation string and what it equals.
Output:
Enter a value: 2
Enter second value: 8
2+5+6=13
1+3=4
Enter a value: 2
Enter second value: 6
6+4=10
1+0=1
Enter a value: 2
Enter second value: 50
1+1+2+5+8+9+9+9+0+6+8+4+2+6+2+4=76
7+6=13
1+3=4
sol = 0
if (a^b)%9==0:
sol = 9
else:
sol = (a^b)%9

I am altering a variable, but how can i return the original state of it at the end of the function?

I edited the post to get the word cross sum instead of factorial in it, thanks for your help.
def assignment_2():
# write a function that outputs the cross sum of a number (54321 -> 5 + 4 + 3 + 2 + 1 = 15)
number = int(input('enter a number'))
result = 0
while number:
result = result + number % 10
number = int(number / I0)
return result, number
when I call the function I get the result no problem, but the number is = 0 because its going through that loop.
That's how I call the function
result, number = assignment_2()
print(f'assignment 2: the cross sum of {number} is {result}')
Just save the value to another variable:
number = int(input('enter a number'))
orig = number
result = 0
while number:
result = result + number % 10
number = int(number / 10)
return result, orig
You'll have to save it in another variable:
number = int(...)
saved_number = number
...
return result, saved_number
Also, I should note that what you're doing here is not the factorial, but the digit sum. Factorial is the product of all numbers from 1 to the argument—for instance, 5 factorial is 5×4×3×2×1 = 120.
You can use the input value as a string to get the digit sum, your algorithm does not need to transform its input at all:
def digit_sum(x):
return sum(int(xx) for xx in str(x)), x
def assignment_2():
return digit_sum(int(input("Please enter a number ")))

greatest product of consecutive digits in numbers python

My program has the purpose of determining the greatest product of a certain amount of consecutive digits. For example the program prompts the user for a string of numbers (ex 255969406) and for the size of consecutive digits (3), thus my program will determine what the greatest product of 3 consecutive digits in the number provided is, my program compiles and runs but the product returned is incorrect.
def Pro(dig,snum):
number = 1
pr = 0
for x in xrange(0,dig-1):
pr = int(snum[x])
number = pr*number
return number
def Product(dig,indx,snum):
number = 1
pr = 0
for x in xrange(1,dig):
pr = int(snum[indx+x])
number = pr*number
return number
def Main():
num = raw_input("Enter a string of digits")
dig = input("Input number of digits in group")
x = 1
val = Pro(dig,num)
grps = int(len(num)/ dig)
while x<grps:
val2= Product(dig,x,num)
if val2>val:
val = val2
x +=1
print("The max product of " + str(dig) +" consecutive digits in " + num + " is " + str(val))
if __name__ == "__main__":
Main()
You can try this out:
x = '134214257248'
m = 0
for i in range(len(x) - 2):
m = max(m, int(x[i])*int(x[i+1])*int(x[i+2]))
print m
# 2*5*7 = 70
70
EDIT: Accept any amount (n) of consecutive digits
import numpy as np
x = '134214257248'
m = 0
n = 3
for i in range(len(x) - n + 1):
m = max(m, np.prod(list(int(l) for l in x[i:i + n])))
print m
70

Why does this Python code not work?

Please help, I cannot figure out why this code does not work. I think the first loop runs forever but I don't know why!
def NTN():
list1 = []
count = 0
number = 0
Start = input('Type Start Number')
while number != Start:
count = count + 1
number = number + count
Stop = input('Type Stop Number')
while number != Stop:
count = count + 1
number = number + count
if number != Stop:
(list1).append(number)
return (list1)
print(NTN())
You are increasing number by increasing amounts in every iteration. Here's an idea of how it is increasing. Assume Start = 4
After 1 loop, count = 1 and number = 1, increase of 1
After 2 loops, count = 2 and number = 3, increase of 2
After 3 loops, count = 3 and number = 6, increase of 3
Since number is never really equal to 4, the loop never ends. What you need probably is while number <= Start. That would terminate the loop after 3 iterations when number is past 4.
change "number != Start" and "number != Stop" to "number < Start" and "number < Stop" in all places, and it should work.
What went wrong: if Start is 2, then in the first iteration of the while loop, count becomes 0+1=1 and number becomes 0+1=1; in the second iteration, count becomes 1+1=2 and number becomes 1+2=3, which bypasses 2. Since your while loop only ends when number is equal to Start, it never ends.
A couple of side-points:
By convention Python variable and function names are lower-case.
input() returns a string; if you want a number you have to convert it ie with int() or float(). (Note: if you are using Python 2.x input() calls eval() which is really awful design - you should be using int(raw_input()) instead.)
so,
# This code assumes Python 3.x
from math import ceil, sqrt
def get_int(prompt):
"""
Prompt until an integer value is entered
"""
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter an integer!")
def tri(n):
"""
Return triangular number n,
ie the sum of (1 + 2 + ... + n)
"""
# using Gaussian sum
return n * (n + 1) // 2
def reverse_tri(t):
"""
For positive integer t,
return the least positive integer n
such that t <= tri(n)
"""
# derived by quadratic formula from
# n * (n + 1) // 2 >= t
return int(ceil(((sqrt(8 * t + 1) - 1) / 2)))
def ntn(start, stop):
"""
Return a list of triangular numbers
such that start <= tri < stop
"""
a = reverse_tri(start)
b = reverse_tri(stop)
return [tri(n) for n in range(a, b)]
def main():
start = get_int('Enter a start number: ')
stop = get_int('Enter a stop number: ')
lst = ntn(start, stop + 1) # include stop number in output
print(lst)
if __name__ == "__main__":
main()

Categories

Resources