I would like to make this code somehow work, in this example i used the int() function which obviously gave me the "invalid literal for int() with base 10" error. But is there any way to make python not read the "" around the string and just read "i" in this case as a parameter.
I hope you understand what I mean.
s=0
w=""
for k in range(3):
w+="i"
for i in range(5):
s+=int(w)
I donĀ“t know whats your expected result. Your main problems seems the quotes for w = "" and w+="i" if you want to add numbers instead of textstrings.
Maybe you also mixed up your k and i variable.
Is this your expected result(?):
s = 0
w = 0
for k in range(3):
w += k
for i in range(5):
s += w
print(s)
print(w)
In your current version of code, when you say int(w) you are trying to convert 'iii' into a base 10 number which runs the error. Also, using i as a variable will only work within the for loop 'for i in range(5):'. That is where the variable i has its lifespan.
Related
as a part of my code, I'm trying to get a full factorial matrix, this is not a problem since I already have a working code for it. However, I would like to generalize it in a way that it wouldn't matter the number of inputs. This would require modifying the line:
for combination in itertools.product(X[0,:],X[1,:],X[2,:],X[3,:],X[4,:],X[5,:],X[6,:]):
input_list = dfraw.columns[0:n_inputs]
output_list = dfraw.columns[n_inputs:len(dfraw.columns)]
fflvls = 4
lhspoints = 60000
X = np.zeros((n_inputs, fflvls),float)
ii=0
for entrada in input_list:
X[ii] = np.linspace(min(dfraw[entrada]), max(dfraw[entrada]), fflvls)
ii+=1
number=1
i=0
X_fact=np.zeros((int(fflvls**n_inputs),n_inputs),float)
for combination in itertools.product(X[0,:],X[1,:],X[2,:],X[3,:],X[4,:],X[5,:],X[6,:]):
X_fact[i,:] = (combination)
i +=1
number+=1
I thought of writing the input of itertools.product as a string with a loop and then evaluating but it doesn't work and I've also seen it is regarded as bad practice
prodstring = ['X[0,:]']
for ii in range(n_inputs):
prodstring.append(',X[%d,:]'%(ii))
in_products = ''.join(prodstring)
for combination in itertools.product(eval(in_products)):
X_fact[i,:] = (combination)
i +=1
number+=1
what other way is there to inputing the full range of columns in this function? (or similar ones)
who said working harder is working better? im back from lunch and I delved into *args and **kwargs as a form of procrastination cause ive sometimes seen them mentioned and i was curious. It seems like it was just the tool I needed. In case this can help other code rookies like me in the future:
args = ()
for ii in range(n_inputs):
b = (X[ii,:])
args += (b,)
for combination in itertools.product(*args):
X_fact[i,:] = (combination)
i +=1
number+=1
Seems to work properly. Solved in an hour of "not working" what i haven't solved in approx 4 hours of "working"
I found this question on HackerRank and I am unable to understand the code(solution) that is displayed in the discussions page.
The question is:
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Even though I have solved the problem using if-else, I do not understand how this code works:
n = input()
slist = []
for _ in range(n):
s = input().split()
cmd = s[0]
args = s[1:]
if cmd !="print":
cmd += "("+ ",".join(args) +")"
eval("slist."+cmd)
else:
print slist
Well, the code takes advantage of Python's eval function. Many languages have this feature: eval, short for "evaluate", takes a piece of text and executes it as if it were part of the program instead of just a piece of data fed to the program. This line:
s = input().split()
reads a line of input from the user and splits it into words based on whitespace, so if you type "insert 1 2", s is set to the list ["insert","1","2"]. That is then transformed by the following lines into "insert(1,2)", which is then appended to "slist." and passed to eval, resulting in the method call slist.insert(1,2) being executed. So basically, this code is taking advantage of the fact that Python already has methods to perform the required functions, that even happen to have the same names used in the problem. All it has to do is take the name and arguments from an input line and transform them into Python syntax. (The print option is special-cased since there is no method slist.print(); for that case it uses the global command: print slist.)
In real-world code, you should almost never use eval; it is a very dangerous feature, since it allows users of your application to potentially cause it to run any code they want. It's certainly one of the easier features for hackers to use to break into things.
It's dirty code that's abusing eval.
Basically, when you enter, for example, "remove 1", it creates some code that looks like sList.remove(1), then gives the created code to eval. This has Python interpret it.
This is probably the worst way you could solve this outside of coding competitions though. The use of eval is entirely unnecessary here.
Actually I Find some error in the code, but I came to an understanding of how this code runs. here is it:
input :
3
1 2 3
cmd = 1 + ( 2 + 3)
then eval(cmd) i.e., eval("1 + (2 + 3)") which gives an output 6
another input:
4
4 5 6 2
cmd = 4 + ( 5 + 6 + 2)
eval(cmd)
if __name__ == '__main__':
N = int(raw_input())
lst=[]
for _ in range(N):
cmd, *line = input().split()
ele= list(map(str,line))
if cmd in dir(lst):
exec('lst.'+cmd+'('+','.join(ele)+')')
elif cmd == 'print':
print(lst)
else:
print('wrong command', cmd)
I have a problem in Python I simply can't wrap my head around, even though it's fairly simple (I think).
I'm trying to make "string series". I don't really know what it's called, but it goes like this:
I want a function that makes strings that run in series, so that every time the functions get called it "counts" up once.
I have a list with "a-z0-9._-" (a to z, 0 to 9, dot, underscore, dash). And the first string I should receive from my method is aaaa, next time I call it, it should return aaab, next time aaac etc. until I reach ----
Also the length of the string is fixed for the script, but should be fairly easy to change.
(Before you look at my code, I would like to apologize if my code doesn't adhere to conventions; I started coding Python some days ago so I'm still a noob).
What I've got:
Generating my list of available characters
chars = []
for i in range(26):
chars.append(str(chr(i + 97)))
for i in range(10):
chars.append(str(i))
chars.append('.')
chars.append('_')
chars.append('-')
Getting the next string in the sequence
iterationCount = 0
nameLen = 3
charCounter = 1
def getString():
global charCounter, iterationCount
name = ''
for i in range(nameLen):
name += chars[((charCounter + (iterationCount % (nameLen - i) )) % len(chars))]
charCounter += 1
iterationCount += 1
return name
And it's the getString() function that needs to be fixed, specifically the way name gets build.
I have this feeling that it's possible by using the right "modulu hack" in the index, but I can't make it work as intended!
What you try to do can be done very easily using generators and itertools.product:
import itertools
def getString(length=4, characters='abcdefghijklmnopqrstuvwxyz0123456789._-'):
for s in itertools.product(characters, repeat=length):
yield ''.join(s)
for s in getString():
print(s)
aaaa
aaab
aaac
aaad
aaae
aaaf
...
Ok guys, I am using python to try to complete a task. In short, I need to read in a number from a text file that can be thousands of digits long. I'm getting this error as I try to take the digits from the string and cast them to integers so I can do some math with them.
of = open("input.txt","r")
counter = 0
big=0
of.seek(0,0)
while True:
temp = of.read(5)
if temp=="":
break
else:
a=int(temp[0])
b=int(temp[1])
c=int(temp[2])
d=int(temp[3])
e=int(temp[4])
if a*b*c*d*e>big:
big = a*b*c*d*e
counter+=1
of.seek(counter,0)
print big
of.close()
I'm really stuck on this one so any help much appreciated.
Thanks in advance.
EDIT==============================================================
After tinkering around a bit I finally got the code to run correctly. Here's what I ended with:
x = int(open("input.txt","r").read())
y = str(x)
big = 0
for i in range(0,len(y)-5):
a = int(y[i])
b = int(y[i+1])
c = int(y[i+2])
d = int(y[i+3])
e = int(y[i+4])
if a*b*c*d*e>big:
big = a*b*c*d*e
print big
thanks for the help
Python supports long integers so if the file is just one big integer you can read it like this:
bignum=int(open("input.txt","r").read())
Your indentation is wrong; if-else should be nested inside the while loop.
I want to print the result of the equation in my if statement if the input is a digit and print "any thing" if it is a letter.
I tried this code, but it's not working well. What is wrong here?
while 1:
print '\tConvert ciliuse to fehrenhit\n'
temp = input('\nEnter the temp in C \n\t')
f = ((9/5)*temp +32)
if temp.isdigit():
print f
elif temp == "quit" or temp == "q" :
break
elif temp.isalpha() :
print ' hhhhhhh '
You need to go through your code line by line and think about what type you expect each value to be. Python does not automatically convert between, for example, strings and integers, like some languages do, so it's important to keep types in mind.
Let's start with this line:
temp = input('\nEnter the temp in C \n\t')
If you look at the documentation for input(), input() actually calls eval() on what you type in in Python 2.x (which it looks like you're using). That means that it treats what you type in there as code to be evaluated, just the same as if you were typing it in the shell. So if you type 123, it will return an int; if you type 'abc', it will return a str; and if you type abc (and you haven't defined a variable abc), it will give you an error.
If you want to get what the user types in as a string, you should use raw_input() instead.
In the next line:
f = ((9/5)*temp +32)
it looks like you're expecting temp to be a number. But this doesn't make sense. This line gets executed no matter what temp is, and you're expecting both strings containing digits and strings containing letters as input. This line shouldn't go here.
Continuing on:
if temp.isdigit():
isdigit() is a string method, so here you're expecting temp to be a string. This is actually what it should be.
This branch of the if statement is where your equation should go, but for it to work, you will first have to convert temp to an integer, like this:
c = int(temp)
Also, to get your calculation to work out right, you should make the fraction you're multiplying by a floating-point number:
f = ((9/5.0)*c +32)
The rest of your code should be okay if you make the changes above.
A couple of things first - always use raw_input for user input instead of input. input will evaluate code, which is potentially dangerous.
while 1:
print "\tConvert ciliuse to fehrenhit\n"
temp = raw_input("\nEnter the temp in C \n\t")
if temp in ("quit", "q"):
break
try:
f = ((9.0 / 5.0) * float(temp) + 32)
except ValueError:
print "anything"
Instead of using isalpha to check if input is invalid, use a catch clause for ValueError, which is thrown when a non-numerical value is used.
Why isn't it working? Are you getting an error of any kind?
Straight away I can see one problem though. You are doing the calculation before you verify it as a number. Move the calculation to inside the if temp.isdigit().
Take a look at this for some examples:
http://wiki.python.org/moin/Powerful%20Python%20One-Liners
OK, this works. Only problem is when you quit, you get dumped out of the interpreter.
while 1: import sys; temp=raw_input('\nEnter the temp in C \n\t'); temp.isdigit() and sys.stdout.write('%lf' %((9./5)*float(temp)+32)) or temp=='q' and sys.exit(0) or sys.stdout.write(temp)