I need a feedback, I don't know how to invert the result. I mean for example if I have a 289 that the result is a 982.
def numeros4s():
numero_n = int(input("ingresar un numero porfavor: "))
listax = []
listax.append(numero_n **2) #recordar siempre poner formulas dentro del parentesis
print "la raiz cuadrada de: ",numero_n," es: ",listax
numeros4s()
number = 123
int("".join(reversed(str(number))))
# 321
>>> num = 289
>>> reversed_num = int(str(num)[::-1])
>>> reversed_num
982
If you just want to reverse a number, that would be this:
n = 289
n_str = str(n)
print(''.join(reversed(n_str)))
Another way
def reverse(num):
result = 0
while num > 0:
result = result * 10 + num % 10
num /= 10
return result
print(reverse(18539)) # --> 93581
Related
So i have been working on this code for a while and i cant fin a solution to this problem and i was wondering if anyone in here could help me solve this? The problem is supposed to be in the method "hent_celle" where it takes in a coordinate from a grid and returns the object that is in that position.
The error is:
Traceback (most recent call last):
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 105, in <module>
print(testobjekt._sett_naboer(2,1))
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 64, in
_sett_naboer nabo_u_kol = self.hent_celle(rad+1,kol)
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 43, in hent_celle
return self._rutenett[rad][kol] IndexError: list index out of range
And the code is:
from random import randint
from celle import Celle
class Rutenett:
def init(self,rader,kolonner):
self._ant_rader = int(rader)
self._ant_kolonner = int(kolonner) self._rutenett = []
def _lag_tom_rad(self):
liste = []
for x in range(self._ant_kolonner):
liste.append(None)
return liste
def _lag_tomt_rutenett(self):
liste2 = []
for x in range(self._ant_rader):
liste_ = self._lag_tom_rad()
liste2.append(liste_)
self._rutenett = liste2
def lag_celle(self,rad,kol):
celle = Celle()
tilfeldig_tall = randint(0,100)
if tilfeldig_tall <= 33:
celle.sett_levende()
return celle
else:
return celle
def fyll_med_tilfeldige_celler(self):
for x in self._rutenett:
for y in x:
rad = int(self._rutenett.index(x))
kol = int(x.index(y))
self._rutenett[rad][kol] = self.lag_celle(rad,kol)
def hent_celle(self,rad,kol):
if rad > self._ant_rader or kol > self._ant_kolonner or rad < 0 or kol < 0:
return None
else:
return self._rutenett[rad][kol]
def tegn_rutenett(self):
for x in self._rutenett:
for y in x:
print(y.hent_status_tegn(), end="")
def hent_alle_celler(self):
liste = []
for x in self._rutenett:
for y in x:
liste.append(y)
return liste
def _sett_naboer(self,rad,kol):
cellen = self.hent_celle(rad,kol)
# lik linje
nabo_v_rad = self.hent_celle(rad,kol-1)
nabo_h_rad = self.hent_celle(rad,kol+1)
# under
nabo_u_kol = self.hent_celle(rad+1,kol)
nabo_u_kol_h = self.hent_celle(rad+1,kol+1)
nabo_u_kol_v = self.hent_celle(rad+1,kol-1)
# over
nabo_o_kol = self.hent_celle(rad-1,kol)
nabo_o_kol_h = self.hent_celle(rad-1,kol+1)
nabo_o_kol_v = self.hent_celle(rad-1,kol-1)
liste = [nabo_v_rad,nabo_h_rad,nabo_u_kol_h,nabo_u_kol_v,nabo_o_kol,nabo_o_kol_h,nabo_o_kol_v]
#print(liste)
#print(nabo_o_kol_h)
for x in liste:
if x == None:
pass
else:
cellen._naboer.append(x)
return cellen._naboer
def antall_levende(self):
teller = 0
for x in self._rutenett:
for y in x:
if y._status == "doed":
pass
else:
teller +=1
return teller
testobjekt = Rutenett(3,3)
testobjekt._lag_tomt_rutenett()
testobjekt.fyll_med_tilfeldige_celler()
print(testobjekt._sett_naboer(2,1))
I just cant figure out why the list index is out of range
Pyhton list indexes start at 0, which means a list with 10 elements will use indices 0-9. Assuming self._ant_rader and self._ant_kolonner are the number of rows and columns, then rad and kol would need to be less than those values and cannot be the same value, or you get an index out of bounds error.
Fixed version of the method:
def hent_celle(self,rad,kol):
if rad >= self._ant_rader or kol >= self._ant_kolonner or rad < 0 or kol < 0:
return None
else:
return self._rutenett[rad][kol]
As you can see, the > has been replaced with >= instead. This means indices which are out of bounds will return None.
VALOR_VETOR = 6
nota1 = []
nota2 = []
nota3 = []
mediaAluno = []
soma1 = 0
soma2 = 0
soma3 = 0
somaMedia = 0
mediaTurma = 0
print("Digite as notas dos alunos\n\n")
for i in range (VALOR_VETOR):
print(f"Aluno {i}")
valor = float(input(f"Nota 1: "))
nota1.append(valor)
valor = float(input(f"Nota 2: "))
nota2.append(valor)
valor = float(input(f"Nota 3: "))
nota3.append(valor)
valor = (nota1 + nota2 + nota3)/3
mediaAluno.append(valor)
print (f"Nota final = {mediaAluno[i]:.1f}")
for i in range (VALOR_VETOR):
soma1 = soma1 + nota1
soma2 = soma2 + nota2
soma3 = soma3 + nota3
somaMedia = somaMedia + mediaAluno
mediaProva1 = soma1/VALOR_VETOR
print(f"A media da primeira prova é = {mediaProva1:.1f}")
mediaProva2 = soma2/VALOR_VETOR
print(f"A media da segunda prova é = {mediaProva2:.1f}")
mediaProva3 = soma3/VALOR_VETOR
print(f"A media da primeira prova é = {mediaProva1:.1f}")
mediaTurma = somaMedia/VALOR_VETOR
I am a python learner
try, searched, but could not do.
please help me.
line 23, in
valor = (nota1 + nota2 + nota3)/3
TypeError: unsupported operand type(s) for /: 'list' and 'int'
When you use the '+' operator with lists it will return a list with all the 3
lists concatenated
for example:
l1 = [1,2]
l2 = [5,7]
l = l1 + l2 # [1,2,5,4]
I think you expect to get l =[6,9]
also the operator '/' is not defined for a list
so l/3 will return an error
if you want to to sum individual elements in a list you can use below code
i used for loop for clarity but you can use list comprehension or lambda or ...
l =[]
for i in range(len(l1)):
l.append(l1[i] + l2[i])
""" to make the division we can use the same for loop or make another
loop"""
for x in range(len(l)):
l[x] = l[x]/3
valor = (nota1 + nota2 + nota3)/3 //error
try this line of code as:
valor=(sum(nota1)+sum(nota2)+sum(nota3))/3 //it should work
I am working on a homework program, where I need to create a matrix, I did the function that takes an array with some records (that I previously create) as a parameter, but when I create a high number of records, for instance: 100 records, I get the list index out of range
array creation:
def crearVector(n):
vec = [None] * n
for i in range(len(vec)):
codigo = random.randint(1, 1000)
precio = round(random.uniform(1, 100000), 2)
ubicacion = random.randint(1, 23)
estado = random.randint(0, 1)
cantidad = random.randint(0, 1000)
puntuacion = random.randint(1, 5)
publicacion = Publicacion(codigo, precio, ubicacion, estado, cantidad, puntuacion)
vec[i] = publicacion
return vec
array creation function calling:
def test():
n = validateHigherThan(0)
vec = crearVector(n)
matrix creation and showing function:
mat = crearMatriz(vec)
forma = int(input("How would you like to show the matrix?(0: matrix, 1: list): "))
if forma == 1:
mostrarMatrizLista(mat)
elif forma == 0:
mostrarMatriz(mat)
matrix creation:
def crearMatriz(vec):
mat = [[0] * 5 for i in range(23)]
for i in range(len(vec)):
fil = vec[i].ubicacion
col = vec[i].puntuacion-1
mat[fil][col] += 1
return mat
You create a matrix of 23 * 5
fil = vec[i].ubicacion
should be
fil = vec[i].ubicacion-1
since ubicacion can have random numbers from 1 to 23.
Better yet you could use global variables to define those parameters instead of hardcoding them in both functions.
col_limit = 5
fil_limit = 23
def crearVector(n):
vec = [None] * n
for i in range(len(vec)):
codigo = random.randint(1, 1000)
precio = round(random.uniform(1, 100000), 2)
ubicacion = random.randint(1, fil_limit)
estado = random.randint(0, 1)
cantidad = random.randint(0, 1000)
puntuacion = random.randint(1, col_limit)
vec[i] = Publicacion(codigo, precio, ubicacion, estado, cantidad, puntuacion)
return vec
def crearMatriz(vec):
mat = [[0] * col_limit for i in range(fil_limit)]
for i in range(len(vec)):
fil = vec[i].ubicacion - 1
col = vec[i].puntuacion- 1
mat[fil][col] += 1
return mat
I believe you're missing a -1 on the ubicacion for your fil column on the matrix. Please see the code below. Be careful when you define columns that start with 0s.
# ubicacion = random.randint(1, 23) (range is 1 to 23)
def crearMatriz(vec):
mat = [[0] * 5 for i in range(23)]
for i in range(len(vec)):
fil = vec[i].ubicacion-1 # <- this -1 is what you were missing, when ubicacion = 23 list goes out of range.
col = vec[i].puntuacion-1
mat[fil][col] += 1
return mat
Also, I assume your program does not really need legibility as much, since it is a homework assignment, however, using some variables to help you define your max ranges is useful to help you debug, eg.
import random
CODIGO_MAX = 1000
PRECIO_MAX = 100000
UBICACION_MAX = 23
ESTADO_MAX = 1
CANTIDAD_MAX = 1000
PUNTUACION_MAX = 5
def crearVector(n):
vec = [None] * n
for i in range(len(vec)):
codigo = random.randint(1, CODIGO_MAX)
precio = round(random.uniform(1, PRECIO_MAX), 2)
ubicacion = random.randint(1, UBICACION_MAX)
estado = random.randint(0, ESTADO_MAX)
cantidad = random.randint(0, CANTIDAD_MAX)
puntuacion = random.randint(1, PUNTUACION_MAX)
publicacion = Publicacion(codigo, precio, ubicacion, estado, cantidad, puntuacion)
vec[i] = publicacion
return vec
def crearMatriz(vec):
mat = [[0] * PUNTUACION_MAX for i in range(UBICACION_MAX)]
for i in range(len(vec)):
fil = vec[i].ubicacion-1
col = vec[i].puntuacion-1
mat[fil][col] += 1
return mat
crearMatriz(crearVector(1000))
How can I convert a number with a decimal part to the simple precision system of the IEEE-754 in python in such a way that I enter the number and I throw the standard sign, exponent and mantissa?
Example Input: 10.27
Example Output: 0 10000011 01001000101000111101011
Sign-Exponent-Mantissa
Here is my attempt to solve the problem.
# Conversion de Decimal a Binario con parte fraccionaria
def float_bin(num, dig=23):
# split() separa la parte entera de la parte decimal
# Despues de separarlas las asignas a dos variables distintas
ent, dec = str(num).split(".")
# Convert both whole number and decimal
# Cambia el tipo de dato de un string a un entero
ent = int(ent)
dec = int(dec)
# Convierte la parte entera a su respectivo forma binaria el "Ob" es removido con el metodo strip
res = bin(ent).lstrip("0b") + "."
# Itera el numero de veces dependiendo de numero de posiciones decimales que se buscan
for x in range(dig):
# Multiplica la parte fraccionaria por 2 y se separa la parte entera de la parte decimal para repetir el proceso
ent, dec = str((decimal_conv(dec)) * 2).split(".")
# Se convierte la parte fraccionaria a un entero de nuevo
dec = int(dec)
# Keep adding the integer parts
# receive to the result variable
res += ent
return res
# Function converts the value passed as
# parameter to it's decimal representation
def decimal_conv(num10):
while num10 > 1:
num10 /= 10
return num10
# Take the user input for
# the floating point number
n = input("Ingrese su numero de punto flotante : \n")
# Take user input for the number of
# decimal places user want result as
p = int(input("Ingrese el numero de posiciones decimales para el resultado: \n"))
print(float_bin(n, dig=p))
while True:
ParteSigno = input("Ingresa el signo: ")
ParteEntera = list(input("Ingresa la parte entera: "))
ParteDecimal = list(input("Ingresa la parte decimal: "))
if (ParteSigno == '-'):
signo = 1
else:
signo = 0
Recorrido = []
Topepunto = 0
sacador = 0
saca = 0
cont = 0
if '1' in (ParteEntera):
Topepunto = len(ParteEntera) - 1
ExpPar = 127 + Topepunto
ExpBina = bin(ExpPar)
ExpobinList = []
mantisalncom = ParteEntera + ParteDecimal
mantisalncom.reverse()
parte = mantisalncom.pop()
mantisalncom.reverse()
while len(mantisalncom) < 23:
mantisalncom.extend("0")
for i in ExpBina:
ExpobinList.append(i) #El metodo append añade un elemento a la lista
ExpobinList = (ExpobinList[2:])
if len(ExpobinList) < 8:
ExpobinList.reverse()
while len(ExpobinList) <= 8:
ExpobinList.extend('0')
ExpobinList.reverse()
else:
mantisalncom = ParteEntera + ParteDecimal
ParteDecimal.reverse()
mantisalncom.reverse()
while cont == 0:
parte = mantisalncom.pop()
if parte == '0' and cont == 0:
cont = 0
elif parte == '1' and cont == 0:
cont = cont + 1
mantisalncom.reverse()
while len(mantisalncom) < 23:
mantisalncom.extend('0')
while len(ParteDecimal) > 0:
Reco = ParteDecimal.pop()
if (Reco == '0' and sacador == 0):
Recorrido.extend(Reco)
sacador = 0
else:
sacador = sacador + 1
Topepunto = len(Recorrido) + 1
Topepunto = Topepunto * (-1)
ExpPar = 127 + Topepunto
ExpBina = bin(ExpPar)
ExpobinList = []
for i in ExpBina:
ExpobinList.append(i)
ExpobinList = (ExpobinList[2:])
if len(ExpobinList) < 8:
ExpobinList.reverse()
while len(ExpobinList) < 8:
ExpobinList.extend('0')
ExpobinList.reverse()
print("\n\nSigno\t\tExponente\t\t\t\t\t\t\t\tMantisa\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t")
print("", signo, "", ExpobinList, mantisalncom)
From your description ucyos answer is what you are looking for:
def float_to_bin(num):
bits, = struct.unpack('!I', struct.pack('!f', num))
return "{:032b}".format(bits)
print(float_to_bin(10.27))
# 01000001001001000101000111101100
Here is an example for ieee745 32b-format:
def ieee745(N): # ieee-745 bits (max 32 bit)
a = int(N[0]) # sign, 1 bit
b = int(N[1:9],2) # exponent, 8 bits
c = int("1"+N[9:], 2)# fraction, len(N)-9 bits
return (-1)**a * c /( 1<<( len(N)-9 - (b-127) ))
N = "110000011010010011" # str of ieee-745 bits
print( ieee745(N) ) # --> -20.59375
What you want to do is use struct pack and unpack with !f >f or <f.
This code works for 32 bit floating point numbers.
for reference look at: https://docs.python.org/3/library/struct.html
Character
Byte order
Size
Alignment
#
native
native
native
=
native
standard
none
<
little-endian
standard
none
>
big-endian
standard
none
!
network (big-endian)
standard
none
For 64 bit floating point numbers use d in stead of f
import struct
def from_bytes(b):
return struct.unpack('!f', b)[0]
def from_hex(h):
return from_bytes(bytes.fromhex(h))
def from_bin(b):
return struct.unpack('!f', int(b, 2).to_bytes(4, byteorder='big'))[0]
def to_bytes(f):
return struct.pack('!f', f)
def to_hex(f):
return to_bytes(f).hex()
def to_bin(f):
return '{:032b}'.format(struct.unpack('>I', struct.pack('!f', f))[0])
assert from_hex('c4725c44') == -969.441650390625
assert from_bin('11000100011100100101110001000100') == -969.441650390625
assert from_bytes(b'\xc4r\\D') == -969.441650390625
assert to_hex(-969.441650390625) == 'c4725c44'
assert to_bin(-969.441650390625) == '11000100011100100101110001000100'
assert to_bytes(-969.441650390625) == b'\xc4r\\D'
Basically in the last for loop the k variable uses the number of items in the list and then I have a false and unique answer rather than multiple answers I want to do some sort of n roots of a complex number (if my question isn't clear sorry i'm not a native english speaker I'll do my best to make it clearer)
from math import *
deg = int(input("entrez le degré:"))
re = int(input("le réel:"))
im = int(input("l'imaginaire:"))
counter = 0
while counter < deg:
counter = counter + 1
kkk = []
kkk.append(counter)
r = sqrt(pow(re,2)+pow(im,2))
if im != 0:
teton = round(pi/radians(degrees(acos(re/r))),1)
else:
teton = round(pi/radians(degrees(acos(im/r))),1)
if round(r) != r:
r = "sqrt(",(pow(re,2)+pow(im,2)),")"
else:
r = r
teta = "pi/%s" %teton
print("z = ",r,"e^i",teta,)
for k in kkk:
if re != 0 or im != 0:
print(r,"e^i*2*",teta,"*",k,"pi")
else:
print(r,"^1/",deg,"e^i(",teta,"/",deg," +(2",k,"pi)/",deg)
print(k)
If I understood the problem correctly, you are saying that for loop is not iterating over all the items in the list kkk.
if you check your code the list kkk always have only one item as you are initializing and appending item in same loop.
please move below statement out of the first loop.
kkk = []
like below.
from math import *
deg = int(input("entrez le degré:"))
re = int(input("le réel:"))
im = int(input("l'imaginaire:"))
counter = 0
kkk = []
while counter < deg:
counter = counter + 1
kkk.append(counter)
r = sqrt(pow(re,2)+pow(im,2))
if im != 0:
teton = round(pi/radians(degrees(acos(re/r))),1)
else:
teton = round(pi/radians(degrees(acos(im/r))),1)
if round(r) != r:
r = "sqrt(",(pow(re,2)+pow(im,2)),")"
else:
r = r
teta = "pi/%s" %teton
print("z = ",r,"e^i",teta,)
for k in kkk:
if re != 0 or im != 0:
print(r,"e^i*2*",teta,"*",k,"pi")
else:
print(r,"^1/",deg,"e^i(",teta,"/",deg," +(2",k,"pi)/",deg)
print(k)