Write a program to copy odd lines of one file to another file
file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'w')
lines = file1.readlines()
type(lines)
for i in range(0, len(lines)):
if(i % 2 != 0):
file2.write(lines[i])
file1.close()
file2.close()
file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')
str1 = file1.read()
str2 = file2.read()
print("file1 content...")
print(str1)
print() # to print new line
print("file2 content...")
print(str2)
file1.close()
file2.close()
Write a program to reverse a string that contains digits in Python
def reverse(n):
s=str(n)
p=s[::-1]
return p
num = int(input('Enter a positive value: '))
print('The reverse integer:',reverse(num))
print("Input a string: ")
str1 = input()
no_of_ucase, no_of_lcase = 0,0
for c in str1:
if c>='A' and c<='Z':
no_of_ucase += 1
if c>='a' and c<='z':
no_of_lcase += 1
print("Input string is: ", str1)
print("Total number of uppercase letters: ", no_of_ucase)
print("Total number of lowercase letters: ", no_of_lcase)
print("Input a string: ")
str1 = input()
no_of_letters, no_of_digits = 0,0
for c in str1:
if (c>='a' and c<='z') or (c>='A' and c<='Z'):
no_of_letters += 1
if c>='0' and c<='9':
no_of_digits += 1
print("Input string is: ", str1)
print("Total number of letters: ", no_of_letters)
print("Total number of digits: ", no_of_digits)
Write a python function to implement tower of hanoi
def hanoi(disks, source, auxiliary, target):
if disks == 1:
print('Move disk 1 from peg {} to peg {}.'.format(source, target))
return
hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from peg {} to peg {}.'.format(disks, source, target))
hanoi(disks - 1, auxiliary, source, target)
Write a python program to implement a Stack using One Queue
class Stack:
def __init__(self):
self.q = Queue()
def is_empty(self):
return self.q.is_empty()
def push(self, data):
self.q.enqueue(data)
def pop(self):
for _ in range(self.q.get_size() - 1):
dequeued = self.q.dequeue()
self.q.enqueue(dequeued)
return self.q.dequeue()
class Queue:
def __init__(self):
self.items = []
self.size = 0
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.size += 1
self.items.append(data)
def dequeue(self):
self.size -= 1
return self.items.pop(0)
def get_size(self):
return self.size
s = Stack()
print('Menu')
print('push <value>')
print('pop')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
if s.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'quit':
break