Program is written but cant get it to concatenate - python-3.x

This program takes 4 points on a graph and puts them into a Lagrange polynomial. I got my terms to output correctly but I need to concatenate the 4 terms into 1 line of code. No matter where I seem to try to concatenate, it keeps messing up the loops and therefore messing up my terms. I'm sure there is an easier way to do this, but I have to use strings and concatenation for my assignment. Any help would be appreciated. Thanks.
import string
from math import *
def main():
n=4
abscissa=[-5,-2,3,7]
ordinate=[4,-6,8,1]
for j in range(n):
LP=str(ordinate[j])
denom="1"
for k in range(n):
if k!=j:
denom= denom+"*("+str(abscissa[j])+"-"+str(abscissa[k])+")"
LP=LP+"*(x-"+str(abscissa[k])+")"
LP=LP+'/'+denom
print(LP)
main()

Collect the terms, and join them:
import string
from math import *
def main():
n=4
abscissa=[-5,-2,3,7]
ordinate=[4,-6,8,1]
result = ''
for j,y in enumerate(ordinate):
if j!=0:
result += '+'
LP=str(y)
denom="1"
for k,x in enumerate(abscissa):
if k!=j:
denom += '*({}-{})'.format(abscissa[j],x)
LP += '*(x-{})'.format(x)
LP += '/' + denom
result += LP
print(result)
main()

Related

oneliner using reduce in python

I'm trying to take my Python skills (beginner) to the next level.
and I'm trying to teach myself the functools.reduce() function
So I'm running every time into the same error;
I'd appreciate if someone could explain to me what is the problem in my code
I'm trying to build a simple func that receive a number and return the sum of number digits
import functools
def sum_using_reduce(number):
return str(number)[0] + str(number)[1]
number = 104
print(functools.reduce(sum_using_reduce, number))
Try this:
number = 104
functools.reduce(lambda x, y: x+y, [int(i) for i in str(number)])
Output: 5
Using your example:
import functools
def sum_using_reduce(x, y) -> int:
return x + y
print(functools.reduce(sum_using_reduce, [int(i) for i in str(105)]))
Output: 6
Another approach:
import functools
def sum_using_reduce(number: int) -> int:
return functools.reduce(lambda x, y: x+y, [int(i) for i in str(number)])
print(sum_using_reduce(124))
Output: 7
In your sum_using_reduce function you are trying to sum two strings, which would simply perform concatenation. Moreover, you are providing an integer as the second argument to the reduce function, where the reduce function requires an iterable to be provided.
Below is a solution that fixes both these requirements:
from functools import reduce
number=104
print(reduce(lambda x,y:x+y,map(int,str(number))))
map(int,str(number)) transforms the number to a string (104->"104") and then turns every character in the string to an integer, returning an iterable map object ("104"->[1,0,4]).
lambda x,y:x+y is a function which takes two integers and sums them.

Here is my python code to swapcase the characters in a string .it's not working correct , How to fix this?

only capital alphabets are converted into small but small letters are not getting converted into capital
def swap_case(s):
pi=list(s)
for i in range(len(pi)):
if 'a'<=pi[i]<='z'and ord(pi[i])>0:
pi[i]=chr(ord(pi[i])- 32)
if 'A'<=pi[i]<='Z':
pi[i]=chr(ord(pi[i])+ 32)
return (pi)
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
Python provides functions to address this requirement. Not sure about your exact requirement.
however below answer should swap cases.
def swap_case(s):
swaped= s.swapcase()
return swaped
if __name__ == '__main__':
s = input()
l = swap_case(s)
print(l)
If I am not wrong you might be looking for a code which would convert lowercase to uppercase and vice-versa.
For example:
Input: Sirius Black
Output: sIRIUS bLACK
If so then, the code below might be helpful:
def swapcase (word):
from collections import deque
dq = deque(word)
b=''
while len(dq)>=1:
a = dq.pop()
if a.islower() is True:
b = a.upper()+ b
else:
b = a.lower()+ b
return b
s = input()
result = swapcase(s)
print (result)
Here, I'm using deque ( a double ended queue ) from the 'collections' module for accessing each letter and then converting them as needed and concatenating all of them into a single string.

Formatting lists to display leading zero - Python 3.x

I'm trying to create a matrix with 4 rows and 10 columns and display the leading 0 for all the single digit numbers that will randomly get generated later. This is what I would like it to look like: My teacher gave me this snippet as a way to format the numbers:
print('{:02}'.format(variable))
But when I use this in my function, it gives me the error: unsupported format string passed to list.__format__
I reworked my code and was able to get the leading zero, but now the 4x10 matrix is just 40 ints side by side. Anyone able to give me some help and an explanation?
My code:
def printMatrix(matrix):
for r in range(ROWS):
for c in range(COLS):
print('{:02}'.format(matrix[r][c]), end=' ')
def main():
matrix = [0]*ROWS
for i in range(ROWS):
matrix[i] = [0]*COLS
printMatrix(matrix)
You're really close, looks like you may just need another print() after the for-loop to put a newline after each row. Try this:
def printMatrix(matrix):
for r in range(ROWS):
for c in range(COLS):
print('{:02}'.format(matrix[r][c]), end=' ')
print()
Demo
you need a 0 in front .. i.e. {0:02}
print('{0:02}'.format(variable))
This 0 refer to the index of the parameters passed in e.g. this should work too:
print('{2:02}'.format("x", "y", variable))
Your code:
def printMatrix(matrix):
for r in range(ROWS):
for c in range(COLS):
print('{0:02}'.format(matrix[r][c]), end=' ')
def main():
matrix = [0]*ROWS
for i in range(ROWS):
matrix[i] = [0]*COLS
printMatrix(matrix)

Can you explain why the plot is stopping at J (at index 10)

I am running this program to find the distribution of characters in a specific text.
# this is a paragraph from python documentation :)
mytext = 'When a letter is first k encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.The function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):'
d = dict()
ignorelist = ('(',')',' ', ',', '.', ':', '_')
for n in mytext:
if(n not in ignorelist):
n = n.lower()
if n in d.keys():
d[n] = d[n] + 1
else:
d[n] = 1
xx = list(d.keys())
yy = list(d.values())
import matplotlib.pyplot as plt
plt.scatter(xx,yy, marker = '*')
plt.show()
Both the list has 25 elements. For some strange reason the plot is coming like this. It ends in 'J' in x axis.
If I zoom it the right side gets visible but there is no points plotted.
Note that this will be fixed as of matplotlib version 2.2
It seems you have found a bug in the new categorical feature of matplotlib 2.1. For single letter categories it will apparently limit its functionality to 10 items. If categories consist of more letters, this does not happen.
In any case, a solution is to plot numerical values (just as one would have needed to do prior to matplotlib 2.1 anyways). Then set the ticklabels to the categories.
# this is a paragraph from python documentation :)
mytext = 'When a letter is first k encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.The function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):'
d = dict()
ignorelist = ('(',')',' ', ',', '.', ':', '_')
for n in mytext:
if(n not in ignorelist):
n = n.lower()
if n in d.keys():
d[n] = d[n] + 1
else:
d[n] = 1
xx,yy = zip(*d.items())
import numpy as np
import matplotlib.pyplot as plt
xx_sorted, order = np.unique(xx, return_inverse=True)
plt.scatter(order,yy, marker="o")
plt.xticks(range(len(xx)), xx_sorted)
plt.show()

Trapezoidal approximation error plotting in python

Im trying to code a function that plots the error of the composite trapezoidal rule against the step size.
Obviously this doesn't look to good since i'm just starting to learn these things.
Anyhow i managed to get the plot and everything, but i'm supposed to get a plot with slope 2, so i am in need of help to figure out where i did go wrong.
from scipy import *
from pylab import *
from matplotlib import *
def f(x): #define function to integrate
return exp(x)
a=int(input("Integrate from? ")) #input for a
b=int(input("to? ")) #inpput for b
n=1
def ctrapezoidal(f,a,b,n): #define the function ctrapezoidal
h=(b-a)/n #assign h
s=0 #clear sum1-value
for i in range(n): #create the sum of the function
s+=f(a+((i)/n)*(b-a)) #iterate th sum
I=(h/2)*(f(a)+f(b))+h*s #the function + the sum
return (I, h) #returns the approximation of the integral
val=[] #start list
stepsize=[]
error=[]
while len(val)<=2 or abs(val[-1]-val[-2])>1e-2:
I, h=ctrapezoidal(f,a,b,n)
val.append(I)
stepsize.append(h)
n+=1
for i in range(len(val)):
error.append(abs(val[i]-(e**b-e**a)))
error=np.array(error)
stepsize=np.array(stepsize)
plt.loglog(stepsize, error, basex=10, basey=10)
plt.grid(True,which="both",ls="steps")
plt.ylabel('error')
plt.xlabel('h')

Resources