I am trying to write a script that will allow me to come up with the value below.
When certain integers greater than zero are summed with their transposed value [x + transpose(x)] the result is a number consisting of only odd digits.
For example:
54 + 45 = 99
605 + 506 = 1111
We will call these numbers flip-flops; so 45, 54, 506, and 605 are flip-flops. Zeroes are not acceptable leading digits in either x or transpose(x).
How many flip-flop numbers are there below one billion (10^9)?
I'm thinking of it this way in pseudo-code:
IF [x+TRANSPOSE(x)] = ODD NUMBERS ONLY
THEN FLIPFLOP = TRUE
HOW MANY FLIPFLOPS <1,000,000,000
I'm struggling with the syntax however. Can anyone help? I'm trying to do this in Python
Since it takes an odd plus an even number to make an odd number, you need an odd and an even number to make a flipflop. This limits the number of candidates you need to test to find all flipflops < 10**9.
Furthermore, since the flipflop pairs are composed of an odd and even number, one of the numbers must begin with an odd number and the other must begin with an even number.
Therefore, the even number in a flipflop must be of the form
[odd_digits] + [zero_to_nine]*(ndigits-2) + [even_digits]
In other words, it begins with an odd digit, ends with an even digit, and can be any digit in the middle.
The final even_digit can not be zero since the odd flipflop can not begin with zero.
You only need to generate all the candidate even numbers of the above form, since when you reverse the digits you get the candidate odd numbers. To do more than this would be to count the same flipflops twice.
A further optimization for speed is to use integers only. No strings. Generally, converting between ints and strings takes more time than arithmetic computations.
import itertools as IT
zero_to_nine = range(10)
even_digits = [2, 4, 6, 8]
odd_digits = [1, 3, 5, 7, 9]
flipflops = 0
for ndigits in range(2, 10):
for digits in IT.product(*(
[odd_digits] + [zero_to_nine]*(ndigits-2) + [even_digits])):
reversed_digits = digits[::-1]
carry = 0
# print('testing {!r}'.format(digits))
for a, z in zip(digits, reversed_digits):
total = a+z+carry
# print('total: {}'.format(total))
if total % 2 == 0:
break
else:
carry = total//10
else:
# print('{!r} + {!r}'.format(digits, reversed_digits))
flipflops += 1
print(flipflops)
yields
304360
in about 6 minutes.
def check_odds(num):
for x in num:
if x not in odds:
return False
return True
for x in xrange(11,1000):
if x%10 != 0:
invert = int(str(x)[::-1])
flip_sum = str(x + invert)
if check_odds(flip_sum):
print "Number: " + str(x) + " Reverse: " + str(invert) + " flip_sum: " + flip_sum
output:
Number: 12 Reverse: 21 flip_sum: 33
Number: 14 Reverse: 41 flip_sum: 55
Number: 16 Reverse: 61 flip_sum: 77
Number: 18 Reverse: 81 flip_sum: 99
Number: 21 Reverse: 12 flip_sum: 33
Number: 23 Reverse: 32 flip_sum: 55
Number: 25 Reverse: 52 flip_sum: 77
Number: 27 Reverse: 72 flip_sum: 99
Number: 32 Reverse: 23 flip_sum: 55
Number: 34 Reverse: 43 flip_sum: 77
Number: 36 Reverse: 63 flip_sum: 99
Number: 41 Reverse: 14 flip_sum: 55
Number: 43 Reverse: 34 flip_sum: 77
Number: 45 Reverse: 54 flip_sum: 99
Number: 52 Reverse: 25 flip_sum: 77
Number: 54 Reverse: 45 flip_sum: 99
Number: 61 Reverse: 16 flip_sum: 77
Number: 63 Reverse: 36 flip_sum: 99
Number: 72 Reverse: 27 flip_sum: 99
Number: 81 Reverse: 18 flip_sum: 99
Number: 209 Reverse: 902 flip_sum: 1111
Number: 219 Reverse: 912 flip_sum: 1131
Number: 229 Reverse: 922 flip_sum: 1151
Number: 239 Reverse: 932 flip_sum: 1171
................................
..........
if you want to count:
def check_odds(num):
for x in num:
if x not in odds:
return False
return True
count = 0
for x in xrange(11,1000):
if x%10 != 0:
invert = int(str(x)[::-1])
flip_sum = str(x + invert)
if check_odds(flip_sum):
count += 1
print count
I'm not patient enough to wait for 1 billion, so here is an example up to 1000.
odds = set('13579')
for num in range(1,1000):
if not num % 10:
continue
inverse = int(str(num)[::-1])
s = str(num + inverse)
if all(i in odds for i in s):
print('Num: {}, Inverse: {}, Flip: {}'.format(num, inverse, s))
Output
Num: 12, Inverse: 21, Flip: 33
Num: 14, Inverse: 41, Flip: 55
Num: 16, Inverse: 61, Flip: 77
Num: 18, Inverse: 81, Flip: 99
Num: 21, Inverse: 12, Flip: 33
....
Num: 938, Inverse: 839, Flip: 1777
Num: 942, Inverse: 249, Flip: 1191
Num: 944, Inverse: 449, Flip: 1393
Num: 946, Inverse: 649, Flip: 1595
Num: 948, Inverse: 849, Flip: 1797
Edit
If you just want the count, and don't care what values satisfy the criteria
total = 0
odds = set('13579')
for num in range(1,1000):
if not num % 10:
continue
inverse = int(str(num)[::-1])
s = str(num + inverse)
if all(i in odds for i in s):
total += 1
print(total)
Related
I'm trying to cipher input with three different type or ciphers, and I am completely stuck on XOR 15.
import string
def caesar(text, shift, alphabets):
def shift_alphabet(alphabet):
return alphabet[shift:] + alphabet[:shift]
shifted_alphabets = tuple(map(shift_alphabet, alphabets))
final_alphabet = ''.join(alphabets)
final_shifted_alphabet = ''.join(shifted_alphabets)
table = str.maketrans(final_alphabet, final_shifted_alphabet)
return text.translate(table)
plaintext = input("Enter a sentence to encode: >")
shifted = int(input("Shift by how much? >"))
print("Caesar results:")
print("Original: ", plaintext)
print("Cipher: ",(caesar(plaintext, shifted, [string.printable])))
def rot13(text):
return ''.join([chr((ord(letter) - 97 + 13) % 26 + 97)
if 97 <= ord(letter) <= 122
else letter
for letter in text.lower()])
print("Rot13 results: ")
print("Original: ", plaintext)
print("Rot13:",(rot13(plaintext)))
def xor(plaintext,number):
L = list(plaintext)
L2 = [ord(value) ^ number for value in L]
return L2
i = plaintext.encode('utf-8')
xor_number = 00;
results = xor(plaintext,xor_number)
print ("XOR 15 results:")
print ("Original hex:", i.hex(' '))
print ("XOR 15 hex:", results)
When I get my results back after the user input I am only getting the regular ascii value instead of an XOR 15 of the original hex. Where am I going wrong?
Current Results:
XOR 15 results:
Original hex: 41 42 44 20 78 79 7a 20 31 32 33 21
XOR 15 hex: [65, 66, 68, 32, 120, 121, 122, 32, 49, 50, 51, 33]
Expected Results:
XOR 15 results:
Original hex: 41 42 44 20 78 79 7a 20 31 32 33 21
XOR 15 hex: [be, bd, bc, df, 87, 86, 85, df, ce, cd, cc, de]
my goal is to print prime numbers in a tabular format, instead of printing one value each line. so far all my attempts have ended in either lines, or misprinted tables.
start = int(input("Start number: "))
end = int(input("End number: "))
if start < 0 or end < 0:
print("Start and End must be positive.")
start = int(input("Start number: "))
end = int(input("End number: "))
if end < start:
print("End must be greater than Start number: ")
start = int(input("Start number: "))
end = int(input("End number: "))
prime = True
for num in range(start,end+1):
if num > 1:
for i in range(2,num):
if num % i == 0:
break
else:
num = print(num)
the one i have here can only print it line by line
#start number: 1
#end number: 100
# 2 3 5 7 11 13 17 19 23 29
#31 37 41 43 47 53 59 61 67 71
#73 79 83 89 97
This can be done with str.rjust or its friends
>>> "2".rjust(3)
' 2'
>>>
first we gather the numbers we want to print and calculate how many characters it take the biggest of them and add one to that value, that result is the one we will use for the rjust
>>> nums=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> j = len(str(max(nums))) + 1
>>>
now we pick how many we want to print per line
>>> linesize = 10
>>>
and finally we make use of print keyword-only arguments end to control when to print in the same line or not and enumerate to control how many we have already printed
>>> for i,p in enumerate(nums,1):
print( str(p).rjust(j), end="" )
if i%linesize==0:
print() #to go to the next line
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97
>>>
You could use str.format and implement a reusable solution using a generator:
from math import floor
def tabular(records, line_width=42, sep_space=3):
width = len(str(max(records))) + sep_space
columns = floor(line_width/width)
for i in range(0, len(records), columns):
row_records = records[i:i+columns]
row_format = ("{:>" + str(width) + "}") * len(row_records)
yield row_format.format(*row_records)
# test data / prime numbers
numbers = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97
]
for row in tabular(numbers):
print(row)
# 2 3 5 7 11 13 17 19
# 23 29 31 37 41 43 47 53
# 59 61 67 71 73 79 83 89
# 97
Example with some other numbers:
for row in tabular(list(range(0, 1600, 50)), 79, 2):
print(row)
# 0 50 100 150 200 250 300 350 400 450 500 550 600
# 650 700 750 800 850 900 950 1000 1050 1100 1150 1200 1250
# 1300 1350 1400 1450 1500 1550
Example with str.format but without using a generator:
# test data / prime numbers
numbers = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97
]
width = len(str(max(numbers))) + 3
for i in range(0, len(numbers), 10):
row_records = numbers[i:i+10]
row_format = ("{:>" + width + "}") * len(row_records)
print(row_format.format(*row_records))
# 2 3 5 7 11 13 17 19 23 29
# 31 37 41 43 47 53 59 61 67 71
# 73 79 83 89 97
I have a range in like below. What I am trying to do is to loop back to 0 if the range stop is greater that a certain value (this example 96). I can simply loop through the range as I did below, but is there a better way to do perform this in Python's range?
my_range = range(90, 100)
tmp_list=[]
for i in range(90, 100):
if i >= 96:
tmp_list.append(i-96)
else:
tmp_list.append(i)
print(tmp_list)
[90, 91, 92, 93, 94, 95, 0, 1, 2, 3]
Checkout itertools.cycle:
from itertools import cycle
def clipped_cycle(start, end):
c = cycle(range(0, 96))
# Discard till start
for _ in range(start):
next(c)
return c
c = clipped_cycle(90, 96)
for i in c:
print(i)
what you get is an infinite output stream that cycles along.
90
91
92
93
94
95
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.
.
.
to get a limited number of outputs:
n = 7
for _ in range(n):
print(next(c))
gives
90
91
92
93
94
95
0
First, I did not understand why you have defined my_range = range(90, 100), if you are never going to use it.
You can use 'mod' in these cases.
Try this, short and effective
xlist = [i%96 for i in range(90,100)]
So i'm trying to create a greedy algorithm for a knapsack problem. The txt file below is the knap20.txt file. The first line gives the number of items, in this case 20. The last line gives the capacity of the knapsack, in this case 524. The remaining lines give the index, value and weight of each item.
My function is to ideally return the solution in a list and the value of the weights
From what I can tell by my results, my program is working correctly. Is it working as you would expect, and how can i improve it?
txt file
20
1 91 29
2 60 65
3 61 71
4 9 60
5 79 45
6 46 71
7 19 22
8 57 97
9 8 6
10 84 91
11 20 57
12 72 60
13 32 49
14 31 89
15 28 2
16 81 30
17 55 90
18 43 25
19 100 82
20 27 19
524
python file
import os
import matplotlib.pyplot as plt
def get_optimal_value(capacity, weights, values):
value = 0.
numItems = len(values)
valuePerWeight = sorted([[values[i] / weights[i], weights[i]] for i in range(numItems)], reverse=True)
while capacity > 0 and numItems > 0:
maxi = 0
idx = None
for i in range(numItems):
if valuePerWeight[i][1] > 0 and maxi < valuePerWeight[i][0]:
maxi = valuePerWeight[i][0]
idx = i
if idx is None:
return 0.
if valuePerWeight[idx][1] <= capacity:
value += valuePerWeight[idx][0]*valuePerWeight[idx][1]
capacity -= valuePerWeight[idx][1]
else:
if valuePerWeight[idx][1] > 0:
value += (capacity / valuePerWeight[idx][1]) * valuePerWeight[idx][1] * valuePerWeight[idx][0]
return values, value
valuePerWeight.pop(idx)
numItems -= 1
return value
def read_kfile(fname):
print('file started')
with open(fname) as kfile:
print('fname found', fname)
lines = kfile.readlines() # reads the whole file
n = int(lines[0])
c = int(lines[n+1])
vs = []
ws = []
lines = lines[1:n+1] # Removes the first and last line
for l in lines:
numbers = l.split() # Converts the string into a list
vs.append(int(numbers[1])) # Appends value, need to convert to int
ws.append(int(numbers[2])) # Appends weigth, need to convert to int
return n, c, vs, ws
dir_path = os.path.dirname(os.path.realpath(__file__)) # Get the directory where the file is located
os.chdir(dir_path) # Change the working directory so we can read the file
knapfile = 'knap20.txt'
nitems, capacity, values, weights = read_kfile(knapfile)
val1,val2 = get_optimal_value(capacity, weights, values)
print ('values',val1)
print('value',val2)
result
values [91, 60, 61, 9, 79, 46, 19, 57, 8, 84, 20, 72, 32, 31, 28, 81, 55, 43, 100, 27]
value 733.2394366197183
I have been working on a programming challenge, problem here, which basically states:
Given integer array, you are to iterate through all pairs of neighbor
elements, starting from beginning - and swap members of each pair
where first element is greater than second.
And then return the amount of swaps made and the checksum of the final answer. My program seemingly does both the sorting and the checksum according to how it wants. But my final answer is off for everything but the test input they gave.
So: 1 4 3 2 6 5 -1
Results in the correct output: 3 5242536 with my program.
But something like:
2 96 7439 92999 240 70748 3 842 74 706 4 86 7 463 1871 7963 904 327 6268 20955 92662 278 57 8 5912 724 70916 13 388 1 697 99666 6924 2 100 186 37504 1 27631 59556 33041 87 9 45276 -1
Results in: 39 1291223 when the correct answer is 39 3485793.
Here's what I have at the moment:
# Python 2.7
def check_sum(data):
data = [str(x) for x in str(data)[::]]
numbers = len(data)
result = 0
for number in range(numbers):
result += int(data[number])
result *= 113
result %= 10000007
return(str(result))
def bubble_in_array(data):
numbers = data[:-1]
numbers = [int(x) for x in numbers]
swap_count = 0
for x in range(len(numbers)-1):
if numbers[x] > numbers[x+1]:
temp = numbers[x+1]
numbers[x+1] = numbers[x]
numbers[x] = temp
swap_count += 1
raw_number = int(''.join([str(x) for x in numbers]))
print('%s %s') % (str(swap_count), check_sum(raw_number))
bubble_in_array(raw_input().split())
Does anyone have any idea where I am going wrong?
The issue is with your way of calculating Checksum. It fails when the array has numbers with more than one digit. For example:
2 96 7439 92999 240 70748 3 842 74 706 4 86 7 463 1871 7963 904 327 6268 20955 92662 278 57 8 5912 724 70916 13 388 1 697 99666 6924 2 100 186 37504 1 27631 59556 33041 87 9 45276 -1
You are calculating Checksum for 2967439240707483842747064867463187179639043276268209559266227857859127247091613388169792999692421001863750412763159556330418794527699666
digit by digit while you should calculate the Checksum of [2, 96, 7439, 240, 70748, 3, 842, 74, 706, 4, 86, 7, 463, 1871, 7963, 904, 327, 6268, 20955, 92662, 278, 57, 8, 5912, 724, 70916, 13, 388, 1, 697, 92999, 6924, 2, 100, 186, 37504, 1, 27631, 59556, 33041, 87, 9, 45276, 99666]
The fix:
# Python 2.7
def check_sum(data):
result = 0
for number in data:
result += number
result *= 113
result %= 10000007
return(result)
def bubble_in_array(data):
numbers = [int(x) for x in data[:-1]]
swap_count = 0
for x in xrange(len(numbers)-1):
if numbers[x] > numbers[x+1]:
numbers[x+1], numbers[x] = numbers[x], numbers[x+1]
swap_count += 1
print('%d %d') % (swap_count, check_sum(numbers))
bubble_in_array(raw_input().split())
More notes:
To swap two variables in Python, you dont need to use a temp variable, just use a,b = b,a.
In python 2.X, use xrange instead of range.