I have to create a decimal to binary converter without using lists yet my code is giving my wrong values and I can't figure out why.
def DecToBin(val):
bine = 128
counter = 8
coded = 10
binary = 0
while val > 0 and bine != 0.5:
if val < bine:
bine = bine/2
counter -= 1
elif val > bine:
val = val - bine
binary = binary + (coded ^ counter)
counter -= 1
bine = bine/2
elif val == bine:
binary = binary + (coded ^ counter)
counter = 0
val = 0
return binary
When the value input is 3 it gives me 19.
You have two issues. First, the python power operator is ** not ^. Second, bine should be 256, not 128 given your counter value. Your code should look like this:
def DecToBin(val):
bine = 256
counter = 8
coded = 10
binary = 0
while val > 0 and bine != 0.5:
if val < bine:
bine = bine/2
counter -= 1
elif val > bine:
val = val - bine
binary = binary + (coded ** counter)
counter -= 1
bine = bine/2
elif val == bine:
binary = binary + (coded ** counter)
counter = 0
val = 0
return binary
Related
I have the following code to find the minimum amount of exchangeable coins. How can I find out what denomination of the coins got there?
def get_min_coin(coins, val):
if val < 0:
return -1
max_val = val + 1
min_coins = [max_val] * (val + 1)
min_coins[0] = 0
for coin in coins:
for v in range(coin, val + 1):
min_coins[v] = min(1 + min_coins[v - coin], min_coins[v])
return min_coins[-1]
change = int(input())
coins = list(map(int, input().split()))
get_min_coin(coins , a)
UPD:
Input - 1 - the amount to be decomposed, 2 - denomination of coins
in:
6
1 3 4
out:
3 3
Here is how to use dynamic programming to produce the answer.
def get_min_coin(coins, val):
if val < 0:
return None
max_val = val + 1
min_coins = [(max_val, None)] * (val + 1)
min_coins[0] = (0, None)
for coin in coins:
for v in range(coin, val + 1):
min_coins[v] = min((1 + min_coins[v - coin][0], coin), min_coins[v])
if min_coins[-1][1] is None:
return None
else:
answer = []
while 0 < val:
answer.append(min_coins[val][1])
val -= min_coins[val][1]
return answer
change = 10 # int(input())
coins = [3, 4, 1] # list(map(int, input().split()))
print(get_min_coin(coins , change))
However for coins of very different sizes it is much more efficient to use A* Search. The heuristic is that the number of steps to finish is the number of steps that you have taken + how much distance left / coin size. And then you ONLY move to smaller coins.
I have a tensor data of size (1000,110) and I want to iterate over the first index of the tensor and calculate the following.
data = torch.randn(size=(1000,110)).to(device)
male_poor = torch.tensor(0).float().to(device)
male_rich = torch.tensor(0).float().to(device)
female_poor = torch.tensor(0).float().to(device)
female_rich = torch.tensor(0).float().to(device)
for i in data:
if torch.argmax(i[64:66]) == 0 and torch.argmax(i[108:110]) == 0:
female_poor += 1
if torch.argmax(i[64:66]) == 0 and torch.argmax(i[108:110]) == 1:
female_rich += 1
if torch.argmax(i[64:66]) == 1 and torch.argmax(i[108:110]) == 0:
male_poor += 1
if torch.argmax(i[64:66]) == 1 and torch.argmax(i[108:110]) == 1:
male_rich += 1
disparity = ((female_rich/(female_rich + female_poor))) / ((male_rich/(male_rich + male_poor)))
Is there a faster way than for loop to do this?
The key in pytorch (as well as numpy) is vectorizataion, that is if you can remove loops by operating on matrices it will be a lot faster. Loops in python are quite slow compared to the loops in the underlying compiled C code. On my machine the execution time for your code was about 0.091s, the following vectorized code was about 0.002s so about x50 faster:
import torch
torch.manual_seed(0)
device = torch.device('cpu')
data = torch.randn(size=(1000, 110)).to(device)
import time
t = time.time()
#vectorize over first dimension
argmax64_0 = torch.argmax(data[:, 64:66], dim=1) == 0
argmax64_1 = torch.argmax(data[:, 64:66], dim=1) == 1
argmax108_0 = torch.argmax(data[:, 108:110], dim=1) == 0
argmax108_1 = torch.argmax(data[:, 108:110], dim=1) == 1
female_poor = (argmax64_0 & argmax108_0).sum()
female_rich = (argmax64_0 & argmax108_1).sum()
male_poor = (argmax64_1 & argmax108_0).sum()
male_rich = (argmax64_1 & argmax108_1).sum()
disparity = ((female_rich / (female_rich + female_poor))) / ((male_rich / (male_rich + male_poor)))
print(time.time()-t)
print(disparity)
I've written a Timsort sorting algorithm for a computer science class, I would like to be able to compare the runtime to other similar algorithms, such as merge sort for instance. However, I am not sure where I should put the count (ie: count +=1)within the code to have an accurate run time. Any help would be much appreciated.
RUN = 32
def insertion_sort(arr, left, right):
for i in range(left + 1, right + 1):
temp = arr[i]
j = i - 1
while (arr[j] > temp and j >= left):
arr[j + 1] = arr[j]
arr[j] = temp
j -= 1
def merge(arr, left, right, count):
c = 0
index = count
length = len(left) + len(right)
while left and right:
if left[0] < right[0]:
arr[index] = left.pop(0)
c += 1
index += 1
else:
arr[index] = right.pop(0)
c += 1
index += 1
if len(left) == 0:
while c < length:
arr[index] = right.pop(0)
c += 1
index += 1
elif len(right) == 0:
while c < length:
arr[index] = left.pop(0)
c += 1
index += 1
def tim_sort(arr):
n = len(arr)
for i in range(0, n, RUN):
insertion_sort(arr, i, min((i + (RUN - 1)), (n - 1)))
size = RUN
while size < n:
for left in range(0, n, 2 * size):
if (left + size > n):
merge(arr, arr[left:n], [], left)
else:
left_sub_arr = arr[left:(left + size)]
right_sub_arr = arr[(left + size):min((left + 2 * size), n)]
merge(arr, left_sub_arr, right_sub_arr, left)
size *= 2
return arr
I am doing the strStr II problem on Lintcode. For the input ("abcdef","bcd"), the output is -1, which is different from the expected value, 1. I did some debug process and found that the way I did could not get the same code value for the 'bcd' in the source and 'bcd' in the target. I just don't know what's going on.
def strStr2(self, source, target):
if source is None or target is None:
return -1
m = len(target)
if m == 0:
return 0
n = len(source)
base = 1000000
power = 1
for i in range(m - 1):
power = 26 * power % base
targetcode = 0
for i in range(m):
targetcode = (targetcode * 26 + ord(target[i]) - ord('a')) % base
if targetcode < 0:
targetcode += base
sourcecode = 0
for i in range(n):
sourcecode = (sourcecode * 26 + ord(source[i]) - ord('a')) % base
if i >= m:
sourcecode = (sourcecode - ord(source[i-m]) * power - ord('a')) % base
if sourcecode < 0:
sourcecode += base
if sourcecode == targetcode:
if source[i - m + 1, i + 1] == target:
return i - m + 1
return -1
It would seem you are trying to implement Rabin-Karp algorithm. There are a few errors in your code. Here is a commented version with the fixes.
Also, I believe you would gain efficiency by reducing hash collisions if your chose 1000000 and 26 to be prime numbers instead.
def strStr2(source, target):
# There is no need to check that source and target are not None
# Also, storing lengths as m and n only makes the code harder to read
if len(target) == 0:
return 0
base = 1000000
power = 1
for i in range(len(target)): # Your range was incorrect
power = 26 * power % base
targetcode = 0
for i in range(len(target)):
# There is no need to normalize your chars at 'a'
# That would not work for uppercase anyway
targetcode = (targetcode * 26 + ord(target[i])) % base
sourcecode = 0
for i in range(len(source)):
sourcecode = (sourcecode * 26 + ord(source[i])) % base
if i >= len(target):
# In the line below was an error in your priority of operation
sourcecode = (sourcecode - ord(source[i-len(target)]) * power) % base
# you do not need to check that sourcecode is < 0, since base is > 0
if sourcecode == targetcode:
# For slicing use : instead of , in Python
if source[i - len(target) + 1:i + 1] == target:
return i - len(target) + 1
return -1
And here are a few example to show it works.
strStr2("abcdef","bcd") # 1
strStr2("aaaabcdef","bcd") # 4
strStr2("abcdef","bcda") # -1
I am struggling with a very simple loop that perfectly works if run "standalone", but doesn't work anymore if I use it as an outer loop for many other instructions (which also perfectly work if run standalone for only 1 iteration).
The simple outer loop is a
for i in range(0,somevalue):
do some inner instructions
Here is the full code, which perfectly works if I put a range of dimension 1, whilst it never ends if I put even a simple range of dimension 2:
import numpy as np
import numpy.ma as ma
import random
import matplotlib.pyplot as plt
i = int
x = np.zeros(1440)
class_x = np.zeros(1440)
w1 = np.array([0,6*60])
w2 = np.array([20*60,23*60])
x[w1[0]:(w1[1])] = np.full(np.diff(w1),0.001)
x[w2[0]:(w2[1])] = np.full(np.diff(w2),0.001)
x_masked = np.zeros_like(ma.masked_not_equal(x,0.001))
c = 10
func_time = 300
max_free_spot = int
i = 0
for i in range(0,1):
tot_time = 0
switch_count = 0
switch_ons = []
while
tot_time <= func_time:
switch_on = random.choice([random.randint(w1[0],(w1[1]-c)),random.randint(w2[0],(w2[1]-c))])
if x[switch_on] == 0.001:
if switch_on in range(w1[0],w1[1]):
if np.any(x[switch_on:w1[1]]!=0.001):
next_switch = [switch_on + k[0] for k in np.where(x[switch_on:]!=0.001)]
if (next_switch[0] - switch_on) >= c and max_free_spot >= c:
upper_limit = min((next_switch[0]-switch_on),min(func_time,w1[1]-switch_on))
elif (next_switch[0] - switch_on) < c and max_free_spot >= c:
continue
else: upper_limit = next_switch[0]-switch_on
else:
upper_limit = min(func_time,w1[1]-switch_on) #max random length of cycle
if upper_limit >= c:
indexes = np.arange(switch_on,switch_on+(random.randint(c,upper_limit)))
else:
indexes = np.arange(switch_on,switch_on+upper_limit)
else:
if np.any(x[switch_on:w2[1]]!=0.001):
next_switch = [switch_on + k[0] for k in np.where(x[switch_on:]!=0.001)]
if (next_switch[0] - switch_on) >= c:
upper_limit = min((next_switch[0]-switch_on),min(func_time,w2[1]-switch_on))
elif (next_switch[0] - switch_on) < c and max_free_spot >= c:
continue
else: upper_limit = next_switch[0]-switch_on
else:
upper_limit = min(func_time,w2[1]-switch_on)
if upper_limit >= c:
indexes = np.arange(switch_on,switch_on+(random.randint(c,upper_limit)))
else:
indexes = np.arange(switch_on,switch_on+upper_limit)
tot_time = tot_time + indexes.size
switch_ons.append(switch_on)
if tot_time > func_time:
indexes_adj = indexes[:-(tot_time-func_time)]
coincidence = random.randint(1,5)
np.put(x_masked,indexes_adj,(2*coincidence),mode='clip')
np.put(x,indexes_adj,(2*coincidence))
x_masked = np.zeros_like(ma.masked_greater_equal(x_masked,0.001))
tot_time = (tot_time - indexes.size) + indexes_adj.size
switch_count = switch_count + 1
break
else:
coincidence = random.randint(1,5)
np.put(x_masked,indexes,(2*coincidence),mode='clip')
np.put(x,indexes,(2*coincidence))
x_masked = np.zeros_like(ma.masked_greater_equal(x_masked,0.001))
tot_time = tot_time
switch_count = switch_count + 1
free_spots = []
for j in ma.notmasked_contiguous(x_masked):
free_spots.append(j.stop-j.start)
max_free_spot = max(free_spots)
class_x = class_x + x
plt.plot(class_x)
Any help is really really appreciated