How do I check hexadecimal numbers between range Hexadecimal number in python - python

I Having list of hexadecimal numbers and want to find the numbers base on specific range, without range method in python
h = ["00000100", "000000c0", "000000a0" "00000620", "00000660", "00006000"]
I want to find the numbers which is greater than "00000100" and less than "00000610" in python.
So how do I do it.
I Tried:
h = ["00000100", "000000c0", "000000a0" "00000620", "00000660", "00006000"]
num =
for i in h:
if i >="00000100"and <= "00000610":
print(i)

The int built-in function can convert a string in any base:
h = ["00000100", "000000c0", "000000a0" "00000620", "00000660", "00006000"]
for s in h:
if int("00000100", 16) <= int(s, 16) <= int("00000610", 16):
print(s)
Prints:
00000100

This will work if all the elements are of same length as posted by OP. If values are of variables length then we can convert them using int() as posted by #Booboo
h = ["00000100", "000000c0", "000000a0" "00000620", "00000660", "00006000"]
for i in h:
if i >="00000100"and i<= "00000610":
print(i)
#output
00000100
oneliner List comp:
[i for i in h if i >="00000100"and i<= "00000610"]
["00000100"]

Related

How do I take out the 2 or more-digit numbers in a python string?

I am trying to add up the numbers in the string like such: 76 977
I need to add up these numbers, but I get a 1st+2nd digit sum.
My code:
a = list(input())
a.remove(' ')
print(a)
print(int(a[0])+int(a[1]))
use the split function:
a = "76 977"
b=a.split(" ")
sum = 0
for num in b:
sum += int(num)
print(sum)
Try a.split(' '), it takes a string and returns a list of strings seperated by that string.
a = input()
b = a.split(' ')
print(b)
print(int(b[0])+int(b[1]))
Slightly different answer :
string = '76 977'
print(sum([int(x) for x in string.split()]))
print('Enter string of numbers : ')
a = list(input())
print('\nThis is character list of entered string : ')
print(a)
numbers = []
num = 0
for x in a:
# ord() is used to get ascii value
# of character ascii value of
# digits from 0 to 9 is 48 to 57 respectively.
if(ord(x) >= 48 and ord(x) <= 57):
#this code is used to join digits of
#decimal number(base 10) to number
num = num*10
num = num+int(x)
elif num>0 :
# all numbers in string are stored in
# list called numbers
numbers.append(num)
num = 0
if num>=0:
numbers.append(num)
num = 0
print('\nThis is number list : ', numbers)
sum=0
for num in numbers:
# all numbers are added and and sum
# is stored in variable called sum
sum = sum+num
print('Sum of numbers = ', sum)

need help in understanding a code

Can anyone explain this code a little. I can't understand what n does here? We already have taken N = int(input()) as input then why n=len(bin(N))-2? I couldn't figure it out.
N = int(input())
n = len(bin(N))-2
for i in range(1,N+1):
print(str(i).rjust(n) + " " + format(i,'o').rjust(n) + " " + format(i,'X').rjust(n) + " " + format(i,'b').rjust(n))
n counts the number of bits in the number N. bin() produces the binary representation (zeros and ones), as as string with the 0b prefix:
>>> bin(42)
'0b101010'
so len(bin(n)) takes the length of that output string, minus 2 to account for the prefix.
See the bin() documentation:
Convert an integer number to a binary string prefixed with “0b”.
The length is used to set the width of the columns (via str.rjust(), which adds spaces to the front of a string to create an output n characters wide). Knowing how many characters the widest binary representation needs is helpful here.
However, the same information can be gotten directly from the number, with the int.bitlength() method:
>>> N = 42
>>> N.bit_length()
6
>>> len(bin(N)) - 2
6
The other columns are also oversized for the numbers. You could instead calculate max widths for each column, and use str.format() or an f-string to do the formatting:
from math import log10
N = int(input())
decwidth = int(log10(N) + 1)
binwidth = N.bit_length()
hexwidth = (binwidth - 1) // 4 + 1
octwidth = (binwidth - 1) // 3 + 1
for i in range(1, N + 1):
print(f'{i:>{decwidth}d} {i:>{octwidth}o} {i:>{hexwidth}X} {i:>{binwidth}b}')

Reverse digits in a number

I want to reverse digits in a number in python. Here are my two implementations.
One: convert the number into string and reverse each char in it
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
Two: using simple mathematics
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
As I'm pretty new to python programming, so could someone help me with the following questions:
with the first approach, will "".join(str_list) produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to StringBuffer in java)
which of the implementations is better from performance perspective?
You can reverse a string using -1 as the step in a slice. So this works:
number = 2376674032
number_s = str(number)
reverse_s = number_s[::-1]
reversed = int(reverse_s)
you want to reverse a number …..input it as string format , and do this:
number="8374783246837"
revnumber=number[::-1]
Done
a = 1234
a = int("".join(reversed(str(a))))
This will give a = 4321
reversed functions returns an iterable object.
If we do :
a = list(reversed(str(a)))
it will return [“3”,”2″,”1″]. We have then joined it and converted into int.
To make the number an integer type, we have to use the int function, as below:
numbers=str(123456)
#or numbers="123456"
print((int(numbers[::-1])))
print((type(int(numbers[::-1]))))
output:
654321
<class 'int'>
We can do this in a single line as well using [::-1]
print(int(str(int(input()))[::-1]))
#here is my answer . you can do it using simple recursion
# count digits recursively
def reverse_digits(n):
# base case
if n == 0:
pass
#recursive case
else:
print(n%10,end='')
return reverse_digits(n//10)
# reverse 123
reverse_digits(123)
````````````````````````````````````````````````````

Python - How to convert a string from binary to integer list?

I got a string like:
s = "\0x01\0x02\0x01\0x11"
And I want to get the average number of that string. I tried this:
sum = 0
for d in s:
sum += int(d)
But it said "invalid literal for int() with base 10:'\x08'" :-(
I recommend the struct module.
>>> import struct
>>> s = '\x01\x02\x01\x11'
>>> struct.unpack('=4B', s)
(1, 2, 1, 17)
You can use the python int() function, the first argument is the string, the second is the base of the number.
You need to check the base, because what you posted looks like hexadecimal numbers (0x0 usually denotes a HEX number, additionally 02 is not a valid binary number).
For binary (base two):
num = int("0x11", 2); # num will be 3
For hexadecimal (base 16):
num = int("0x0A", 16); # num will be 10
To convert your string ("\0x01\0x02\0x01\0x11"):
numbers = [int(s, base) for s in "\\0x01\\0x02\\0x01\\0x11".split("\\") if len(s)]
If run with base = 16, outputs: numbers = [1, 2, 1, 17]
You can then find the average using:
average = sum(numbers)/len(numbers)
The ord() will, when given a string of length one, give you the code point of the character in that string. You should just be able to use this instead of int() in your code, which would look something like this:
sum = 0
for d in s:
sum += ord(d)
You can do it like this:
s = "\0x01\0x02\0x01\0x11"
list = s.split('\0x')
list.remove('')
sum = 0
for d in list:
sum += int(d)
# 15

Encoding a 128-bit integer in Python?

Inspired by the "encoding scheme" of the answer to this question, I implemented my own encoding algorithm in Python.
Here is what it looks like:
import random
from math import pow
from string import ascii_letters, digits
# RFC 2396 unreserved URI characters
unreserved = '-_.!~*\'()'
characters = ascii_letters + digits + unreserved
size = len(characters)
seq = range(0,size)
# Seed random generator with same randomly generated number
random.seed(914576904)
random.shuffle(seq)
dictionary = dict(zip(seq, characters))
reverse_dictionary = dict((v,k) for k,v in dictionary.iteritems())
def encode(n):
d = []
n = n
while n > 0:
qr = divmod(n, size)
n = qr[0]
d.append(qr[1])
chars = ''
for i in d:
chars += dictionary[i]
return chars
def decode(str):
d = []
for c in str:
d.append(reverse_dictionary[c])
value = 0
for i in range(0, len(d)):
value += d[i] * pow(size, i)
return value
The issue I'm running into is encoding and decoding very large integers. For example, this is how a large number is currently encoded and decoded:
s = encode(88291326719355847026813766449910520462)
# print s -> "3_r(AUqqMvPRkf~JXaWj8"
i = decode(s)
# print i -> "8.82913267194e+37"
# print long(i) -> "88291326719355843047833376688611262464"
The highest 16 places match up perfectly, but after those the number deviates from its original.
I assume this is a problem with the precision of extremely large integers when dividing in Python. Is there any way to circumvent this problem? Or is there another issue that I'm not aware of?
The problem lies within this line:
value += d[i] * pow(size, i)
It seems like you're using math.pow here instead of the built-in pow method. It returns a floating point number, so you lose accuracy for your large numbers. You should use the built-in pow or the ** operator or, even better, keep the current power of the base in an integer variable:
def decode(s):
d = [reverse_dictionary[c] for c in s]
result, power = 0, 1
for x in d:
result += x * power
power *= size
return result
It gives me the following result now:
print decode(encode(88291326719355847026813766449910520462))
# => 88291326719355847026813766449910520462

Categories

Resources