Use the function expired to write a function mayadate(). The function has two parameters: a parameter date that takes a date in the Gregorian calendar, and an optional parameter separator that takes a string containing a single character. The function must return the date in the Mayan calendar that corresponds to the given date in the Gregorian calendar. To determine the date in the Maya calendar, you may assume that the date 01/01/1970 in the Gregorian calendar corresponds to the date 12.17.16.7.5 in the Maya calendar. Count the number of days that have passed since this reference date, until you reach the requested date. The individual values for the time periods in the Maya calendar must be represented without leading zeroes, and are separated from one another using the given separator. If no separator was explicitly passed to the function, the function must use the same character used to separate the numbers in the given Gregorian date.
I am trying to solve the last function for different cases but it is still not working for some, for example it is not working with:
mayadate(date='05-0004-002294', separator='/')
correct answer: '13/14/5/6/18'
Traceback (most recent call last): File <code>, line 131, in mayadate TypeError: object of type 'NoneType' has no len()
If I try to solve it than some of the other cases stops working.
Other cases:
mayadate('5.4.2051') solution: '13.1.18.15.4'
mayadate('9+10+0002267', '|') solution: '13|12|18|9|3'
mayadate('21 12 2012', separator='+') solution: '13+0+0+0+0'
Can anyone help me?
def dmy(n):
'''
>>> dmy('01/01/1970')
(1, 1, 1970)
>>> dmy('20-7-1988')
(20, 7, 1988)
>>> dmy('00012+00012+02012')
(12, 12, 2012)
>>> dmy('21 12 2012')
(21, 12, 2012)
>>> dmy('26.03.2407')
(26, 3, 2407)
'''
new = n.replace('/', " ")
new2 = new.replace('-', " ")
new3 = new2.replace('+', " ")
new4 = new3.replace('=', " ")
new5 = new4.replace('~', " ")
new6 = new5.replace('.', " ")
new7 = new6.replace('#', " ")
new8 = new7.replace('|', " ")
new9 = new8.replace('*', " ")
new10 = new9.replace(':', " ")
k = [int(s) for s in new10.split() if s.isdigit()]
r = tuple(k)
return r
def expired(n):
'''
>>> expired('01/01/1970')
0
>>> expired('20-7-1988')
6775
>>> expired('00012+00012+02012')
15686
>>> expired('21 12 2012')
15695
>>> expired('26.03.2407')
159695
'''
s = dmy(n)
a = s[0]
b = s[1]
c = s[2]
from datetime import date, timedelta
d1 = date(c, b, a) # start date
d2 = date(1970, 1, 1) # end date
delta = d2 - d1
return abs(delta.days)
def mayadate(*args, **kwargs):
'''
>>> mayadate('01/01/1970')
'12/17/16/7/5'
>>> mayadate('20-7-1988',separator='/')
'12/18/15/4/0'
>>> mayadate('00012+00012+02012',separator='-')
'12-19-19-17-11'
>>> mayadate('21 12 2012',separator='+')
'13+0+0+0+0'
>>> mayadate('26.03.2407')
'14.0.0.0.0
'''
args1 = args if args else None
args2 = [kwargs.get(i) for i in ['date', 'separator']]
if args1 is not None:
s = expired(args1[0]) + 1856305
if args2[0] is not None:
s = expired(args2[0]) + 1856305
w = s // 144000
q = s%144000
v = q // 7200
q2 = q%7200
u = q2 // 360
q3 = q2%360
t = q3 // 20
q4 = q3%20
r = q4
k = str()
if args1 is not None:
symbol = "~`|!##$%^&*()_-+={}[]:>;',</?*-+.' '"
for i in args1[0]:
if i in symbol:
k = str(i)
if args2[0] is not None:
symbol = "~`|!##$%^&*()_-+={}[]:>;',</?*-+.' '"
for i in args2[0]:
if i in symbol:
k = str(i)
import re
w = re.sub(r"\b0{2}", "", str(w))
v = re.sub(r"\b0{2}", "", str(v))
u = re.sub(r"\b0{2}", "", str(u))
t = re.sub(r"\b0{2}", "", str(t))
r = re.sub(r"\b0{2}", "", str(r))
if args2 is None and len(args1) == 1:
q = str(w) + k + str(v) + k + str(u) + k + str(t) + k + str(r)
return q
if len(args1) == 1 and args2[1] is None:
q = str(w) + k + str(v) + k + str(u) + k + str(t) + k + str(r)
return q
else:
q = str(w) + k + str(v) + k + str(u) + k + str(t) + k + str(r)
char = "~`|!##$%^&*()_-+={}[]:>;',</?*-+.:' '"
kas = ' '
if args2[1] is not None:
for x in q:
if x in char or x in kas:
q = q.replace(x, args2[1], 4)
return q
if args1 is not None:
for x in q:
if x in char or x in kas:
q = q.replace(x, args1[1], 4)
return q
The problem is in your call and your args handling.
mayadate(date='05-0004-002294', separator='/')
There are no normal args: they're all kwargs. Therefore, in your function, args is empty. You convert it to None. Later, you call for its length; as the error says, len(None) is illegal.
Decide how you want to handle that case, and change your code accordingly.
Related
I am trying to store the values obtained from excel sheet cells to a list. The code provided basically collects data from different continuous rows and columns and creates a string of those values. I could work upt o storing the string value but I don't really know how to store the strings in a list, Can anyone help me with this?
for i in range(NR):
print("This TC checks the output for")
for j in range(NC):
inputVariable = str(ws[get_column_letter(ColumnStart+j) + str(rowStart-1)].value)
c = str((ws.cell(row = (rowStart + i),column = (ColumnStart +j)).value))
if (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MaxValRow),column = (ColumnStart+j)).value):
b = '(maximum)'
elif (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MinValRow),column = (ColumnStart+j)).value):
b = '(minimum)'
else:
b ='(intermediate)'
Commentstr = str(j+1) + '. The value of input ' + inputVariable + ' =' + " " + c + b
# need to create a list here to store the commentstr for each iteration
NR = no. of rows, NC = no. of columns
my_list=[]
for i in range(NR):
x=0
print("This TC checks the output for")
for j in range(NC):
inputVariable = str(ws[get_column_letter(ColumnStart+j) + str(rowStart-1)].value)
c = str((ws.cell(row = (rowStart + i),column = (ColumnStart +j)).value))
if (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MaxValRow),column = (ColumnStart+j)).value):
b = '(maximum)'
elif (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MinValRow),column = (ColumnStart+j)).value):
b = '(minimum)'
else:
b ='(intermediate)'
Commentstr = str(j+1) + '. The value of input ' + inputVariable + ' =' + " " + c + b
my_list[x]=Commentstr
x+=1
I´m having some troubles on my code, that implements a function that verifies the lenght of a string and return that string with or without spaces.
If String b >= 15 return b
If strinf < 15 return "number os spaces until len(b)2 + string b
But I get a IndexError: list index out of range Error. I cannot figure out where or why.
Traceback:
============= RESTART: C:\Users\pbo\Desktop\Trab_04.py =============
ascii_letters = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Traceback (most recent call last):
File "C:\Users\pbo\Desktop\Trab_04.py", line 30, in
o2.append(a(o1[e]))
IndexError: list index out of range
============= ============= ============= ============= =============
Thanks a lot for any possible help.
from random import seed
from random import randint
from random import choice
from string import ascii_letters
seed(930)
def a(b):
if(len(b)<15) :
s = "";
l = len(b)
while(len(s) + len(b) < 15) :
s += " "
s += b
return s
else:
return b
print("ascii_letters = " + ascii_letters)
o1 = []
for e in range(9622):
k = randint(1, 25)
s = ""
for l in range(k):
s = s + choice(ascii_letters)
o1.append(s)
o2 = []
for e in range(9622):
o2.append(a(o1[e]))
print("000000000111111111122222222223333333333")
print("123456789012345678901234567890123456789")
for e in range(9):
print(o1[e] + "|")
print("000000000111111111122222222223333333333")
print("123456789012345678901234567890123456789")
for e in range(9):
print(o2[e] + "|")
x1 = ""
x2 = "a"
x3 = "abc"
x4 = "abcdefghijklmnopqrstuvwxyz"
print("000000000111111111122222222223333333333")
print("123456789012345678901234567890123456789")
print(x1 + "|")
print(x2 + "|")
print(x3 + "|")
print(x4 + "|")
print("000000000111111111122222222223333333333")
print("123456789012345678901234567890123456789")
print(a(x1) + "|")
print(a(x2) + "|")
print(a(x3) + "|")
print(a(x4) + "|")
It looks like your indentation is incorrect (see also What is Python Whitespace and how does it work?).
If you change the following:
o1 = []
for e in range(9622):
k = randint(1, 25)
s = ""
for l in range(k):
s = s + choice(ascii_letters)
o1.append(s)
to:
o1 = []
for e in range(9622):
k = randint(1, 25)
s = ""
for l in range(k):
s = s + choice(ascii_letters)
o1.append(s)
Then, your code appears to work.
The problem is that your list o1 only has one element in it. Snipping out all of the rest of the code, you do this:
s = "some string"
o1 = []
o2 = []
# now has one element
o1.append(s)
for i in range(9622):
# when i > 0, IndexError will be raised
state = o1[i]
o2.append(a(state))
This happens because you are iterating over a range that has no relationship to the size/contents of o1. To fix this, you might consider:
s = "some string"
o1 = []
o2 = []
o1.append(s)
for element in o1:
o2.append(a(element))
The reason being is that now you are iterating over o1 directly, rather than assuming it will always have 9622 elements in it, which it doesn't in this case.
Also, upon further inspection, it looks like your a function is just trying to pad a string with spaces out to 15 characters. Fortunately, there's a builtin for this:
x = "some string"
x.rjust(15)
' some string'
Where rjust will left-insert spaces to create a string of the given length
I'm trying to use this dictionary:
student_data_dict = {'Student_1': 'bbbeaddacddcddaaadbaabdad', 'Student_2': 'acbccaddcadaaacdadbcabcad', 'Student_3': 'babcabdccadcDdbccdbaadbad', 'Student_4': 'bcbcabddcadcdabccdbaadcbd', 'Student_5': 'DCBCCADDCADBDACCDBBACBCAD', 'Student_6': 'acbeccddcadbaaccabbacdcad', 'Student_7': 'BCBCBCDABADCADCCDABAACCAD', 'Student_8': 'dcbccbddcadaabcbcacabbcad', 'Student_9': 'DDBDBBCDDCCBABCCBACADAAAC', 'Student_10': 'cbbdacdacadcbadbabaabcaTa', 'Student_11': 'BDBECADCAADCAAAAACBACACAD', 'Student_12': 'DBBCCBDCCADCDABABCBAABCAD', 'Student_13': 'BCBCBCDDCADCAAACCABACACAD', 'Student_14': 'DBBECBDACADAAACBCBAAABCBD', 'Student_15': 'acbebbddcadbaacccbcaddcad', 'Student_16': 'ACBEBCDDCADBAACCAACADBCAD', 'Student_17': 'DBBCACDDCADCAABCADBABDDAD', 'Student_18': 'dcbcdcdbbddccabbdacacccbd', 'Student_19': 'dbbccbddcadaaaccbdcaaacad', 'Student_20': 'abbdaaddcadcaaccbdcaaccbd', 'Student_21': 'DCDCABDBCADAAACDCCDAACAAD', 'Student_22': 'dabdaddabddbaacdacbaaaaad', 'Student_23': 'BCBCDDDACCDCAABDDABACACAD', 'Student_24': 'ACBDCBDBBCDAACCCCBDAADCBD', 'Student_25': 'DCBCACDAADDCADCBAABACBCAD', 'Student_26': 'dcbaabdccadcdadcccbaabdbd', 'Student_27': 'abbadbddcadacbcacccacbdad'}
and store the first letter for all students as a dictionary entry and then do the same for the next letter ect... to result in:
{'question_1': 'babbDaBdDcBDBDaADddaDdBADda', 'question_2': 'bcacCcCcDbDBCBcCBcbbCaCCCcb', 'question_3': 'bbbbBbBbBbBBBBbBBbbbDbBBBbb', 'question_4': 'ecccCeCcDdECCEeECccdCdCDCaa', 'question_5': 'acaaCcBcBaCCBCbBAdcaAaDCAad', 'question_6': 'dabbAcCbBcABCBbCCcbaBdDBCbb', 'question_7': 'ddddDdDdCdDDDDdDDdddDdDDDdd', 'question_8': 'adcdDdAdDaCCDAdDDbddBaABAcd', 'question_9': 'ccccCcBcDcACCCcCCbccCbCBAcc', 'question_10': 'daaaAaAaCaAAAAaAAdaaAdCCDaa', 'question_11': 'ddddDdDdCdDDDDdDDdddDdDDDdd', 'question_12': 'caccBbCaBcCCCAbBCcacAbCACca', 'question_13': 'daDdDaAaAbADAAaAAcaaAaAAAdc', 'question_14': 'dadaAaDbBaAAAAaAAaaaAaACDab', 'question_15': 'acbbCcCcCdABACcCBbccCcBCCdc', 'question_16': 'adccCcCbCbAACBcCCbccDdDCBca', 'question_17': 'aaccDaDcBaABCCcAAdbbCaDCAcc', 'question_18': 'ddddBbAaAbCCABbADaddCcABAcc', 'question_19': 'bbbbBbBcCaBBBAcCBcccDbBDBbc', 'question_20': 'acaaAaAaAaAAAAaAAaaaAaAAAaa', 'question_21': 'aaaaCcAbDbCACAdDBcaaAaCACac', 'question_22': 'bbddBdCbAcABABdBDcacCaADBbb', 'question_23': 'dcbcCcCcAaCCCCcCDcccAaCCCdd', 'question_24': 'aaabAaAaATAAABaAAbabAaABAba', 'question_25': 'ddddDdDdCaDDDDdDDdddDdDDDdd'}
x = 1
all_letters = ''
letter = ''
y = 1
i = 0
z = 0
for start in student_data_dict:
student = student_data_dict.get('Student_' + str(y))
letter = student[z]
all_letters = all_letters + letter
y = y + 1
i = i + 1
question_data_dict["question " + str(x)] = all_letters
if i == 27:
z = z + 1
x = x + 1
i = 0
print(question_data_dict)
data_file.close()
{'question 1': 'babbDaBdDcBDBDaADddaDdBADda'}
is what I get but I can't get the answers for the other 25 questions.
I tried changing for start in student_data_dict: into while z<26: but at the line "letter = student[z]" I get the error "'NoneType' object is not subscriptable"
num_questions = 25
answers_dict = {}
for i in range(num_questions):
answers_dict['question' + str(i)] = ''.join(c[i] for c in student_data_dict.values())
print(answers_dict)
Will give you the result you want.
Edit
Fixed code. Extracted number of questions to a variable so it can be used as index
Edit2
I created an OrderedDict from your original dictionary to maintain answer order when iterating. Now the answers_dict contains valid data.
from collections import OrderedDict
ordered_data = OrderedDict()
for i in range(len(student_data_dict.items())):
ordered_data['Student_' + str(i + 1)] = student_data_dict.get('Student_' + str(i + 1))
num_questions = 25
answers_dict = {}
for i in range(num_questions):
answers_dict['question' + str(i + 1)] = ''.join(c[i] for c in ordered_data.values())
You need to reset y when you move to the next question.
Here's an alternative a way to get what you're looking for with Pandas:
import pandas as pd
sdd = {k:[x for x in v] for k,v in student_data_dict}
df = pd.DataFrame(sdd)
df = df.reindex_axis(sorted(df.columns,
key = lambda col: int(col.split("_")[-1])), axis=1)
df.index = [f"Question {i+1}" for i in df.index]
{k:''.join(v) for k,v in zip(df.index, df.values)}
I wrote a python script trying to solve the 'calculate 24' problem, which originated from a game, drawing 4 cards from a deck of cards and try to get the value 24 using +,-, *, and /.
The code is working, only that it have many duplications, for example, I input 2, 3, 4, 5 to get the value of 24, it will find and print that 2*(3 + 4 + 5) is 24, but it will also print 2*(5 + 4 + 3), 2*(5 + 3 + 4), etc., while it will find 4*(3 + 5 - 2), it will also print 4*(5 + 3 - 2). Could anyone please give me some hints on how to remove duplicated answers?
The code is as follows:
def calc(oprands, result) :
ret=[]
if len(oprands)==1 :
if oprands[0]!=result :
return ret
else :
ret.append(str(oprands[0]))
return ret
for idx, x in enumerate(oprands) :
if x in oprands[0:idx] :
continue
remaining=oprands[0:idx]+oprands[idx+1:]
temp = calc(remaining, result-x) # try addition
for s in temp :
ret.append(str(x) + ' + ' + s)
if(result%x == 0) : # try multiplication
temp = calc(remaining, result/x)
for s in temp :
ret.append(str(x) + ' * (' + s + ')')
temp = calc(remaining, result+x) # try subtraction
for s in temp :
ret.append(s + ' - ' + str(x))
temp = calc(remaining, x-result)
for s in temp :
ret.append(str(x) + ' - (' + s + ')')
temp = calc(remaining, result*x) # try division
for s in temp :
ret.append('(' + s + ') / ' + str(x))
if result!=0 and x%result==0 and x/result!=0 :
temp = calc(remaining, x/result)
for s in temp :
ret.append(str(x) + ' / ' + '(' +s +')')
return ret
if __name__ == '__main__' :
nums = raw_input("Please input numbers seperated by space: ")
rslt = int(raw_input("Please input result: "))
oprds = map(int, nums.split(' '))
rr = calc(oprds, rslt)
for s in rr :
print s
print 'calculate {0} from {1}, there are altogether {2} solutions.'.format(rslt, oprds, len(rr))
Calculate 24 is an interesting and challenging game. As other users pointed out in the comments, it's difficult to create a solution that doesn't present any flaw.
You could study the Rosetta Code (spoiler alert) implementation and compare it to your solution.
I am currently doing a python exercise for my University studies. I am very stuck at this task:
The taylor polynomial of degree N for the exponential function e^x is given by:
N
p(x) = Sigma x^k/k!
k = 0
Make a program that (i) imports class Polynomial (found under), (ii) reads x and a series of N values from the command line, (iii) creates a Polynomial instance representing the Taylor polynomial, and (iv) prints the values of p(x) for the given N values as well as the exact value e^x. Try the program out with x = 0.5, 3, 10 and N = 2, 5, 10, 15, 25.
Polynomial.py
import numpy
class Polynomial:
def __init__(self, coefficients):
self.coeff = coefficients
def __call__(self, x):
"""Evaluate the polynomial."""
s = 0
for i in range(len(self.coeff)):
s += self.coeff[i]*x**i
return s
def __add__(self, other):
# Start with the longest list and add in the other
if len(self.coeff) > len(other.coeff):
result_coeff = self.coeff[:] # copy!
for i in range(len(other.coeff)):
result_coeff[i] += other.coeff[i]
else:
result_coeff = other.coeff[:] # copy!
for i in range(len(self.coeff)):
result_coeff[i] += self.coeff[i]
return Polynomial(result_coeff)
def __mul__(self, other):
c = self.coeff
d = other.coeff
M = len(c) - 1
N = len(d) - 1
result_coeff = numpy.zeros(M+N+1)
for i in range(0, M+1):
for j in range(0, N+1):
result_coeff[i+j] += c[i]*d[j]
return Polynomial(result_coeff)
def differentiate(self):
"""Differentiate this polynomial in-place."""
for i in range(1, len(self.coeff)):
self.coeff[i-1] = i*self.coeff[i]
del self.coeff[-1]
def derivative(self):
"""Copy this polynomial and return its derivative."""
dpdx = Polynomial(self.coeff[:]) # make a copy
dpdx.differentiate()
return dpdx
def __str__(self):
s = ''
for i in range(0, len(self.coeff)):
if self.coeff[i] != 0:
s += ' + %g*x^%d' % (self.coeff[i], i)
# Fix layout
s = s.replace('+ -', '- ')
s = s.replace('x^0', '1')
s = s.replace(' 1*', ' ')
s = s.replace('x^1 ', 'x ')
#s = s.replace('x^1', 'x') # will replace x^100 by x^00
if s[0:3] == ' + ': # remove initial +
s = s[3:]
if s[0:3] == ' - ': # fix spaces for initial -
s = '-' + s[3:]
return s
def simplestr(self):
s = ''
for i in range(0, len(self.coeff)):
s += ' + %g*x^%d' % (self.coeff[i], i)
return s
def _test():
p1 = Polynomial([1, -1])
p2 = Polynomial([0, 1, 0, 0, -6, -1])
p3 = p1 + p2
print p1, ' + ', p2, ' = ', p3
p4 = p1*p2
print p1, ' * ', p2, ' = ', p4
print 'p2(3) =', p2(3)
p5 = p2.derivative()
print 'd/dx', p2, ' = ', p5
print 'd/dx', p2,
p2.differentiate()
print ' = ', p5
p4 = p2.derivative()
print 'd/dx', p2, ' = ', p4
if __name__ == '__main__':
_test()
Now I'm really stuck at this, and I would love to get an explaination! I am supposed to write my code in a separate file. I'm thinking about making an instance of the Polynomial class, and sending in the list in argv[2:], but that doesn't seem to be working. Do I have to make a def to calculate the taylor polynomial for the different values of N before sending it in to the Polynomial class?
Any help is great, thanks in advance :)
Not quite finished, but this answers your main question I believe. Put class Polynomial in poly.p and import it.
from poly import Polynomial as p
from math import exp,factorial
def get_input(n):
''' get n numbers from stdin '''
entered = list()
for i in range(n):
print 'input number '
entered.append(raw_input())
return entered
def some_input():
return [[2,3,4],[4,3,2]]
get input from cmd line
n = 3
a = get_input(n)
b = get_input(n)
#a,b = some_input()
ap = p(a)
bp = p(b)
print 'entered : ',a,b
c = ap+bp
print 'a + b = ',c
print exp(3)
x = ap
print x
sum = p([0])
for k in range(1,5):
el = x
for j in range(1,k):
el el * x
print 'el: ',el
if el!=None and sum!=None:
sum = sum + el
print 'sum ',sum
output
entered : [2, 3, 4] [4, 3, 2]
a + b = 6*1 + 6*x + 6*x^2
20.0855369232
2*1 + 3*x + 4*x^2
sum 2*1 + 3*x + 4*x^2
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4
sum 6*1 + 15*x + 29*x^2 + 24*x^3 + 16*x^4
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4
el: 8*1 + 36*x + 102*x^2 + 171*x^3 + 204*x^4 + 144*x^5 + 64*x^6
sum 14*1 + 51*x + 131*x^2 + 195*x^3 + 220*x^4 + 144*x^5 + 64*x^6
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4
el: 8*1 + 36*x + 102*x^2 + 171*x^3 + 204*x^4 + 144*x^5 + 64*x^6
el: 16*1 + 96*x + 344*x^2 + 792*x^3 + 1329*x^4 + 1584*x^5 + 1376*x^6 + 768*x^7 + 256*x^8
sum 30*1 + 147*x + 475*x^2 + 987*x^3 + 1549*x^4 + 1728*x^5 + 1440*x^6 + 768*x^7 + 256*x^8
I solved the task in the following way, though im not sure if it answers question (iv).
The output just compares the exact value of e**x to the calculated value from module Polynomial.
from math import factorial, exp
from Polynomial import *
from sys import *
#Reads x and N from the command line on the form [filename.py, x-value, N-value]
x = eval(argv[1])
N = eval(argv[2])
#Creating list of coefficients on the form [1 / i!]
list_coeff = [1./factorial(i) for i in range(N)]
print list_coeff
#Creating an instance of class Polynomial
p1 = Polynomial(list_coeff)
print 'Calculated value of e**%f = %f ' %(x, p1.__call__(x))
print 'Exact value of e**%f = %f'% (x, exp(x))
"""Test Execution
Terminal > python Polynomial_exp.py 0.5 5
[1.0, 1.0, 0.5, 0.16666666666666666, 0.041666666666666664]
Calculated value of e**0.500000 = 1.648438
Exact value of e**0.500000 = 1.648721
"""