text
stringlengths
37
1.41M
"""Implement quick sort in Python. Input a list. Output a sorted list.""" def quicksort(array): if len(array) <= 1: return array else: # get last item from array as pivot pivot = array[-1] # move elements<pivot in array-{pivot} to the left side small_part = [x for x in a...
from math import log import random import time deckList = [] suitList = ['C', 'D', 'H', 'S'] # make a list # make a string with numbers 1-13 + suit(C D H S) # append list with strings for element in suitList: for deckNum in range(1,14): deckList.append(str(deckNum) + element) def createList(): shuf...
cont = 0 n = 1 soma = 0 while n <= 6: numero = float(input()) if numero > 0: cont += 1 if numero > 0: soma += numero media = (soma)/cont n += 1 print('%d valores positivos' %(cont)) print('%.1f' %(media))
salario = float(input()) if salario > 0 and salario <= 2000: print('Isento') elif salario >= 2000.01 and salario <= 3000: valor1 = salario - 2000 imposto1 = (valor1 * 0.08) print('R$ %.2f' %imposto1) elif salario > 3000.01 and salario <= 4500: valor2 = salario - 2000 taxa2 = valor2 - 1000 ...
numero = float(input()) if numero < 0 or numero > 100: print('Fora de intervalo') else: if numero >= 0 and numero <= 25: print('Intervalo [0,25]') if numero > 25 and numero <= 50: print('Intervalo (25,50]') if numero > 50 and numero <= 75: print('Intervalo (50,75]') if nume...
salario = float(input()) if salario == 0 or salario <= 400: salario_novo = salario + (salario*0.15) reajuste = salario * 0.15 print('Novo salario: %.2f' %salario_novo) print('Reajuste ganho: %.2f' %reajuste) print('Em percentual: 15 %') elif salario >= 400.001 and salario <= 800: salario_novo ...
valores = input().split() valor_x = float(valores[0]) valor_y = float(valores[1]) if valor_x == 0 and valor_y == 0: print('Origem') elif valor_x != 0 and valor_y == 0: print('Eixo X') elif valor_x == 0 and valor_y != 0: print('Eixo Y') elif valor_x > 0 and valor_y > 0: print('Q1') elif valor_x ...
lista = input().split() codigo = int(lista[0]) quantidade = int(lista[1]) if codigo == 1: total_pagar = quantidade * 4.0 print('Total: R$ %.2f' %total_pagar) elif codigo == 2: total_pagar = quantidade * 4.5 print('Total: R$ %.2f' %total_pagar) elif codigo == 3: total_pagar = quantidade *...
numero1 = int(input()) numero2 = int(input()) soma = numero1 + numero2 print("X = " + str(soma))
n = int(input()) num = n + 1 cont = 0 while cont < 6: if num % 2 != 0: print('%d' %num) cont += 1 num += 1
valores = input().split() numero1 = int(valores[0]) numero2 = int(valores[1]) numero3 = int(valores[2]) if numero1 < numero2 and numero1 < numero3 and numero2 < numero3: print('%d \n%d\n%d' %(numero1, numero2, numero3)) print('%d \n%d\n%d' %(numero1, numero2, numero3)) elif numero1 < numero3 and numero1 < n...
import pandas as pd import pdf_converter csv_data = r"covid.csv" covid_data = pd.read_csv(csv_data, usecols=['Province/State','Country/Region','Last Update','Confirmed','Deaths','Recovered']) print("First Five rows of data\n", covid_data.head()) print("Data shape: ", covid_data.shape) print("Data columns:\n ", co...
class ImgEncryption: """ Purpose: Provides capability to encrypt an image """ _xormap = {('0', '1'): '1', ('1', '0'): '1', ('1', '1'): '0', ('0', '0'): '0'} @staticmethod def xor_encrypt(binary_filename, encrypted_filename, password): """ Purpose: Encrypts se...
""" cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4 Implement car and cdr. """ def cons(a, b): def pair(f): return f(a, b) return pair def car(c): def first(a, b): ...
# Name: Jessica Morton # Evergreen Login: morjes14 # Computer Science Foundations # Programming as a Way of Life # Homework 1 # You may do your work by editing this file, or by typing code at the # command line and copying it into the appropriate part of this file when # you are done. When you are done, running this ...
import csv from data import * d1 = data() with open('satellite.csv', 'r') as file: reader = csv.reader(file) for row in reader: for i in range(len(row)): name = row[0] operator = row[1] user = row[2] purpose = row[3] OrbitC...
class Expenses(): def __init__(self, incomes_list): self.name_of_incomes_list = incomes_list self.dictionary = {} def expenses_list(self, object_list): x = 0 # Luo sanakirjan olioiden menojen perusteella. for object in object_list: name = object.get_name(...
import sys USAGE = """ Program finds Amstrong numbers in given range. N digit Amstrong number is the number equal sum of N-th power of its digits. Example: 153 = 1^3 + 5^3 + 3^3 Usage: {program} [[start] stop] """ def is_amstrong_number(x: int): digits = list(map(int, str(x))) return sum(map(la...
from tkinter import * from tkinter import simpledialog import random # Example of how to use the line below: prompts = ["Enter Wage", "Enter Hours Worked"] prompts = ["Enter a comma separated list of words", "Enter a space separated list of test scores"] fields = [None] * (len(prompts)) values = ["All, fish, play, in,...
x=10 if x>=10: print("hello world") print(x) y=15 print("this is to demonstrate if and else ") if x>y: print(x,y) else : print("we are in else as the condion failed") #this is example for multiple condition in if block if x>y and x==y: print("condition for x and y passed ") if x>y or x==y: print(...
#multiple inheritance means getting properties from multiple classes # and it should be only one child class #if nothing is given inside child it will inherit all properties from first super class mentioned class Father(): age=50 haircolour="black" eye="brown" def __init__(self,age,haircolour,eye): ...
class Example(): def __init__(self,name,age): self.name=name self.age=age @classmethod def clsmth(cls,name,age): name="naveen" print("we are in class method") return cls(name,age-2) @staticmethod def sttcmthd(): print("we are in static method") ...
#Hybrid inheritance is some this whil have diamond shaped relationship #Grandfather #son and daughter in law #grandchildren # this is a combination of heirarichal and multiple inheritance class GrandFather: age=72 colour="brown" def __init__(self): print("i'm in grand father") def healthconditi...
#In multilevel inheritance you have grandparent and grand cild relationship #grandfather #father #child class GrandFather: age=72 eyecolour="brown" def __init__(self,age,eyecolour): print("we are in grandfather") self.age=age self.eyecolour=eyecolour def healthcondition(self): ...
def print_old_letter(old_letters_gussed): """bla bla bla""" old_letters_gussed.sort() k=0 i=len(old_letters_gussed) print('X') while (i>0): print(old_letters_gussed[k],end='->') k+=1 i-=1 print("\n") def cheack_valid_input(letter_guessed,old_letters_gussed): "...
#!/bin/python3 import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, no...
#!/bin/python3 import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, no...
#This is a function to draw a playing board in respect of width and length so that it don't wrap def DrawBoard(rows, col): if rows <= 50 and col <= 50: #rows and columns fit into terminal without wrapping if rows%2 == 1 and col%2 == 0: #Pattern must be rows odd Number and col even Number for row in ra...
# let user input age and country, output is whether the user can drive or not country = input('Which country are you from: ') age = input('Please enter your age:') age = int(age) # casting very important if country == 'Taiwan': if age >= 18: print('You can take driving licence test') else: print('You can not take...
# -*- coding: utf-8 -*- """ Created on Tue May 21 12:38:25 2019 @author: Rai """ """ Code Challenge Name: Exploratory Data Analysis - Automobile Filename: automobile.py Dataset: Automobile.csv Problem Statement: Perform the following task : 1. Handle the missing values for Pric...
# -*- coding: utf-8 -*- """ Created on Wed May 8 16:53:16 2019 @author: Rai """ """ # Make a function to find whether a year is a leap year or no, return True or False """ year = 2016 if(year%4)==0 : if(year%100)==0 : if(year%400)==0: print("year is a leap year") else: pri...
a=21 b=0 while a>b: #print(a) a-=1 if a == 15: print(a) a -= 2 print(a) if a == 11: print(a) print('halfway done') a-=2 if a == 5: a-=1
shopping_list = ['banana','apple'] prices = { 'banana':20, 'apple':30 } stock = { 'banana':40, 'apple':20 } #total = 0 # for key in prices: # print # print key # print 'prices = %s' % prices[key] # print 'stock = %s' % stock[key] # total = prices[key] * stock[key] # print '{} price: {} in t...
__author__ = 'kalyani' class Animal(): is_alive = True def __init__(self, name, number, is_good): self.name = name self.number = number self.is_good = is_good kk = Animal('panda', 12, True) ll = Animal('Monkey', 10, False) print kk.name, kk.number, kk.is_good, kk.is_alive print ll.name...
#!/usr/bin/env python3 #import sys.intern with open('enable1.txt') as f: words = f.read().splitlines() def funnel( w, l_prev, l_solutions=[] ): for i in range(len(w)): s = w[0:i] + w[i+1:] if s in words: # s is a valid word, so continue recursion temp = l_pre...
def solution(bridge_length, weight, truck_weights): weight_list = [] weight_sum = 0 count = [] finish = len(truck_weights) f_c = 0 sec = 0 while (f_c != finish): sec = sec + 1 if (sec > 2): if (count[0] == bridge_length): count.pop(0) ...
#!/usr/bin/env python """This is a solver for Problem 1 in projecteuler.net. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ from itertools import takewhile def multiples(n):...
''' function vs method: name = "Mark" len(name) - returns int, length of obj name.upper() - changes name name is an instance of the str type. name is an obj of that type(str) obj is wrapper around data & functionality related to data ie methods methods are defined in a class definition methods live inside...
import datetime import time time1 = time.localtime() #[0:tm_year,1:tm_mon,2:tm_day,3:tm_hour,4:tm_min,5:tm_sec,6:tm_wday,7:tm_yday,8:tm_isdst] hour=time1.tm_hour minute = time1.tm_min second = time1.tm_sec if(hour<=5): print("You should be sleeping!") elif(6<=hour&hour<=10): print("Good Morning!") elif...
import sys if __name__ == '__main__': list1=[] if len(sys.argv)==4: k=1 for i in range(2,4): if(int(sys.argv[i])>int(sys.argv[k])): k=i print "largest of 3 is : ",sys.argv[k] else: print "Enter 3 numbers : " for x in range(0,3): list1.append(int(raw_input())) k=0 for i in range(1,3): if(...
#!/usr/bin/env python # -*- encoding: utf-8 -*- import os dir = 'E:/Music/1、俄罗斯' # dir = 'E:/Music/2、欧美' # dir = 'E:/Music/3、日韩' # dir = 'E:/Music/4、中国' # dir = 'E:/Music/5、歌手' # dir = 'E:/Music/6、张学友' os.chdir(dir) i = 0 for name in os.listdir(): i += 1 lst = name.split('、') if len(lst) == 1: p...
# esercizio 1 cand1 = input("come si chiama il primo candidato?") cand2 = input("come si chiama il secondo candidato?") voti1 = int(input("quanti voti ha ottenuto " + cand1 + "?")) voti2 = int(input("quanti voti ha ottenuto " + cand2 + "?")) somma = voti1 + voti2 percvoti1 = (voti1*100/somma) percvoti2 = (voti2*100/som...
# This script checks a book shelf for books and adds to it if the book isn't there current_books = ['musashi', 'the universe in a nutshell', 'man\'s search for meaning', 'pulp fiction'] # defines the initial list print('What book do you want to add?') book = input() # defines the book to add if book not in current_...
# This is a simple program that takes a birthday in the DD/MM UK format and reverses to US MM/DD format. # There is little error checks here - just a simple program. uk_dob = input('What is your birthday in DD/MM format? ') us_dob = uk_dob[3:] + '/' + uk_dob[0:2] print(f'Your US birthday is {us_dob}')
# This is a short program to round any float (decimal number) to one decimal place. decimal = float(input('Give me a number with decimal digits. ')) rounded_decimal = round(decimal*10)/10 print(f'To one decimal place, your number is {rounded_decimal}')
from pprint import pprint import random # 2018/03/07 ''' ####### 生日问题(birthday problem)#######''' # 有一个足够大的房间,现每次进入一个人,直到进入的人中有两个人的生日相同,则停止进入 # 问题:平均进入多少个人,才能有两个人有相同的生日? # 问题简化:生日在1~365之间(不考虑闰年),房间看做已个列表数组 # 问题的关键是:数组的元素重复的查找,判断一个元素是否在这个数组中(可以用 in 来进行判断) # 代码如下: import random # 获取试验进行次数 times = int(input("试验进行的次数:"...
# 二维数组的应用实例:自回避随机行走(本例所使用的的数组为矩阵,不考虑交错数组) # self-avoiding random walk # 一个城市的道路上,假设该城市的道路网络为矩阵,一只AlphaGo在该城市随机行走,走到已走过的点即为失败,请问AlphaGo走出的概率是多大 # 以交叉路口为节点(False),先行构建一个 m*n 的二维数组,所有的值均为False,在 AlphaGo 经过的节点,修改成True # 自回避:前进的方向上的下一节点为True时(说明该节点已经走过),回避此方向(抛弃这个方向) ''' 与书上的稍有区别,书上的对方向的选择上,会出现回头,但是不做操作 还有在二维的数组构建过程中,出现了一...
# 两个数的最大公约数是指能同时整除它们的最大正整数 # 欧几里得算法:求取两个数字之间的最大公约数(辗转相除法) # use Euclid's algorithm get two intgrate's Greatest Commom Divisor(GCD) ''' 基本原理: 设两数为a、b(a≥b),求a和b最大公约数 的步骤如下: (1) 用 a 除以 b (a≥b),得 a / b = q...r1 (2) 若 r1 = 0 , 则 (a,b) = b (3) 若 r1 != 0 , 则再用 b 除以 r1 ,得 b / r1 = q1....r2 (4) 若 r2 = 0...
# text progress bar # 刷新的关键是:之后打印的覆盖之前打印的数据 import time scale = 100 print('start'.center(scale//2,'-')) for i in range(scale + 1): a = '>>' * (i//10) b = ' _' * ((scale - i + 9)//10) c = i/scale print('[{}{}]{:^6.2%}'.format(a,b,c),end = '\r') time.sleep(0.1) print('\n'+'finish'.center(scale//2,'-...
'''This is a simple python program to create a database of switch name and its corresponding switchport name''' print "This programs will create a switchport list based on the switch name \ which you enter" switch=raw_input("Enter switch name: ") stacks=raw_input("Enter number of stacks: ") stacks=int(stacks) for i in...
Age= int(input("How old are you? : ")) print ("My age is", Age)
#!/usr/bin/env python3 from slice import Slice pizza = [] jambons = [] # tableau de tuples (x, y) : ou y == line # liste des parts là où il y a du jambon # récupérer le jambon le plus proche, puis le plus proche de l'autre # puis du détermine le carré with open("test_round.in", "r") as f: R, C, ...
# setup new document size(600, 740) background('#004477') noFill() stroke('#FFFFFF') strokeWeight(3) xco = 400 yco = 440 ''' 1. Draw a line beginning at an x-coordinate of half the display window width, and y-coordinate of a third of the window height. The endpoint must have an x/y-coordinate equal to xco & yco ''...
# https://en.wikipedia.org/wiki/Parametric_equation def setup(): size(800,800) background('#004477') strokeWeight(3) def parabola(x): return x*x def circl(t): x = cos(t) y = sin(t) return [x,y] def ellips(t): x = 2 * cos(t) y = 1 * sin(t) return [x,y] def lissajous(t,a,b,kx,...
#coding:utf-8 import os class Path2Tree(object): def __init__(self, path_list): self.path_list = path_list self.tree_str = '' self.build_tree() def get_space(self, tree_list): if len(tree_list) < 2: return "└─" end = tree_list[-1] front_list = tree...
from urllib.request import urlopen from urllib.error import HTTPError from urllib.error import URLError try: PageUrl = urlopen("https://www.google.in/") except HTTPError: print("HTTP error") except URLError: print("Page not found!") else: print("Page Found") try: PageUrl = urlopen("htt...
import numpy as np A = np.array([4, 7, 3, 4, 2, 8]) print(A == 4) print(A < 5) print(A[4]) print(A[A==4]) #index print(A[A<5]) # booleanlist print(A[3:5]) #slicing
def getNames(): names = ['Christopher', 'Susan', 'Danny'] newName = input('Enter last guest: ') names.append(newName) return names def printNames(names): for name in names: print(name) return printNames(getNames())
subject = input("Sub: ") while: year = int(input("Year: ")) if (year == 2018 or year == 2019): break while: duration = int(input("Duration: ")) if (duration >= 10 and duration <= 14): break
minh = {'1':'minh', '2': 'toan'} for a, b in minh.items(): if a == '1': minh['1'] = 'minhdeptrai' print(minh)
import numpy as np list_input = [1,2,3,4,5,6,7,8] print("Type of list: ", type(list_input)) np_arry = np.array(list_input) # print("Numpy array: ", np_arry) print("Type of numpy array: ", type(np_arry))
print("Tinh tong cac chuc so cua mot so") number = input("Nhap vao mot so nguyen di: ") result =0 for i in list(number): result += int(i) print("Tong cac chu so la: %d" %(result))
import os for folderName, subfolders, filenames in os.walk('C:\\Users\\vanquangcz\\Desktop\\python'): print('The current folder is ' + folderName) for subfolder in subfolders: print('SUBFOLDER OF '+ folderName + ': '+ subfolder) for filename in filenames : print('File inside '+ folderName + ': ' + filename) ...
import datetime as dt import math firstDay = input("Moi nhap so ngay dau tien: ") firstDays = dt.datetime.strptime(firstDay, '%d%m%Y').date() sencondDay = input("Moi nhap so ngay thu hai: ") sencondDays = dt.datetime.strptime(sencondDay, '%d%m%Y').date() days = (sencondDays - firstDays) print(days)
def tinhTong(ds): sum= 0 for i in ds : sum += ds return sum number = int(input("Nhap vao so chu so: ")) mang = dict(number) for i in range(0, number): mang[i] = input() tinhTong(mang)
# 3.用三个列表表示三门学科的选课学生姓名(一个学生可以同时选多门课) discipline1 = ['1', '2', '5', '8', '11', '15', '12', '3', '7', '17'] discipline2 = ['11', '7', '9', '14', '6', '8', '4', '1', '34', '17'] discipline3 = ['2', '8', '24', '1', '4', '9', '14', '18', '3', '19'] # a. 求选课学生总共有多少人 num = len(set(discipline1 + discipline2 + discipline3)) pr...
"""__author__=余婷""" # 如果一个类继承enum模块中的Enum类,那么这个就是枚举 from enum import Enum from random import shuffle from copy import copy # 5.写一个扑克游戏类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥) class PokerNum(Enum): Three = (3, '3') Four = (4, '4') Five = (5, '5') Six = (6, '6') Seven = (7, '7') Eight = (8, '8') ...
"""__author__=桃花寓酒寓美人""" """ import :在导入模块的时候会检查当前模块之前是否已经导入过,如果已经导入过不会重新导入 include 联系:都是导入文件 区别:import会检查是否已经导入 include不会检查每次都会重新导入 """ dict1 = {'name': 1, 'age': 25} generate = ({key, dict1[key]} for key in dict1) for key in generate: print(key) dict2 = dict((dict1[key], key) for key in dict1) print(...
"""__author__=蒋志颖""" # 1.根据实参的传值方式将实参分为: 位置参数、关键字参数 """ 1)位置参数 - 直接让实参的值和形参一一对应 2)关键字参数 - 调用函数的时候以'形参名1=值1,形参名2=值2,...'的形式传参 3) 位置参数和关键字参数混用 - 混用的时候必须保证位置参数在关键字参数的前面, 同时保证每个参数都有值 """ def func1(a, b, c): # a=10, b=20,c=30 print('a:{},b:{},c:{}'.format(a, b, c)) # 位置参数 func1(10, 20, 30) # a:10,b:20,c:30 # ...
"""__author__=余婷""" from socket import socket from threading import Thread class ConnectionThread(Thread): def __init__(self, connection: socket, address): super().__init__() self.connection = connection self.address = address def run(self): # 实现和一个客户端不断聊天的效果 while Tru...
"""__author__=桃花寓酒寓美人""" # 1.什么是生成器 """ 生成器就是迭代器中的一种 - 但它是自己生产数据(当程序需要它才会产生数据,之间是没有数据) 生成器作为容器它保存的不是数据,而是产生数据的算法 """ # **2.怎么创建生成器 """ 调用带有yield的关键字的函数,就可以得到一个生成器(只有一种创建方式) **注意:函数只要存在关键字yield无论yield在何方,这个函数都是一个生成器 """ def func1(): print('====') print('++++') yield re = func1() # 生成器 print(re) # ...
"""__author__=桃花寓酒寓美人""" # 内置类属性 - 声明类的时候系统提供的属性 class Dog: """狗类""" num = 100 # __slots__是用来约束当前类最多能够拥有的对象属性 # __slots__ = ('name', 'age', 'gender', 'height') # 约束对象属性的范围 def __init__(self, name, age=4, gender='公狗'): self.name = name self.age = age self.gender = gender...
"""__author__=桃花寓酒寓美人""" import time # 1.什么是装饰器 """ 装饰器本质是一个函数 = 返回值高阶函数+实参高阶函数+糖语法 装饰器是python的三大神器之一:装饰器、迭代器、生成器 作用:给已经写好的函数添加新的功能 """ # 给函数添加一个功能:统计函数的执行时间 # 方法一:在每个需要添加功能的函数中加入相应代码 def yt_sum(x, y): start = time.time() # 获取当前时间 sum1 = x + y print(sum1) end = time.time() print('函数执行时间:%fs' % (e...
"""__author__=桃花寓酒寓美人""" # 1.变量可以作为函数的返回值 def yt_sum(x, y): t = x+y return t yt_sum(10, 20) # 函数可以作为函数的返回值 - 返回值高阶函数 # func1就是一个返回值高阶函数 def func1(): def func2(): print('function2') return func2 print(func1()) print('=====================') print(func1()()) # 2.闭包 - 函数1中声明了一个函数2,并且在函数2中...
"""Draw module for X's and O's This module is able to draw an X's and O's game board or series of moves that comprise a game. The module is specifically intended to be run in a Google Colab notebook and requires that `ColabTurtle` be installed within the notebook environment. This can be installed using the followin...
import math # Solution to Project Euler problem 20 result = 0 number = str(math.factorial(100)) for character in number: result += int(character) print(result)
size = int(input()) time = int(input()) for row in range(0, size - 1): if time == 0: if row % 2 == 1: print('?' * row + '* ' *(size - row - 1) + '*' + '?' * row) else: print(' ' * row + '* ' * (size - row - 1) + '*' + ' ' * row) elif time == size: if row % 2 == ...
a = int(input()) tens = '' ones = '' if a == 100: print('one hundred') else: if a <= 20: if a == 1: print('one') elif a == 0: print('zero') elif a == 2: print('two') elif a == 3: print('three') elif a == 4: print...
import math r = float(input()) perimeter = 2 * math.pi * r area = math.pi * r * r print(area) print(perimeter)
n = int(input()) type = input() if n < 100: if n >= 20: print(0.09 * n) else: if type == 'day': print(0.7 + 0.79 * n) elif type == 'night': print(0.7 + 0.9 * n) else: print(0.06 * n)
size = int(input()) time = int(input()) for row in range(0, size): if row == size - 1 and row % 2 == 0: print('?' * (size -1) + 'o' + '?' * (size - 1)) if row == size - 1 and row % 2 == 1: print(' ' * (size -1) + 'o' + ' ' * (size - 1)) if time == 0: if row % 2 == 0: pri...
# To use print function from Python 3 in Python2 # from __future__ import print_function # String word print("hello world") print('this is a string') # this code will get error # print('I'm a string') print("i'm a string") print('"this is a quote"') print('Here is a new line \n and here is the second line') print(...
x = 0 # while x < 10: # print("x i currently!", x) # x += 1 # while x < 10: # print("x i currently!", x) # x += 1 # else: # print("all done") #break continue pass # while x < 10: # print('x is currently: ', x) # print('x is still less then 10, adding 1 to x') # x +=1 # # if x==3...
# for x in range(21): # print(type(x), x) start = 0 stop = 20 stepSize = 2 for x in range(start, stop, stepSize): print(x)
import random # Problem 1 def gensqares(N): for i in range(N): yield i ** 2 for x in gensqares(10): print(x) # Problem 2 print(random.randint(1, 10)) def rand_num(low, high, n): for i in range(n): yield random.randint(low, high) for num in rand_num(1, 10, 12): print(num) # Prob...
from collections import namedtuple t = (1,2,3) print(type(t)) print(t[1]) Dog = namedtuple('Dog', 'age breed name') sam = Dog(age=2, breed='lab', name='sammy') print(sam.age) print(sam.breed) print(sam.name) print(sam[0]) print(sam[1]) Cat = namedtuple('Cat', 'fur claws name') c = Cat(fur= 'Fuzzy', claws=False,...
# l = [1, 2, 3] # print(l) # print(len(l)) class Book(object): def __init__(self, title, author, pages): print("A book is created") self.title = title self.author = author self.pages = pages def __str__(self): return "Title:%s, author:%s , pages:%s " %(self.title, self....
def make_advanced_counter_maker(): """Makes a function that makes counters that understands the messages "count", "global-count", "reset", and "global-reset". See the examples below: >>> make_counter = make_advanced_counter_maker() >>> tom_counter = make_counter() >>> tom_counter('count') 1...
#Himma, Nyasia, Sophie from tkinter import * import random num = 0 root = Tk() names= ['Himma' ,'Nyasia' ,'Logan' ,'Jonah', 'Aidan','Alex' ,'Nyeema' ,'Zoe','Justin' ,'Phillip','Matthew' ,'Andrew' ,'Sophie' ,'Jack','Ian','Henry' ,'Angelina' ] random.shuffle(names) def pairs(): global num ...
from abc import abstractmethod import pygame import os import json import logging from typing import List import random class ImageDrawable: """ an abstract class, for all Drawable surfaces/images that Can been drawn on the window surface """ def __init__(self, x: int, y: int, image_path: str, vel: i...
# -*- coding: utf-8 -*- import sys import random def IsCircle(): """ Проверяет попадание точки в радиус круга. Возврат ------- bool Возвращает True если выполняется условие, иначе - False. """ x = random.random() y = random.random() ...
# Coded by: Miguel Angel Garcia Acosta # Contact: MAGA.DevCS@Gmail.com # -------------------------- # MATRIX RECURSIVE REPLACER: # -------------------------- # ----- ----- ----- ----- -- # # ----- ----- ----- IMPORTS ----- ----- ----- # import csv # ----- ----- ----- IMPORTS ----- ----- ----- # # # START # ...
import sqlite3 def createTable(): conn = sqlite3.connect('contacts.db') conn.execute('DROP table IF EXISTS ABC') conn.execute('''CREATE TABLE ABC (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Phone CHAR(50) NOT NULL)''') print ("Table created successf...
from random import choice def main(): question = input('Ask a question: ') answers = ['Yes!', 'No!', 'Maybe', 'Do not count on it!', 'It\'s certain', 'No way!', 'Maybe'] print(choice(answers)) if __name__ == "__main__": main()
name = input ("What's your name?").strip().title() print ("Hey " + name) other_name = input("What's the other dude's name?") .strip().title() print ("Please tell {} hello for me".format(other_name)) first_age = input ("How old are you {}?".format(name)).strip().title() other_age = input ("And how old is {}?".format(oth...
def merge_sort(alist): if len(alist) <= 1: return alist mid = int(len(alist)/2) left = merge_sort(alist[:mid]) print("left = " + str(left)) right = merge_sort(alist[mid:]) print("right = " + str(right)) return merge_sorted_array(left, right) def merge_sorted_array(alist, blist): ...
import heapq def heap_sort(alist): ret = [] while alist: heapq.heapify(alist) ret.append(heapq.heappop(alist)) return ret arr = [4, 7, 8, 9, 1, 5] print(heap_sort(arr))
age = input("how old are you: ") age = int(age) if age <= 18: print("you are a baby!!!") elif age >= 21: print("you can come and you can drink. ") else: print("you can come and you can drink too.")
def problem1(stop): " solved by katayama" sum = 0 for x in range(1, stop): if (x%3==0) or (x%5==0): sum += x return sum def problem2(stop): " solved by miyoshi " a, b = 1, 2 sum = b while True: a, b = b, a+b if b % 2 == 0: sum += b ...
import sys import re from collections import defaultdict # This is a script to identify pronouns in Japanese # It requires data segmented by KyTea (http://www.phontron.com/kytea/) # # If you have raw Japanese text (with no spaces), use this script like: # cat japanese.txt | kytea | python identify_japanese_pronouns.p...