1.Write code that opens a file called numbers.txt for writing. Use a loop to wri
ID: 3816846 • Letter: 1
Question
1.Write code that opens a file called numbers.txt for writing. Use a loop to write the numbers from 1 through 30 to the file, and close the file.
Write code that opens the numbers.txt (created above).
(i) Read the numbers from the file
(ii) Adds every third number starting from 1
(iii) Display every third number starting from 1 and displays their total.
2. Given the following sets below:
s1 = {1,2,3,4,5} s2 = {2,4,6,8}
s3 = {1,5,9,13,17}
Write code for the following questions.
(i) Is s1 a subset of s2?
(ii) Is the intersection of s1 and s3 empty? (iii) Union of s1 and s2
(iv) Intersection of s2 and s3
(v) Intersection of s1, s2, and s3
(vi) Difference between s1 and s2 (s1 – s2)
please code in python!
Explanation / Answer
##The python program that writes 30 integer values to file
#called numbers.txt and read the file numbers.txt and calculate
#sum of every third element and print total sum to console
def main():
fileName="numbers.txt"
#open file for writing
filewriter=open(fileName,'w')
#write 1 to 30 numbers to file
for num in range(0,30):
filewriter.write(str(num+1)+' ')
filewriter.close()
print('writing complete')
total=0
counter=1
#Open input file
filereader= open(fileName, 'r')
data=filereader.readline()
#read 1 to 30 numbers to file
while True:
if data == '':
break
# convert from string to number
data = int(data)
if counter % 3 == 0:
print('%d'%counter)
total+=data
counter=counter+1
data = filereader.readline()
filereader.close();
print('Total %d'%int(total))
#calling main method
main()
---------------------------------------------------------------------------
numbers.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
---------------------------------------------------------------------------
Result:
>>>
writing complete
3
6
9
12
15
18
21
24
27
30
Total 165
Note :Please post 2 nd question in another post
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.