So basically, this prog reads 5 numbers:
X, Y, startFrom, jump, until
with space separating each number. an example:
3 4 1 1 14
X = 3
Y = 4
1 = startFrom
jump = 1
until = 14
In order to do that, I used:
#get X, Y, startFrom, jump, until
parameters = raw_input()
parametersList = parameters.split()
X = int(parametersList[0])
Y = int(parametersList[1])
#start from startFrom
startFrom = int(parametersList[2])
#jumps of <jump>
jump = int(parametersList[3])
#until (and including) <until>
until = int(parametersList[4])
The program outputs a chain (or however you would like to call it) of, let's call it BOOZ and BANG, when BOOZ is X if exists in the number (i.e X is 2 and we are at 23, so it's a BOOZ) . in order to check that (I used: map(int, str(currentPos)) when my currentPos (our number) at first is basically startFrom, and as we progress (add jump every time), it gets closer and closer to until), or if X divides the currentPos (X%num == 0. i.e: X is 2 and we are at 34, it's also a BOOZ).
BANG is the same, but with Y. If currentPos is both BOOZ & BANG, the output is BOOZ-BANG.
startFrom, startFrom+ jump, startFrom+2*jump, startFrom+3*jump, ..., until
We know the numbers read are int type, but we need to make sure they are valid for the game.
X and Y must be between 1 and 9 included. otherwise, we print (fter all 5 numbers have been read): X and Y must be between 1 and 9 and exit the prog.
In addition, jump can't be 0. if it is, we print jump can't be 0 and exit the prog. Else, if we can't reachuntil using jump jumps (if startFrom+ n * jump == until when n is an int number) so we need to print can't jump from <startFrom> to <until> and exit the prog.
My algorithm got too messy there with alot of ifs and what not, so I'd like an assistance with that as well)
so for our first example (3 4 1 1 14) the output should be:
1,2,BOOZ,BANG,5,BOOZ,7,BANG,BOOZ,10,11,BOOZ-BANG,BOOZ,BANG
another example:
-4 -3 4 0 19
OUTPUT:
X and Y must be between 1 and 9
juump can't be 0
another:
5 3 670 7 691
OUTPUT:
BOOZ,677,BANG,691
another:
0 3 4 -5 24
OUTPUT:
X and Y must be between 1 and 9
can't jump from 4 to 24
another:
3 4 34 3 64
OUTPUT:
BOOZ-BANG,BOOZ,BANG,BOOZ-BANG,BANG,BANG,BANG,55,58,61,BANG
my prog is toooo messy ( I did a while loop with ALOT of ifs.. including if currentPos==until so in that cause it won't print the comma (,) for the last item printed etc.. but like I said, all of it is so messy, and the ifs conditions came out so long and messy that I just removed it all and decided to ask here for a nicer solution.
Thanks guys
I hope it was clear enough
My version has no if :)
parameters = raw_input()
sx, sy, sstartfrom, sjump, suntil = parameters.split()
x = "0123456789".index(sx)
y = "0123456789".index(sy)
startfrom = int(sstartfrom)
jump = int(sjump)
until = int(suntil)
for i in range(startfrom, until+jump, jump):
si = str(i)
booz = sx in si or i%x == 0
bang = sy in si or i%y == 0
print [[si, 'BANG'],['BOOZ','BOOZ-BANG']][booz][bang]
Easiest way to get the commas is to move the loop into a generator
def generator():
for i in range(startfrom, until+jump, jump):
si = str(i)
booz = sx in str(i) or i%x == 0
bang = sy in str(i) or i%y == 0
yield [[si, 'BANG'],['BOOZ','BOOZ-BANG']][booz][bang]
print ",".join(generator())
Sample output
$ echo 3 4 1 1 14 | python2 boozbang.py
1,2,BOOZ,BANG,5,BOOZ,7,BANG,BOOZ,10,11,BOOZ-BANG,BOOZ,BANG
$ echo 5 3 670 7 691 | python2 boozbang.py
BOOZ,677,BANG,691
$ echo 3 4 34 3 64 | python2 boozbang.py
BOOZ-BANG,BOOZ,BANG,BOOZ-BANG,BANG,BANG,BANG,55,58,61,BANG
def CheckCondition(number, xOrY):
return (xOrY in str(number)) or not (number % xOrY)
def SomeMethod(X, Y, start, jump, end):
for i in range(start, end, jump):
isPassX = CheckCondition(i, X)
isPassY = CheckCondition(i, Y)
if isPassX and isPassY:
print "BOOZ-BANG"
elif isPassX:
print "BOOZ"
elif isPassY:
print "BANG"
else:
print i
def YourMethod():
(X, Y, start, jump, end) = (3, 4, 1, 1, 14)
if (X not in range(1, 10) or Y not in range(1, 10)):
print "X and Y must be between 1 and 9"
if jump <= 0:
print "juump can't be less than 0"
SomeMethod(X, Y, start, jump, end)
Related
I am new to coding, so forgive me if this is answered elsewhere. I am not sure what to search for to find a relevant answer. I also am not sure if my title is even correct. I want to print out each value in C_numbers that is associated with the same index in barcode_names. I want to separate these numbers each time the value in barcode_names changes. So I am using a third list unique_barcodes to compare to.
barcode_names = [1111,1111,1111,2222,2222,2222,3333,3333]
C_numbers = [12,5,7,28,32,13,2,9]
unique_barcodes = [1111,2222,3333]
x = 0
y = 0
for z in barcode_names:
if barcode_names[x] == unique_barcodes[y]:
print(C_numbers[x])
x = x+1
else:
y = y+1
print('next page')
result:
12
5
7
next page
28
32
13
next page
For some reason, it doesn't print the last two values 2 and 9. How do I get it to continue looping until it finishes printing all the values?
You're looping over barcode_names, so the most iterations that loop can make is eight. Increasing y while printing next page counts as one of those iterations. This prevents you from doing the last two things you wanted to do, as then you'd need a total of ten iterations. To fix this, you need to keep looping as long as x is a valid index in barcode_names. Change for z in barcode_names: to while x < len(barcode_names):.
Using x and y was throwing off your loop and is why it didn't complete.
Maybe something like this is more simple?
barcode_names = [1111,1111,1111,2222,2222,2222,3333,3333]
C_numbers = [12,5,7,28,32,13,2,9]
last_name = barcode_names[0]
for i in range(len(barcode_names)):
barcode_name = barcode_names[i]
if not barcode_name == last_name:
last_name = barcode_name
print('next page')
print(C_numbers[i])
result:
12
5
7
next page
28
32
13
next page
2
9
The loop control variable z is not stopping itself from being incremented when y index value is incrementing. Hence, before your desired print, the loop gets terminated.
I found this by adding the following line to your code inside the loop at the beginning
print('z value: ', z)
i.e. complete program becomes:
barcode_names = [1111,1111,1111,2222,2222,2222,3333,3333]
C_numbers = [12,5,7,28,32,13,2,9]
unique_barcodes = [1111,2222,3333]
x = 0
y = 0
for z in barcode_names:
print('z value: ', z)
if barcode_names[x] == unique_barcodes[y]:
print(C_numbers[x])
x = x+1
else:
y = y+1
print('next page')
Output:
z value: 1111
12
z value: 1111
5
z value: 1111
7
z value: 2222
next page
z value: 2222
28
z value: 2222
32
z value: 3333
13
z value: 3333
next page
>
Try this instead:
barcode_names = [1111,1111,1111,2222,2222,2222,3333,3333]
C_numbers = [12,5,7,28,32,13,2,9]
unique_barcodes = [1111,2222,3333]
x = 0
y = 0
for z in barcode_names:
# print('z value: ', z)
if barcode_names[x] != unique_barcodes[y]:
y = y+1
print('next page')
print(C_numbers[x])
x = x+1
Output:
12
5
7
next page
28
32
13
next page
2
9
>
I am a bit confused on how to get this to print either true or false, for example, you have 4 of Xobject which have a value of 2 each and you have 5 of Yobject which have a value of 5 each.
you have to see if 3 xobject and 2 yobject fit into 15. this should print false as you are not able to break the objects in half or count all of them together.
as in you can not do 3(2) + 2(5) = 16, which is larger than 15 but involves you adding the objects together which is not allowed as they are meant to be two completely different things
ok so here's one way of doing it:
x = 2 #value of each x object
y = 5 #value of each y object
xObjects = int(input('How many x objects:'))
yObjects = int(input('How many y objects:'))
if ((xObjects * x) + (yObjects * y)) == 15:
print("True")
else:
print("False")
I need to create a game that every number that divides in 7 or has the digit 7 should be printed as boom:
[1 2 3 4 5 6 boom 8 ... 13 boom 15 16 boom ...]
my line get invalid text. I think its because of the mix of int and str. not shore what to do to fix the code.
boom7 = [x = "boom" if 7 in x else x*1 for x in range(1,99)]
print(boom7)
almost, this should do it
[ "boom" if "7" in str(x) or x%7==0 else x for x in range(1,99)]
let me know if you need explaining
def seven_boom(end_number):
for x in range(0,end_number+1):
str_first = str(x)
replace_first_num = str_first.replace(str_first[0],"boom")
if "7" in str_first or x%7 ==0:
new_seven_boom = str_first.replace(str_first,"boom")
print(new_seven_boom)
else:
print(x)
replace_last_num = str_first.replace(str_first[-1],"boom")
seven_boom(27)
I've been asked to do the following:
Using a while loop, you will write a program which will produce the following mathematical sequence:
1 * 9 + 2 = 11(you will compute this number)
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
Then your program should run as far as the results contain only "1"s. You can build your numbers as string, then convert to ints before calculation. Then you can convert the result back to a string to see if it contains all "1"s.
Sample Output:
1 * 9 + 2 = 11
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
1234 * 9 + 5 = 11111
Here is my code:
def main():
Current = 1
Next = 2
Addition = 2
output = funcCalculation(Current, Addition)
while (verifyAllOnes(output) == True):
print(output)
#string concat to get new current number
Current = int(str(Current) + str(Next))
Addition += 1
Next += 1
output = funcCalculation(Current, Next)
def funcCalculation(a,b):
return (a * 9 + b)
def verifyAllOnes(val):
Num_str = str(val)
for ch in Num_str:
if(str(ch)!= "1"):
return False
return True
main()
The bug is that the formula isn't printing next to the series of ones on each line. What am I doing wrong?
Pseudo-code:
a = 1
b = 2
result = a * 9 + b
while string representation of result contains only 1s:
a = concat a with the old value of b, as a number
b = b + 1
result = a * 9 + b
This can be literally converted into Python code.
Testing all ones
Well, for starters, here is one easy way to check that the value is all ones:
def only_ones(n):
n_str = str(n)
return set(n_str) == set(['1'])
You could do something more "mathy", but I'm not sure that it would be any faster. It would much more easily
generalize to other bases (than 10) if that's something you were interested in though
def only_ones(n):
return (n % 10 == 1) and (n == 1 or only_ones2(n / 10))
Uncertainty about how to generate the specific recurrence relation...
As for actually solving the problem though, it's actually not clear what the sequence should be.
What comes next?
123456
1234567
12345678
123456789
?
Is it 1234567890? Or 12345678910? Or 1234567900?
Without answering this, it's not possible to solve the problem in any general way (unless in fact the 111..s
terminate before you get to this issue).
I'm going to go with the most mathematically appealing assumption, which is that the value in question is the
sum of all the 11111... values before it (note that 12 = 11 + 1, 123 = 111 + 11 + 1, 1234 = 1111 + 111 + 11 + 1, etc...).
A solution
In this case, you could do something along these lines:
def sequence_gen():
a = 1
b = 1
i = 2
while only_ones(b):
yield b
b = a*9 + i
a += b
i += 1
Notice that I've put this in a generator in order to make it easier to only grab as many results from this
sequence as you actually want. It's entirely possible that this is an infinite sequence, so actually running
the while code by itself might take a while ;-)
s = sequence_gen()
s.next() #=> 1
s.next() #=> 11
A generator gives you a lot of flexibility for things like this. For instance, you could grab the first 10 values of the sequence using the itertools.islice
function:
import itertools as it
s = sequence_gen()
xs = [x for x in it.islice(s, 10)]
print xs
I have the following file I'm trying to manipulate.
1 2 -3 5 10 8.2
5 8 5 4 0 6
4 3 2 3 -2 15
-3 4 0 2 4 2.33
2 1 1 1 2.5 0
0 2 6 0 8 5
The file just contains numbers.
I'm trying to write a program to subtract the rows from each other and print the results to a file. My program is below and, dtest.txt is the name of the input file. The name of the program is make_distance.py.
from math import *
posnfile = open("dtest.txt","r")
posn = posnfile.readlines()
posnfile.close()
for i in range (len(posn)-1):
for j in range (0,1):
if (j == 0):
Xp = float(posn[i].split()[0])
Yp = float(posn[i].split()[1])
Zp = float(posn[i].split()[2])
Xc = float(posn[i+1].split()[0])
Yc = float(posn[i+1].split()[1])
Zc = float(posn[i+1].split()[2])
else:
Xp = float(posn[i].split()[3*j+1])
Yp = float(posn[i].split()[3*j+2])
Zp = float(posn[i].split()[3*j+3])
Xc = float(posn[i+1].split()[3*j+1])
Yc = float(posn[i+1].split()[3*j+2])
Zc = float(posn[i+1].split()[3*j+3])
Px = fabs(Xc-Xp)
Py = fabs(Yc-Yp)
Pz = fabs(Zc-Zp)
print Px,Py,Pz
The program is calculating the values correctly but, when I try to call the program to write the output file,
mpipython make_distance.py > distance.dat
The output file (distance.dat) only contains 3 columns when it should contain 6. How do I tell the program to shift what columns to print to for each step j=0,1,....
For j = 0, the program should output to the first 3 columns, for j = 1 the program should output to the second 3 columns (3,4,5) and so on and so forth.
Finally the len function gives the number of rows in the input file but, what function gives the number of columns in the file?
Thanks.
Append a , to the end of your print statement and it will not print a newline, and then when you exit the for loop add an additional print to move to the next row:
for j in range (0,1):
...
print Px,Py,Pz,
print
Assuming all rows have the same number of columns, you can get the number of columns by using len(row.split()).
Also, you can definitely shorten your code quite a bit, I'm not sure what the purpose of j is, but the following should be equivalent to what you're doing now:
for j in range (0,1):
Xp, Yp, Zp = map(float, posn[i].split()[3*j:3*j+3])
Xc, Yc, Zc = map(float, posn[i+1].split()[3*j:3*j+3])
...
You don't need to:
use numpy
read the whole file in at once
know how many columns
use awkward comma at end of print statement
use list subscripting
use math.fabs()
explicitly close your file
Try this (untested):
with open("dtest.txt", "r") as posnfile:
previous = None
for line in posnfile:
current = [float(x) for x in line.split()]
if previous:
delta = [abs(c - p) for c, p in zip(current, previous)]
print ' '.join(str(d) for d in delta)
previous = current
just in case your dtest.txt grows larger and you don't want to redirect your output but rather write to distance.dat, especially, if you want to use numpy. Thank #John for pointing out my mistake in the old code ;-)
import numpy as np
pos = np.genfromtxt("dtest.txt")
dis = np.array([np.abs(pos[j+1] - pos[j]) for j in xrange(len(pos)-1)])
np.savetxt("distance.dat",dis)