why does my BIP39 seed generation doesnt work? - python

i'm trying to code a BIP39 wallet, i've generated my entropy and followed the steps to generate the seed...
Here's my code:
import os
import string
import binascii
from binascii import hexlify
import hashlib
import unicodedata
import secrets
import random
bits = 128
print("Bytes = " + str(bits//8))
N = 64
def main():
nb_mots = ask_nb_mot()
nb_total_bit = nb_mots * 11
nb_bits_generes = nb_total_bit - checksum
entropie = ask_entropie(nb_bits_generes)
checksum = nb_mots // 3
def ask_nb_mot():
default_nb_mot = 12
input_string = 'Entrer le nb de mots que vous souhaitez générer: (12 ou 24, default: {0}): '.format(default_nb_mot)
while True:
nb_mot_string = input(input_string)
if len(nb_mot_string) == 0:
return default_nb_mot
word_count = int(nb_mot_string)
if word_count == 12 or word_count == 24:
return word_count
r = os.urandom(bits//8)
def ask_entropie(nb_bits_generes):
entropie = secrets.randbits(nb_bits_generes) # generer les bits
entropie_bin = int_to_bin(entropie, nb_bits_generes) # conversion en binaire
nb_char_genere = nb_bits_generes // 4
input_string = 'Entrez une entropie ou taper sur entrer pour générer automatiquement: '.format(nb_char_genere)
while True:
entropie_string = input(input_string)
entropie_len = len(entropie_string)
if entropie_len == 0:
return generate_entropie(nb_bits_generes)
if entropie_len == nb_char_genere + 2:
entropie_bin = int_to_bin(int(entropie_string, 16), nb_bits_generes)
return entropie_bin
print(entropie_bin)
def generate_entropie(nb_bits_generes):
nb_char_generes = nb_bits_generes // 4
entropie = secrets.randbits(nb_bits_generes) # generer les bits
entropie_bin = int_to_bin(entropie, nb_bits_generes) # conversion en binaire
print('Initial entropy:', entropie_bin) # print string de bits
print('Length of initial entropy:', len(entropie_bin)) # print longueur de ce string
entropie_hex = bin_to_hex(entropie_bin, nb_char_generes) #Hexa conversion
print('Initial entropy as hex:', entropie_hex) # print string en heva base 16
print('Length of entropy as hex:', len(entropie_hex)) # print longueur de cette var
return entropie_bin
# secrets.choice() pour generation du string random + entropie + conversion
def hashage(entropie): #SHA 256
nb_bits_generes = len(entropie)
nb_char_genere = nb_bits_generes // 4
print('char:', nb_char_genere)
entropie_hex = bin_to_hex(entropie, nb_char_genere) # string hexa -> entropie_hex var
entropie_hex_no_padd = entropie_hex[2:]
print('Longueur de lentropie sans le 0x pad:', len(entropie_hex)) # printlongueur sans 0x pad
print('Entropie hexa initiale sans pad', entropie_hex_no_padd)
entropie_bytearray = bytearray.fromhex(entropie_hex_no_padd) # hexa string à bytearray conversion
print(entropie_bytearray, '<--- Entropy as bytes') # print cette var
print('Sa longueur est de :', len(entropie_bytearray)) # print length of bytearray
bits = hashlib.sha256(entropie_bytearray).hexdigest()
print(bits, '<--- SHA-256 hash digest of entropy bytes') # print le hash du bytearray
return bits
def slicing(entropie, entropie_hash, checksum_bit_count):
nb_bits_generes = len(entropie)
nb_char_genere = nb_bits_generes // 4
entropie_hex = bin_to_hex(entropie, nb_char_genere) # hexa string -> entropie_hex var
checksum_char = checksum_bit_count // 4
bit = entropie_hash[0:checksum_char] # prend les x premiers bits
print(bit, '<--- Premiers bits utilisés pour le hash') # print première partie du hash
print((bit[0:checksum_char]), '<--- 1ers n bits à convertir en heva')
check_bit = int(bit, 16) # conversion heva binaire
checksum = int_to_bin(check_bit, checksum_bit_count)
print(checksum, '<--- Checksum (hex to bits)')
print('Entropie + checksum = total bits:', str(entropie) + str(checksum)) # to bin string
print('Longueur totale des bits:', len(str(entropie) + str(checksum))) # print longueur des bits
source = str(entropie) + str(checksum) #+ checksum
groups = [source[i:i + 11] for i in range(0, len(source), 11)] # division en lot de 11 bits
print(groups) # group -> index val -> word in list
totalbits = hex(int(str('0b') + entropie + str(checksum), 2))
print('Le hash de lentropie initiale des bytes:', entropie_hash)
# pour indexer
indice = [int(str('0b') + source[i:i + 11], 2) for i in range(0, len(source), 11)] # (str('0b') for i in range(0,len(source),11)))
print(indice)
print(bip39wordlist([indice]))
return indice
bip39wordlist = []
with open("english.txt", "r", encoding="utf-8") as f:
for w in f.readlines():
bip39wordlist.append(w.strip())
def print_mots(indices):
# print(bip39wordlist)
# print(len(bip39wordlist))
# wordindexes=for i in indices
mots = [bip39wordlist[indices[i]] for i in range(0, len(indices))]
mots_string = ' '.join(mots)
print(mots_string)
wordlist = []
num = int(bin, 2)
bin_num = format(num, "b")
print(bin_num)
for i in range(str(bin_num) // 11):
nb_mots = ask_nb_mot()
nb_total_bit = nb_mots * 11
nb_bits_generes = nb_total_bit - checksum
entropie = ask_entropie(nb_bits_generes)
checksum = nb_mots // 3
nb_char_genere = nb_bits_generes // 4
#print(bin_result[i*11 : (i+1)*11])
index = int(bin_num[i*11 : (i+1)*11], 2)
#print(str(index))
wordlist.append(bip39wordlist[index])
def bin_to_hex(bin, padding): #Fonction de conversion de binaire à heva
num = int(bin, 2)
num = str(num)
return '0x{0:0{1}x}'.format(num, padding)
def int_to_bin(num, padding): #Fonction de conversion de int à binaire
bin_num = format(num, "b")
print(bin_num)
return f'{0:08b}'.format(num, padding)
and i've got this error:
Une exception s'est produite : TypeError
'str' object cannot be interpreted as an integer
Nothing happens when i run my script, it used to generate the seed and convert it to binary, but nothing happens after generate entropy function, i think i missed something, thanks in advance for your time.

Related

AttributeError: 'str' object has no attribute 'decode'. Could not find anywhere [duplicate]

This question already has answers here:
'str' object has no attribute 'decode' in Python3
(4 answers)
Closed 3 years ago.
The conversion from py2 to py3 gave this error and could not find anywhere. In line 242 is the error. Below the code that calls it.
ERROR:
Traceback (most recent call last):
File "CHAMADA_KECCAK.py", line 51, in <module> f = g.funcao()
File "CHAMADA_KECCAK.py", line 46, in funcao y = x.sha3_256(t).digest()
File "C:\Users\asus\Desktop\UENF\11 PERIODO\MONOGRAFIA ARTHUR EM ANDAMENTO\python_sha3.py", line 242, in digest
M = _build_message_pair(self.buffered_data.decode('hex'))
AttributeError: 'str' object has no attribute 'decode'
Code: CHAMADA_KECCAK.py
import python_sha3
class principal:
def funcao(self):
t = 'arthurrieofkmdslmvdsmveribmfkdbdfmbero'
x = python_sha3
y = x.sha3_256(t).digest()
return y
print ("\nO hash Keccak-256 do texto: \n %s \nEh:\n %s"%(t , y))
g = principal()
f = g.funcao()
Code: python_sha3.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import math
def sha3_256(data=None):
return Keccak(c=512, r=1088, n=256, data=data)
class KeccakError(Exception):
#Classe de erro personalizada usada na implementacao do Keccak
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Keccak:
def __init__(self, r, c, n, data=None):
# Inicialize as constantes usadas em todo o Keccak
# taxa de bits
self.r = r
# capacidade
self.c = c
# tamanho da saida
self.n = n
self.b = r + c
# b = 25*w
self.w = self.b // 25
# 2**l = w
self.l = int(math.log(self.w, 2))
self.n_r = 12 + 2 * self.l
self.block_size = r
self.digest_size = n
# Inicialize o estado da esponja
# O estado eh composto por 25 palavras, cada palavra sendo w bits.
self.S =[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
# Uma sequencia de hexchars, em que cada caractere representa 4 bits.
self.buffered_data = ""
# Armazene o resumo calculado.
# Apenas aplicaremos preenchimento e recalcularemos o hash se ele for modificado.
self.last_digest = None
if data:
self.update(data)
# Constantes
# # Constantes redondas
RC = [0x0000000000000001,
0x0000000000008082,
0x800000000000808A,
0x8000000080008000,
0x000000000000808B,
0x0000000080000001,
0x8000000080008081,
0x8000000000008009,
0x000000000000008A,
0x0000000000000088,
0x0000000080008009,
0x000000008000000A,
0x000000008000808B,
0x800000000000008B,
0x8000000000008089,
0x8000000000008003,
0x8000000000008002,
0x8000000000000080,
0x000000000000800A,
0x800000008000000A,
0x8000000080008081,
0x8000000000008080,
0x0000000080000001,
0x8000000080008008]
## Deslocamentos de rotacao
r = [[0, 36, 3, 41, 18],
[1, 44, 10, 45, 2],
[62, 6, 43, 15, 61],
[28, 55, 25, 21, 56],
[27, 20, 39, 8, 14]]
#staticmethod
def Round(A, RCfixed, w):
"""Execute uma rodada de calculo conforme definido na permutacao Keccak-f
A: estado atual (matriz 5x5)
RCfixed: valor da constante arredondada a ser usada (inteiro)"""
#Inicializacao de variaveis temporarias
B = [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
C = [0, 0, 0, 0, 0]
D = [0, 0, 0, 0, 0]
#Etapa Theta
for x in range(5):
C[x] = A[x][0] ^ A[x][1] ^ A[x][2] ^ A[x][3] ^ A[x][4]
for x in range(5):
D[x] = C[(x - 1) % 5] ^ _rot(C[(x + 1) % 5], 1, w)
for x in range(5):
for y in range(5):
A[x][y] = A[x][y] ^ D[x]
#Etapa Rho e Pi
for x in range(5):
for y in range(5):
B[y][(2 * x + 3 * y) % 5] = _rot(A[x][y], Keccak.r[x][y], w)
#Etapa Chi
for x in range(5):
for y in range(5):
A[x][y] = B[x][y] ^ ((~B[(x + 1) % 5][y]) & B[(x + 2) % 5][y])
#Etapa Iota
A[0][0] = A[0][0] ^ RCfixed
return A
#staticmethod
def KeccakF(A, n_r, w):
"""Execute a funcao Keccak-f no estado A
A: matriz 5x5 contendo o estado, em que cada entrada eh uma sequencia de hexchars com 'w' bits de comprimento
n_r: numero de rodadas
w: tamanho da palavra
"""
for i in xrange(n_r):
A = Keccak.Round(A, Keccak.RC[i] % (1 << w), w)
# print (A)
return A
### Regra de preenchimento
#staticmethod
def pad10star1(M, n):
"""PAD M com a regra de preenchimento pad10 * 1 para atingir um comprimento multiplo de r bits
M: par de mensagens (comprimento em bits, sequencia de caracteres hexadecimais ('9AFC ...')
n: comprimento em bits (deve ser multiplo de 8)
Exemplo: pad10star1 ([60, 'BA594E0FB9EBBD30'], 8) retorna 'BA594E0FB9EBBD93'
"""
[my_string_length, my_string] = M
# Verifique o parametro n
if n % 8 != 0:
raise KeccakError.KeccakError("n deve ser um multiplo de 8")
# Verifique o comprimento da string fornecida
if len(my_string) % 2 != 0:
#Pad com um '0' para atingir o comprimento correto (nao sei codificacao de vetores de teste)
my_string += '0'
if my_string_length > (len(my_string) // 2 * 8):
raise KeccakError.KeccakError("A cadeia eh muito curta para conter o numero de bits anunciados")
nr_bytes_filled = my_string_length // 8
nbr_bits_filled = my_string_length % 8
l = my_string_length % n
if ((n - 8) <= l <= (n - 2)):
if (nbr_bits_filled == 0):
my_byte = 0
else:
my_byte = int(my_string[nr_bytes_filled * 2:nr_bytes_filled * 2 + 2], 16)
my_byte = (my_byte >> (8 - nbr_bits_filled))
my_byte = my_byte + 2 ** (nbr_bits_filled) + 2 ** 7
my_byte = "%02X" % my_byte
my_string = my_string[0:nr_bytes_filled * 2] + my_byte
else:
if (nbr_bits_filled == 0):
my_byte = 0
else:
my_byte = int(my_string[nr_bytes_filled * 2:nr_bytes_filled * 2 + 2], 16)
my_byte = (my_byte >> (8 - nbr_bits_filled))
my_byte = my_byte + 2 ** (nbr_bits_filled)
my_byte = "%02X" % my_byte
my_string = my_string[0:nr_bytes_filled * 2] + my_byte
while((8 * len(my_string) // 2) % n < (n - 8)):
my_string = my_string + '00'
my_string = my_string + '80'
# print (my_string)
return my_string
def update(self, arg):
"""Atualize o objeto hash com a string arg. Chamadas repetidas sao equivalentes a
uma unica chamada com a concatenacao de todos os argumentos: m.update (a);
m.update (b) eh equivalente a m.update (a + b). arg eh um bytestring normal.
"""
self.last_digest = None
# Converta os dados em um formato viavel e adicione-os ao buffer
self.buffered_data += arg.encode("utf-8").hex()
# Absorver todos os blocos que pudermos:
if len(self.buffered_data) * 4 >= self.r:
extra_bits = len(self.buffered_data) * 4 % self.r
# Um ajuste exato!
if extra_bits == 0:
P = self.buffered_data
self.buffered_data = ""
else:
# Fatie-o nos primeiros bits r * a, para alguma constante a> = 1, e o restante total-r * a bits.
P = self.buffered_data[:-extra_bits // 4]
self.buffered_data = self.buffered_data[-extra_bits // 4:]
#Fase de absorcao
for i in xrange((len(P) * 8 // 2) // self.r):
to_convert = P[i * (2 * self.r // 8):(i + 1) * (2 * self.r // 8)] + '00' * (self.c // 8)
P_i = _convertStrToTable(to_convert, self.w, self.b)
# Primeiro aplique o XOR ao estado + bloco
for y in xrange(5):
for x in xrange(5):
self.S[x][y] = self.S[x][y] ^ P_i[x][y]
# Em seguida, aplique a permutacao do bloco, Keccak-F
self.S = Keccak.KeccakF(self.S, self.n_r, self.w)
def digest(self):
"""Retorne o resumo das strings passadas para o metodo update () ate o momento.
Esta eh uma sequencia de bytes digest_size que pode conter dados nao ASCII
caracteres, incluindo bytes nulos."""
if self.last_digest:
return self.last_digest
# AVISO FEIO
# Lidar com conversoes bytestring / hexstring
M = _build_message_pair(self.buffered_data.decode('hex'))
# Primeiro termine o preenchimento e force a atualizacao final:
self.buffered_data = Keccak.pad10star1(M, self.r)
self.update('')
# AVISO FEIO terminado
assert len(self.buffered_data) == 0, "Por que existem dados restantes no buffer? %s com comprimento %d" % (self.buffered_data, len(self.buffered_data) * 4)
# Aperto o tempo!
Z = ''
outputLength = self.n
while outputLength > 0:
string = _convertTableToStr(self.S, self.w)
# Leia os primeiros bits 'r' do estado
Z = Z + string[:self.r * 2 // 8]
outputLength -= self.r
if outputLength > 0:
S = KeccakF(S, verbose)
self.last_digest = Z[:2 * self.n // 8]
return self.last_digest
def hexdigest(self):
"""Como digest(), exceto que o resumo eh retornado como uma sequencia de digitos hexadecimais.
Isso pode ser usado para trocar o valor com seguranca em e-mail ou outros
ambientes nao binarios."""
return self.digest().encode('hex')
def copy(self):
# Inicialize primeiro o que pode ser feito normalmente
duplicate = Keccak(c=self.c, r=self.r, n=self.n)
# Entao copie sobre o estado.
for i in xrange(5):
for j in xrange(5):
duplicate.S[i][j] = self.S[i][j]
# e quaisquer outros dados armazenados
duplicate.buffered_data = self.buffered_data
duplicate.last_digest = self.last_digest
return duplicate
## Funcoes genericas do utilitario
def _build_message_pair(data):
hex_data = data.encode('hex')
size = len(hex_data) * 4
return (size, hex_data)
def _rot(x, shift_amount, length):
"""Gire x shift_amount bits para a esquerda, considerando o \
cadeia de bits tem comprimento bits"""
shift_amount = shift_amount % length
return ((x >> (length - shift_amount)) + (x << shift_amount)) % (1 << length)
### Funcoes de conversao String <-> Tabela (e vice-versa)
def _fromHexStringToLane(string):
"""Converta uma cadeia de bytes gravada em hexadecimal em um valor de faixa"""
#Verifique se a string possui um numero par de caracteres, ou seja, um numero inteiro de bytes
if len(string) % 2 != 0:
raise KeccakError.KeccakError("A cadeia fornecida nao termina com um byte completo")
#Realize a conversao
temp = ''
nrBytes = len(string) // 2
for i in xrange(nrBytes):
offset = (nrBytes - i - 1) * 2
temp += string[offset:offset + 2]
return int(temp, 16)
def _fromLaneToHexString(lane, w):
"""Converta um valor de pista em uma cadeia de bytes gravada em hexadecimal"""
laneHexBE = (("%%0%dX" % (w // 4)) % lane)
#Realize a conversao
temp = ''
nrBytes = len(laneHexBE) // 2
for i in xrange(nrBytes):
offset = (nrBytes - i - 1) * 2
temp += laneHexBE[offset:offset + 2]
return temp.upper()
def _convertStrToTable(string, w, b):
"""Converta uma sequencia de caracteres hexadecimais em sua representacao matricial 5x5
string: sequencia de bytes de bytes codificados em hexadecimal (por exemplo, '9A2C ...')"""
# Verifique se os parametros de entrada sao esperados
if w % 8 != 0:
raise KeccakError("w nao eh multiplo de 8")
# Cada caractere na sequencia representa 4 bits.
# A string deve ter exatamente bits 'b'.
if len(string) * 4 != b:
raise KeccakError.KeccakError("a string nao pode ser dividida em 25 blocos de w bits \
ou seja, a string deve ter exatamente b bits")
#Converter
output = [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
bits_per_char = 2 * w // 8
for x in xrange(5):
for y in xrange(5):
# Cada entrada tera b / 25 = w bits.
offset = (5 * y + x) * bits_per_char
# Cada entrada tera b / 25 = w bits.
hexstring = string[offset:offset + bits_per_char]
output[x][y] = _fromHexStringToLane(hexstring)
return output
def _convertTableToStr(table, w):
"""Converta uma representacao de matriz 5x5 na sua representacao de cadeia"""
#Verifique o formato de entrada
if w % 8 != 0:
raise KeccakError.KeccakError("w nao eh multiplo de 8")
if (len(table) != 5) or any(len(row) != 5 for row in table):
raise KeccakError.KeccakError("a tabela deve ser 5x5")
#Converter
output = [''] * 25
for x in xrange(5):
for y in xrange(5):
output[5 * y + x] = _fromLaneToHexString(table[x][y], w)
output = ''.join(output).upper()
return output
str is already decoded and you are trying to decode it, which is already decoded. but if you really want to decode it, you should encode it, and then decode it again. i don't recommend it.
i recommend you to use binascii. note that the input string should be a byte-like object.
import binascii
a = b'hello'
# encoding string to equivalent hex representation
b=binascii.hexlify(a)
print(b)
>>> b'68656c6c6f'
# decoding b
c=binascii.unhexlify(b)
print(c)
>>> b'hello'

IEEE-754 Python

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'

2 (almost) identical programs don't get me the same results with the same input

I've got a program that takes in input a .txt file with coordinates (t, X, Y). The movement stored in this files is more or less circular, and this program is counting the number of rotation by searching the local optima of X+Y.
The last part at the end is to plot the results.
You can find here 2 .txt :
https://drive.google.com/file/d/0BxmtjR3C4bYBdnFZUzVwSVlPUlk/view?usp=sharing
Here is the first version :
The Interpolation function is a cubic interpolation that return False if it couldn't Interpolate, or (Frame_final, X_final, Y_final) if it managed to interpolate.
The Filtrage function is a first-order lowpass-filter.
def Filtrage(Frame, X, Y, DT = 3, a = 0.1):
"""Fonction réalisant un filtrage passe-bas d'ordre 1 du signal."""
# Initialisation
X_temp, Y_temp = [], []
X_filter, Y_filter = [], []
i = 1
X_temp.append(X[0])
Y_temp.append(Y[0])
# Filtrage par morceau
while i < len(Frame)-1:
while Frame[i] - Frame[i-1] == DT:
Xnew = a * X[i-1] + (1 - a) * X_temp[len(X_temp)-1]
Ynew = a * Y[i-1] + (1 - a) * Y_temp[len(Y_temp)-1]
X_temp.append(Xnew)
Y_temp.append(Ynew)
if i < len(Frame)-1:
i += 1
else:
break
X_filter += X_temp
Y_filter += Y_temp
X_temp, Y_temp = [], []
X_temp.append(X[i])
Y_temp.append(Y[i])
i += 1
return (X_filter, Y_filter)
def Traitement_resultat(Chemin_dossier_res, Trace_Graph):
"""Fonction réalisant le traitement des résultats pour déterminer le nombre de tour
effectué par la trajectoire circulaire.
- Le paramètre Chemin_dossier_res est une str.
- Le paramètre Trace_graph est un booléen
"""
print ("Début du traitement des résultats")
# Listage des fichiers résultats + ouverture du fichier de résultats finaux
Fichiers_res = os.listdir(Chemin_dossier_res)
res = open("Data_Results.txt", "w")
res.write("{} {} {}\n".format("Souris", "Nombre de tours", "Distance parcourue"))
# On boucle sur les fichiers
for i in range(0, len(Fichiers_res)):
# Affiche l'état du traitement
print ("{} / {} : {}".format(str(i+1), str(len(Fichiers_res)), Fichiers_res[i]))
# On ouvre le fichier résultat
results = open("{}/{}".format(Chemin_dossier_res, Fichiers_res[i]), "r")
# On récupère les datas dans 2 listes
X, Y, Frame = [], [], []
c = 0
try:
for ligne in results:
# Permet d'éliminer la première ligne d'en-tête
if c >= 1:
row = ligne.split()
if row[0] == "None":
continue
else:
Frame.append(int(row[0]))
X.append(int(row[1]))
Y.append(int(row[2]))
c += 1
results.close()
except:
print ("Fichier {} eronné ! Il ne sera pas traité.".format(Fichiers_res[i]))
results.close()
continue
if len(X) != len(Y):
print ("Fichier {} eronné ! Il ne sera pas traité.".format(Fichiers_res[i]))
continue
# Inteprolation
Data = Interpolation(Frame, X, Y)
if not Data:
print ("Fichier {} eronné ! Il ne sera pas traité.".format(Fichiers_res[i]))
continue
Frame = Data[0]
X = Data[1]
Y = Data[2]
# Filtrage
Data = Filtrage(Frame, X, Y)
X = Data[0]
Y = Data[1]
Diff_len = len(Frame) - len(X)
if Diff_len != 0:
Frame = Frame[:len(Frame)-Diff_len]
# Suppression des extremum
if len(Frame) > 1000:
for k in range(30):
maxX_ID = X.index(max(X))
del X[maxX_ID]
del Y[maxX_ID]
del Frame[maxX_ID]
minX_ID = X.index(min(X))
del X[minX_ID]
del Y[minX_ID]
del Frame[minX_ID]
maxY_ID = Y.index(max(Y))
del X[maxY_ID]
del Y[maxY_ID]
del Frame[maxY_ID]
minY_ID = Y.index(min(Y))
del X[minY_ID]
del Y[minY_ID]
del Frame[minY_ID]
elif len(Frame) > 100:
for k in range(3):
maxX_ID = X.index(max(X))
del X[maxX_ID]
del Y[maxX_ID]
del Frame[maxX_ID]
minX_ID = X.index(min(X))
del X[minX_ID]
del Y[minX_ID]
del Frame[minX_ID]
maxY_ID = Y.index(max(Y))
del X[maxY_ID]
del Y[maxY_ID]
del Frame[maxY_ID]
minY_ID = Y.index(min(Y))
del X[minY_ID]
del Y[minY_ID]
del Frame[minY_ID]
else:
print ("{} : Moins de 100 pts !!".format(Fichiers_res[i]))
Sum = []
# Conversion en minute et creation de la somme
for k in range(len(Frame)):
Frame[k] = Frame[k] / (30 * 60)
Sum.append(X[k] + Y[k])
if len(X) > 2:
# Détermination de la distance parcourue
Distance = 0
for k in range(len(X)-1):
Distance += sqrt((X[k+1] - X[k])**2 + (Y[k+1] - Y[k])**2)
Segments = range(200, 1400, 200)
Res = []
for k in range(len(Segments)):
if Segments[k] < len(Sum):
Sum_calc = []
length = len(Sum) // Segments[k]
last = len(Sum) % Segments[k]
for j in range(length):
Sum_calc.append(Sum[j:j + Segments[k]])
if last > Segments[k] //2:
Sum_calc.append(X[len(Sum) - last:])
else:
Sum_calc[len(Sum_calc) - 1] = Sum_calc[len(Sum_calc) - 1] + Sum[len(Sum) - last:]
# Initialisation of the counter
K = 0
for j in range(len(Sum_calc)):
Counter = 0
b = 0
Moyenne = np.mean(Sum_calc[j])
while b < len(Sum_calc[j]):
if Sum_calc[j][b] <= Moyenne + 10:
b += 1
continue
else:
Counter += 1
while Sum_calc[j][b] >= Moyenne + 10:
b += 1
try:
Sum_calc[j][b]
except:
break
K += Counter
Res.append(K)
if len(Res) > 4:
Res_F = int(np.mean(sorted(Res)[1:len(Res)-1]))
else:
Res_F = int(np.mean(Res))
# Ajout au fichier résultat des données
res.write(Fichiers_res[i][0:len(Fichiers_res[i])-4] + " " * (25 - len(Fichiers_res[i])) + str(Res_F)
+ " " * (26 - len(str(Res_F))) + str(int(Distance)) + "\n")
if Trace_Graph:
# Création des graphiques
plt.figure(figsize = (15, 11), dpi = 600)
# Ligne 2 / Colonne 1 / Position 1
plt.subplot(2, 1, 1)
plt.plot(X, Y, color = "green", linewidth = 0.3, linestyle="-")
plt.xlim(min(X) - 0.1 * np.mean(X), max(X) + 0.1 * np.mean(X))
plt.ylim(min(Y) - 0.1 * np.mean(Y), max(Y) + 0.1 * np.mean(Y))
plt.xlabel("pixel")
plt.ylabel("pixel")
plt.title("Trajectoire de la souris")
# Ligne 2 / Colonne 1 / Position 2
plt.subplot(2, 1, 2)
plt.plot(Frame, X, color = "blue", linewidth = 0.5, linestyle="-", label = "X")
plt.plot(Frame, Y, color = "red", linewidth = 0.5, linestyle="-", label = "Y")
plt.xlim(0, Frame[len(Frame)-1])
plt.ylim(min(min(X),min(Y)) - 0.1 * min(min(X),min(Y)) , max(max(X),max(Y)) + 0.1 * max(max(X),max(Y)))
plt.legend(loc = 'upper left')
plt.xlabel("Temps (minutes)")
plt.xticks(np.linspace(0, int(Frame[len(Frame)-1]), int(Frame[len(Frame)-1]) + 1))
plt.ylabel("Position")
plt.title("Position X et Y de la souris en fonction du temps")
plt.savefig("{}/{}.png".format("Graphiques", Fichiers_res[i][0:len(Fichiers_res[i])-4]), dpi = 600)
plt.close()
res.close()
print ("Fin du traitement des résultats !")
print ("---------------------------------------")
The second programm is exactly the same, with only 3 minors change : some of the variable are placed in a different file.
File Parameters.py :
# Parameters to adjust the analysis
# Low-pass filtering between 0 and 1
a = 0.1
# Thershold to count the maximum as a local maximum
Moy_Up = 10
# Segments cutting
Segments = range(200, 1400, 200)
Programm File :
from Parameters import *
def Filtrage(Frame, X, Y, DT = 3, a = 0.1):
"""Fonction réalisant un filtrage passe-bas d'ordre 1 du signal."""
# Initialisation
X_temp, Y_temp = [], []
X_filter, Y_filter = [], []
i = 1
X_temp.append(X[0])
Y_temp.append(Y[0])
# Filtrage par morceau
while i < len(Frame)-1:
while Frame[i] - Frame[i-1] == DT:
Xnew = a * X[i-1] + (1 - a) * X_temp[len(X_temp)-1]
Ynew = a * Y[i-1] + (1 - a) * Y_temp[len(Y_temp)-1]
X_temp.append(Xnew)
Y_temp.append(Ynew)
if i < len(Frame)-1:
i += 1
else:
break
X_filter += X_temp
Y_filter += Y_temp
X_temp, Y_temp = [], []
X_temp.append(X[i])
Y_temp.append(Y[i])
i += 1
return (X_filter, Y_filter)
def Traitement_resultat(Chemin_dossier_res, Trace_Graph):
"""Fonction réalisant le traitement des résultats pour déterminer le nombre de tour
effectué par la trajectoire circulaire.
- Le paramètre Chemin_dossier_res est une str.
- Le paramètre Trace_graph est un booléen
"""
print ("Début du traitement des résultats")
# Listage des fichiers résultats + ouverture du fichier de résultats finaux
Fichiers_res = os.listdir(Chemin_dossier_res)
res = open("Data_Results.txt", "w")
res.write("{} {} {}\n".format("Souris", "Nombre de tours", "Distance parcourue"))
# On boucle sur les fichiers
for i in range(0, len(Fichiers_res)):
# Affiche l'état du traitement
print ("{} / {} : {}".format(str(i+1), str(len(Fichiers_res)), Fichiers_res[i]))
# On ouvre le fichier résultat
results = open("{}/{}".format(Chemin_dossier_res, Fichiers_res[i]), "r")
# On récupère les datas dans 2 listes
X, Y, Frame = [], [], []
c = 0
try:
for ligne in results:
# Permet d'éliminer la première ligne d'en-tête
if c >= 1:
row = ligne.split()
if row[0] == "None":
continue
else:
Frame.append(int(row[0]))
X.append(int(row[1]))
Y.append(int(row[2]))
c += 1
results.close()
except:
print ("Fichier {} eronné ! Il ne sera pas traité.".format(Fichiers_res[i]))
results.close()
continue
if len(X) != len(Y):
print ("Fichier {} eronné ! Il ne sera pas traité.".format(Fichiers_res[i]))
continue
# Inteprolation
Data = Interpolation(Frame, X, Y)
if not Data:
print ("Fichier {} eronné ! Il ne sera pas traité.".format(Fichiers_res[i]))
continue
Frame = Data[0]
X = Data[1]
Y = Data[2]
# Filtrage
Data = Filtrage(Frame, X, Y, a)
X = Data[0]
Y = Data[1]
Diff_len = len(Frame) - len(X)
if Diff_len != 0:
Frame = Frame[:len(Frame)-Diff_len]
# Suppression des extremum
if len(Frame) > 1000:
for k in range(30):
maxX_ID = X.index(max(X))
del X[maxX_ID]
del Y[maxX_ID]
del Frame[maxX_ID]
minX_ID = X.index(min(X))
del X[minX_ID]
del Y[minX_ID]
del Frame[minX_ID]
maxY_ID = Y.index(max(Y))
del X[maxY_ID]
del Y[maxY_ID]
del Frame[maxY_ID]
minY_ID = Y.index(min(Y))
del X[minY_ID]
del Y[minY_ID]
del Frame[minY_ID]
elif len(Frame) > 100:
for k in range(3):
maxX_ID = X.index(max(X))
del X[maxX_ID]
del Y[maxX_ID]
del Frame[maxX_ID]
minX_ID = X.index(min(X))
del X[minX_ID]
del Y[minX_ID]
del Frame[minX_ID]
maxY_ID = Y.index(max(Y))
del X[maxY_ID]
del Y[maxY_ID]
del Frame[maxY_ID]
minY_ID = Y.index(min(Y))
del X[minY_ID]
del Y[minY_ID]
del Frame[minY_ID]
else:
print ("{} : Moins de 100 pts !!".format(Fichiers_res[i]))
Sum = []
# Conversion en minute et creation de la somme
for k in range(len(Frame)):
Frame[k] = Frame[k] / (30 * 60)
Sum.append(X[k] + Y[k])
if len(X) > 2:
# Détermination de la distance parcourue
Distance = 0
for k in range(len(X)-1):
Distance += sqrt((X[k+1] - X[k])**2 + (Y[k+1] - Y[k])**2)
Res = []
for k in range(len(Segments)):
if Segments[k] < len(Sum):
Sum_calc = []
length = len(Sum) // Segments[k]
last = len(Sum) % Segments[k]
for j in range(length):
Sum_calc.append(Sum[j:j + Segments[k]])
if last > Segments[k] //2:
Sum_calc.append(X[len(Sum) - last:])
else:
Sum_calc[len(Sum_calc) - 1] = Sum_calc[len(Sum_calc) - 1] + Sum[len(Sum) - last:]
# Initialisation of the counter
K = 0
for j in range(len(Sum_calc)):
Counter = 0
b = 0
Moyenne = np.mean(Sum_calc[j])
while b < len(Sum_calc[j]):
if Sum_calc[j][b] <= Moyenne + Moy_Up:
b += 1
continue
else:
Counter += 1
while Sum_calc[j][b] >= Moyenne + Moy_Up:
b += 1
try:
Sum_calc[j][b]
except:
break
K += Counter
Res.append(K)
if len(Res) > 4:
Res_F = int(np.mean(sorted(Res)[1:len(Res)-1]))
else:
Res_F = int(np.mean(Res))
# Ajout au fichier résultat des données
res.write(Fichiers_res[i][0:len(Fichiers_res[i])-4] + " " * (25 - len(Fichiers_res[i])) + str(Res_F)
+ " " * (26 - len(str(Res_F))) + str(int(Distance)) + "\n")
if Trace_Graph:
# Création des graphiques
plt.figure(figsize = (15, 11), dpi = 600)
# Ligne 2 / Colonne 1 / Position 1
plt.subplot(2, 1, 1)
plt.plot(X, Y, color = "green", linewidth = 0.3, linestyle="-")
plt.xlim(min(X) - 0.1 * np.mean(X), max(X) + 0.1 * np.mean(X))
plt.ylim(min(Y) - 0.1 * np.mean(Y), max(Y) + 0.1 * np.mean(Y))
plt.xlabel("pixel")
plt.ylabel("pixel")
plt.title("Trajectoire de la souris")
# Ligne 2 / Colonne 1 / Position 2
plt.subplot(2, 1, 2)
plt.plot(Frame, X, color = "blue", linewidth = 0.5, linestyle="-", label = "X")
plt.plot(Frame, Y, color = "red", linewidth = 0.5, linestyle="-", label = "Y")
plt.xlim(0, Frame[len(Frame)-1])
plt.ylim(min(min(X),min(Y)) - 0.1 * min(min(X),min(Y)) , max(max(X),max(Y)) + 0.1 * max(max(X),max(Y)))
plt.legend(loc = 'upper left')
plt.xlabel("Temps (minutes)")
plt.xticks(np.linspace(0, int(Frame[len(Frame)-1]), int(Frame[len(Frame)-1]) + 1))
plt.ylabel("Position")
plt.title("Position X et Y de la souris en fonction du temps")
plt.savefig("{}/{}.png".format("Graphiques", Fichiers_res[i][0:len(Fichiers_res[i])-4]), dpi = 600)
plt.close()
res.close()
print ("Fin du traitement des résultats !")
print ("---------------------------------------")
I don't know why placing this parameters in a different file is changing my result. When I placed print (a), print (Moy_Up) and print (Segments) in the second program just before they are called, they have the right value (respectively, a, 10 and range(200, 1400, 200)).
But with the first program I get :
Souris Nombre de tours Distance parcourue
1 48 13062
2 44 12927
And with the second one :
Souris Nombre de tours Distance parcourue
1 77 40328
2 76 39235
Moreover, if in the second version I change back :
Data = Filtrage(Frame, X, Y, a) by Data = Filtrage(Frame, X, Y)
Moy_Up by 10
and place back the Segments line, my results come back to those of the first version (quite normal).
Thanks for reading this long post, I tried to be explicit with my problem. I just can't understand why placing this variable in a separate file change my result even thou if I print them, they have the right value.
EDIT : I've used the compare module of Notepad, there is nothing else that differs.
You define Filtrage as follows:
def Filtrage(Frame, X, Y, DT = 3, a = 0.1):
Note the fourth parameter is DT, but when you call it:
Data = Filtrage(Frame, X, Y, a)
...you're passing a as the fourth parameter. You probably mean to do:
Data = Filtrage(Frame, X, Y, a=a)

get round twitter api limits

I have some problem that I can't get out of.
I'm trying to use the API twitter to get some tweets with a certain query.
I make a count with the api.rate_limit_status()['resources']['search']['/search/tweets']['remaining'] not to have the error code 429 of "Too Many Requests".
But before the end I have another error code 88 that means " The request limit for this resource has been reached for the current rate limit window."
So, I'd like to know what's the return limits per request or per 15 minutes ?
does i have some errors in my code ?
My code is here :
# coding: utf8
import chardet
import tweepy
import csv
import unidecode
import codecs
import datetime
import time
code_dep = "80"
motcle = "inondations"
#optionnel
motcle1 = "Pas-de-Calais"
#Entrer Twitter API informations
consumer_key = 'XXX'
consumer_secret = 'XXX'
access_token = 'XXX'
access_secret = 'XXX'
#connexion à l'API twitter avec les codes ci-dessus
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
#Création d'un fichier de sortie au format .csv
with codecs.open("D:/VIGNERON/test_inondations_80.csv", "w" , encoding='iso8859-1') as csvfile:
file = csv.writer(csvfile, delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL, dialect='excel')
file.writerow(['Nom_utilisateur'] + ['Date'] + ['Evenement'] + ['Source'] + ['Commune'] + ['Insee'] +['Localisation'] + ['Contenu'] + ['media']+ ['X'] + ['Y'] + ['Confiance'])
# Lecture de mes fichier commune, le traite regroupant les commuene sans caractères spéciaux
# Le brut regroupant les communes avec caractères spéciaux
# Les recherche par mot clé passent outre les accents
r = csv.reader(open("D:/VIGNERON/BD_Commune_traite.csv", "r"),delimiter = ';')
r1 = csv.reader(open("D:/VIGNERON/BD_Commune_brut.csv", "r"),delimiter = ';')
# Récuperation des communes brutes et placement dans un liste
com_brut_in_dep = []
for row in r1 :
if row[4] == code_dep :
com_brut_in_dep.append(str(row[0]))
# Récuperation des communes traitées ainsi que le code Insee et intégration dans deux listes
com_traite_in_dep = []
code_insee = []
for row in r :
if row[4] == code_dep :
com_traite_in_dep.append(str(row[0]))
code_insee.append(str(row[1]))
print ("Nombre de commune présente dans le " + str(code_dep) + " : " + str(len(com_traite_in_dep)))
lst_rech = []
tZero=time.time() #Récupération de tZero
print datetime.datetime.today()
t=time.time() -tZero # Temps après tZero
boucle = True
compteur = 0
# Parcour de ma liste de commune
while boucle == True :
global count
global compteur
if compteur < 7 :
for i in range (0,len(com_traite_in_dep)):
if i < len(com_traite_in_dep) :
commune = com_traite_in_dep[i]
test =commune + " " + motcle + " " + "since:\"2017-05-17\""
print test
nb_demande_restante = api.rate_limit_status()['resources']['search']['/search/tweets']['remaining']
print ("Demandes restantes : " + str(nb_demande_restante) )
if nb_demande_restante > 1 :
t = time.time() - tZero
# print t
time.sleep(0.01)
# Recherche de tweets.
# items(200) permet de récupérer les 200 premiers status
for status in tweepy.Cursor(api.search, q = test, count= 60 ).items():
#print commune
nb_demande_restante = api.rate_limit_status()['resources']['search']['/search/tweets']['remaining']
try :
# Récupération des données twitter et lecture du format Json
json_data = status._json
# Récuperation du nom de l'utilisateur
user = status.user.name.encode('ascii', 'ignore')
tweet_id = status.user.id
#print tweet_id
print ("Nom d'utilisateur : " + user)
# Récuperation de la date de publication
date = str(status.created_at)
print("Date de publication : " + str(status.created_at))
# Evenement survenu
evenement = u"Innondation"
print ("Evenement : " + evenement)
# Source de l'information
source = u"twitter"
print ("source : " + source )
# Récuperation du nom de la commune
commune = com_brut_in_dep[i]
print ("Nom de la commune : " + commune)
# Récuparation du code Insee de la commune
insee = code_insee[i]
print ("Code Insee commune : " + insee)
# Information complémentaire
localisation = u"Null"
print ("localisation : " + localisation)
# récuperation du texte tweeter
contenu = status.text
contenu = contenu.replace("\n" , ". ")
contenu = contenu.replace(";" , ".")
contenu = contenu.encode('iso8859-1','ignore')
print ("Tweet text: " + contenu)
url = json_data["entities"]["urls"]
if not url :
url = u"None"
else :
url = url[0]['expanded_url']
media = url.encode('iso8859-1', 'ignore')
print ("Media present : " + str(media))
# récuperation des coordonnées du tweet
coord = json_data["coordinates"]
if status.coordinates != None :
lon = coord["coordinates"][0]
lat = coord["coordinates"][1]
if lat < 51.40 and lat > 41.00 and lon < 10.50 and lon > -5.00 :
lon = lon
lat = lat
else :
lon = u"None"
lat = u"None"
print ("Longitude : " + str(lon))
print ("Latitude : " + str(lat))
confiance = u"Null"
print ("Indice de confiance : " + confiance)
print ("")
# Ajout des informations dans le .csv de sortie
file =open("D:/VIGNERON/test_inondations_80.csv", "a" )
wri = csv.writer( file , csvfile, delimiter = ';' , quotechar = '|' , quoting = csv.QUOTE_MINIMAL )
wri.writerow([user]+[date]+[evenement]+[source]+[commune]+[insee]+[localisation]+[contenu]+[media]+[lon]+[lat])
#fermeture du fichier rempli
#/!\ si le fichier n'est pas fermé il est inutilisable
file.close()
except :
break
else :
i = i
print i
compteur += 1
print compteur
print t
time.sleep (905 - t)
tZero=time.time()
#t = time.time() - tZero
else:
boucle = False
else :
boucle = False
Twitter's rate limit documentation seems to suggest you can apply 900 searches per 15 minute window - though if you're using a cursor to tab through pages, I think each page counts as 1 towards this limit.
To help avoid crashes on hitting rate limits, Tweepy as rate limit handling built into its API - if you change:
api = tweepy.API(auth)
to
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
Tweepy will be able to catch the rate limit errors, and waits the minimum amount of time before trying again.
EDIT: also, you shouldn't try to "get around" the rate limits - they exist for a reason, and trying to exceed them violates Twitter's terms of service.

Battleship with Python

Here I've some difficulties with my program ... I tried everything but nothing works ...
Here is my code:
import random
XBateau_un_joueur = 0
YBateau_un_joueur = 0
XBateau_deux_joueur = 1
YBateau_deux_joueur = 1
XBateau_un_IA = 0
YBateau_un_IA = 0
XBateau_deux_IA = 1
YBateau_deux_IA = 1
def Grille(): #définition du tableau qui servira de grille
tableau_joueur = [(0,)*taille]*taille
for i in range(taille):
tableau_joueur[i] = list(tableau_joueur[i])
tableau_joueur[XBateau_deux_joueur][YBateau_deux_joueur] = 1
tableau_joueur[XBateau_un_joueur][YBateau_un_joueur] = 1
if XBateau_un_joueur == XBateau_deux_joueur and YBateau_un_joueur == YBateau_deux_joueur :
XBateau_deux_joueur = XBateau_deux_joueur + 1
YBateau_deux_joueur = YBateau_deux_joueur + 1
if XBateau_deux_joueur > taille - 1 :
XBateau_deux_joueur = XBateau_deux_joueur - 2
if YBateau_deux_joueur > taille - 1 :
YBateau_deux_joueur = YBateau_deux_joueur - 2
tableau_IA = [(0,)*taille]*taille
for j in range(taille):
tableau_IA[j] = list(tableau_IA[j])
tableau_IA[XBateau_un_IA][YBateau_deux_IA] = 1
tableau_IA[XBateau_deux_IA][YBateau_deux_IA] = 1
if XBateau_un_IA and YBateau_un_IA == XBateau_deux_IA and YBateau_deux_IA :
XBateau_deux_IA = XBateau_deux_IA + 1
YBateau_deux_IA = YBateau_deux_IA + 1
if XBateau_deux_IA > taille - 1 :
XBateau_deux_IA = XBateau_deux_IA - 2
if YBateau_deux_joueur > taille - 1 :
YBateau_deux_IA = YBateau_deux_IA - 2
print tableau_joueur
print tableau_IA
def tour_IA():
compteur_de_point_IA = 0
for tour_IA in range (0, 3):
print "L'ennemi nous attaque Capitain !"
x = int(random.randint(0, taille - 1))
y = int(random.randint(0, taille - 1))
if ((x == XBateau_un_joueur) and (y == YBateau_un_joueur)) or ((x == XBateau_deux_joueur) and (y == YBateau_deux_joueur)) :
compteur_de_point_IA = compteur_de_point_IA + 8
print "Arg ! Cette raclure de fond de calle nous a coulé en vaisseau... prenez garde !"
else:
if (x == XBateau_un_joueur) or (y == YBateau_un_joueur) or (x == XBateau_deux_joueur) or (y == YBateau_deux_joueur) :
compteur_de_point_IA = compteur_de_point_IA + 1
print "nous sommes en vue de l'ennemi Cap'tain ! Faite attention !"
else:
print "A l'eau ! Il nous a raté !"
print "Voici les points marqué par l'ennemis :", compteur_de_point_IA
# tour du joueur IRL
def tour_joueur():
list_resultat = []
List_tot = []
print " C'est à vous d'attaquer"
for tour_joueur in range (0, 3):
compteur_de_point_joueur = 0
print "En attente des ordres, lattitude du tir mon capitain ?"
print "(colone)"
x = int(input())
print "longitude du tir ?"
print "(ligne)"
y = int(input())
if ((x == XBateau_un_IA) and (y == YBateau_un_IA)) or ((x == XBateau_deux_IA) and (y == YBateau_deux_IA)) :
compteur_de_point_joueur = compteur_de_point_joueur + 8
print "Aarrrr ! Navire ennemi envoyé par le fond Cap'tain!"
print "Vous marqué 8 points supplémentaires !! Bien joué!"
else:
if (x == XBateau_un_IA) or (y == YBateau_un_IA) or (x == XBateau_deux_IA) or (y == YBateau_deux_IA):
compteur_de_point_joueur = compteur_de_point_joueur + 1
print "L'ennemis est en vue ! Pas mal boucanier !"
print "Vous marqué 1 point supplémentaire !!"
else:
print "Mille sabords !!! Raté !!! Recommencez marins d'eau douce !"
print "Voici votre total de point marqué :", compteur_de_point_joueur
print " "
list_resultat.append(compteur_de_point_joueur)
print list_resultat[0]
print
def nombre_de_joueur() :
print "Combien de joueur êtes vous ?"
nombre = int(input())
print "Vent dans les voiles !! Vent dans les voiles !!"
for k in range(0, nombre) :
Grille()
tour_joueur()
print " "
print " "
tour_IA()
taille = int(input("Veuillez saisir la taille du champs de bataille matelot !"))
XBateau_un_joueur = random.randint(0, taille - 1)#bateau n°1 du joueur
YBateau_un_joueur = random.randint(0, taille - 1)
XBateau_deux_joueur = random.randint(0, taille - 1)#bateau n°2 du joueur
YBateau_deux_joueur = random.randint(0, taille - 1)
XBateau_un_IA = random.randint(0, taille - 1)#bateau n°1 de l'IA
YBateau_un_IA = random.randint(0, taille - 1)
XBateau_deux_IA = random.randint(0, taille - 1)#bateau n°2 de l'IA
YBateau_deux_IA = random.randint(0, taille - 1)
nombre_de_joueur()
And this is the shell:
Traceback (most recent call last):
File "C:\Users\Marion\Documents\Marion\Work\ISN\BatailleNavale2.py", line 138, in <module>
nombre_de_joueur()
File "C:\Users\Marion\Documents\Marion\Work\ISN\BatailleNavale2.py", line 116, in nombre_de_joueur
Grille()
File "C:\Users\Marion\Documents\Marion\Work\ISN\BatailleNavale2.py", line 17, in Grille
tableau_joueur[XBateau_deux_joueur][YBateau_deux_joueur] = 1
UnboundLocalError: local variable 'XBateau_deux_joueur' referenced before assignment
So if you have an idea..
PS : Sorry if my english is bad... I'm french!
You are assigning a value to the variable here:
XBateau_deux_joueur = XBateau_deux_joueur + 1
Python sees this assignment within your function and then, as a result, understands this variable within a local, rather than a global, scope. So the variable does not refer to the global variable that you probably think it should refer to. Thus when you reference the local variable here:
tableau_joueur[XBateau_deux_joueur][YBateau_deux_joueur] = 1
Python has never seen this variable before within the local scope of the function. The name is unbound, and Python throws an error. If you want to refer to the global variable instead, try this: before any reference to the variable, declare it as a global variable (within the function):
def Grille(): #définition du tableau qui servira de grille
global XBateau_deux_joueur
. . .
Any time you assign a value to a variable within a function, Python will assume that the variable is local in scope throughout the entire function unless told otherwise.

Categories

Resources