In my code it says x is not defined? - python

def randomcheetahs():
x = random.randint(1,2)
if x == 1:
r = 'present'
elif x == 2:
r = 'absent'
return r
cheetahs = randomcheetahs()
it says that x==1:
is not defined. How might I go about fixing that?
Tanks

Probably since you didn't use indentation correctly.
Indent every line except the first with 4 spaces.
However I do not have a compiler here so I cannot check it.
Btw but offtopic, your code can be rewritten as:
def randomcheetahs():
return 'present' if random.randint(1,2) == 1 else 'absent'

I guess maybe your code is indented like this
def randomcheetahs():
x = random.randint(1,2)
if x == 1:
r = 'present'
elif x == 2:
r = 'absent'
return r
cheetahs = randomcheetahs()
You need to indent it like this instead. Be careful not to mix tabs and spaces. It's a good idea to just use spaces
def randomcheetahs():
x = random.randint(1,2)
if x == 1:
r = 'present'
elif x == 2:
r = 'absent'
return r
cheetahs = randomcheetahs()
As wim says, you can also just do this:
def randomcheetahs():
return random.choice(['present', 'absent'])
but it is important for beginners to understand how the indenting works in Python

Related

How to solve pylint (too-many-return-statements) elegantly?

The example of too-many-return-statements is as above, but my scenario is as follows, how to make the function more beautiful?
def func():
# do something1
ret1 = do_something1()
if ret1 != 0:
return ret1
# do something2
ret2 = do_something2()
if ret2 != 0:
return ret2
# ......
return 0
You could try something like this:
def foo(x):
nums = ['one','two','three','four','five','six','seven']
return 'This is ' + nums[x-1]
to solve your example. And you could solve your scenario like this:
def func():
functions = [do_something1,do_something2,...]
for function in functions:
ret = function()
if ret != 0:
return ret
return 0
Check out this example.
It converted:
def func(x):
if x == 1:
return "hi1"
if x == 2:
return "hi2"
if x == 3:
return "hi3"
if x == 4:
return "hi4"
if x == 5:
return "hi5"
if x == 6:
return "hi6"
if x == 7:
return "hi7"
to:
d = {1: "hi1", 2: "hi2", 3: "hi3", 4: "hi4", 5: "hi5", 6: "hi6", 7: "hi7"}
def func(x):
return d[x]
Just to silence it another option is:
def func(x):
if x == something1:
res = "something1"
elif x == something2:
res = "something2"
elif x == something3:
res = "something3"
elif x == something4:
res = "something4"
elif x == something5:
res = "something5"
elif x == something6:
res = "something6"
elif x == something7:
res = "something7"
else:
res = "default"
return res
You can also silence it in settings.json file if you think it's too strict rule which I think it is:
"python.linting.pylintArgs": [
"--disable=R0911"
],
def func():
res = default_res
if foo:
res = res_foo
elif bar:
res = res_bar
return res
I recommend doing it this way
Using some form of lookup is the way to handle this. A dictionary is a good general purpose idea. A list is useful when the lookup 'key' is an integer.
HOWEVER
When using a lookup technique you have to consider that your 'key' may not be available. If your dictionary (for example) has 7 integer keys (1->7 inclusive) and your function is passed a value of 8, what are you going to do? You could allow the exception and deal with that separately or you need to avoid an exception and return some default value, perhaps implicitly.
In general you can use the proposed solution by pylint documentation:
https://pylint.pycqa.org/en/latest/user_guide/messages/refactor/too-many-return-statements.html
But IMHO in some case it's impossible to use.
I don't kwonw your specific case, but you can disable pylint in a specific line of code using a comment like this.
def func(): #pylint: disable=R0911
# do something1
ret1 = do_something1()
if ret1 != 0:
return ret1
# do something2
ret2 = do_something2()
if ret2 != 0:
return ret2
# ......
return 0

simple string program doesent work, python

A friend of mine told me that she needs help with some homework, I owe her a favor so I said fine, why not. she needed help with a program that checks a sequence, if the sequence is made of the same 2 chars one after the other it will print "yes" (for example "ABABABAB" or "3$3$3$3:)
The program works fine with even length strings (for example "abab") but not with odd length one ("ububu")
I made the code messy and "bad" in purpose, computers is her worst subject so I don't want it to look obvious that someone else wrote the code
the code -
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 0
while i <= len(StringInput):
if i % 2 == 0:
if StringInput[i] == L1:
i = i + 1
else:
GoodOrBad = False
break
if i % 2 != 0:
if StringInput[i] == L2:
i = i + 1
else:
GoodOrBad = False
break
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
main()
I hope someone will spot the problem, thanks you if you read everything :)
How about (assuming s is your string):
len(set(s[::2]))==1 & len(set(s[1::2]))==1
It checks that there is 1 char in the even locations, and 1 char in the odd locations.
a) Showing your friend bad and messy code makes her hardly a better programmer. I suggest that you explain to her in a way that she can improve her programming skills.
b) If you check for the character at the even position and find that it is good, you increment i. After that, you check if i is odd (which it is, since you found a valid character at the even position), you check if the character is valid. Instead of checking for odd position, an else should do the trick.
You can do this using two methods->
O(n)-
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 2
while i < len(StringInput):
l=StringInput[i]
if(l==StringInput[i-2]):
GoodOrBad=True
else:
GoodOrBad=False
i+=1
if GoodOrBad == True:
print("yes")
elif GoodOrBad == False:
print("no")
main()
Another method->
O(1)-
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = set(StringInput[0::2])
L2 = set(StringInput[1::2])
if len(L1)==len(L2):
print("yes")
else:
print("no")
main()
There is a lot in this that I would change, but I am just showing the minimal changes to get it to work. There are 2 issues.
You have an off by one error in the code:
i = 0
while i <= len(StringInput):
# in the loop you index into StringInput
StringInput[i]
Say you have 5 characters in StringInput. Because your while loop is going from i = 0 to i < = len(StringInput), it is going to go through the values [0, 1, 2, 3, 4, 5]. That last index is a problem since it is off the end off StringInput.
It will throw a 'string index out of range' exception.
You need to use:
while i < len(StringInput)
You also need to change the second if to an elif (actually it could just be an else, but...) so you do not try to test both in the same pass of the loop. If you go into the second if after the last char has been tested in the first if it will go out of range again.
elif i % 2 != 0:
So the corrected code would be:
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 0
while i < len(StringInput):
if i % 2 == 0:
if StringInput[i] == L1:
i = i + 1
else:
GoodOrBad = False
break
elif i % 2 != 0:
if StringInput[i] == L2:
i = i + 1
else:
GoodOrBad = False
break
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
main()
def main():
StringInput = input('your string here - ')
MaxLength = len(StringInput) // 2 + (len(StringInput) % 2 > 0)
start = StringInput[:2]
chained = start * MaxLength
GoodOrBad = chained[:len(StringInput)] == StringInput
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
I believe this does what you want. You can make it messier if this isn't bad enough.

if statement wont take variable 'a' and 'b' when declared in python if statement

I have been curious about how to simplify my work. But for now, my
problem is how to pass variables through functions and to get this If
statement to work. The variable a and b need to pass into the if
statement to check if the string is in the array 'colors' or
'other_colors'
import random;
hot_spot=0;
colors = ['R','G','B','O','P']
other_colors =['RED','GREEN','BLUE','ORANGE','PURPLE']
guesser_array=[]
def code_maker():
code_maker_array=[]
for i in range(4):
ran = random.randint(0,4)
print (ran)
code_maker_array.append(colors[ran])
print(code_maker_array)
return code_maker_array
x = code_maker()
def code_breaker():
trys = 0;
cbi = input('please put in r,g,b,o,p or red,green,blue,orange,purple_ ')
cbi = cbi.upper()
if ( isinstance(cbi,str) == True):
print ('it is a string')
print (cbi)
for i in range(4):
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
y = code_breaker()
"""
def code_checker(x):
print (x)
code_checker(x)
"""
Try this:
import random
hot_spot=0
colors = ['R','G','B','O','P']
other_colors =['RED','GREEN','BLUE','ORANGE','PURPLE']
guesser_array=[]
def code_maker():
code_maker_array=[]
for i in range(4):
ran = random.randint(0,4)
print (ran)
code_maker_array.append(colors[ran])
print(code_maker_array)
return code_maker_array
x = code_maker()
def code_breaker():
trys = 0;
cbi = input('please put in r,g,b,o,p or red,green,blue,orange,purple_ ')
cbi = cbi.upper()
if ( isinstance(cbi,str) == True):
print ('it is a string')
print (cbi)
for i in range(4):
a=b=0 #This line added
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
y = code_breaker()
"""
def code_checker(x):
print (x)
code_checker(x)
"""
The variables a and b you have defined run out of scope as soon as their respective if blocks end. To prevent this, you can simply define them by initializing them to 0 (or any other value) outside of the if statement.
While Lucefer's answer simplified code a lot, I added this because defining variables in an outer scope like this is and modifying their values later on (in the if blocks in your case) is a very common practice, you might find it helpful somewhere else as well.
remove this whole code segment
for i in range(4):
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
just simply add
if( (cbi in other_colors) or (cbi in colors) ):
print ('yummmeiabui aebfiahfu dsdsde')

Issue with map function

Below is the hacker rank code and x is not being mapped to instance args.Can someone please provide me with a reason?https://www.hackerrank.com/challenges/python-lists/problem
if __name__ == '__main__':
N = int(input())
l=[]
for _ in range(N):
line = input().split()
cmd = line[0]
args= line[1:] # <=> here we have 0, 1 or 2 parameters, right?
"""if cmd!= "print":
cmd += "(" + ",".join(args)+")"""
#x = ",".join(map(str,args))
if len(args) == 2:
x, y = map(int, args)
if cmd == "insert":
l.insert(x, y)
elif len(args) == 1:
x = map(int,args)
if cmd == "remove":
l.remove(x)
elif cmd == "append":
l.append(x)
elif cmd == "sort":
l.sorted()
elif cmd == "pop":
l.pop()
elif cmd =="reverse":
l.reverse()
elif cmd == 'print':
print(l)
Your issue is with this line:
x = map(int,args)
This does not work like the line you have in a different branch of your code:
x, y = map(int, args)
The reason is that the first one binds the name x to the map call. It doesn't unpack the map object to get the single value it will yield. For that you'd need:
x, = map(int, args) # note the comma!
But if you know that you have only a single value in args, there's really no need to call map on it at all. Just use x = int(args[0]) instead.
You have couple of issues in your code.
By x = map(int,args) (line 16), x becomes a map object. To obtain integer from this map, first convert it into a list and then use indexing. x = list(map(int,args))[0] will solve your issue. Or you could simply use x = int(args[0]).
list has no sorted function, change l.sorted() to l.sort().

Dispatch function in python, how does the data is saved?

I'm now learning about software engineering and as a part of my studies i had to implement a dispatch function for a mutable pair type.
Here is my implementation:
def make_mutable_pair(*args):
x = None
y = None
numargs = len(args)
if (numargs == 1):
x = args[0]
elif (numargs == 2):
x = args[0]
y = args[1]
elif (numargs >= 3):
raise Exception("Too many arguements!")
else:
pass
def dispatch(msg, i=None, v=None):
if(msg == 'get'):
return get_item(i)
elif(msg == 'set'):
return set_item(i,v)
def get_item(i):
if(i == 0):
return x
elif(i == 1):
return y
else:
raise Exception("Wrong index!")
def set_item(i,v):
nonlocal x,y
if(i == 0):
x = v
elif(i == 1):
y = v
else:
raise Exception("Wrong index!")
return dispatch
I understand everything pretty well but there is something that is against everything i know in software and coding, the 'make_mutable_pair' is basically a function, here is some test i did:
test = make_mutable_pair(5,10)
print('({},{})'.format(test('get',0),test('get',1)))
test('set',0,3)
test('set',1,6)
print('({},{})'.format(test('get',0),test('get',1)))
As expected, the output will be:
(5,10)
(3,6)
What i don't understand is how the x and y are saved...
I mean from what i know, when i'm done with a function all the data in the stack memory will be deleted, and in the next call to that function i'm starting fresh.
In this case i called the function with some data for x and y, and later i changed it, and called it again, and it's still saved...
I will love to hear some explanation about it... Thanks!

Categories

Resources