I'm trying to write a function that finds both the signed/unsigned max/min values given a bit length. But every time I execute the function I get an error, here is my code
#function to find max and min number of both signed and unsigned bit values
def minmax (n) :
for numbers in n :
unsignedmax = (2**n)-1
unsignedmin = 0
signedmax = 2**(n-1)-1
signedmin = -2**(n-1)
print "number ", "unsigned ", "signed"
#Main
bitlist = [2, 3, 8, 10, 16, 20, 32]
minmax(bitlist)
the error is
Traceback (most recent call last):
File "C:/Users/Issac94/Documents/Python Files/sanchez-hw07b.py", line 23, in <module>
minmax(bitlist)
File "C:/Users/Issac94/Documents/Python Files/sanchez-hw07b.py", line 6, in minmax
unsignedmax = (2**n)-1
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'list'
>>>
I wasn't done writing it but ran it to make sure there was no error in the logic part but i get that one error when trying to find the values. Is there maybe a way to insert int() or something similar to have the number be treated as type integer and not tyle list which im assuming is happening?
Change the method definition and first line to this:
def minmax (numbers) :
for n in numbers :
That is, in these two lines, replace 'n' with 'numbers' everywhere it appears and replace 'numbers' with 'n' where it appers.
As you have it written the variable "numbers" holds the item in the list you want to process and the variable "n" is holding the list. But the rest of your code is written with the reverse assumption.
Related
Trying to take strings from my networkx dict and append them to a certain place within an array:
def sameSports(node1, node2, G):
A = [G.node[node1]['sport1'], G.node[node1]['sport2'], G.node[node1]['sport3']]
B = [G.node[node2]['sport1'], G.node[node2]['sport2'], G.node[node2]['sport3']]
sharedSports = np.intersect1d(A,B)
sharedSports = np.delete(sharedSports, np.where(sharedSports == 'N/A'))
return sharedSports
def meetingDay(sharedSports,rightAxis):
meetingDays = [[] for i in range (len(sharedSports))]
columns=['Monday','Tuesday','Wednesday','Thursday','Friday']
for i in range (0,5):
for t in sharedSports:
n=np.where(sharedSports==t)
meetingDays[n].append(t)
if t in rightAxis[i]:
meetingDays[n].append(columns[i])
return meetingDays
The G.node[n]['sport'] dicts return single letter strings 'A'-'W', and the rightAxis array is a 5-section array containing some of the same letters. Getting this error:
Traceback (most recent call last):
File ".\main.py", line 18, in
a,b=add_sport_to_edges(G , rightAxis)
File "C:\Users\rjtkr\OneDrive\Documents\Work\Summer 2020 Research\epidemic\Athletics Network\sportsnetwork.py", line 99, in add_sport_to_edges
temp = meetingDay(sharedSports, rightAxis)
File "C:\Users\rjtkr\OneDrive\Documents\Work\Summer 2020 Research\epidemic\Athletics Network\sportsnetwork.py", line 90, in meetingDay
meetingDays[n].append(t)
TypeError: list indices must be integers or slices, not tuple
Unsure if it's 'n' or 't' that it doesn't like, but fairly sure that neither is a tuple. Hopefully I included all relevant code. The other lines showing up in the error come after the attached code, and the error remains the same when they are removed.
i need to find the smallest difference between numbers in a list.
For some reason it doesnt work when i input numbers in the console, and i get this error TypeError: unsupported operand type(s) for -: 'str' and 'str'
def najmanja_razlika(): #smallest_diff
a=input('unesite brojeve liste')
b=len(a)
razlika=10**20 #difference
for i in range(b-1):
for j in range(i+1,b):
if int(abs(a[i]-a[j]))<razlika:
razlika=abs(a[i]-a[j])
return razlika
print(str(najmanja_razlika()))
What i get when i run this is:
unesite brojeve liste5,4,9,3
Traceback (most recent call last):
File "C:/Users/Nina/PycharmProjects/klkOR/klk4.py", line 19, in <module>
print(str(najmanja_razlika()))
File "C:/Users/Nina/PycharmProjects/klkOR/klk4.py", line 11, in najmanja_razlika
if int(abs(a[i]-a[j]))<razlika:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
You did not convert the string input into an int or float, you might like to do something like this.
def najmanja_razlika(): #smallest_diff
a=[int(i) for i in input('unesite brojeve liste').split(',')]
b=len(a)
razlika=10**20 #difference
for i in range(b-1):
for j in range(i+1,b):
if int(abs(a[i]-a[j]))<razlika:
razlika=abs(a[i]-a[j])
return razlika
print(str(najmanja_razlika()))
Also, note that indentation matters in Python.
This is the output that I obtained:
unesite brojeve liste5,4,2,9,6
1
By the way, if you sort your vector first, you reduce the complexity from O(n^2) to O(nlogn).
If you have numpy installed you could use it to efficiently compute the minimum difference (it is always faster than pure Python loops). I would also use json (part of the standard library, no need to install it) to parse the input string.
import json
import numpy as np
def min_difference():
input_string = '[' + input('Enter comma-separated numbers: ') + ']'
a = np.array(json.loads(input_string))
mask = ~np.eye(a.shape[0], dtype=bool)
return np.abs(a[:, None] - a[None, :])[mask].min()
import sys
def func():
T = int(next(sys.stdin))
for i in range(0,T):
N = int(next(sys.stdin))
print (N)
func()
Here I am taking input T for for loop and iterating over T it gives Runtime error time: 0.1 memory: 10088 signal:-1 again-again . I have tried using sys.stdin.readline() it also giving same error .
I looked at your code at http://ideone.com/8U5zTQ . at the code itself looks fine, but your input can't be processed.
Because it is:
5 24 2
which will be the string:
"5 24 2"
this is not nearly an int, even if you try to cast it. So you could transform it to the a list with:
inputlist = next(sys.stdin[:-2]).split(" ")
to get the integers in a list that you are putting in one line. The loop over that.
After that the code would still be in loop because it want 2 integers more but at least you get some output.
Since I am not totally shure what you try to achieve, you could now iterate over that list and print your inputs:
inputlist = next(sys.stdin[:-2]).split(" ")
for i in inputlist
print(i)
Another solution would be, you just put one number per line in, that would work also
so instead of
5 24 2
you put in
5
24
2
Further Advice
on Ideone you also have an Error Traceback at the bottom auf the page:
Traceback (most recent call last):
File "./prog.py", line 8, in <module>
File "./prog.py", line 3, in func
ValueError: invalid literal for int() with base 10: '1 5 24 2\n'
which showed you that it can't handle your input
EDIT: SOLVED--SOURCE CODE HERE: http://matthewdowney20.blogspot.com/2011/09/source-code-for-roku-remote-hack.html
thanks in advance for reading and possibly answering this. So I have a slice of code that looks like this (the commands Down() Select() and Up() are all predefined):
def c1(row):
row_down = row
row_up = row
while row_down > '1':
Down()
row_down = row_down - 1
time.sleep(250)
Select()
time.sleep(.250)
while row_up > '1':
Up()
row_up = row_up - 1
time.sleep(250)
So when I run this with either c1('3') or c1(3) (not jut 3, any number does this) it stops responding, no error or anything, but it executes the first Down() command, and it doesnt seem to get past the row_down = row_down - 1 . So i figure maybe it is stuck on time.sleep(.250), because it isnt executing the Select(), so if i remove time.sleep(.250) from the code i get an error like this:
Traceback (most recent call last):
File "test.py", line 338, in <module>
c1('3')
File "test.py", line 206, in c1
row_down = row_down - 1
TypeError: unsupported operand type(s) for -: 'str' and 'int'
this code snippet is part of a larger program designed for controlling the roku player from a computer, and so far everything has worked but this, which is to automate the typing in the search field, so that you do not have to continually scroll until you find a letter and select. c1(row) would be column 1 row x, if any of you would like the source code for the program over all, i would be happy to send it out. Anyway thanks for listening.
Perhaps you meant
while row_down > 1:
(note 1 is written without quotes). If so, call c1 with c1(3) not c1('3').
Also, in CPython (version 2, but not version 3) integers are comparable to strings, but the answer is not what you might expect:
3 > '1'
# False
When comparing any integer to any string, the integer is always less than string because (believe it or not!) i (as in integer) comes before s (as in string) in the alphabet.
As TokenMacGuy has already pointed out, addition of integers with strings raises a TypeError:
'3' - 1
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
This might explain the error you are seeing when calling c1('3').
>>> x = raw_input('enter a number: ')
enter a number: 5
>>> x
'5'
>>> type(x)
<type 'str'>
>>> x + 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> type(int(x))
<type 'int'>
>>> int(x) + 5
10
>>>
(if you're using python3, use input instead of raw_input)
I suspect that the loop is running with out error because you can subtract from a character to change it: "b - 1 = a". (read edit) It also doesn't error is because, like Marcelo Cantos said in his comment, the first time.sleep is for 250 seconds, not .250 seconds. The error when you remove the time.sleep might be coming up when you subtract past the the ASCII character range since it runs through the loop a lot quicker without the time.sleep.
I hope that helps!
Edit: Actually, I think what I said works in C or something. In python, it doesn't work. The other stuff I said might shed some light though!
I'm trying to simulate a substring in Python but I'm getting an error:
length_message = len(update)
if length_message > 140:
length_url = len(short['url'])
count_message = 140 - length_url
update = update["msg"][0:count_message] # Substring update variable
print update
return 0
The error is the following:
Traceback (most recent call last):
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 54, in <module>
x.updateTwitterStatus({"url": "http://xxx.com/?cat=49s", "msg": "Searching for some ....... tips?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffff "})
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 35, in updateTwitterStatus
update = update["msg"][0:count_message]
TypeError: string indices must be integers
I can't do this?
update = update["msg"][0:count_message]
The variable "count_message" return "120"
Give me a clue.
Best Regards,
UPDATE
I make this call, update["msg"] comes from here
x = TwitterC()
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=49", "msg": "Searching for some ...... ....?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffffddddddddddddddddd"})
Are you looping through this code more than once?
If so, perhaps the first time through update is a dict, and update["msg"] returns a string. Fine.
But you set update equal to the result:
update = update["msg"][0:int(count_message)]
which is (presumably) a string.
If you are looping, the next time through the loop you will have an error because now update is a string, not a dict (and therefore update["msg"] no longer makes sense).
You can debug this by putting in a print statement before the error:
print(type(update))
or, if it is not too large,
print(repr(update))