0% found this document useful (0 votes)
13 views9 pages

solutionsExerciseMaster1 10

This document provides code solutions to 10 programming exercises. The solutions cover a range of topics including loops, conditionals, functions, file I/O, regular expressions, and more. Each exercise is solved with a short Python script of 10 lines of code or less.

Uploaded by

Huy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views9 pages

solutionsExerciseMaster1 10

This document provides code solutions to 10 programming exercises. The solutions cover a range of topics including loops, conditionals, functions, file I/O, regular expressions, and more. Each exercise is solved with a short Python script of 10 lines of code or less.

Uploaded by

Huy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Suggested solutions exercises 1-10

1.py
Code

#!/usr/bin/env python3

for i in range(1,1001): # 1001 is exclusive


if i % 3 == 0:
print(i)

2.py
Code

#!/usr/bin/env python3

for i in range(3000,4001): # 4001 is exclusive


if i % 3 == 0:
if i % 5 == 0:
continue
print(i)

1
3.py
Code

#!/usr/bin/env python3

# The number will be imported as a string so we cast it to an integer


userValue = int(input('Type a number: '))

if userValue == 1:
print(1)
elif userValue == 2:
print(1, '\n', 1, sep='')
else:
print(1, '\n', 1, sep='')
values = [1, 1]
for i in range(userValue - 2):
newValue = sum(values)
print(newValue)
values[0] = values[1]
values[1] = newValue

2
4.py
Code

#!/usr/bin/env python3

import sys
number = int(input('Type a number: '))

if number == 0:
print(1) # 0! = 1
sys.exit() # To avoid an else statement
elif number < 0:
print('The number can not be negative', file=sys.stderr)
sys.exit() # To avoid an else statement

total = 1

for i in range(2, number + 1):


total *= i

print(total)

3
5.py
Code

#!/usr/bin/env python3

# https://en.wikipedia.org/wiki/List_of_prime_numbers#The_first_1000_prime_numbers

primeList = ['2'] # Ta be able to join in the last step the list must contain strings
currentValue = 3
while True:

prime = True # We assume that the value we test is a prime

# We only test a factor up to half of the number we investigate to save speed


for i in range(3, int((currentValue + 1) / 2), 2):
# If we find that the number dividable by a smaller number
# it's not a prime and we break
if currentValue % i == 0:
prime = False
break

if prime is True:
# To be able to join in the last step the list must contain strings
primeList.append(str(currentValue))

currentValue += 2 # We only test 3, 5, 7 and so on as the denominators to save speed

if len(primeList) == 1000:
print('\n'.join(primeList))
break

4
6.py
Code

#!/usr/bin/env python3

import re
import sys
import random

nucleotide = ('a', 'c', 'g', 't')

oligo = input('Type a sequence: ')

# Test is the string the user types is valid


matchObject = re.match('[acgtACGT]{' + str(len(oligo)) + '}', oligo)
if not matchObject:
print('Only characters a, c, g, t, A, C, G, T should be used', file = sys.stderr)
sys.exit()

oligoLowercase = oligo.lower() # So we do the comparisons using only lowercase nucleotides

while True: # There is a 25% risk that we pick a nucleotide that the position already has

randomPosition = random.randrange(len(oligo)) # Pick a random position


indexNt = random.randrange(len(nucleotide)) # And the length is of course 4
randomNucleotide = nucleotide[indexNt]

if oligoLowercase[randomPosition] != randomNucleotide:
# The oligo string is immutable so we print out two parts
# that have not changed plus the mutated nucleotide
print(oligoLowercase[:randomPosition] + randomNucleotide + \
oligoLowercase[randomPosition + 1:])
break # When we found a different nucleotide we break the while loop

5
7.py
Code

#!/usr/bin/env python3

ingredients = ['bread']
ingredient1 = input('Input first ingredient: ')
ingredients.append(ingredient1)
ingredient2 = input('Input second ingredient: ')
ingredients.append(ingredient2)
ingredient3 = input('Input third ingredient: ')
ingredients.append(ingredient3)
ingredients.append('bread')

print(ingredients)

6
8.py
Code

#!/usr/bin/env python3

import re
import sys

par = [4, 3, 5, 2, 5, 4, 7, 6]

hole = input('Which hole? ')

# Test is the hole number is valid


matchObject = re.match('[1-8]$', hole) # If we don't use $ the user could input 10
if not matchObject:
print('Only numbers between 1 and 8 can be used', file = sys.stderr)
sys.exit()
hole = int(hole) # Cast from string to integer

strokes = input('How many strokes? ')

# Test is the stroke number is valid


matchObject = re.match('\d+$', strokes)
if not matchObject:
print('Only positive numbers can be used', file = sys.stderr)
sys.exit()
strokes = int(strokes) # Cast from string to integer

result = strokes - par[hole - 1] # -1 to get the index right

if result <= -3:


print('Albatross')
elif result == -2:
print('Eagle')
elif result == -1:
print('Birdie')
elif result == 0:
print('Par')
elif result == 1:
print('Boogie')
elif result >= 2:
print('Double boogie')

7
9.py
Code

#!/usr/bin/env python3

import sys
import os.path

if len(sys.argv) != 3:
print('The program should be run as 9.py fasta_file sequence_id', file=sys.stderr)
sys.exit()

if not os.path.isfile(sys.argv[1]):
print("The input file doesn't exist", file=sys.stderr)
sys.exit()

i = 0 # row counter

with open(sys.argv[1]) as fin:

for line in fin:


i += 1
if line.startswith('>'):
id = line.split()[0]
id = id[1:] # Remove the >
if id == sys.argv[2]:
print('The sequence for id {} starts at line {}'.format(id, i +1))

8
10.py
Code

#!/usr/bin/env python3

import sys
import os.path

if len(sys.argv) != 3:
print('The program should be run as 10.py fastq_input_file fasta_output_file', \
file=sys.stderr)
sys.exit()

if not os.path.isfile(sys.argv[1]):
print("The input file doesn't exist", file=sys.stderr)
sys.exit()

i = 0

with open(sys.argv[1], 'r') as fin, open(sys.argv[2], 'w') as fout:

for line in fin:


i += 1
line = line.rstrip()
if i % 4 == 1:
line = line.replace('@', '>', 1) # Only replace first occurance
print(line, file=fout)
elif i % 4 == 2:
print(line, file=fout)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy