Appending To Files Challenge - python

I write a program to append the times table for our poem in sample.txt
So , this is all of my code
numbers = 1
for i in range(2, 12):
while 13 >= numbers > 0:
multiply = numbers * i
print('| {0} Times {1} is {2} '.format(numbers, i, multiply))
numbers += 1
print('=' * 21)
with open('times_table.txt', 'w') as times:
for table in times:
print(table, file=times)
and the output is:
| 1 Times 2 is 2
| 2 Times 2 is 4
| 3 Times 2 is 6
| 4 Times 2 is 8
| 5 Times 2 is 10
| 6 Times 2 is 12
| 7 Times 2 is 14
| 8 Times 2 is 16
| 9 Times 2 is 18
| 10 Times 2 is 20
| 11 Times 2 is 22
| 12 Times 2 is 24
| 13 Times 2 is 26
========================================
But because of code at the end lines for files appending , I'm facing this error below :
for table in times:
io.UnsupportedOperation: not readable
So , finally I don't know how to append this time table stuffs into a sample.txt file .
I really appreciate you all guys . If you can possibly help me with this .

If you want to append to the file, you should use 'a' instead of 'w' ! you can write these contents on file directly.
numbers = 1
with open('times_table.txt', 'a') as file:
for i in range(2, 12):
while 13 >= numbers > 0:
multiply = numbers * i
file.write(f'| {numbers} Times {i} is {multiply}\n')
numbers += 1
file.write('=' * 21)

Related

How is print('\r') or print(' ') giving me the output?

We were asked to print the following output:
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6
7 7 7 7
8 8 8
9 9
10
I understand that it would require two loops so I tired this:
a = int(input())
i = a
f = 1
while i>0:
for j in range(i):
print(f,end=' ')
f += 1
i -= 1
print('\r')
With this I am getting the desired output, but as soon as I remove the last line of print('\r') the output becomes something like this:
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 6 6 6 6 6 7 7 7 7 8 8 8 9 9 10
The desired output also comes out when I used print(' ') instead of print('\r'), I don't understand why this is happening?
Ps: I am a noob coder, starting my freshman year, so please go easy on me, if the formatting is not up to the mark, or the code looks bulky.
Probably not helping you so much but the following code produces the expected output:
a = 10
for i, j in enumerate(range(a, 0, -1), 1):
print(*[i] * j)
# Output:
1 1 1 1 1 1 1 1 1 1 # i=1, j=10
2 2 2 2 2 2 2 2 2 # i=2, j=9
3 3 3 3 3 3 3 3 # i=3, j=8
4 4 4 4 4 4 4 # i=4, j=7
5 5 5 5 5 5 # i=5, j=6
6 6 6 6 6 # i=6, j=5
7 7 7 7 # i=7, j=4
8 8 8 # i=8, j=3
9 9 # i=9, j=2
10 # i=10, j=1
The two important parameters here are sep (when you print a list) and end as argument of print. Let's try to use it:
a = 10
for i, j in enumerate(range(a, 0, -1), 1):
print(*[i] * j, sep='-', end='\n\n')
# Output:
1-1-1-1-1-1-1-1-1-1
2-2-2-2-2-2-2-2-2
3-3-3-3-3-3-3-3
4-4-4-4-4-4-4
5-5-5-5-5-5
6-6-6-6-6
7-7-7-7
8-8-8
9-9
10
Update
Step by step:
# i=3; j=8
>>> print([i])
[3]
>>> print([i] * j)
[3, 3, 3, 3, 3, 3, 3, 3]
# print takes an arbitrary number of positional arguments.
# So '*' unpack the list as positional arguments (like *args, **kwargs)
# Each one will be printed and separated by sep keyword (default is ' ')
>>> print(*[i] * j)
To make it all easier and prevent errors, you can simply do this:
n = 10
for i in range(1, n + 1):
txt = str(i) + " " # Generate the characters with space between
print(txt * (n + 1 - i)) # Print the characters the inverse amount of times i.e. 1 10, 10 1
Where it generates the text which is simply the number + a space, then prints it out the opposite amount of times, (11 - current number), i.e. 1 ten times, 10 one time.
I suggest using 2 or 4 spaces for indenting. Let's take a look:
a = int(input())
i = a
f = 1
while i>0:
for j in range(i):
print(f,end=' ')
f += 1
i -= 1
print('\r')
Notice the print(f,end=' ') within the inner loop. the end=' ' bit is important because print() appends a trailing new line \n to every call by default. Using end=' ' instead appends a space.
Now take a look at print('\r'). It does not specify end=' ', so it does still append a newline after each call to print. The fact that you additionally print a \r is inconsequential in this case. You could also just do print().
you can do this way :
rows = 10
b = 0
for i in range(rows, 0, -1):
b += 1
for j in range(1, i + 1):
print(b, end=' ')
print('\r')
No need for multiple loops.
for i in range(1,11):
# concatenate number + a space repeatedly, on the same line
# yes, there is an extra space at the end, which you won't see ;-)
print(f"{i} " * (11-i))
output:
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6
7 7 7 7
8 8 8
9 9
10
As to what's happening with your code...
A basic Python print prints on a line, meaning that it ends with a line feed (which moves it to the next line).
So, if I take your word for it, you've done all the hard work of say the first line of 10 ones with spaces, when you are done at the following point.
#your code
f += 1
i -= 1
Now, so far you've avoided that line feed by changing the end parameter to print so that it doesn't end with a newline. So you have:
1 1 1 1 1 1 1 1 1 1
And still no line feed. Great!
But if you now start printing 2 2 2 2 2 2 2 2 2 , it will just get added to... the end of the previous line, without line feed.
So to force a line feed, you *print anything you want, but without the end parameter being set, so that print now ends with the linefeed it uses by default.
Example:
#without line feed
print("1 " * 3, end=' ')
print("2 " * 2, end=' ')
output:
1 1 1 2 2
Lets try printing something, anything, without a end = ' ')
print("1 " * 3, end=' ')
#now add a line by a print that is NOT using `end = ' '`
print("!")
print("2 " * 2, end=' ')
output:
1 1 1 !
2 2
OK, so now we have a line feed after ! so you jump to the next line when printing the 2s. But you don't want to see anything after the 1s.
Simples, print anything that is invisible.
print("1 " * 3, end=' ')
#now add a line by a print, but using a non-visible character.
#or an empty string. Tabs, spaces, etc... they will all work
print(" ")
print("2 " * 2, end=' ')
output:
1 1 1
2 2
This would also work:
print("1 " * 3, end=' ')
#we could also print a linefeed and end without one...
print("\n", end="")
print("2 " * 2, end=' ')

How to make code to print 1 2 3 4 2 2 3 4 3 2 3 4, and so on? using For Loops [duplicate]

This question already has answers here:
Print several values in the same line with commas
(2 answers)
Closed 4 years ago.
I need to modify this code, to replace the
number 1 with the number of the current measure. So, the first
number in each measure will always rise.
instead of
1
2
3
4
1
2
3
4
1
2
3
4
(with each number on its own line), I'd now print
1 2 3 4 2 2 3 4 3 2 3 4
, and so on.
beats_per_measure = 4
measures = 5
for measure in range(0, measures):
for beat in range(1, beats_per_measure + 1):
print(beat)
Perhaps you need something like below.
beats_per_measure = 4
measures = 5
### loop from 1 to 5 measures ###
# remove +1 to get sequence of 4
# iterations
for measure in range(1, measures+1):
# print the measure value in a single line
# first at iteration of outer loop to get
# the sequence
print(measure, end = " ")
## then loop from 2 to measure
for beat in range(2, beats_per_measure + 1):
# print each beat
print(beat, end = " ")
Output
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4
If you are using python 3, this is the answer(tested):
beats_per_measure = 4
measures = 5
for measure in range(1, measures+1):
print(measure, end = ' ')
for beat in range(2, beats_per_measure + 1):
print(beat, end = ' ')
Or if you are using python 2, use this (tested):
beats_per_measure = 4
measures = 5
for measure in range(1, measures+1):
print measure,
for beat in range(1, beats_per_measure + 1):
print beat,
More info here: https://www.quora.com/How-do-I-print-something-on-the-same-line-in-Python
You can solve this by manually printing the measure you are currently in - followed by the remaining beats:
beats_per_measure = 4
measures = 5
for m in range(measures):
# manually print the measure you are in
print(m+1, end=" ") # do not put a newline after the print statement
# print the beats 0...bmp-1 == 0,1,2 - output adds 2 to each => 2,3,4
for beat in range(beats_per_measure - 1):
print(beat+2, end = " ") # do not put a newline after the print statement
Output:
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4
* * * * *
The * are manually printed, the others filled in by the for-loop
You can read more about printing in one line here:
Print in one line dynamically
Python: multiple prints on the same line
Print several values in the same line with commas
Doku: https://docs.python.org/3/library/functions.html#print
You can also create a generator that counts measures on its own (I'll mark the measure-number with * manually):
def gimme_measure(beats_per_measure):
beats = list(range(2,beats_per_measure+1))
yield gimme_measure.measure
gimme_measure.measure += 1
yield from beats
gimme_measure.measure = 1 # defines the starting measure
# print 2*10 measures
for _ in range(10):
print(*gimme_measure(4), end = " ") # the * decomposes the values from the generator
for _ in range(10): # continues the beat measuring
print(*gimme_measure(4), end = " ") # the * decomposes the values from the generator
Output:
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4 6 2 3 4 7 2 3 4 8 2 3 4 9 2 3 4 10 2 3 4 11 2 3 4 12 2 3 4 13 2 3 4 14 2 3 4 15 2 3 4 16 2 3 4 17 2 3 4 18 2 3 4 19 2 3 4 20 2 3 4
* * * * * * * * * ** ** ** ** ** ** ** ** ** ** **
The generator gimme_measure has it's own measure counter which is initialized to 1 and incremented each time you generate a new measure using the generator - if you do not reset the gimme_measure.measure to some other number it keeps counting upwards any time you print another generated measure.
You can even chain different bpm together:
# piece with 2 measures of 4 beats, 2 measures of 8 beats, 2 measures of 3 beats
for _ in range(2):
print(*gimme_measure(4), end = " ")
for _ in range(2): # continues the beat measuring
print(*gimme_measure(8), end = " ")
for _ in range(2): # continues the beat measuring
print(*gimme_measure(3), end = " ")
Output:
1 2 3 4 2 2 3 4 3 2 3 4 5 6 7 8 4 2 3 4 5 6 7 8 5 2 3 6 2 3
* * * * * *

How can I split a column in a specific range?

I'm working with proteins trajectory and I've got a long data frame. (File with one column and 600.000 lines.
This is and example:
100
100
0
100
100
...
n=600.000
What I wish is to split this data every 3000 lines, creating a new column beside like this example:
Col1 Col2 Col3 Col4 Col...200:
n=1 n=3001 n=6001 n=9001 ...
0 0 0 0 ...
0 0 0 0 ...
100 100 100 100 ...
... ... ... ... ...
n=3000 n=6000 n=9000 n=12000 n=600.000
n= line number.
Is there any way to do this in R or bash?
Thank you very much in advance.
EDIT: I'm using this script in python to generate that column:
from decimal import *
i = 1
while(i <= 15):
output = open('cache/distances_'+str(i)+'.dat.results', 'w')
with open('cache/distances_medias_'+str(i)+'.dat', 'r') as f:
for line in f:
columns = line.split(' ')
if(Decimal(columns[0]) <= 2.5 and (Decimal(columnas[1]) > 120 and Decimal(columnas[1]) < 180)):
salida.write("100\n")
else:
salida.write("0\n")
salida.close()
i+=2
Is there any way to modify the script and when it reaches the line 3000, start in a new column?
I am not sure I understand your example, but you should be able to use a combination of split and paste:
$ cat filetosplit
1
2
3
4
5
6
7
8
9
10
$ split filetosplit "split." -l 3 -d ; paste split*
1 4 7 10
2 5 8
3 6 9
The split command will generate files for 3 lines per row (you can modify to 3000). The paste will put all them together. You can use sed to add an header with column names and initial number.
In R you may just may add a dim attribute:
dim(your_vector) <- c(3000, 600000/3000)
It will change an object class to matrix, so if you need data frame, you will need:
df <- data.frame(your_vector)
With awk:
awk -v n=5 '{data[(NR-1)%n FS int((NR-1)/n)]=$0}
END {cols=NR/n;
for (i=0;i<n;i++) {
for (j=0;j<cols;j++)
printf "%s%s", data[i FS j], FS}
print ""
}
}'
That is: store all the content in a kind-of matrix and then loop accordingly.
Sample outputs
$ seq 15 | awk -v n=3 '{data[(NR-1)%n FS int((NR-1)/n)]=$0} END {cols=NR/n; for (i=0;i<n;i++) {for (j=0;j<cols;j++) {printf "%s%s", data[i FS j], FS} print ""}}'
1 4 7 10 13
2 5 8 11 14
3 6 9 12 15
$ seq 15 | awk -v n=7 '{data[(NR-1)%n FS int((NR-1)/n)]=$0} END {cols=NR/n; for (i=0;i<n;i++) {for (j=0;j<cols;j++) {printf "%s%s", data[i FS j], FS} print ""}}'
1 8 15
2 9
3 10
4 11
5 12
6 13
7 14
$ seq 15 | awk -v n=5 '{data[(NR-1)%n FS int((NR-1)/n)]=$0} END {cols=NR/n; for (i=0;i<n;i++) {for (j=0;j<cols;j++) {printf "%s%s", data[i FS j], FS} print ""}}'
1 6 11
2 7 12
3 8 13
4 9 14
5 10 15

Improving runtime of truck pick up and drop off

If anyone can help with improving the runtime that would be great!
I have a truck that has a max capacity of C and a beginning stock on it of S1 The truck goes through a fixed route Depot --> 1 --> 2 --> ... --> N-1 --> N --> Depot
Each station i=1…n has a current stock items of Xi and the objective stock items of Xi* At each station the truck can decide to drop-off or take the amount of items possible according to the situation. Let Yi be the number of items left after the truck visited station i The total cost is TC (as written in the code).
I implemented a dynamic programming code whereas xd is the number of units taken or dropped at each station and s is the number of items on the truck:
run on -min(c-s,xi)<= xd <= s: f(i,s) = f(i+1, s-xd) - so if xd is in minus it means the truck took items from a station.
this is the code - the problem is that it's running for days and not returning an answer.
anyone know a way to implement it better?
n = 50
c=10
s1 = 6
xi = [59,33,14,17,26,31,91,68,3,53,53,73,86,24,98,37,55,14,97,61,57,23,65,24,50,31,39,31,24,60,92,80,48,28,47,81,19,82,3,74,50,89,86,37,98,11,12,94,6,61]
x_star = [35,85,51,88,44,20,79,68,97,7,68,19,50,19,42,45,8,9,61,60,80,4,96,57,100,22,2,51,56,100,6,84,96,69,18,31,86,6,39,6,78,73,14,45,100,43,89,4,76,70]
c_plus = [4.6,1.3,2.7,0.5,2.7,5,2.7,2.6,4.1,4,3.2,3.1,4.8,3.1,0.8,1,0.5,5,5,4.6,2.5,4.1,2.1,2.9,1.4,3.9,0.5,1.7,4.9,0.6,2.8,4.9,3.3,4.7,3.6,2.4,3.4,1.5,1.2,0.5,4.3,4.3,3.9,4.8,1.2,4.8,2,2.2,5,4.5]
c_minus = [8.7,7.5,11.7,6.9,11.7,14.4,7.5,11.1,1.2,1.5,12,8.1,2.7,8.7,9.3,1.5,0.3,1.5,1.2,12.3,5.7,0.6,8.7,8.1,0.6,3.9,0.3,5.4,14.7,0,10.8,6.6,8.4,9.9,14.7,2.7,1.2,10.5,9.3,14.7,11.4,5.4,6,13.2,3.6,7.2,3,4.8,9,8.1]
dict={}
values={}
def tc(i,xd):
yi = xi[i-1] + xd
if yi>=x_star[i-1]:
tc = c_plus[i-1]*(yi-x_star[i-1])
else:
tc = c_minus[i-1]*(x_star[i-1]-yi)
return tc
def func(i,s):
if i==n+1:
return 0
else:
a=[]
b=[]
start = min(c-s,xi[i-1])*-1
for xd in range(start,s+1):
cost = tc(i,xd)
f= func(i+1,s-xd)
a.append(cost+f)
b.append(xd)
min_cost = min(a)
index = a.index(min_cost)
xd_optimal = b[index]
if i in values:
if values[i]>min_cost:
dict[i] = xd_optimal
values[i] = min_cost
else:
values[i] = min_cost
dict[i] = xd_optimal
return min_cost
best_cost = func(1,s1)
print best_cost
print dict
First, the solution:
The function is called very often with exactly the same parameters. Thus, I added a cache that avoids repeating the calculations for recurring parameter sets. This returns the answer almost instantly on my computer.
cache = {}
def func(i,s):
if i==n+1:
return 0
else:
try:
return cache[(i,s)]
except KeyError:
pass
a=[]
...
cache[(i,s)] = min_cost
return min_cost
And here is how I found out what to do...
I modified your code to produce some debug output:
...
count = 0
def func(i,s):
global count
count += 1
print count, ':', i, s
...
Setting n to 2 results in the following output:
1 : 1 6
2 : 2 10
3 : 3 10
4 : 3 9
5 : 3 8
6 : 3 7
7 : 3 6
8 : 3 5
9 : 3 4
10 : 3 3
11 : 3 2
12 : 3 1
13 : 3 0
14 : 2 9
15 : 3 10
16 : 3 9
17 : 3 8
18 : 3 7
19 : 3 6
20 : 3 5
21 : 3 4
22 : 3 3
23 : 3 2
24 : 3 1
25 : 3 0
26 : 2 8
27 : 3 10
28 : 3 9
29 : 3 8
30 : 3 7
31 : 3 6
32 : 3 5
...
You will notice that the function is called very often with the same set of parameters.
After (i=2, s=10) it runs through all combinations of (i=3, s=x). It does that again after (i=2, s=9). The whole thing finishes after 133 recursions. Setting n=3 takes 1464 recursions, and setting n=4 takes 16105 recursions. You can see where that leads to...
Remark: I have absolutely no idea how your optimization works. Instead I simply treated the symptoms :)

Multiplication Table For Python in IEP?

I Am using python 3.3 with IEP and i am trying to make a multiplication table that is nice an orderly. Everywhere i look online says it will be nice but it ends up just being 1 row and long where i want
1 2 3 4
2 4 6 8
3 6 9 12
the code i find is generally like this... SO whats wrong with it?
def main():
i = 1
print("-" * 50)
while i < 11:
n = 1
while n <= 10:
print("%4d" % (i * n),)
n += 1
print("")
i += 1
print("-" * 50)
main()
Because there is a line break after each print
Change 7th line to
print("%4d" % (i * n), end=" ")
The problem is right here:
print("%4d" % (i * n),)
Each print call implicitly puts a line break at the end of the output, but you can change that by providing the end keyword argument to print().
You can do something like this:
In [1]: def print_table(size):
...: for i in range(1, size+1):
...: print(''.join('{:>4d}'.format(i*j) for j in range(1, size+1)))
...:
In [2]: print_table(5)
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Categories