Polynomial functions in python - python

I am very new in writing Python code. I have to represent polynomial like this,
4x^230+7x^96+1
testP = [[4,512],[7,256],[1,0]]
def printPoly2(P):
for i in range(len(P)):
if P[i] != 0:
print("%s x^%s + "%(P[i], i)),
print
printPoly2(testP)
but my answer is not correct. I need help on this.

I (hopefully) improved your code with some pythonic magic. Now it´s a list of tuples and uses automatic tuple-unwrapping.
testP = [(4, 230), (7, 96), (1, 0)]
def printPoly2(P):
for i, e in P:
if e != 0:
print("{} x^{} + ".format(i, e))
printPoly2(testP)
Prints out
4 x^230 +
7 x^96 +

Your problem is in the print statement. By writing:
print("%s x^%s + "%(P[i], i))
You are actually printing the entire tuple. For example, P[0] equals the entire list [4, 512]. So in directly printing P[i] you're just printing the entire sublist.
Instead, you want to print each element in the sublist.
print("%s x^%s" % (P[i][0], P[i][1]))
Additionally, your solution as-is will print each part of the answer on a separate line. To fix this you have a couple options, but here's one that doesn't depend on the python version you have. Basically, you create a string that represents your result, and keep building on it as you go through the loop. Then at the very end of the function, you print that string.
result = '' # initialize an empty string before your loop
Then inside your loop replace the print call with:
result = "%s + %s x^%s" % (result, P[i][0], P[i][1]
And at the very end of the function you can print the string.
print (result)

this is how I would write this code in something I think is a more pythonic way of writting it:
def poly2(P):
result = []
for item in P:
n, e = item
if e == 0:
result.append("1")
else:
result.append("{}x^{}".format(n, e))
return " + ".join(result)
# 4x^230 + 7x^96 + 1
testP = [(4,230), (7,96), (1,0)]
print poly2(testP)
note that its more flexible to return a string representation than to print it directly from the function.

Just had 5 more minutes... here you go
testP = [(4, 230), (7, 96), (1, 0)]
def printPoly2(polynom):
parts = []
for i, e in polynom:
parts.append(_format_polynome(i,e))
print " + ".join(parts)
def _format_polynome(i, e):
if e == 0:
return "{}".format(i)
else:
return "{} x^{}".format(i, e)
printPoly2(testP)

Related

How to increment and decrement with a string Python?

Hope you all are doing well in these times.
here's my code:
def ab(n):
first = 0
last = -1
endprod = n[first] + n[last]
endprod2 = n[first+1] + n[last-1]
endprod3 = n[first+2] + n[last-2]
endprod4 = n[first+3] + n[last-3]
endprod5 = n[first+4] + n[last-4]
endprod100 = endprod[::-1] + endprod2[::-1] + endprod3[::-1]+ endprod4[::-1]+ endprod5[::-1]
return endprod100
I was able do to it, however mine isn't a loop. Is there a way to convert my code into a for loop. So, increment by 1 and decrement by 1.
Thanks,
Try this:
def ab(n):
result = ''
for j in range(len(n) // 2):
result += n[-j-1] + n[j]
if len(n) % 2 == 1:
result += n[len(n) // 2]
return result
You also need the part
if len(n) % 2 == 1:
result += n[len(n) // 2]
because your input string might have an odd number of characters
Examples:
>>> ab('0123456789')
'9081726354'
>>> ab('01234956789')
'90817263549'
If you want to reuse your original logic:
def ab(n):
result = ''
first = 0
last = -1
for j in range(len(n) // 2):
result += n[last-j] + n[first+j]
if len(n) % 2 == 1:
result += n[len(n) // 2]
return result
You could also recurse it:
def ab(s):
if len(s)>2:
return s[-1]+s[0]+ab(s[1:-1])
else:
return s
But the last part of Riccardo's answer fits your question more closely.
you need to split your string for your loop, means first you broke your string to half then build your string, you could use zip to iterate over multiple iteratable. something like this:
def ab(s):
out = ""
for v0,v1 in zip(s[:len(s)//2 -1 :-1], s[:len(s)//2 ]):
out += v0 + v1
return out
the better version you should write without loop.
like this:
out = "".join(map(lambda x: "".join(x), zip(s[:len(s)//2 -1 :-1], s[:len(s)//2 ])))
There are already a lot of good answers that are probably clearer, easier to read and much better suited for learning purposes than what I'm about to write. BUT... something I wanted to bring up (maybe just telling myself, because I tend to forget it) is that sometimes destroying the original argument can facilitate this sort of things.
In this case, you could keep "poping" left and right, shrinking your string until you exhaust it
def swap_destr(my_str):
result = ""
while len(my_str) > 1:
result += my_str[-1] # Last char
result += my_str[0] # First char
my_str = my_str[1:-1] # Shrink it!
return result + my_str # + my_str just in case there 1 char left
print(swap_destr("0123456789"))
print(swap_destr("123456789"))
# Outputs:
# 9081726354
# 918273645
This is also a good problem to see (and play with) recursion:
def swap_recur(my_str):
if len(my_str) <= 1:
return my_str
return my_str[-1] + my_str[0] + swap_recur(my_str[1:-1])
print(swap_recur("0123456789"))
print(swap_recur("123456789"))
# Outputs:
# 9081726354
# 918273645

formatting print statement based on different end argument values

I am making a UI for termux terminal on android.
This code below prints the content of the directory.
It works perfectly fine but the output is not even, ie, irregular spaces between the columns.
I've seen people using format but in my case the end argument value differ on each print.
def display_dir(dir_name):
direc = os.listdir(dir_name)
for index, d in enumerate(direc):
if index % 2 == 0:
print(f"{index}- {d}", end=" " * 10)
else:
print(f"{index}- {d}", end="\n")
but I want perfectly aligned 2 column output.I've tried many things. Is there a short way to do this?
I actually have a solution where I check the longest string and add white spaces for remaining strings but it's not optimal.
You are probably looking for something like this:
def display_dir(dir_name):
direc = os.listdir(dir_name)
max_len = len(max(direc, key=len))
for index, d in enumerate(direc):
if index % 2 == 0:
print("{:2}- {:<{}}".format(index, d, max_len), end=" ")
else:
print("{:2}- {:<{}}".format(index, d, max_len), end="\n")
Or even further:
def display_dir(dir_name):
direc = os.listdir(dir_name)
max_len_even = len(max(direc[::2], key=len))
max_len_odd = len(max(direc[1::2], key=len))
index_pad_len = len(str(len(direc)))
for index, d in enumerate(direc):
if index % 2 == 0:
print("{:{}}- {:<{}}".format(index, index_pad_len, d, max_len_even), end=" ")
else:
print("{:{}}- {:<{}}".format(index, index_pad_len, d, max_len_odd), end="\n")

i have a problem with strings and for loop in python

I have a string and I saved it inside a variable.
I want to change even characters to capitalize with for loop.
so i give my even characters and capitalized it. But
i cant bring them with odd characters .
can someone help me?
here is my code:
name = "mohammadhosein"
>>> for even in range(0, len(name), 2):
... if(even % 2 == 0):
... print(name[even].title(), end=' ')
...
M H M A H S I >>>
>>> ###### I want print it like this:MoHaMmAdHoSeIn```
I assume you are quite new to programing, so use a the following for loop:
name = "mohammadhosein"
output = ''
for i, c in enumerate(name):
if i % 2 == 0:
output += c.upper()
else:
output += c
# output will be 'MoHaMmAdHoSeIn'
enumerate will give you a pair of (i, c) where i is an index, starting at 0, and c is a character of name.
If you feel more comfortable with code you can use a list comprehension and join the results as follows:
>>> ''.join([c.upper() if i % 2 == 0 else c for i, c in enumerate(name)])
'MoHaMmAdHoSeIn'
As #SimonN has suggested, you just needed to make some small changes to your code:
for index in range(0, len(name)):
if(index % 2 == 0):
print(name[index].upper(), end='') # use upper instead of title it is more readable
else:
print(name[index], end='')
print()

How to run a function for each row in a nested list?

I'm a Python newbie and trying to write code that checks if a nested list has a valid set of numbers. Each row and each column have to be valid. I have written a function called check_sequence which validates if a list has a valid set of numbers. How would I call that function from another to check to see if the row is valid? So for example, I need something like this for check_rows:
check_sequence(list):
checks if list is valid
check_rows(list):
For each of the rows in the nested list call check_sequence
Here is my code for check_sequence:
def check_sequence(mylist):
pos = 0
sequence_counter = 1
while pos < len(mylist):
print "The pos is: " + " " + str(pos)
print "The sequence_counter is:" + " " + str(sequence_counter)
for number in mylist:
print "The number is:" + " " + str(number)
if number == sequence_counter:
sequence_counter = sequence_counter + 1
pos = pos + 1
break
else:
# if list is at the last position on the last item
if sequence_counter not in mylist:
print "The pos is:" + " " + str(pos) + " and the last position is:" + " " + str(mylist[len(mylist) - 1])
print "False"
return False
print "True"
return True
So I'd call the main method like below:
check_square([[1, 2, 3],
[2, 3, 1],
[3, 1, 2]])
def check_square(list):
if check_rows() and check_columns() == True:
return True
else:
return False
Here's a solution that'll work for any arbitrary 2D list.
l = [[1,2,3],[1,2],[1,4,5,6,7]]
try:
if len([1 for x in reduce(lambda x, y :x + y, l) if type(x) != type(0)]) > 0:
raise Exception
catch Exception:
pass # error, do something
The intuition is to flatten the list and then successively check if its type is int.
Given the nested list is row oriented (the rows are the lowest dimension), you can simply use:
check_rows(list):
return all(check_sequence(sublist) for sublist in list)
Here we thus use the all(..) builtin: it evaluates to True if and only if the truthiness of all elements the generator (boldface part) is True, otherwise the result is False. So from the moment one of the rows is not valid, the matrix is not valid.
If on the other hand the nested list is column oriented (the columns are the lowest dimension), we will first need to do a transpose using zip:
check_rows(list):
return all(check_sequence(list(sublist)) for sublist in zip(*list))
The zip(*..) transposes the list and we use list(..) to make sure that check_sequence(..) is still working with lists (if any iterable is sufficient, the list(..) part can be omitted.
Are you looking for an iterative for loop?
check_sequence(list):
#your check here
check_rows(list):
for row in list:
if not check_sequence(row):
return False
return True
You have to separate in two function, and think the first one will return the complete check for each value of the other:
def check_sequence(lis):
ret = True
for row in lis:
ret = ret and check_rows(row)
return ret
def check_rows(row):
ret = True
for elem in row:
pass #do your checking
return ret
a concrete example could be:
l = [[1,2,3],[1,2],[1,4,5,6,7]]
def check_sequence(lis):
ret = True
for row in lis:
ret = ret and check_rows(row)
return ret
def check_rows(row):
return 1 in row #ask if 1 belongs to the list
check_sequence(l) ---> True
check_sequence([[1],[2,3]]) ---> False

Create multiplication table?

Am a beginner in Programming and am practicing how to use nested for loops to make a multiplication table in python 2.7.5.
Here is my code
x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j
pass
well,the result is correct but it does not appear in a square matrix form as i wish.Please help me improve the code
You should print without a line break.
x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
print i*j, # will not break the line
print # will break the line
you may add formatting to keep constant cell width
x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
# substitute value for brackets
# force 4 characters, n stands for number
print '{:4n}'.format(i*j), # comma prevents line break
print # print empty line
Python's print statement adds new line character by default to the numbers you wish to have in your output. I guess you would like to have just a trailing spaces for inner loop and a new line character at the end of the outer loop.
You can achieve this by using
print i * j, # note the comma at the end (!)
and adding just a new line at the end of outer loop block:
print ''
To learn more about the trailing coma, and why it works, look here: "How to print in Python without newline or space?". Mind that it works differently in Python 3.
The final code should look like:
x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j,
print ''
You can also look for '\t' special character which would allow you to get better formatting (even this old resource is good enough: https://docs.python.org/2.0/ref/strings.html)
USE This Code. It works MUCH better. I had to do this for school, and I can tell you that after putting about 4 hours into this it works flawlessly.
def returnValue(int1, int2):
return int1*int2
startingPoint = input("Hello! Please enter an integer: ")
endingPoint = input("Hello! Please enter a second integer: ")
int1 = int(startingPoint)
int2 = int(endingPoint)
spacing = "\t"
print("\n\n\n")
if int1 == int2:
print("Your integers cannot be the same number. Try again. ")
if int1 > int2:
print("The second number you entered has to be greater than the first. Try again. ")
for column in range(int1, int2+1, 1): #list through the rows(top to bottom)
if column == int1:
for y in range(int1-1,int2+1):
if y == int1-1:
print("", end=" \t")
else:
individualSpacing = len(str(returnValue(column, y)))
print(y, " ", end=" \t")
print()
print(column, end=spacing)
for row in range(int1, int2+1, 1): #list through each row's value. (Go through the columns)
#print("second range val: {:}".format(row))
individualMultiple = returnValue(row, column)
print(individualMultiple, " ", end = "\t")
print("")
Have a good day.
#Generate multiplication table by html
import random
from copy import deepcopy
N = 15
colors = ['F','E','D','C','B','A']
i = 0
colorsall = []
while i < N:
colornow = deepcopy(colors)
random.shuffle(colornow)
colornow = "#"+"".join(colornow)
colorsall.append(colornow)
i += 1
t = ""
for i in range(1,N+1):
s = ''
for j in range(1,N+1):
if j >= i:
s += '<td style="background-color:' + colorsall[i-1] + '">'+str(i*j)+'</td>'
else:
s += '<td style="background-color:' + colorsall[j-1] + '">'+str(i*j)+'</td>'
s = "<tr>" + s + "</tr>"
t = t + s + '\n'
print('<table>' + t + '</table>')
Taken from https://todaymylearn.blogspot.com/2022/02/multiplication-table-in-html-with-python.html [Disclosure : my blog]

Categories

Resources