program in binary to decimal in python using array list - python-3.x

Hi I'm new to programming and have a project to create a program to convert binary to decimal in Python. I have to make use of the values stored in the list and multiply based on user input. I keep getting errors regarding int/str. Any help would be appreciated.Please see code below of what I have so far.
denaryNumber = 0
binaryNumber = input("Please enter binary number: ")
placeValues = [128, 64, 32, 16, 8, 4, 2, 1]
for i in range(0, len(binaryNumber) -1):
denaryNumber = denaryNumber + (binaryNumber(i) * placeValues[i])
print (denaryNumber)

There are a few issues in your code.
Every input by default in python is taken in as 'str' , so your binaryNumber is str
To access an element from a list, you use[] not () as you have used here: binaryNumber(i)
Since your binary number is str you cant apply mathematical operations on str , so binaryNumber(i) * placeValues[i] is invalid. You need to type-cast str to int like this : int(binaryNumber[i])
So change your 2nd last line to this:
denaryNumber = denaryNumber + (int(binaryNumber[i]) * placeValues[i])
It would work then.
jbtw, your code would return correct results only if your input is 8bits.

Related

How to iterate through numbers greater than a given number

So I am trying to solve a problem, where a user will input a number and you have to find the next number that has all unique digits. For example:
Input: 1987, Output:
2013
Input:
999, Output:
1023
The way I thought of tackling this question was to go through every number after the number given by the user until I find a number that has all unique digits.
My question is that is there a way to check through every whole number greater than a number given. Until I find a specific one. So this is without a list or range. Just want to check every number until I find a specific type. Would I have to use a for loop or something similar.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
num = 5
given = 10
new = [i for i in arr if i >= num and i <= given]
i dont know if this is what you wanted you did not specify it.
The beginner way - while True loop
i = int(input()) + 1
while True:
if digits_are_unique(i): # Undefined
break
i += 1
print(i)
The pro way - itertools.count()
import itertools
i = int(input()) + 1
for i in itertools.count(i):
if digits_are_unique(i): # Undefined
break
print(i)
Assignment expression - new in Python 3.8
Right now Python 3.8 is in beta and I don't have the interpreter to test this with, but it should work.
i = int(input()) + 1
while i := i + 1:
if digits_are_unique(i): # Undefined
break
print(i)

How can I fix my program, it always show TypeError no matter how I change the type of the object?

I recently wrote a piece of code (an decryptor) to convert the result to a specific number (I took inspiration from Shamir's Secret Scheme, which uses Lagrange Polynomials as core). I previously wrote another program, which changes the secret into 'pieces', and now I stuck at converting 'pieces' into the secret again.
This is what I wrote:
x_values = []
y_values = []
while -1 not in x_values:
adder = int(input('Enter x value (Enter "-1" to end): '))
x_values.append(adder)
else:
x_values.pop()
while len(y_values) != len(x_values):
adder = input('Enter y value: ')
adder = int(adder, 16)
y_values.append(adder)
S = 0
for i in range(len(x_values)):
x_other = x_values
x_current = x_other.pop(i)
y_other = y_values
y_current = y_other.pop(i)
num = y_values[i]
for a in x_current:
num *= -a
den = 1
for a in x_current:
den *= (x_values[i] - x_current[a])
S += (num / den)
print('Secret: ', S)
input()
When I run it, it shows:
File "C:\Python Code\Decryptor.py", line 37, in <module>
for a in x_current:
TypeError: 'int' object is not iterable
I have read many articles about this problem but I couldn't fix it. Could you help me with this? Thanks in advance!
EDIT: Thank you everyone for helping me with my problem. I’ve finally managed to fix this and the program worked like a charm.
When you call pop method on a python list, it removes the entered index element from the list and then returns that element.
So x_current variable in first iteration is an integer with value equal to 1(In the example list: x_values = [1, 2, 3, 4]).
So the second for loop is incorrect, Because you trying to loop in an integer that is not possible. So If you want to iterate in a list that contains every elements except that has been poped, you should replace second loop with following:
for a in x_other:
Otherwise you should loop in range of x_current.
If you still have problems, you can leave a comment to notice me.

Groovy: String to integer array

Im coding in Groovy and I have a string parameter "X" which looks like this:
899-921-876-123
For now i succesfully removed the "-" from it by
replaceAll("-", "")
And now I want to divide this String into separete numbers - to an array, like (8,9,9...) to make some calculations using those numbers. But somehow I cannot split() this String and make it an Integer at the same time like that:
assert X.split("")
def XInt = Integer.parseInt(X)
So then when Im trying something like:
def sum = (6* X[0]+ 5 * X[1] + 7 * X[2])
I get an error that "Cannot find matching method int#getAt(int). Please check if the declared type is right and if the method exists." or "Cannot find matching method int#multiply(java.lang.String). Please check if the declared type is right and if the method " if im not converting it to Integer...
Any idea how can I just do calculations on separate numbers of this string?
def X = '899-921-876-123'
def XInt = X.replaceAll(/\D++/, '').collect { it as int }
assert XInt == [8, 9, 9, 9, 2, 1, 8, 7, 6, 1, 2, 3]
assert 6* XInt[0]+ 5 * XInt[1] + 7 * XInt[2] == 6* 8+ 5 * 9 + 7 * 9
the replaceAll removes all non-digits
the collect iterates over the iterable and converts all elements to ints
a String is an iterable of its characters
Given you already just have a string of numbers:
"123"*.toLong() // or toShort(), toInteger(), ...
// ===> [1, 2, 3]
If found #cfrick approach the most grooviest solution.
This makes it complete:
def n = "899-921-876-123".replaceAll("-", "")
print n*.toInteger()

Python convert string to variable name

Im aware that this may come up as a duplicate but so far I haven't found (or should that be understood) an answer to what Im looking for.
I have a list of strings and want to convert each one into a variable name which I then assign something to. I understand that I may need a dict for this but I am unfamiliar with them as I am relatively new to python and all the examples I have seen so far deal with values whilst I'm trying something different.
Im after something like:
list = ['spam', 'eggs', 'ham']
for i in range(len(list)):
list[i] = rat.readColumn(ratDataset, list[i])
where the first list[i] is a variable name and not a string. The second list[i] is a string (and for context is the name of a column Im reading from a raster attribute table (rat))
Essentially I want each string within the list to be set as a variable name.
The idea behind this is that I can create a loop without having to write out the line for each variable I want, with matching rat column name (the string). Maybe there is a beer way of doing this than I am suggesting?
Try the following:
lst = ['spam', 'eggs', 'ham']
d = {} # empty dictionary
for name in lst:
d[name] = rat.readColumn(ratDataset, name)
Do not use list for your identifiers as it is a type identifier and you would mask its existence. The for loop can iterate directly for the elements inside -- no need to construct index and use it aganist the list. The d['spam'] will be one of your variables.
Although, it is also possible to create the real variable names like spam, eggs, ham, you would not probably do that as the effect would be useless.
Here comes a simple dictionary use :
variables = ['spam', 'eggs', 'ham']
data = {}
datum = 0
for variable in variables:
data[variable] = datum
datum+=1
print(data)
print("value : ",data[variables[2]])
It gives as result :
{'eggs': 1, 'ham': 2, 'spam': 0}
value : 2
NB : don't use list as a variable name, list is a type identifier that you can use to transform an object into a list if possible (list("abc")==['a', 'b', 'c']) and you are overriding it with your value list right now.
one way is setting the variable name as a string and changing a part or all of it via format() method and then using the string as a varibale via vars()[STRING]
import numpy as np
X1= np.arange(1,10)
y1=[i**2 for i in X1]
X2= np.arange(-5,5)
y2=[i**2 for i in X2]
for i in range(1,3):
X = 'X{}'.format(i)
y = 'y{}'.format(i)
print('X_{}'.format(i) , vars()[X])
print('y_{}'.format(i) , vars()[y])
Output:
X_1 [1 2 3 4 5 6 7 8 9]
y_1 [1, 4, 9, 16, 25, 36, 49, 64, 81]
X_2 [-5 -4 -3 -2 -1 0 1 2 3 4]
y_2 [25, 16, 9, 4, 1, 0, 1, 4, 9, 16]

How I add values in a list I am using as the parameter for a function?

I am trying to understand these instructions.
Set up a new function in your main program file named “summer” that takes a list as a parameter and returns a value we will determine in the next steps.
In the “summer” function, set up a loop that uses a counter variable named “n” that will take on the values 0, 2, 4, 6, 8, 10, 12.
Each time through the loop, you are to call your “powerval” function from the “mymath” module passing as parameters item “n” and “n+1” from the list of data passed into “summer”. Add up all these values and return the final result to the caller.
So far I have:
def summer(list):
for n in range(0,13,2):
value=powerval(n,n+1)
After that I am lost. How do i perform step 3?
You add them up:
from mymath import powerval
def summer(somelist):
sum = 0
for n in range(0, 13, 2):
sum += powerval(somelist[n], somelist[n + 1])
return sum
So the return value of powerval() is added to the total sum so far, which was started at 0. You do need to pass in the somelist[n] and somelist[n + 1] values, not the indices themselves.
You need to add them up:
from mymath import powerval
def summer(lst):
total = 0
for n in range(0, 13, 2):
total += powerval(lst[n], lst[n + 1])
return total
I'm not sure where you use lst (I renamed list to lst, as list is a built-in function), so I'm guessing you're trying to get the nth and n + 1th elements from that list.
You can use the sum method to accomplish this in a very fashionable way :)
def summer(myList):
return sum(powerval(myList[n], myList[n+1]) for n in range(0, 13, 2))
This is also the fastest way.
PS: It's not a good idea to name you list "list", bacause that's a reserved name in python. That's why I have renamed it to myList in the example above.

Resources