how to display multiplication table by defining function - python-3.x

I know how to display the multiplication table using loops but how do I make a function that can do the same thing? Pls tell me the whole program

#In this method the value of the highest multiple is passed in mult
#base is base value which will be multiplied
#this function runs from mult to 1
def multiply_rev(base,mult):
if(mult == 0):
return
else:
print("{} * {} = {}".format(base,mult,base*mult))
multiply_rev(base,mult-1)
#In this method the value of the lowest multiple is passed in mult
#base is base value which will be multiplied
##this function runs from mult to 10
def multiply_for(base,mult):
if(mult == 11):
return
else:
print("{} * {} = {}".format(base,mult,base*mult))
multiply_for(base,mult+1)
multiply_rev(2,10)
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++")
multiply_for(2,1)
This is a typical example for recursion. Google recursion for more informaion.

Related

Python3 Determine if logarithm is "perfect," i.e., no remainder on float

Problem statement:
I am trying to determine if a logarithm is "perfect," i.e., there is no remainder. The issue I am having is that math.log() always returns a float.
I read this: https://docs.python.org/3/tutorial/floatingpoint.html
Here is my current solution:
import sys
import math
def is_even_log(argument, base):
x = math.log(argument, base) # yields float
numerator, denominator = x.as_integer_ratio()
print(
f"numeratorerator: {numerator}, "
f"denominatorominator: {denominator}")
if numerator % denominator == 0:
print(f"Log base {base} of {argument} is even")
return True
else:
print(f"Log base {base} of {argument} is not even")
return False
is_even_log(int(sys.argv[1]), int(sys.argv[2]))
Question
Just curious if anyone has better way to do this? I would imagine that I could access some property of the PyObject which indicates if there is a remainder or not.
You can round the logarithm to the nearest integer, and check if it's correct by exponentiating back up again:
def is_even_log(argument, base):
return argument == base**round(math.log(argument, base))
Log b in base i equals x is equivalent to b equals i to the power x. So the code would be:
def is_even_log(arg, base):
x = math.log(arg, base)
return arg == base ** int(x+1/2)
As the int function returns the truncation of a float, int(x+1/2) returns the rounded number.
This solution works for integers (both arg and base) because in this case the if statement is a comparaison between integers
Testing the equality of floats is not recommended anyways because of the approximations.

Need help writing a function which returns a dictionary with the keys as recursive digit sums

So I have written a function which calculates the sum of the digits when a number is input to the function. Now I am trying to write another function which would return a dictionary with the values from my digitsum function as the keys and the values would be how many times the count of that specific digitsum has occurred. Any ideas on how to go about writing the second function?
def digitsum(x):
if x < 10:
return x
else:
return (x%10) + digitsum(x//10)
def digitsumdictionary(lnum=0, hnum=100):
L =[digitsum(num) for num in range(100)]
counter = Counter(L).items()
return counter
Digitsum function is called depending on the length of the number.
You can simply find it by using len(list(str(num))). But if you want to count as the function calls itself, Then try this,
def digitsum(x, count=1):
if x < 10:
return { x : count }
else:
return {(x%10) + int(list(digitsum(x//10 , count+1).keys())[0]) : int(list(digitsum(x//10 , count+1).values())[0])}
Setting the count to 1 or 0 initially, includes or excludes the first call respectively.
The below code returns a list of dictionaries of the desired output.
[digitsum(i) for i in range(10)]

Count number of basic instruction and their type

I have some code (few hundreds of lines) and i would like to reproduce the code on some "real" controller.
I would like to predict how long the code would take to run by counting how many instructions (basic arithmetic, type of operation (floating point, binary, etc..)
And i wonder if it is possible to do on python (if yes how so ? haven't found anything yet)
I know there is a time feature to measure how long it takes to run the code but the calculation power of my PC and the controller i plan to use are not the same.
Also i tried counting it myself but it is quite a pain and subject to errors
Ideal result would be like:
X number of basic arithmetic operation using INT
Y number of basic arithmetic operation using FLOAT
Z binary operation
etc ...
Thank you
Your question got me thinking. I wrote a little framework for how you might implement something like this. Basically you create your own number class and a collection to hold them all. Then you over-ride the default operators and increment a variable every time you enter those functions. Note that this is NOT robust.. There's no error checking and it assumes that all operations are done with the custom class objects.
from collections import defaultdict # Acts like a dictionary, but every time you add a key, the value defaults to a specified value
class Collection(object): # Use this to hold your custom types
def __init__(self):
self.items = []
return
def add_item(self, item):
self.items.append(item)
class myFloat(object): # Your custom float class
def __init__(self, val, collection):
""" val is the value, collection is the Collections object where we will place your object """
self.val = float(val)
self.op_counts = defaultdict(int) # a dictionary where values default to an integer, 0.
collection.add_item(self) # Add this object to the collection
def __add__(self, other): # Called when you use + on two myFloat
self.op_counts["+"] += 1 # Adds 1 to the number of "+" used
return self.val + other.val # returns the result.
def __sub__(self, other): # Called when you use - on two myFloat
self.op_counts["-"] += 1
return self.val - other.val
def __mul__(self, other): # Called when you use * on two myFloat
self.op_counts["*"] += 1
return self.val * other.val
def __truediv__(self, other): # Called when you use / on two myFloat
self.op_counts["/"] += 1
return self.val / other.val
### EXAMPLE
import random
ops = ["+", "-", "*", "/"]
# We should create a separate Collection object for each custom type we have.
# Since we only have myFloat, we make one Collection object to hold the myFloats.
float_collection = Collection()
# This instantiates a myFloat object with val=7.12 and uses your float_collection
y = myFloat(7.12, float_collection)
for x in range(1, 1000):
op = random.choice(ops) # Pick a random operation
xx = myFloat(x, float_collection) # Instantiate another myFloat
# Now perform the operation on xx and y. eval evaluates the string but
# opens the door for security holes if you are worried about hackers. CAREFUL.
eval(f"y{op}xx") # Remove this line and use the one below if your python < 3.6
# eval("y{}xx".format(op))
print("### RESULTS ###")
result_op_counts = defaultdict(int) # We use this to count up our results
# Sorry for the confusing syntax. The items parameter of the Collection object
# is NOT the same as the items() method for dictionaries.
# float_collection.items is a list of your myFloats.
# the items() method for dictionary returns a dict_items object that you can iterate through.
# This loop tallies up all the results
for myFloatObj in float_collection.items:
for op, ct in myFloatObj.op_counts.items():
result_op_counts[op] += ct
# And this loop prints them.
for k,v in result_op_counts.items():
print(f"{k}: {v} operations") # Remove this line and use the one below if your python < 3.6
# print("{}: {} operations".format(k, v))
This outputs
### RESULTS ###
*: 227 operations
/: 247 operations
+: 275 operations
-: 250 operations

Wanted a failing test case for code for Subset with maximum sum so that no two elements in it are adjacent to each other

Given a multi-set of non-zero integers find a multi-subset of integers with maximum sum such that no two elements in this multi-subset are adjacent to each other. If there are at least two such multi-subsets then that multi-subset is chosen whose smallest element is the largest of all smallest elements in the candidate multi-subsets.
I saw solutions for finding the maximum sum, but I want the actual multi-subset too. Also, I don't want code; I just want a failing test case for my code.
Input is in the following format.
T positive integer (# of test cases)
N1 (positive integer followed by N1 integers representing the set whose "maximum sum" subset has to be identified)
a1 a2 a3 ... aN1
N2
...
NT
....
Output
a3a1 (required subset in reverse order - for example, a1 + a3 forms the largest sum in the first set above and so output is a3a1)
Concrete examples:
2
4
3 6 2 -2
4
4 5 3 4
Output
6
45
({4,4} and {3,5} both form the largest sum but 35 is not output because smallest element in {4,4} > smallest element in {5,3})
I wrote code and it passes on all test cases I can think of. But it fails a formal assessment and I don't know what the failing test cases are. My idea is the following. Either the first element F in the set is a member of the required subset or it is not. If it is, then we recursively find the "minimum sum" subset from the third element onwards in the original set and adjoin it to F. If it is not, then we recursively find this subset from the second element onwards of the original set.
Below is the code I wrote. Can someone give a failing test case?
#returns 1 if all but the first element are negative
def all_neg(t):
sum=0
for i in range(1,len(t)):
if t[i]<0:
sum+=1
if sum==len(t)-1:
return 1
#reverses string
def reverse(t):
if len(t)<=1:
return t
else:
l=[t[-1]]
l.extend(reverse(t[:-1]))
return l
def max(a1,a2):
if a1>a2:
return a1
else:
return a2
#returns the sum of the subset with the maximum sum
def sum_max(t):
if len(t)==0:
return 0
elif len(t)==1:
return (t[0])
elif len(t)==2:
if t[0]>t[1]:
return t[0]
else:
return t[1]
else:
if t[0]>0:
if sum_max(t[2:])>0:
c1=t[0]+sum_max(t[2:])
else:
c1=t[0]
else:
return sum_max(t[1:])
c2=sum_max(t[1:])
return(max(c1,c2))
#returns the subset with the maximum sum
def arr_max(t):
if len(t)<=1:
return t
elif len(t)==2:
if t[0]>t[1]:
return [t[0]]
else:
return [t[1]]
elif sum_max(t)>sum_max(t[1:]):
if all_neg(t[1:]):
return([t[0]])
l=[]
l.append(t[0])
tmp=arr_max(t[2:])
l.extend(arr_max(t[2:]))
return l
elif sum_max(t)==sum_max(t[1:]):
l=[]
if (t[0]<0):
return arr_max(t[1:])
l.append(t[0])
l.extend(arr_max(t[2:]))
m=arr_max(t[1:])
sl=sum(l)
sm=sum(m)
if sl>sm:
return l
elif sm>sl:
return m
lm=min(l)
mm=min(m)
if lm<mm:
return m
else:
return l
else:
return arr_max(t[1:])
def main():
test=int(input())
for i in range(0,test):
N=int(input())
t=[int(s) for s in input().split()]
y=arr_max(t)
print(''.join(str(i) for i in reverse(y)))
main()

how to print the median of a list in python

I've written code to find the median of a list but I'm unsure how to display it when I run the code.
I've tried the print function but I'm not sure what to print.
My code is:
wages = [1,2,3]
def median(wages):
sorted_list = sorted(wages)
length = len(sorted_list)
center = length // 2
if length == 1:
return sorted_list[0]
elif length % 2 == 0:
return sum(sorted_list[center - 1: center + 1]) / 2.0
else:
return sorted_list[center]
Any help would be appreciated.
You can just call your function in the print statement:
print(median(wages))
or
print(median([1,2,3])
You might be confused because you labelled wages as the array and put it in the definition of your function, but there is no connection between the two wages in your code. The line
wages = [1,2,3]
creates a variables called wages but it doesn't impact the wages in the line:
def median(wages):
or inside your function definition. To read more have a look into variable scopes in python.
For example, you could call your function on any array such as,
test_array = [1,2,3,4]
print(median(test_array))
You can just print the return value of your median method.
def median():
your code here
print(median())
PS : There are some indentation errors in your code.

Resources