text stringlengths 37 1.41M |
|---|
def overlapping(lst1, lst2):
lst= list(set(lst1) & set(lst2))
if lst!=[]:
return True
else:
return False
lst1 = [int(item) for item in input("Enter numbers space separated : ").split()]
lst2 = [int(item) for item in input("Enter numbers space separated : ").split()]
print(overlapping... |
#---------------------------Clase Persona-------------------------------------------------->
class Persona():
#this java funcion constructor
def __init__(self, nombre, apellido, edad):
self.nombre = nombre
self.apellido = apellido
self.edad = edad
@property #cambiar la funcion en a... |
entrada = input()
entrada = entrada.split()
n = int(entrada[0])
m = int(entrada[1])
A = ""
for i in range(n,m+1):
if i % 5 == 0:
A = A+str(i)+"|"
A = A.strip("|")
print(A)
|
x = input('enter the string:')
if (x == x[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome") |
print("Choose Options To Perform : ")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
choice = int(input("Enter Your Choice :"))
a = int(input("Enter First Number :"))
b = int(input("Enter Second number:"))
if (choice==1) :
print("Addition of A + B is : {} ".format(a+b))
elif (... |
'''
Determine the prime factors of a given positive integer.
Construct a flat list containing the prime factors in ascending order.
Example:
* (prime-factors 315)
(3 3 5 7)
'''
def calcPrimeFactorsList(number):
divisor_number = 2
prime_factors_list = list()
while number > 1.0: # checking ... |
'''
Pack consecutive duplicates of list elements into sublists.
If a list contains repeated elements they should be placed in separate
sublists.
Example:
* (pack '(a a a a b c c a a d e e e e))
((A A A A) (B) (C C) (A A) (D) (E E E E))
'''
#taking input of list elements at a single time seperating by space and... |
'''
Generate a random permutation of the elements of a list.
Example:
* (rnd-permu '(a b c d e f))
(B A D C E F)
'''
#importingrandint function from random module
from random import randint
input_list = input("Enter list seperated by space(max 10): ").split(' ')
print(f"given list is: {input_list}")
#... |
'''
Eliminate consecutive duplicates of list elements.
If a list contains repeated elements they should be replaced with a
single copy of the element. The order of the elements should not be
changed.
Example:
* (compress '(a a a a b c c a a d e e e e))
(A B C A D E)
'''
#taking input of list elements at a si... |
'''
Truth tables for logical expressions (2).
Continue problem P46 by defining and/2, or/2, etc as being operators.
This allows to write the logical expression in the more natural way,
as in the example: A and (A or not B). Define operator precedence as
usual; i.e. as in Java.
Example:
* table(... |
'''
Binary search trees (dictionaries)
Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer numbers.
Example:
* construct([3,2,5,7,1],T).
T = t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil)))
Then use t... |
import fractions
import random
def perfect_power(n):
"""Get the integer and power that make up `n`.
Args:
n (int): The number to check.
Returns:
A tuple containing the values that correspond to the perfect powers of n
or None if they do not exist. For example:
(2, 3)
... |
#Factorial workshop
def factorial(num):
toFactorial = 1
for numFactorial in range(1,(num+1)):
toFactorial *= numFactorial
return toFactorial
num = int(input("Enter a number :"))
if (num < 0) :
print("factorial of negative number cannot calculate")
else:
print(factorial(num)) |
#list
print("---- STUDENT ----")
students = ["Yusuf","Talha"]
print(students[1])
#append
print("---- APPEND ----")
students.append("Arda")
print(students[2])
#remove
print("---- REMOVE ----")
students.remove("Arda")
print("students[2] WILL BE SHOWING ERROR")
print("---- CITIES ----")
cities = list(("Ne... |
# Variables
counter = 10 # An integer assignment
miles = 250.75 # A floating point
name ="Yusuf" # A string
boolean= True # A bool variable, its turn true and false
print(counter)
print(miles)
print(name)
print(boolean)
#Output
# 10
# 250.75
# Yusuf
# True |
#map
numbers = [1,2,3,4,5]
numbersSquared = list(map(lambda x: x**2,numbers))
# for i in numbers:
# numbersSquared.append(i*i)
print(numbersSquared)
#filter
numbersFiltered = list(filter(lambda x: x>2,numbers))
print(numbersFiltered)
#reduce
from functools import reduce
numbersFactorial = reduce... |
exit_choice="nothing"
while exit_choice !="EXIT":
intentos=5
contraseña="desactivar"
print("Te acabas de encontrar una bomba en tu casa")
print("Explotará a menos que pongas la contraseña correcta")
print("Tienes cinco intentos")
guess=input("Introduzca contraseña: ")
while guess !=c... |
import random
player_choice="nothing"
while player_choice != "EXIT":
number=random.randint(1,10)
adivinanza=int(input("Estoy pensando en un número entre el 1 y el 10...¿Cúal crees que es?: "))
while adivinanza !=number:
if adivinanza<number:
print("Ese número es demasiado bajo")
... |
from google_API import *
def main():
exit_code = True
while exit_code:
location = input("Enter address or zip code: ")
place_of_interest = input(f"What do you want to find at {location}? ")
location_radius = input(f"How far around {location} do you want to search?(meters) ")
c... |
# coding: utf-8
# 本项目要求矩阵统一使用二维列表表示,如下:
A = [[1,2,3],
[2,3,3],
[1,2,5]]
B = [[1,2,3,5],
[2,3,3,5],
[1,2,5,1]]
#TODO 创建一个 4*4 单位矩阵
def identity_matrix(n):
I = [0] * n
for i in range(0, n):
I[i] = [0]*n
I[i][i] = 1
return I
print identity_matrix(4)
# 使用len直接获取矩阵的行和列数
de... |
def func():
global x
print 'x beginning of func(): ',x
x=2
print 'x ending of func(): ',x
x=50
func()
print 'x after calling func(): ',x
|
# 10 nested squares
import turtle
def square(width):
turtle.forward(width)
turtle.left(90)
turtle.forward(width)
turtle.left(90)
turtle.forward(width)
turtle.left(90)
turtle.forward(width)
turtle.left(90)
turtle.shape('turtle')
y = 5
x = 0
for i in range(0, 25):
x += y
squar... |
numbers = range(10)
print(numbers)
print(type(numbers))
print(list(numbers)) # Если хотим посмотреть все элементы
numbers = range(0, 51, 5)
print(list(numbers)) |
# Write only positive numbers to the list
numbers = [1, 2, 3, 4, 5, -1, -2, -3]
# Classic method
result = []
for number in numbers:
if number > 0:
result.append(number)
print(result)
# Using 'filter' function
result = filter(lambda number: number > 0, numbers)
print(list(result))
# Using list-generator... |
# Open the file for writing bytes
with open('bytes.txt', 'wb') as f:
str = 'Привет мир'
f.write(str.encode('utf-8'))
with open('bytes.txt', 'w', encoding='utf-8') as f:
f.write('Привет мир')
# Reading text as bytes
with open('bytes.txt', 'rb') as f:
result = f.read()
print(result)
print(type(... |
# Написать функцию is_full_house, которая принимает список карт (руку, 5 карт иначе говоря)
# и определяет наличие комбинации Full House на руке.
# Возвращает True, если определён Full House, в противном случае - False.
# Full House это когда из пяти карт 2 одного достоинства и 3 одного достоинства (но отличающегося от... |
friends = 'Максим Леонидович'
print(friends[0])
print(friends[1])
print(friends[-1])
print(len(friends))
print(friends.find('Лео'))
print(friends.split())
print(friends.isdigit())
print(friends.upper())
print(friends.lower())
help(list)
|
# Draw a spiral
import turtle
turtle.shape('turtle')
for i in range(1000):
turtle.forward(i * 0.001)
turtle.left(2)
|
import math
numbers = [4, 1, 2, 3, -4, -2, 7, 16]
# Create list from numbers that have square root of less than 2
result = []
# Classic method
for number in numbers:
if number > 0:
sqrt = math.sqrt(number)
if sqrt < 2:
result.append(number)
print(result)
result = []
# with AND
for n... |
# На вход программа получает набор чисел, заканчивающихся решеткой.
# Вам требуется найти: среднее, максимальное и минимальное число в последовательности.
# Так же нужно вывести cумму остатков от деления суммы троек на последнее число тройки
# (каждые 3 введеных числа образуют тройку).
#
# Для понимания рассмотрим прим... |
def check_sorted(A, ascending=True):
"""
Проверка отсортированности за О(len(A))
Function checks array sorting for O(n)
:param A:
:param ascending:
:return:
"""
flag = True
s = 2 * ascending - 1
for i in range(0, len(A) - 1):
if s * A[i] > s * A[i + 1]:
flag =... |
# слово -> СлОвО
word = 'рефрежератор'
result = []
for i in range(len(word)):
letter = word[i].lower() if i % 2 != 0 else word[i].upper()
result.append(letter)
result = ''.join(result) # conversion from list to string
print(result) |
# Вычислите XOR от двух чисел.
#
# Входные данные
# Два целых шестнадцатеричных числа меньших FF.
#
# Выходные данные
# Побитовый XOR этих чисел в шестнадцетиричном виде.
numbers = [int(n, 16) for n in input().split()]
a = numbers[0]
b = numbers[1]
# print(f'{a^b:02x}')
print("{0:x}".format(a ^ b))
|
# Python3 распознает ввод значений переменных
# в разных системах счислениях
# Запись начинается с 0, т.к Python3 понимает,
# что с буквы начинаются все переменные
x = 0b111101 # Ввод числа в двоичной системе "0b" - двоичная
print(x) # Вывод будет в 10-ой системе счисления
y = 0o0732 # Ввод числа в восьмеричной с... |
# Common string
s = 'Hello world'
# String bytes
sb = b'Hello bytes'
# Index of common string
print(s[1]) # The result will be 'e'
# Index of string bytes
print(sb[1]) # The result will be '101'
# Slice of common string
print(s[1:3]) # The result will be 'el'
# Slice of string bytes
print(sb[1:3]) # The re... |
import random
def game_reverse():
user_number = int(input('Enter a number between 0 and 100: '))
result = None
min_result = 0
max_result = 100
while result != '=':
number = random.randint(min_result, max_result)
print(number)
result = input('Enter your decision (Exam.">","... |
# Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках.
# Примечание: Списки фруктов создайте вручную в начале файла.
fruit_list_1 = ['груша', 'яблоко', 'манго', 'абрикос', 'слива', 'алыча',
'вишня', 'папая', 'клубника', 'бананы', 'апельсин', 'мандарин']
fruit_li... |
cities = {'Las Vegas', 'Paris', 'Moscow'}
print(cities)
cities.add('Berlin')
cities.add('London')
print(cities)
cities.remove('Moscow')
print(cities)
print(len(cities))
print('London' in cities)
for city in cities:
print(city) |
import turtle
corner = 0
turtle.shape('turtle')
while corner != 1000: # Result is circle
turtle.forward(2)
turtle.left(1)
corner += 1
|
from tkinter import *
def new_win():
win = Toplevel(root)
label1 = Label(win, text='Text on TopWindow level', font=20)
label1.pack()
def exit_app():
root.destroy() # Уничтожаем главное окно и всех его потомков
root = Tk()
main_menu = Menu(root)
root.configure(menu=main_menu)
first_item = Menu(m... |
from matplotlib import pyplot as plt
def neighbours(x,y,image):
img = image.copy()
row, column = img.shape
x_left, x_right, y_down, y_up = neighbors = x-1, x+1, y-1, y+1
neighbours = -1
for i in range(x_left, x_right+1):
for j in range(y_down, y_up+1):
neighbours += image[j][... |
edad = input('ingrese su edad \n==>')
if edad.isnumeric():
edad = int(edad)
if edad<18:
print('no pasas')
elif edad >= 17 and edad <21:
print('paga 60 tanto')
elif edad >22:
print('paga 70 dolares')
else:
print('paga 50 dolares especil')
else:
print(... |
""" Write a function distance_between_points(p1, p2) that takes two points
and returns the Cartesian distance between them.
"""
import math
class Point:
"""Represents a point in a 2D space"""
def distance(point_a,point_b):
dis=math.sqrt((point_a.x-point_b.x)**2+(point_a.y-point_b.y)**2)
return dis
poi... |
firstnumber = int(raw_input("Enter first number"))
secondnumber = int(raw_input ("Enter the number that you wich to multiply by"))
print "Are this the numbers that you which?"
print firstnumber, "X", secondnumber
for i in range(1, secondnumber + 1):
print firstnumber, 'times', i, '=', secondnumber * i
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 19:16:49 2021
@author: nitinsinghal
"""
# Chapter 10 - Unsupervised Learning - Clustering
# KMeans and Kmeans++ Clustering
#Import libraries
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn import metrics
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 16:47:15 2021
@author: nitinsinghal
"""
# Chapter 2 - Pandas - Data Analysis Library
import pandas as pd
import numpy as np
d = {'item': ['a','b','c','d','e','f'],
'price': [10, 25, 33.43, 51.2, 9, np.nan],
'quantity': [48, 12, 7, 3, 8... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 13:27:51 2021
@author: nitinsinghal
"""
# Chapter 1 – Programming – Python
# Data Structures
# Lists
mylist = [1,3,6,8,9,9,15]
print(mylist)
print(mylist[1])
mylist[5] = 18
print(mylist)
mylist.append(32)
print(mylist)
words = ['car', 'fruit'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 13:27:51 2021
@author: nitinsinghal
"""
# Chapter 1 – Programming – Python
# Data Structures
#Sets
myset = {'cow', 'cat', 'dog'}
print(myset)
print(myset[0])
myset.add('rat')
print(myset)
myset.remove('cow')
print(myset)
print(myset.pop())
m... |
fresh_tea_list = [ {'name':'阿里山冰茶', 'price':"25",'尺寸':'L'},
{'name':'日月潭紅玉', 'price':"30",'尺寸':'L'},
{'name':'文山包種茶', 'price':"35",'尺寸':'XL'},
]
fresh_tea_list_price1 = int(fresh_tea_list[0]['price'])
fresh_tea_list_price2 = int(fresh_tea_list[1]['price'])
fresh_tea_... |
import sys
def reverse(string):
print(string[::-1])
if __name__ == "__main__":
input = sys.argv[1]
reverse(input) |
def binary_search(A, toFind):
left = 0
right = len(A) - 1
while left <= right:
mid = (left + right) // 2
if A[mid] == toFind: # Returns index
return mid
elif A[mid] < toFind: # If smaller than toFind, discard current and left side.
left = mid... |
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
root = l3 = ListNode(0)
while l1 or l2 or carry:
if l1:
val1 = l1.val
l1 = l1.next
... |
a=int(input('Enter range of series: '))
b=0
c=1
r=" "
print('FIBONACCI SERIES: ')
for i in range(a+1):
print(b, r)
d=b+c
b=c
c=d
|
R = float(input())
v = (4/3.0) * 3.14159 * (R*R*R)
print("VOLUME = {:.3f}".format(v))
|
d = input().split()
a = float(d[0])
b = float(d[1])
c = float(d[2])
tri = a*c/2
cir = 3.14159*(c*c)
tra = (a+b)/2 *c
qua = b*b
ret = a*b
print("TRIANGULO: {:.3f}\nCIRCULO: {:.3f}\nTRAPEZIO: {:.3f}\nQUADRADO: {:.3f}\nRETANGULO: {:.3f}".format(tri, cir, tra, qua, ret)) |
for i in range(int(input())):
stack = list()
a = input()
for j in a:
if(j == '(') :
stack.append('(')
elif(j == ')') :
if (len(stack) == 0 or stack[0] != '(') : stack.append("Error")
else : stack.pop()
if(len(stack)==0) : print("YES")
else : print... |
""" Linear Algebra Project 1
202011353 이호은 """
import cv2
import numpy as np
# N by N Haar Matrix 생성
def MakeNHaarMatrix(n):
array_A = np.array([[1], [1]])
array_B = np.array([[1], [-1]])
# n이 1이면
if n == 1:
return np.array([1])
# n이 2 이상이면
else:
m = 1
H_m = np.a... |
def check(a,b,c):
if (a+b==c or a-b == c or b-a==c or b*a== c):
print("Possible")
return
elif a == 0 and c == 0:
print("Possible")
return
elif b == 0 and c == 0:
print("Possible")
return
elif a/b == c or b/a ==c:
print("Possible")
return
... |
from math import cos, sin, radians
def check_safe(v0, theta, x1, h1, h2):
t = x1/(v0*cos(radians(theta)))
center = v0*t*sin(radians(theta))-.5*9.81*(t**2)
if center-1 > h1 and center+1 < h2:
print("Safe")
else:
print("Not safe")
cases = int(input())
for i in range(cases):
v0, theta... |
steps = list(map(int, input().split(" ")))
min_side = min(steps)
max_side = -1
max_steps = max(steps)
second_biggest = -1
idx = -1
found_max = False
for i in range(4):
if (steps[i] == max_steps and found_max is False):
found_max = True
elif steps[i] == max_steps:
max_side = max_steps
bre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
class Food(object):
def __init__(self, game):
self.position = None
self.color = (255, 0, 0)
self.game = game
def draw(self):
if self.position:
self.game.draw_rect(self.position, self.color)
... |
# NOTE: This problem is a significantly more challenging version of Problem 81.
#
# In the 5 by 5 matrix below, the minimal path sum from the top left to the
# bottom right, by moving left, right, up, and down, is indicated in bold
# red and is equal to 2297.
#
# 131 673 234 103 18
# 201 96 342 965 150
# 630 803 746 4... |
# In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.
#
# 131 673 234 103 18
# 201 96 342 965 150
# 630 803 746 422 111
# 537 699 497 121 956
# 805 732 524 37 331
#
# Find the minimal path sum, in ... |
#
#
# A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
#
# 012 021 102 120 201 ... |
#
#
# If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
#
# Not all numbers produce palindromes so quickly. For example,
#
# 349 + 943 = 1292,
# 1292 + 2921 = 4213
# 4213 + 3124 = 7337
#
# That is, 349 took three iterations to arrive at a palindrome.
#
# Although no one has proved it yet, it is... |
from microbit import *
pin1.write_analog(90) # reset to straight on start
MAX_ANGLE = 15
MID_ANGLE = 90
def norm(n):
"""
Normalise an accelerometer reading across an angle.
Returns an offset angle to apply to the base (90) in
whichever direction it is steering.
"""
n = abs(n)
if n < 100:
... |
#!/usr/bin/python3
def fizzbuzz():
for fb in range(1, 101):
if fb % 3 == 0 and fb % 5 == 0:
print("FizzBuzz ", end='')
elif fb % 3 == 0:
print("Fizz ", end='')
elif fb % 5 == 0:
print("Buzz ", end='')
else:
print("{} ".format(fb), end='... |
#!/usr/bin/python3
"""
function that reads a text file (UTF8) and prints it to stdout
"""
import json
def to_json_string(my_obj):
"""defining to_json_string function"""
return json.dumps(my_obj)
|
#!/usr/bin/python3
for alpha in range(9):
for alpha2 in range(alpha + 1, 10):
if alpha != alpha2:
if alpha == 8 and alpha2 == 9:
print("{}{}".format(alpha, alpha2))
else:
print("{}{}, ".format(alpha, alpha2), end='')
else:
continue
|
count = 10
while count > 0:
if count % 2 == 0:
print(count)
count = count - 1
print("Happy New Year!")
|
from turtle import *
# count = 4
#
# while count > 0 :
# print(forward(300))
# right(90)
# count = count -1
# steve = 1
# limit = 300
#
# speed(30)
# pencolor('cyan')
#
# while steve < limit :
# forward(steve)
# left(89)
# steve = steve + 1
print ( bgcolor("orange") )
colors = ['red', 'purpl... |
class RingBuffer:
# This class starts out empty (not full yet)
def __init__(self, capacity):
# Give the class a max size
self.capacity = capacity
self.data = []
# Appends an element at the end of the buffer
def append(self, item):
self.data.append(item)
# If the ... |
参考文献:https://www.cnblogs.com/ajaxa/p/9049518.html
多态的理解:
一 多态
多态指的是一类事物有多种形态
动物有多种形态:人,狗,猪
复制代码
import abc
class Animal(metaclass=abc.ABCMeta): #同一类事物:动物
@abc.abstractmethod
def talk(self):
pass
class People(Animal): #动物的形态之一:人
def talk(self):
print('say hello')
class Dog(Animal): #动物的... |
import pandas as pd
# 再pandas中一行一列都是一个序列,类似于字典一样,可以将字典转成序列,索引index就是键
dat = {"a": 10, "b": 20, "c": 30}
s1 = pd.Series(dat, index=dat.keys(), name="A")
print(s1.index)
# 还可以使用指定索引的创建方法
l1 = ['a', 'b', 'c', 'd']
l2 = [100, 200, 300, 400]
s2 = pd.Series(l2, index=l1, name="B")
print(s2.index)
# 将序列加入到dataFrame中,才能算一行或... |
import asyncio
import time
import functools
"""
参考文章:https://segmentfault.com/a/1190000008814676
"""
async def first():
print("nihao shijie")
await asyncio.sleep(3)
return "first"
async def second():
print("woshi d")
await asyncio.sleep(1)
return "second"
async def three():
print("woshi d... |
1 #利用集合,直接将列表转化为集合,自动去重后转回列表。有一个问题,转换为集合的同时,数据无序了。
2 # li = [11,22,22,33,44,44]
3 # set = set(li)
4 # li = list(set)
5 # print(li)
6 #
7 #
8 # 第二种运用新建字典的方式,去除重复的键
9 # list = [11,22,33,22,44,33]
10 # dic = {}
11 # list = dic.fromkeys(list).keys()#字典在创建新的字典时,有重复key则覆盖
12 # print(list)
13 #
14 #
15 #
16 #第三种是用列表... |
import pandas as pd
data = pd.read_excel("pd操作.xlsx", index_col="ID")
# 计算列相乘,运算符重载,前面行和后面每一行一一对应相乘
# data["Price"] = data['Lprice'] * data['Cate']
# 只对指定行的数据做运算
for i in range(1, 6):
data["Price"].at[i] = data["Lprice"].at[i] * data["Cate"].at[i]
def add_2(x):
return x + 2
# 可以对每一项做函数调用计算操作
# data["Lprice"... |
# TASK 1
# Importing the necessary classes and methods
from flask import Flask,jsonify,request,render_template,make_response,send_file,redirect
import requests
# Creating an instance of Flask class
app = Flask(__name__)
# Displaying a Hello World string
# The decorator (@app.route('/')) followed by the method to invok... |
# for item in ["mash","john","sera"]:
# print(item)
# for item in range(5,10,2):
# print(item)
# for x in range(4):
# for y in range(3):
# print(f"({x}, {y})")
numbers = [5, 2 , 5 ,2 ,2]
for item in numbers:
output = ""
for count in range(item):
output += "X"
print(output) |
def is_even (x):
if ( x % 2 ) == 0 :
return('TRUE')
else:
return('FALSE')
is_even(7) |
# Importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Importing data
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,0:1].values
y = dataset.iloc[:,1].values
# Splitting into train and test sets
from sklearn.model_selection import train_test_split
X_train,X_test,y_... |
num1 = int(input("Palun sisestage esimene arv:"))
num2 = int(input("Palun sisestage teine arv:"))
print ('Paarisarvud on:')
for x in range (num1, num2):
if (x % 2) == 0:
print(x)
|
"""
Extract the primary colors from each frame of a video file
"""
__author__ = "prOttonicFusion"
__version__ = "0.1.0"
__license__ = "MIT"
import sys
import cv2
import argparse
import numpy as np
from PIL import Image
def analyze_movie(
video_path, aspect_ratio=0, palette_size=32, frames=-1, step=1, show_f... |
#----------------------------------------------------------------------------------------
# Description: This Python script uses the file newfile.txt and prints it's record such
# that the python interpretor counts "line two" but doesn't print it,
# and it stops after printing "line four".
#... |
#selection sort program
def selectionSort(a):
for i in range(len(a)):
minpos=i
for j in range(i+1,len(a)):
if a[j]<a[minpos]:
minpos=j
swap(a,i,minpos)
def swap(a,i,j):
a[i],a[j]=a[j],a[i]
print ("Enter array Elements")
arr=[int(x) for x in input().split(" ")]
selectionSort(arr)
print (... |
#Q1. Please provide a class in Python 3 that will include 3 different functions for rectangular prisms. The
#first function will calculate the surface area of a rectangular prism, the second one will calculate the
#volume of this prism, and the third one should properly print these two calculated values on the consol... |
sen = "the quick brown fox jumps over the lazy dog"
dt = list(sorted(set(sen)))
for k,v in enumerate(dt):
print ('{} {}'.format(k,v))
|
def time_converter(time_str):
time_str = time_str.rjust(4,'0')
if time_str[-2:] == 'PM':
return str(int(time_str[0:2]) + 12) + time_str[2:len(time_str) - 2]
else:
return time_str.replace('PM', '').replace('AM', '')
# if __name__ == "__main__":
# print time_converter('1AM')
|
class MyDate(object):
def __init__(self, d, m, y):
self.day = int(d)
self.month = int(m)
self.year = int(y)
def __lt__(self, obj):
ret_val = False
if self.year < obj.year:
ret_val = True
else:
if self.month < obj.month:
r... |
import Queue
class IterableQueue():
def __init__(self,source_queue):
self.source_queue = source_queue
def __iter__(self):
while True:
try:
yield self.source_queue.get_nowait()
except Queue.Empty:
return
q = Queue.Queue()
q.put(1)
q.put(2)... |
import re
def add(num_list):
total=0
numbers= re.findall(r'-?\d+', num_list)
negatives= []
for number in numbers:
number= int(number)
if number>=1000:
pass
elif number>=0:
total+=number
else:
negatives.append(number)
if ne... |
def fizzbuzz():
for i in range(1, 101):
if (i % 3):
print 'fizz',
if (i % 5):
print 'buzz',
print ''
fizzbuzz()
|
# Lab 07 - Problem 01
def calc_bmi():
height = float(input("Enter height (in inches):"))
weight = float(input("Enter weight (in pounds):"))
bmi = (703 * weight) / (height*height)
print("Your BMI is:", bmi,"\n")
def hypertension():
systolic_p = float(input("Enter your systolic pressure:"))
... |
#lists
mylist=[1,2,3]
mylist=[1,'two',3,False]
print(mylist)
#lenght of the list
print(len(mylist))
#pick an item
print(mylist[0])
#add new item
mylist.append("New Item")
print(mylist)
mylist.append(['x','y','z'])
print(mylist)
mylist.extend(['x','y','z'])
print(mylist)
item=mylist.pop()
print(item)
print(m... |
def int_input(num):
l = []
for i in range(num):
l.append(int(input(f"Enter number {i + 1} :")))
return l
def str_input(num):
l = []
for i in range(num):
l.append(input(f"Enter string {i + 1} :"))
return l
print(int_input(4))
print("\n")
print(str_input(3)) |
#Triangle is valid if sum of its any two sides is greater than the third side
a= int(input("Enter value of a:"))
b= int(input("Enter value of b:"))
c= int(input("Enter value of c:"))
#
# if (a+b > c) or (a+c > b) or (b+c > a):
# print("Triangle is valid")
# else:
# print("not valid")
def tria... |
# try:
# print(2/0)
# except ZeroDivisionError:
# print("No se puede dividir por cero")
#
# print("Fin del script")
try:
lista = [1,2]
print(lista[1])
except ZeroDivisionError:
print("No se puede dividir por cero")
except IndexError:
print("No es posible obtener ese valor")
finally:
print(... |
from tkinter import *
tk=Tk()
tk.title("Tic Tac Toe")
#for changing alternet X and O
change = True
#for draw condition
check =0
#for winner at last button click
abc = True
#for printing X winner
def winner():
messageVar = Message(tk, text='x is winner')
messageVar.grid(row=5, column=2)
... |
""" Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a
list of words. For each word on each line check to see if the word is already in the list and if not append it to the list.
When the program completes, sort and... |
def soma(v1, v2, v3):
return v1 + v2 + v3
v1 = int(input("Digite o primeiro valor: "))
v2 = int(input("Digite o segundo valor: "))
v3 = int(input("Digite o terceiro valor: "))
print(soma(v1, v2, v3)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.