PROGRAMY NAJS Flashcards

1
Q

Write a program to take a number as input, and output a list of all the numbers below that number, that are a multiple of both, 3 and 5.

Sample Input
42

Sample Output
[0, 15, 30]

A

x = int(input())

list=[i for i in range(x) if i % 15 == 0]

print(list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

program do fiszek 1

A
class flashcard:
    def \_\_init\_\_(self, word, meaning):
        self.word = word
        self.meaning = meaning
    def \_\_str\_\_(self):
        #we will return a string 
        return self.word+' ( '+self.meaning+' )'

flash = []
print(“welcome to flashcard application”)

#the following loop will be repeated until
#user stops to add the flashcards
while(True):
    word = input("enter the name you want to add to flashcard : ")
    meaning = input("enter the meaning of the word : ")
flash.append(flashcard(word, meaning))
option = int(input("enter 0 , if you want to add another flashcard : "))

if(option):
    break
# printing all the flashcards 
print("\nYour flashcards")
for i in flash:
    print(">", i)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

program do fiszek 2

A

import random

class flashcard:
    def \_\_init\_\_(self):
    self.fruits={'apple':'red',
                 'orange':'orange',
                 'watermelon':'green',
                 'banana':'yellow'}
    def quiz(self):
        while (True):
        fruit, color = random.choice(list(self.fruits.items()))

        print("What is the color of {}".format(fruit))
        user_answer = input()

        if(user_answer.lower() == color):
            print("Correct answer")
        else:
            print("Wrong answer")

        option = int(input("enter 0 , if you want to play again : "))
        if (option):
            break

print(“welcome to fruit quiz “)
fc=flashcard()
fc.quiz()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Python Program to Calculate the Area of a Triangle

A

Python Program to find the area of triangle

a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Python Program to Generate a Random Number

A

Program to generate a random number between 0 and 9

# importing the random module
import random

print(random.randint(0,9))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Python Program to Check Leap Year

A

Python program to check if year is a leap year or not

year = 2000

# To get year (integer input) from the user
# year = int(input("Enter a year: "))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
    print("{0} is a leap year".format(year))
# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
    print("{0} is a leap year".format(year))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
    print("{0} is not a leap year".format(year))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Python Program to Check Prime Number
Liczby pierwsze

for…else

A

Aby sprawdzić, czy liczba jest liczbą pierwszą, należy sprawdzić czy posiada ona dzielniki inne niż 1 i samą siebie.

Należy pamiętać, że 0 i 1 nie są liczbami pierwszymi, natomiast 2 jest liczbą pierwszą.

Program to check if a number is prime or not

num = 407

# To take input from the user
#num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
   # check for factors
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Program to check if a number is prime or not

Using a flag variable

A

Program to check if a number is prime or not

num = 29

# To take input from the user
#num = int(input("Enter a number: "))
# define a flag variable
flag = False
# prime numbers are greater than 1
if num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break
# check if flag is True
if flag:
    print(num, "is not a prime number")
else:
    print(num, "is a prime number")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Python Program to Print all Prime Numbers in an Interval

A

Python program to display all the prime numbers within an interval

lower = 900
upper = 1000

print(“Prime numbers between”, lower, “and”, upper, “are:”)

for num in range(lower, upper + 1):
   # all prime numbers are greater than 1
   if num > 1:
       for i in range(2, num):
           if (num % i) == 0:
               break
       else:
           print(num)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Python Program to Print the Fibonacci sequence

A

Program to display the Fibonacci sequence up to n-th term

nterms = int(input(“How many terms? “))

# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
# generate fibonacci sequence
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Python Program to Make a Simple Calculator

A

Program make a simple calculator

# This function adds two numbers
def add(x, y):
    return x + y
# This function subtracts two numbers
def subtract(x, y):
    return x - y
# This function multiplies two numbers
def multiply(x, y):
    return x * y
# This function divides two numbers
def divide(x, y):
    return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
    # take input from the user
    choice = input("Enter choice(1/2/3/4): ")
    # check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
    if choice == '1':
        print(num1, "+", num2, "=", add(num1, num2))

    elif choice == '2':
        print(num1, "-", num2, "=", subtract(num1, num2))

    elif choice == '3':
        print(num1, "*", num2, "=", multiply(num1, num2))

    elif choice == '4':
        print(num1, "/", num2, "=", divide(num1, num2))
        # check if user wants another calculation
        # break the while loop if answer is no
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation == "no":
          break
else:
    print("Invalid Input")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Python Program to Display Calendar

A

Program to display calendar of the given month and year

# importing calendar module
import calendar
yy = 2014  # year
mm = 11    # month
# To take month and year input from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Python Program to Sort Words in Alphabetic Order

A

Program to sort alphabetically the words form a string provided by the user

my_str = “Hello this Is an Example With cased letters”

# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = [word.lower() for word in my_str.split()]
# sort the list
words.sort()

display the sorted words

print(“The sorted words are:”)
for word in words:
print(word)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Python Program to Find the Size (Resolution) of a Image

A
def jpeg_res(filename):
   """"This function prints the resolution of the jpeg image file passed into it"""
   # open image for reading in binary mode
   with open(filename,'rb') as img_file:
       # height of image (in 2 bytes) is at 164th position
       img_file.seek(163)
       # read the 2 bytes
       a = img_file.read(2)
       # calculate height
       height = (a[0] << 8) + a[1]
       # next 2 bytes is width
       a = img_file.read(2)
       # calculate width
       width = (a[0] << 8) + a[1]

print(“The resolution of the image is”,width,”x”,height)

jpeg_res(“img1.jpg”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Python Program to Copy a File

A

from shutil import copyfile

copyfile(“/root/a.txt”, “/root/b.txt”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Python Program to generate a Random String

A
import string    
import random # define the random module  
S = 10  # number of characters in the string.  
# call random.choices() string module to find the string in Uppercase + numeric data.  
ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S))    
print("The randomly generated string is : " + str(ran)) # print the random data
17
Q

Python Program to Remove Duplicate Element From a List

A

list_1 = [1, 2, 1, 4, 6]

print(list(set(list_1)))

PRZYKLAD2:

list_1 = [1, 2, 1, 4, 6]
list_2 = [7, 8, 2, 1]

print(list(set(list_1) ^ set(list_2)))

18
Q

Python Program to Create a Countdown Timer

A

import time

def countdown(time_sec):
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = ‘:{:02d}’.format(mins, secs)
print(timeformat, end=’\r’)
time.sleep(1)
time_sec -= 1

print("stop")

countdown(5)

wyjasnienia:
The divmod() method takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder.
end=’\r’ overwrites the output for each iteration.
The value of time_sec is decremented at the end of each iteration.

19
Q

Python Program to Check the File Size

2 wersje

A

import os

file_stat = os.stat(‘my_file.txt’)
print(file_stat.st_size)

———2wersja:

from pathlib import Path

file = Path(‘my_file.txt’)
print(file.stat().st_size)

20
Q

ZADANIE: Pobierz od użytkownika trzy liczby, sprawdź, która jest najmniejsza i wydrukuj ją na ekranie.

POJĘCIA: pętla while, obiekt, typ danych, metoda, instrukcja warunkowa zagnieżdżona.

A
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

op = “t”
while op == “t”:
a, b, c = input(“Podaj trzy liczby oddzielone spacjami: “).split(“ “)

print("Wprowadzono liczby:", a, b, c)
print("\nNajmniejsza:")
    if a < b:
        if a < c:
            najmniejsza = a
        else:
            najmniejsza = c
    elif b < c:
        najmniejsza = b
    else:
        najmniejsza = c
print(najmniejsza)

op = input("Jeszcze raz (t/n)? ")

print(“Koniec.”)

21
Q

ZADANIE: Napisz program, który podany przez użytkownika ciąg znaków szyfruje przy użyciu szyfru Cezara i wyświetla zaszyfrowany tekst.

A
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

KLUCZ = 3

def szyfruj(txt):
    zaszyfrowny = ""
    for i in range(len(txt)):
        if ord(txt[i]) > 122 - KLUCZ:
            zaszyfrowny += chr(ord(txt[i]) + KLUCZ - 26)
        else:
            zaszyfrowny += chr(ord(txt[i]) + KLUCZ)
    return zaszyfrowny
def main(args):
    tekst = input("Podaj ciąg do zaszyfrowania:\n")
    print("Ciąg zaszyfrowany:\n", szyfruj(tekst))
    return 0

if __name__ == ‘__main__’:
import sys
sys.exit(main(sys.argv))

22
Q

Zadanie jest następujące. Przy użyciu języka Python, należy znaleźć najmniejszą oraz największa liczbę na liście.
Czyli, dla przykładu, jeżeli nasza lista to:

lista = [1,4,-4,7]

To najmniejsza liczba wynosi -4, natomiast największa 7.

A

przykład rozwiązania zadania

lista = [1,3,7,11,2,-6,0]

# zmienne przecowujące najmniejsza i największa wartość
# na poczatku przypisujemy im wartość None, aby w pętli for
# wiedzieć że jest to pierwsza interakcja
# później zmienne, zaczynają zawierać liczby z listy
najmniejsza = None
najwieksza = None

for i in lista:

    # przy każdej iteracji, sprawdzamy czy zmienna i 
    # jest mniejsza lub większa niż przechowywane przez
    # nas zmienne
if najmniejsza == None or najmniejsza > i: 
    najmniejsza = i

if najwieksza == None or najwieksza < i:
    najwieksza = i

print (“najmniejsza liczba to:”, najmniejsza)
print (“największa liczba to:”, najwieksza)

23
Q

Naszym zdaniem jest napisać program, grający z użytkownikiem w rzut monetą.
Działanie programu powinno być zbliżone do następującego:

Użytkownik wybiera czy obstawia resztę, czy orła (literka r – reszka, literka o – orzeł)
Po dokonaniu wybory, Komputer odlicza 3,2,1, a następnie dokonuje ‘rzutu’, czyli losowego wyboru orzeł / reszka.
Komputer wyświetla wynik rzutu.
Jeżeli wygrał użytkownik, to dodaje punkt dla użytkownika, jeżeli komputer to dodaje punkt dla komputera.
Wyświetla wyniki
Wracamy do punktu 1.

A

importujemy potrzebne biblioteki

import random
import time

# ustawiamy początkowy wynik dla użytkownika oraz komputera
user = 0
computer = 0 

while True:

    # wczytujemy wybór uzytkownika
    x = input()
    if x == '0': break
    elif x == 'o': x = "orzeł"
    elif x == 'r': x = "reszka"
    else:
        print("Proszę dokonać prawidłowego wyboru:")
        print("o - orzeł")
        print("r - reszka")
        print("0 - zakończenie gry")
        # jezeli użytkownik nie wybrał ani, o, r, 0, to wróć do początku wykonywania pętli 
        continue
    # rzucamy monetą
    y = random.choice(["orzeł", "reszka"])
    # Odliczamy 3,2,1
    for i in range (0,3):
        print (3-i)
        time.sleep(1)
print ("Wynik rzutu: ", y)
    # sprawdzamy kto wygrał
    if x == y: 
        user+=1
    else:
        computer+=1
    # Drukujemy podsumowanie
    print ("Wyniki łacznie.")
    print ("Użytkownik: ", user)
    print ("Komputer: ", computer)
24
Q

program ktory zamyka PC

A

import os

shutdown = input(“Do you wish to shutdown your computer ? (yes / no): “)

if shutdown == ‘no’:
exit()
else:
os.system(“shutdown /s /t 1”)

25
Q

DUZY LOTEK KSIAZECZKA

A

import random

gramy = ‘tak’

podane=[]
wylosowane=[]

while gramy == 'tak':
    for i in range(6):
        podane.append(int(input('podaj liczbę numer ' +str(i+1)+': ')))
        wylosowane.append(random.randint(1,50))
    trafione = 0
    for z in podane:
        for j in wylosowane:
            if z==j:
                trafione=trafione+1
    print('Twój wynik to : ' +str(trafione))
    print('Wylosowane liczby:')
    for i in wylosowane:
        print(i)
    podane.clear()
    wylosowane.clear()
    gramy=input('Czy chcesz zagrac ponownie?')
26
Q

PROGRAM WYLACZAJACY PC WLASNY

A
import os
import time
print('Hello... It\'s '+time.ctime()+'\n')
time.sleep(0.7)
print('Ten program wyłączy komputer.')
time.sleep(0.7)
print ('za ile sekund wylaczyc pc?')
czas=input()
sekundy=czas
godziny= float(sekundy)/3600
os.system ('shutdown /s /t '+str(czas))
print('Wpisałeś '+str(czas) +'sekund.') 
print(' To ' +str(round(godziny,3))+'godzin.')
time.sleep(0.7)
print ('czy chcesz anulowac wylaczenie pc t/n?')
anulowanie=input()
#print ('czy chcesz anulowac wylaczenie pc t/n?')
if anulowanie =='t':
    print('OK, Anulowanie...')
    time.sleep(0.5)
    os.system ('shutdown /a')
elif anulowanie =='n':
    print('Ok')
    time.sleep(3)
    print('Wyłączę się za '+str(godziny)+'godzin,')
    time.sleep(2)
else:
        print('nie rozumię...')
        time.sleep(3)
input('Wcisnij ENTER by wyjsc...')
#MOŻNABY DOLOZYC WYLACZANIE PROGRAMOW, czyszcenie kosza?, moze nawet wlaczanie ambientów z youtuba
27
Q

program do wrzucania postów na grupy facebookowe

A

import pyautogui
import time

groups = [‘251123409000385’,’843804142348443’,’900389246658181’]

time.sleep(5)

pyautogui. keyDown(‘ctrl’)
pyautogui. keyDown(‘t’)
pyautogui. keyUp(‘t’)
pyautogui. keyUp(‘ctrl’)

for i in range(len(groups)):
link = ‘https://facebook.com/groups/’+groups[i]
pyautogui.typewrite(link)
pyautogui.typewrite(‘\n’)

print("Waiting for 45 seconds\n")
time.sleep(45)

pyautogui.typewrite('p')
time.sleep(2)
print("Writing post\n")
pyautogui.typewrite("Hello there, it's a testing post from messy programmers")
time.sleep(4)

pyautogui. keyDown('ctrl')
pyautogui. keyDown('enter')
pyautogui. keyUp('enter')
pyautogui. keyUp('ctrl')

time.sleep(3)

pyautogui. write(['f6'])
time. sleep(1)