I'm working on a for-fun-project that I will be doing some calculations with and I need some help.
one module from my program:
def ARK(rawArk):
refArk = rawArk/200
arkTrit = refArk*300
arkMeg = refArk*333
arkZyd = refArk*166
print "Totals from your Arkonor:"
print "Tritanium=", arkTrit
print "Megacyte=", arkMeg
print "Zydrine=", arkZyd
return arkTrit, arkMeg, arkZyd
Right now it is just doing simple division and multiplication. What I want to do is be able to do this with remainders.
So if 'refArk = rawArk/200' gives a total of 16.3, I want to be able to separate the 16.0 and the 0.3 and use them as separate variables for separate calculations.
So far:
def ARK(rawArk):
refArk = float(rawArk/200)
arkTrit = refArk*300
arkMeg = refArk*333
arkZyd = refArk*166
print "Totals from your Arkonor:"
print "Tritanium=", arkTrit
print "Megacyte=", arkMeg
print "Zydrine=", arkZyd
strval = str(refArk)
head,tail = strval.split(".")
whole = float(head)
frac = float("."+tail)
print whole
print frac
return arkTrit, arkMeg, arkZyd
def main():
rawArk=input("How much Arkonor?")
ARK(rawArk)
return
main()
USING '450' as my input value
returns
How much Arkonor?450
Totals from your Arkonor:
Tritanium= 600.0
Megacyte= 666.0
Zydrine= 332.0
2.0
0.0
The 2.0 is right but the 0.0 should be 0.25
Removing the float() from the 'rawArk/200' spits out an error:
How much Arkonor?450
Totals from your Arkonor:
Tritanium= 600
Megacyte= 666
Zydrine= 332
Traceback (most recent call last):
File "E:\eve stuff\Calculator\test.py", line 23, in <module>
main()
File "E:\eve stuff\Calculator\test.py", line 20, in main
ARK(rawArk)
File "E:\eve stuff\Calculator\test.py", line 11, in ARK
head,tail = strval.split(".")
ValueError: need more than 1 value to unpack
Numerically
val1 = 22.0
val2 = 7.0
whole,frac = divmod(val1,val2)
frac = frac/val1
Kind of a hack but with strings
val = 22.0/7.0
strval = str(val)
head,tail = strval.split(".")
whole = float(head)
frac = float("."+tail)
either way
>>> frac
0.14285714286000001
>>> whole
3.0
May be first use round function then use split
refArk = refArk.split(".")
Why not just do:
intpart=int(variable)
decimalpart=variable-intpart
I would guess this to be more efficient than casting to a string and then splitting.
The following session at the IDLE should show how to solve your problem.
>>> lis=str(refArk).split('.')
>>> lis[-1]='.'+lis[-1]
>>> map(float,lis)
[16.0, 0.3]
Related
So I have been trying to study Python for a little while now (roughly 2 months) and while I have the basics down, I am trying some more challenging scenarios from HackerRank.com. I feel like I am somewhat close to the answer here, because I feel like the ask here is fairly simple.
I know that the values need to be setup so that n (number of keyboards) and m (number of drives) do not go over b (budget), but comes as close to that number as possible.
If it is not possible to be less than or equal to b, then I need to print a -1 instead.
The order of the arguments is b (budget), n (keyboards), m (drives). The next line of input is the prices of the keyboards, and the last line of input is the prices of drives.
For example:
Sample input:
10 2 3
3 1
5 2 8
Sample output:
9
Here is the code so far:
#!/bin/python3
import os
import sys
#
# Complete the getMoneySpent function below.
#
def getMoneySpent(keyboards, drives, b):
keyboards = int(keyboards * n)
drives = int(drives * m)
if keyboards + drives > b:
return -1
else:
return keyboards + drives
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
bnm = input().split()
b = int(bnm[0])
n = int(bnm[1])
m = int(bnm[2])
keyboards = list(map(int, input().rstrip().split()))
drives = list(map(int, input().rstrip().split()))
#
# The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
#
moneySpent = getMoneySpent(keyboards, drives, b)
fptr.write(str(moneySpent) + '\n')
fptr.close()
As it is, I get an error stating:
Traceback (most recent call last):
File "Solution.py", line 39, in <module>
moneySpent = getMoneySpent(keyboards, drives, b)
File "Solution.py", line 11, in getMoneySpent
keyboards = int(keyboards * n)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
I recently saw a video on Youtube about genetic algorithms and thought it was quite interesting and decided to give it a go. Me, being new to programming and not having experience with any language other than Python, thought C#, which seemed to be the most widely used language for genetic algorithms, was t0o hard and decided to give it a try in Python. And I am currently stuck because of an error, and I can't quite figure out what is wrong with the code.
This is the code:
import random
#Wanted String
STRING_NAME = "this is a genetic algorithm"
LENG = len(STRING_NAME)
#Used Characters
VALID_CHARACTERS = "abcdefghijklmopqrstuvwxyz "
#Generation Size
POPULATION_SIZE = 200
#List of String Objects
POPULATION = []
closest = 100
choiceList = []
#Generating random strings
def randomStringGeneration(size=len(STRING_NAME)):
return ''.join(random.choice(VALID_CHARACTERS) for _ in range(size))
#string object
class ranString:
def __init__(self,manualstr=""):
if manualstr == "":
self.string = randomStringGeneration()
else:
self.string = manualstr
self.fitness = fitnessCheck(self)
#fitness checking
def fitnessCheck(String):
result = 0;
for x in range(0,LENG-1):
if (String.string[x] == STRING_NAME[x]):
result += 1
return result
#order population list by fitness decrementaly
def sortByFitness(Obj):
Obj.sort(key=lambda x: x.fitness, reverse=True)
#mating two strings
def mate(x,y):
tempxstr = x.string
tempystr = y.string
child1 = tempxstr[0:10]+tempystr[14:20]+tempxstr[21:26]
child2 = tempystr[0:10]+tempxstr[14:20]+tempystr[21:26]
ranchild1 = ranString(manualstr = child1)
ranchild2 = ranString(manualstr = child2)
POPULATION.append(child1,child2)
#main function
def generatePopulation(num):
generation = 1
for x in range(num):
if (generation == 1):
for x in range(POPULATION_SIZE):
f = ranString()
POPULATION.append(f)
sortByFitness(POPULATION)
for x in POPULATION:
print(x.string + " " + str(x.fitness))
generation +=1
else:
sortByFitness(POPULATION)
del POPULATION[100:]
for x in POPULATION:
for j in range(x.fitness):
choiceList.append(x)
for j in range(100):
x = random.choice(choiceList)
y = random.choice(choiceList)
mate(x,y)
print("\n\n\n\nGeneration"+generation)
for x in POPULATION:
print(x.string + " " + str(x.fitness))
generation += 1
generatePopulation(10)
This is the log(do you call these log files?) file with the error:
egf ukcob uf oyhtuikmdritiz 4
ouaelyf ef wufsjh aqkcyacef 3
rbuwptsdjmwskfzyccsfgzlwdyo 3
fqyg zhhhswesdfetqjy ohrpyj 3
qfirzajzhafdv dicmueavdrguv 3
pxqsxtehe bckbvadapezgrqdkb 3
zvosvvsspgbpmxhadwxkfzkqjhi 3
tfsofiurlpyakhhwqqexoafhtxi 3
qkmslihwskukcecldykkp caiqo 3
fhfh ctluzbr vty skgozgqclg 3
dglsfwimwqfxdhdzx lkcvrraev 3
jbuwaoxua uteissqfpxodciaoa 3
if qpvpcsixe kagmxyludcicwl 3
vspwdxwqkewcaethcs g dxcxao 3
d jpylld gzuojvccuh gzjxbs 3
pvzsjkxtzrjgjegimalvcaxjbjw 3
zolqfli sdahohjiryerabkvmme 2
ufslbdexaa wrfuscfbkfdulzfr 2
*
* (middle part omitted because it would be too long)
*
jcjigwzhyxwwyikfoiyrtolclg 0
srjqfxjbuppfd drlrkjkuqegvb 0
zbsbkedazmxyghrmhzdzjytcqza 0
xqxmtxrkhctqayrmkvefkpy zad 0
waxpeefkvqjjwvylre jfvedyfa 0
udyetsjd lmhuzamrwt rip dqv 0
Traceback (most recent call last):
File "/Users/Johnwon/Desktop/Genetic String.py", line 80, in <module>
generatePopulation(10)
File "/Users/Johnwon/Desktop/Genetic String.py", line 73, in generatePopulation
mate(x,y)
File "/Users/Johnwon/Desktop/Genetic String.py", line 48, in mate
ranchild1 = ranString(manualstr = child1)
File "/Users/Johnwon/Desktop/Genetic String.py", line 28, in __init__
self.fitness = fitnessCheck(self)
File "/Users/Johnwon/Desktop/Genetic String.py", line 34, in fitnessCheck
if (String.string[x] == STRING_NAME[x]):
IndexError: string index out of range
I've searched the Internet for the out of index error and it seems that I incremented too much or searched for an index that is not existent but I can't find the cause for the error. What is wrong with my code?
Also, currently my mate() function works by adding the strings to a separate list multiplied by their fitness then randomly selecting 2 of them and swapping a third of their 'genes' and popping out 2 babies. This is the only way I could think of to give more fit objects a higher chance to mate but this seems horribly unoptimized as the generations go and fitness levels grow higher. What could be a good way to do this and implement mutation?
I'm a beginner in Python and I'm open to any opinions on how to improve my code. Thanks for reading!
child1 = tempxstr[0:10]+tempystr[14:20]+tempxstr[21:26]
child2 = tempystr[0:10]+tempxstr[14:20]+tempystr[21:26]
This doesn't look right to me. These strings will each have a length of 21. But inside fitnessCheck, you're comparing them against STRING_NAME, which has a length of 27. So once x reaches 21 inside fitnessCheck, you'll get an IndexError.
You should change how you create child1 and child2 so that they have the same length as STRING_NAME.
This isn't a duplicate because I have checked everything before this post on this site. I think I have managed to do the first two bullet points. The first one I will do through a string but I am willing to change that if you know another way. The 2nd one is using comma seperators for the $'s. So I will use a float but once again am willing to change if better way is found.
But I am stuck.
And the "print("%.2f") % str) is something I found but I need work on rounding to two decimal spaces and the last bullet point.
Code:
import random
def random_number():
random_dollars = random.uniform(1.00, 10000.00)
print(round(random_dollars, 2))
print("%.2f") % str
print(random_number())
Shell:
C:\Users\jacke\PycharmProjects\ASLevelHomeworkWeek18\venv\Scripts\python.exe C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py 6567.62 Traceback (most recent call last): %.2f File
C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py", line 10, in <module> print(random_number()) File
C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py", line 7, in random_number print("%.2f") % str TypeError: unsupported operand type(s) for %: 'NoneType' and 'type' Process finished with exit code 1
You can format currency like this:
def random_number():
random_dollars = random.uniform(1, 10000)
result = '$ {:0>9}'.format('{:,.2f}'.format(random_dollars))
print(result)
{:0>10} means: pad string left to width 9 with 0's.
{:,.2f} rounds to two decimal places (.2f) and adds a comma as thousands-separator.
Just one side note: by using random.uniform(1, 10000) most of your numbers will be large (>1000), if you want to test your script with small amounts you could use random_dollars = 10**random.uniform(0, 4) instead:
def random_number():
random_dollars = 10**random.uniform(0, 4)
result = '$ {:0>9}'.format('{:,.2f}'.format(random_dollars))
print(result)
If I get what you are saying you want to round a number to 2 decimal places. Here is how I would do it.
import random
def random_number():
random_dollars = random.uniform(1, 10000)
split = str(random_dollars).split(".")
if (len(split) == 2 ):
if (len(split[1]) == 1 ):# checks if 1 digit after decimal place
answer = split[0] + ".0"
split[1] = str(int(int(split[1]) / (10 ** (len(split[1]) - 3) )))
# Gets 3 decimal places
if int(split[1][-1:]) => 5: #Checks if last digit is above or equal to 5
split[1] = int(split[1][:-1])
split[1] += 1
else:
split[1] = int(split[1][:-1])
answer = split[0] + '.' + str(split[1])
else:
answer = split[0] + ".00"
print(answer)
random_number()
This makes it so if the random number is somehow 100 it will add 2 zeros. If the number is like 100.1 it will add one zero. It will also round it.
def random_number():
random_dollars = random.uniform (1.00, 10000.00)
n = round(random_dollars,2)
bd, d = str(n).split('.')
if len(d) == 1:
n = bd + "." + d + '0'
return n
else:
return n
for i in range(1, 20):
print(random_number())
7340.55
7482.70
3956.81
3044.50
4108.57
4864.90
235.00
9831.98
960.97
1172.28
5221.31
3663.50
5410.50
3448.52
8288.13
293.48
1390.68
9216.15
6493.65
TL;DR: you have to put the % directly after the string and you have to put a real variable there, not the type str
from the last line of your error message you can see that the problem is the % operator. You can also see that it tried to do the operation with two objects of types 'NoneType' and 'type'. Since you put the entire print statement in front of the % and print returns None (which is of type NoneType), the first operand is of type NoneType. then, the second operand is the type str, which is, as just said, a type. You can fix this by moving the % operator after the string and replacing str with your variable random_dollars since that is what you want to insert into the string.
import random
def random_number():
random_dollars = random.uniform(1.00, 10000.00)
print(round(random_dollars, 2))
# this:
print("%.2f" % random_dollars)
print(random_number())
I have got these code, But it gives a zero division error. I am not able to figure out what is wrong. I need your help. Thank you. :)
from math import sqrt
def inisialisasi():
filename = raw_input('File will be read? ')
return filename
def readdatafile(filename):
datafile = open('kalibration.txt','r')
datax = []; datay = []; datae = []; i = 0
for row in datafile:
i +=1
data = row.split()
x = float(data[0])
datax.append(x)
y = float(data[1])
datay.append(y)
e = float(data[2])
datae.append(e)
print 'x = %5.2f y = %5.2f e = %5.2f' % (x, y, e)
datafile.close()
n = i
print 'Jumlah data = ', n
return n, datax, datay, datae
def regresilinear(x, y, e):
sum1=0.0; sum2=0.0; sum3=0.0; sum4=0.0; sum5=0.0
for i in range(0, n):
sum1=sum1+(x[i]**2/e[i]**2)
sum2=sum2+(y[i]/e[i]**2)
sum3=sum3+(x[i]/e[i]**2)
sum4=sum4+(x[i]*y[i])/e[i]**2
sum5=sum5+1/e[i]**2
det = (sum5*sum1)-sum3**2
#parameter a dan b
a = ((sum1*sum2)-(sum3*sum4))/det
b = ((sum5*sum4)-(sum3)*(sum2))/det
#ralat
sigmaa2 = sum1/det
sigmab2 = sum5/det
sigmaa = sqrt(sigmaa2)
sigmab = sqrt(sigmab2)
return a, b, sigmaa, sigmab
filename = inisialisasi()
n, datax, datay, datae = readdatafile(filename)
a, b, sigmaa, sigmab = regresilinear(datax,datay, datae)
print 'a= %8.6f b= %8.6f sigmaa= %8.6f sigmab= %8.6f' % (a, b, sigmaa, sigmab)
error :
Traceback (most recent call last):
File "coba6.py", line 55, in
a, b, sigmaa, sigmab = regresilinear(datax, datay, datae)
File "coba6.py", line 42, in regresilinear
a = ((sum1*sum2)-(sum3*sum4))/det
ZeroDivisionError: float division by zero
Somehow, det is set equal to 0. Since you never explicitly prevent that from happening, a single input line like...
1.0 <whatever> 1.0
...can result in division by zero. (The y value doesn't matter in this case.) After substituting, you'll have:
sum1 = 0.0 + 1.0**2 / 1.0**2 # sum1 == 1.0
sum3 = 0.0 + 1.0 / 1.0**2 # sum3 == 1.0
sum5 = 0.0 + 1 / 1.0**2 # sum5 == 1.0
det = 1.0 * 1.0 - 1.0**2 # det == 0.0
...
a = <whatever> / det # KABOOM!
Actually, no input will also produce this error, since the for loop in regresilinear will never alter the various sum* variables from their default 0.0 values.
If you're sure your input isn't doing this, you might want to add print statements inside regresilinear to see how det is getting set to zero. (Or use the pdb debugger, if you're familiar with it.)
PS: It would be much easier to debug your functions if they weren't dependent on global data like n. You don't even need it, since it should always equal the length of the three lists datax, datay, and datae.
PPS: readdatafile completely ignores its filename parameter. So if the hard-coded kalibration.txt file happens to be present but empty, you'll get the exact same ZeroDivisionError.
What does your variable e look like? That is, what does it contain? If there's values of zero in it, you have your answer.
Here's my code:
# Note: Return a string of 2 decimal places.
def Cel2Fah(temp):
fah = float((temp*9/5)+32)
fah_two = (%.2f) % fah
fah_string = str(fah_two)
return fah_string
Here's what I should get:
>>> Cel2Fah(28.0)
'82.40'
>>> Cel2Fah(0.00)
'32.00'
But I get an error:
Traceback (most recent call last):
File "Code", line 4
fah_two = (%.2f) % fah
^
SyntaxError: invalid syntax
I'm not sure what is going on...
This doesn't seem to work either for some reason:
# Note: Return a string of 2 decimal places.
def Cel2Fah(temp):
fah = temp*9/5+32
fah_cut = str(fah).split()
while len(fah_cut) > 4:
fah_cut.pop()
fah_shorter = fah_cut
return fah_shorter
It looks like you want:
fah_two = "%.2f" % fah
The result of the % formatting operator is a string, so you don't need fah_string because fah_two is already a string.
sucmac:~ ajung$ cat x.py
def toF(cel):
return '%.2f' % (cel * 1.8 +32)
print toF(0)
print toF(50)
print toF(100)
sucmac:~ ajung$ python x.py
32.00
122.00
212.00
Further, I think temp * 9 / 5 should be temp * 9 / 5.0.