text stringlengths 37 1.41M |
|---|
#Jamie Christy and Mai Li Goodman
#CS 111 Final Project
#Framework Script
import Tkinter as tk
import animation
import random
import rabbit
import Image
import ImageTk
class GameApp(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root, pady=20,padx=20,width=600, height=600)
root... |
import sqlite3
def create_tables(cursor):
cursor.execute("""CREATE TABLE employees
(id INTEGER PRIMARY KEY, name text, monthly_salary int, yearly_bonus int, position text)""")
def insert(item, cursor):
name = item["name"]
monthly_salary = item["monthly_salary"]
yearly_bonus = ite... |
import unittest
from solution import count_words
class CountWordsTest(unittest.TestCase):
"""docstring for CountWordsTest"""
def test_count_words(self):
res1 = {'banana': 1, 'pie': 1, 'apple': 2}
res2 = {'python': 3, 'ruby': 1}
self.assertEqual(res1, count_words(["apple", "banana", "a... |
def sum_of_divisors(num):
total = 0
for i in range(1, num + 1):
if num % i == 0:
total += i
return total
def main():
print(sum_of_divisors(7))
print(sum_of_divisors(1000))
if __name__ == '__main__':
main()
|
def magic_string(string):
k = len(string) // 2
count_changes = 0
for index, char in enumerate(string):
if index < k and char == "<":
count_changes += 1
elif index >= k and char == ">":
count_changes += 1
return count_changes
def main():
print(magic_string(">... |
coins = [100, 50, 20, 10, 5, 2, 1]
def calculate_coins(sum):
int_sum = sum * 100
num_coins = {}
for coin in coins:
count = 0
while int_sum >= coin:
int_sum -= coin
count += 1
num_coins[coin] = count
return num_coins
def main():
print(calculate_co... |
def list_to_number(numList):
num = 0
exp = 0
for item in numList[::-1]:
num += item * (10 ** exp)
exp += 1
return num
def main():
print(list_to_number([1, 2, 3]))
print(list_to_number([9, 9, 9, 9, 9]))
print(list_to_number([1, 2, 3, 0, 2, 3]))
if __name__ == '__main__':
... |
def is_an_bn(word):
n = len(word)
if n % 2 != 0:
return False
n = n // 2
check = 'a' * n + 'b' * n
if word == check:
return True
return False
def main():
print(is_an_bn(""))
print(is_an_bn("rado"))
print(is_an_bn("aaabb"))
print(is_an_bn("aaabbb"))
print(is_... |
# output the square of a number as value with the number as key in a dictionary
myDict = {}
x = int(raw_input())
for a in range(1, x + 1):
myDict[a] = a * a
print myDict
|
from Piece import *
import os
class Player(object):
def __init__(self,name,color):
self.name = name
self.color = color
self.listOfPieces = [] #a list containing all the pieces the player has
self.pieceKeys = {} # a dict which returns the piece based on it's nom
self.list... |
# string review
mystring = 'testing hello there'
print(mystring + ' ' + mystring)
# index - get everything there and after
print(mystring[2:])
# index - get everything up to but not including index 3
print(mystring[:3])
# index - get everything up to but not including index 3
print(mystring[1:3])
# skipping every ... |
def pca(X, ncomp):
"""
Principal component analysis.
Parameters
----------
X : array_like
Samples-by-dimensions array.
ncomp : int
Number of components.
Returns
-------
components : ndarray
First components ordered by explained variance.
explained_varian... |
"""
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
In this example, assume nodes with the same value are the exact same node objects.
Do this in O(M + N... |
from __future__ import print_function
def main():
bilanganPertama = 5
bilanganKedua = 4
listSaya = [1,2,3,4,5]
if(bilanganPertama == bilanganKedua):
print('Bilangan Sama ')
if(bilanganPertama >= bilanganKedua):
print('Bilangan pertama lebih besar ')
if(bilanganPertama <= bilanga... |
from __future__ import print_function
def main():
# for iterasi in range(5):
# print(iterasi)
threshodl = True
iterasiWhile = 0
a = 0
# while(iterasiWhile<5):
# print('Ganteng')
# iterasiWhile +=1
while(threshodl):
print('Ganteng')
if(a == 4):
... |
from __future__ import print_function
def main():
bilanganPertama = int(input('Bilangan Pertama : '))
bilanganKedua = int(input('Bilangan Kedua : '))
hasilTambah = bilanganPertama + bilanganKedua
hasilKurang = bilanganPertama - bilanganKedua
hasilKali = bilanganPertama * bilanganKedua
hasilBagi... |
"""
created by Nagaj at 02/05/2021
"""
from album import Album
from song import Song
class Artist:
def __init__(self, name):
self.name = name
self.songs = []
self.albums = []
self.items = []
def __repr__(self):
return f"Artist-<{self.name}>"
def __contains__(self... |
import simplegui
import random
range_max = int(100)
guess_max = int(7)
# helper function to start and restart the game
def new_game():
global secret_number
global remain_guess
global range_max
global guess_max
secret_number = random.randint(0,range_max)
remain_guess = guess_max
... |
def triangular_sum(n):
"""
Example of a recursive function that computes
a triangular sum
"""
if n == 0:
return 0
else:
return n + triangular_sum(n-1)
#print triangular_sum(3)
def number_of_threes(n, count):
"""
Takes a non-negative integer num... |
"""
# Mini-project #3 - Monte Carlo Tic-Tac-Toe Player
# as a Coursera's "Principles of computing"
# course assignment.
# Author: Sergey Korytnik
# Date: 12th August 2016
#
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
import time
# Constants for Monte Carlo simulator
# You m... |
# -*- coding: utf-8 -*-
import urllib
import urllib2
URL_IP = 'http://httpbin.org/ip'
URL_GET = 'http://httpbin.org/get'
def use_simple_urllib2():
response = urllib2.urlopen(URL_IP)
print '>>>>Response Headers:'
print response.info()
print ''.join([line for line in response.readlines()])
def use_params_urllib2()... |
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if not nums1 or not nums2:
return []
nums1.sort()
nums2.sort()
res = []
i = j = 0
... |
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# input / output type?
# time / space req
# duplicate?
# corner case?
if not nums:
return -1
# not rotate
if nums[-1] > nu... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
... |
# Array - count() and extend()
import array
arr1 = array.array('i', [1, 2, 3, 1, 2, 5])
arr2 = array.array('i', [1, 2, 3])
print("The occurrences of 1 in array is: ", end='')
print(arr1.count(1))
arr1.extend(arr2)
print("Modified array: ", end='')
for i in range(0, len(arr1)):
print(arr1[i], end=' ')
|
# Type conversion using tuple(), set(), list()
s = 'Geeks'
c = tuple(s)
print("After converting string to tuple: ", end='')
print(c)
c = set(s)
print("After converting string to set: ", end='')
print(c)
c = list(s)
print("After converting string to list: ", end='')
print(c)
|
# Demo of conditional statement
num = int(input("Enter a number: "))
if(num > 15):
print("Good number!")
else:
print("Bad number!")
|
# Adding elements to a set
set1 = set()
print("Initial blank set: ")
print(set1)
set1.add(8)
set1.add(9)
set1.add(11)
print("Set after addition of three elements: ")
print(set1)
for i in range(1, 6):
set1.add(i)
print("Set after the addition of elements in range 1-6: ")
print(set1)
set1.add((6, 7))
print("Set a... |
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'for', 'geeks')
Tuple3 = Tuple1 + Tuple2
print("Tuple1: ")
print(Tuple1)
print("Tuple2: ")
print(Tuple2)
print("Tuples after concatenation: ")
print(Tuple3)
|
# Unpacking of dictionary items using **
def fun(a, b, c):
print(a, b, c)
d = {'a':2, 'b':4, 'c':10}
fun(**d)
|
# Use of absolute function in Math library
import math
def main():
num = float(input("Enter a decimal number: "))
num = math.fabs(num)
print(num)
if __name__ == '__main__':
main() |
# coding=utf-8
import sys
import string
vowels = 'aeiouyåäöAEIOUYÅÄÖ'.decode('utf-8')
while True:
word = raw_input("Please type in a word: ")
if word == '--quit':
sys.exit()
word = word.decode('utf-8')
modified_word = []
for c in word:
if c not in vowels and c not in string.punctua... |
def leaderboard_sort(leaderboard, changes):
for move in changes:
movement = move.split()
indx = leaderboard.index(movement[0])
if '+' in movement[1]:
dist = int(movement[1].strip('+'))
leaderboard.insert(indx-dist, leaderboard.pop(indx))
else:
... |
# Best Solution:
# def anagrams(word, words): return [item for item in words if sorted(item)==sorted(word)]
def anagrams(word, words):
word_dict, output = {}, []
for letter in word:
try:
word_dict[letter] += 1
except KeyError:
word_dict[letter] = 1
for se... |
def is_valid_walk(walk):
if len(walk) != 10:
return False
location = [0,0]
for direction in walk:
if direction == 'e':
location[0] += 1
elif direction == 'w':
location[0] -= 1
elif direction == 'n':
location[1] += 1
elif ... |
def likes(arry):
no_likes = len(arry)
if no_likes == 0:
return 'no one likes this'
elif no_likes == 1:
return f'{arry[0]} likes this'
elif no_likes ==2:
return f'{arry[0]} and {arry[1]} like this'
elif no_likes == 3:
return f'{arry[0]},{arry[1]} and {arry[2... |
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
pass
class Cat(Animal):
pass
dog=Dog()
dog.run()
cat=Cat()
cat.run()
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
print(isinstance(dog, Cat))
def run_twice(animal):
animal.run()
animal.run()
run_twice(Ani... |
# coding: utf-8
__author__ = 'Leon.Nie'
# 返回用户输入的密码的
import hashlib
# 用于存储用户名密码
db = {}
def get_md5(str):
md5 = hashlib.md5()
md5.update(str.encode('utf-8'))
return md5.hexdigest()
def register(user, pw):
if(user in db)==False:
db[user] = get_md5(pw + user + 'the_Salt')
print('User %s has been registered ... |
from decorator_test import my_decorator
import time
from time import sleep
@my_decorator
def just_some_function():
print("Wheee!")
just_some_function()
print("___________________")
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
... |
L = ['a', 'b', 'c']
for i, value in enumerate(L):
# enumerate函数可以把一个list变成索引-元素对
print(i, value)
|
def set_adj_list(vertex_list,edge_list):
for i in vertex_list:
for j in vertex_list:
if (i,j) in edge_list:
adjacency_list[i].append(j)
def print_adj_list(adjacency_list):
for i in range(len(adjacency_list)):
print i,'->',adjacency_list[i]
def bfs(adjacency_list,node_start):
node_queue.append(node_s... |
#!/usr/bin/python2.7
# coding:utf-8
# Aurélien REY
# Groupe 3
# Théorie des graphes
# TP1 - Exercice 4
import random as rand
def Chaine(G, s, t) :
d = list()
current = s
while current != t :
d.append(current)
current = G[current][rand.randint(0, len(G[current]) - 1)]
d.append(t)
retur... |
some_text = '''hello\n
[something between square\n
and still some text\n
brackets, to see if it is working]\n
last time'''
def dropuntil(pred, text):
"""Drop until condition met. Last item dropped."""
if pred(text.pop(0)):
return dropuntil(pred, text)
return text
def parse_text(text, accumulator=... |
#列表或者字典 当做全局变量 可以不用global 直接用
nums = [11,22,33]
infor = {"name":"laowang"}
def test():
#for num in nums:
# print(num)
nums.append(44)
infor["age"]=18
#infor["name"] = "laoli"
def test2():
print(nums)
print(infor)
test()
test2()
|
'''
class Dog:
#私有方法
def __send_msg(self):
print("-----正在发送短信-----")
#公有方法
def send_msg(self,new_money):
if new_money>10000:
#当验证成功后再调用上边的私有方法
self.__send_msg()
else:
print("余额不足请充值后在发送短信……")
dog = Dog()
dog.send_msg(100)
'''
#del
class Dog:... |
#1.打印功能提示
print("="*50)
print(" 名片管理系统 V0.01")
print(" 1.添加一个新的名片")
print(" 2.删除一个新的名片")
print(" 3.修改一个新的名片")
print(" 4.查询一个新的名片")
print(" 5.退出系统")
print("="*50)
#用来存储名片
card_infors = []
while True:
#2.获取用户的输入
num = int(input("请输入操作序号:"))
#3.根据用户的数据执行相应的功能
if num==1:
new_name = input("请输... |
#1.打印菜单功能
print("="*30)
print(" 学生管理系统V0.01 ")
print(" 1.添加一个新的信息")
print(" 2.删除一个学生信息")
print(" 3.修改一个学生信息")
print(" 4.查询一个学生信息")
print(" 5.显示所有学生信息")
print(" 6.退出系统")
print(" 7.删除数据库")
print("="*30)
admin_infors = []
while True:
#2.用户输入
num = int(input("请输入操作序号:"))
#3.添加姓名
if num == 1:
... |
#1. 获取用户的输入
num = int(input("请输入一个数字(1~7:):"))
#2. 判断用户的数据,并且显示对应的信息
if num==1:
print("星期一")
elif num==2:
print("星期二")
elif num==3:
print("星期三")
elif num==4:
print("星期四")
elif num==5:
print("星期五")
elif num==6:
print("星期六")
elif num==7:
print("星期七")
else:
print("你输入的数据有误……")
|
from math import sqrt
def judgePrime(num):
if num <= 1:
return 0
#for i in range(2,int(sqrt(num)+1)):
''' for i in range(2,num):#此两种算法皆可,上面比下面快很多,找素数只需要除到平方根+1
if num%i == 0:
return 0
return 1
'''
i = 1#有问题
while i*i <= num:
if num%i == 0:
return 0... |
#1.打印功能提示
print('='*50)
print(' 名字管理系统 V8.6')
print(' 1:添加一个新的名字:')
print(' 2:删除一个新的名字:')
print(' 3:修改一个新的名字:')
print(' 4:查询一个新的名字:')
print('='*50)
names = []#定义一个空的列表从来存储添加名字
while True: #死循环
#2.获取用的选择
num = int(input("请输入功能序号:"))
#3.根据用户的选择,执行相应的功能
if num==1:
new_name = input('请输入名字:') ... |
import os
#1.获取用户文件夹输入
fold_name = input("请输入您要重命名的文件夹:")
funFlag = int(input("请输入您的需求(1 表示添加标志,2表示删除标志):")) #1表示添加标志 2表示删除标志
string_name = input("请输入您要添加或删除的字符:")
#2.获取所有文件名
file_names = os.listdir(fold_name)
#跳进文件夹执行
os.chdir(fold_name)
#遍历输出所有文件名字
for name in file_names:
#print(name)#for test
if funFlag =... |
#在Python中 值是靠引用来传递
# id() 判断两个变量是否为同一个值的引用 id可理解为内存的地址标示
a = 1
b = a
print(id(a))
print(id(b))
a = 2
print(id(a))
|
class SweetPotato:
"""定义一个地瓜类"""
def __init__(self):
self.cookString = "生的"
self.cookLevel = 0
self.condiments = []#用来保存添加的佐料
def __str__(self):
return "地瓜的状态是%s(%d),添加的佐料有%s"%(self.cookString,self.cookLevel,str(self.condiments))
def cook(self,cookTime):
self.... |
age = input("请输入你的年龄:")
age_number = int(age)
if age_number>18:
print("已成年,可以去网吧嗨皮")
else:
print("未成年,回家写作业吧")
|
def test(a,b):
a+b
result1 = test(11,22)
print(result1)#None 因为没有return
#定义一个匿名函数
func = lambda a,b:a+b
result2 = func(11,22)
print(result2)#和普通函数不一样,不需要return
|
import random
player = input("请输入:剪刀(0) 石头(1) 布(2):")
player = int(player)
computer = random.randint(0,2)
if((player == 0) and (computer == 2)) or ((player == 1) and (computer == 0)) or ((player ==2) and (computer == 1)):
print("获胜,哈哈,你太厉害了!")
elif player == computer:
print("平局,要不要再来一局")
else:
print("输了... |
__author__ = 'Dario Hermida'
import main as calculate
import numpy as np
import matplotlib as plot
def testing_main(min_salary, max_salary, step):
regular_salary = []
ruling_salary = []
salary = list(range(min_salary, max_salary, step))
for input_bruto in salary:
regular_salary.append(calculate... |
# determine if a list is sorted
itemsOrdered = [6, 8, 19, 20, 23, 49, 87]
itemsUnordered = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53]
def isSorted(itemList):
# Use brute force method
""" for i in range(0, len(itemList)-1):
if (itemList[i] > itemList[i+1]):
return False """
return all(itemL... |
"""List partitioning library.
Minimal Python library that provides common functions
related to partitioning lists.
"""
import doctest
def parts(xs, number=None, length=None):
"""
Split a list into either the specified number of parts or
a number of parts each of the specified length. The elements
are... |
"""
003-plot-timeseries.py
Plot data from the Harry Potter data-set as a time-series
"""
import matplotlib.pyplot as plt
import load_hp_data as hp
import math
# We can play with styles:
# plt.style.use('bmh')
plt.style.use('ggplot')
# To see available styles, type:
#plt.style.available
fig, ax = plt.subplots(1)
ax... |
# f = open('demo.txt', 'r')
# content = f.readline(29)
# print(content)
# f.close()
courses = [
("Javascript", 200),
("Python", 290),
("C++", 210),
]
courses.append(("Django", 400))
print(courses)
filtered = list(map(lambda item: item[1], courses))
print(filtered)
print("He said \"this is not a good sof... |
import sqlite3
connection = sqlite3.connect('movies.db')
cursor = connection.cursor()
cursor.execute("INSERT INTO Movies VALUES('Taxi driver', 'Martin Scorsese', 1976)")
cursor.execute("SELECT * FROM Movies")
print(cursor.fetchone())
connection.commit()
connection.close()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 21 18:16:27 2020
@author: vais4
"""
class BinaryTree():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def addChild(self, data):
if data == self.data:
return
... |
#making a class student info as i will use a several objects student 1 , student 2 , etc
class student_info:
#student name as a method
def student_name(self,name):
self.student_name=name
return name
#student mark as a method
def student_mark(self,mark):
self.student_mark=mark
... |
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff = int(input("Which tariff? 11 or 31?"))
while tariff != 11 and tariff !=31:
if tariff == 11:
tariff= TARIFF_11
else:
tariff= TARIFF_31
usage = float(input("Enter daily use in kWh"))
days = int(input("Enter number of days in billing period"))
ca... |
import pywhatkit
print('Convert the text into handwritten\n')
txt = input('Enter the text(paragraph) - \n')
pywhatkit.text_to_handwriting(txt, rgb=[0,0,255]) |
import random
def cebolinha(txt):
txt = txt.replace('\n', ' @¨# ')
txt = txt.split()
final_txt = []
for word in txt:
word.strip()
if word == '@¨#':
word = word.replace('@¨#', '\n')
else:
check_word = ''.join([i for i in word if i.isalpha()])
... |
import time
a=time.strftime("%Y%m%d%H%M%S%MS", time.localtime())
print(a)
"""
Compare the date str and now
"""
##timeA="5 28 22:24:24 2016"
timeA="8 10 14:30:00 2016"
timeATick=time.mktime(time.strptime(timeA,"%m %d %H:%M:%S %Y"))
print(timeATick)
print(time.time())
if timeATick<time.time():
print("The date before... |
def myfun(a,b):
a=5
b=3
return b-a
if __name__=='__main__':
#print(myfun(b=5))
#TypeError: myfun() missing 1 required positional argument: 'a'
for i in range(1,10,2):
print(i) |
from functools import reduce
# дискретная нейронная сеть хопфилда
# пример синхронной работы
instances = [
[1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1], # x1
[-1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1], # x2
[-1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, -1] # x3
]
# испорченные образцы
y1 = [-1, -1, -1, -1, -1, ... |
# coding: utf-8
import random
def montyhall(n=1, change_door=True):
result_list = []
for i in range(0, n):
ds = DoorShow(change_door=change_door)
result_list.append(ds.run())
true_count = result_list.count(True)
false_count = result_list.count(False)
print('True: {} [{}]'.format(... |
def bfs( start, end, graph ):
todo = [(start, [start])]
while len( todo ):
node, path = todo.pop( 0 )
for next_node in graph[node]:
if next_node in path:
continue
elif next_node == end:
yield path + [next_node]
else:
todo.append( (next_node, path + [next_node]) )
if __name__ == '__main__':
... |
import sys
nterms = 10
f1 = 1
f2 = 1
fn = 0
count = 0
if nterms <= 0:
print ("Enter a positive number")
elif nterms == 1:
print (f1)
else:
while count <= nterms:
print(f1,f2)
fth = (fn - 1) + (fn - 2)
f1 = f2
f2 = fth
count += 1 |
#coding: cp949
print ("̿ , α _ver4")
age = int(input("̸ Էϼ: "))
choice = int(input(" ϼ. (1: , 2: ſ ī) "))
kid = 2000
teen = 3000
adult = 5000
if choice == 1:
if age<0:
print("ٽ Էϼ")
elif age<4:
print("ϴ ̸ Դϴ")
elif age>=4 and age<14:
print("ϴ ̸ 2000 Դϴ")
charge... |
# coding: cp949
#pocket = ['paper','cellphone','money']
#pocket = ['paper','cellphone']
pocket=[]
item=input("Ͽ ì⼼: ")
pocket.append(item)
if'card' in pocket:
print("ſī ýø Ż õմϴ")
elif 'money' in pocket:
print(" ̿ ì⼼.")
elif 'cellphone' in pocket:
print("Ʈ ī ִ Ȯϼ")
else:
pass
|
def chocolate_dist(age_list):
age_list.sort(reverse=True)
#print(age_list)
length=len(age_list)
count_arr=[]
#print(age_list)
#print(length)
for i in range(length):
if(i==0):
count_arr.append(1)
continue
if(age_list[i]==age_list[i-1]):
... |
#!/usr/bin/python3
#using os module to change working directory
#os.cwd() returns the path of current working directory.
import os
cwd = os.getcwd()
print("Current Working Directory:\n %s" %(cwd))
os.chdir("dir1")
print("\nWe go to chile directory using os.chdir().\nNow Current Working Directory:\n %s" %(os.getcwd... |
#!/usr/bin/python3
#Shows if a number is prime number or not
import threading
class PrimeNumber(threading.Thread):
def __init__(self, number):
threading.Thread.__init__(self)
self.Number = number
def run(self):
counter = 2
while counter*counter < self.Number:
if self.Number % counter == 0... |
# Binary Indexed Tree
# Reference http://hos.ac/slides/20140319_bit.pdf
class BIT:
def __init__(self, size):
self.bits = [0 for i in range(size+1)]
self.size = size
def update(self, index, value = 1):
index += 1
while index <= self.size:
self.bits[index] += value
... |
#! /usr/bin/env python
import locale
from dialog import Dialog
d = Dialog(dialog="dialog")
def handle_exit_code(d, code):
# if the users clicks 'Cancel' or presses 'ESC' button
if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
# if the user clicks the 'Cancel button'
if code... |
#contador = 1
#while(contador <= 10):
# print(contador)
# contador = contador + 1
#for contador in range(1, 11):
# print(contador)
num_tabuada = int(input('Digite o número você deseja a tabuada: '))
for multiplicador in range(1,11):
calc = num_tabuada*multiplicador
print('{}x{}={}'.forma... |
class Queue:
def __init__(self):
self.__storage = list()
def is_empty(self):
return len(self.__storage) == 0
def push(self, item):
self.__storage.append(item)
def first(self):
if not self.is_empty():
return self.__storage[0]
else:
raise... |
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
get_sum = sum(n_num)
mean = get_sum / n
print("Mean / Average is: " + str(mean)) |
myDic = {
1: {'name': '아아', 'price': 1000, '': 1},
2: {'name': '따아', 'price': 2000, '': 2},
3: {'name': '라떼', 'price': 3000, '': 3},
}
while(True):
money = int(input('준 돈 : '))
menuNum = int(input('''1. 아아
2. 따아
3. 라떼
주문 번호 : '''))
count = int(input('수량 : '))
if(myDic[menuNum]['stock'] - c... |
import unittest
from text_tetris import *
class TestTetrisMethods(unittest.TestCase):
# Simple tests for most important functions
def test_mix_field_and_current_piece(self):
temp_field = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
piece = [[0,1],[0,1]]
current_piece_object = {'piece':pie... |
def square (n):
return n*n
def cube (n):
return n*n*n
def average (values):
nvals = len(values)
sum=0.0
for c in values:
sum+=c
return float (sum)/nvals
|
import cv2
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
img=cv2.imread("photo.jpg")
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#^^We wanted to have a grayscale image of the pic
faces=face_cascade.detectMultiScale(gray_img, # "detectMultiScale" >>See at the bottom for expla... |
#Move Data from second register/Data into first register
def mv(Din):
#mv -> 000
Imm = "000"
#Checks if instruction is between two registers or immediate data and register
imData = isImmediateData(Din[1])
#Calculates primary Register address(3 bits)
rX = DecToBinary(Din[0][1])
#If immedia... |
# Got help from this! https://www.smallsurething.com/comparing-files-in-python-using-difflib/
import sys, pprint
from deepdiff import DeepDiff
pp = pprint.PrettyPrinter(indent=2)
def main():
print(sys.argv)
if len(sys.argv) != 3:
return
with open(sys.argv[1]) as f1, open(sys.argv[2]) as f2:
lines1 = f... |
# Got help from this! https://www.smallsurething.com/comparing-files-in-python-using-difflib/
import sys
import difflib
def main():
print(sys.argv)
if len(sys.argv) != 3:
return
with open(sys.argv[1]) as f1, open(sys.argv[2]) as f2:
lines1 = f1.readlines()
lines2 = f2.readlines()
# print(lines... |
def main():
global randomNumber
randomNumber=getRandomNum()
guessRandomNumber(randomNumber)
def getRandomNum():
import random
return random.randint(1,10)
def guessRandomNumber (randomNumb):
global continueProgram
continueProgram = True
while (continueProgram == True):
pri... |
def main():
CelsiusFahrenheitTemp()
def CelsiusFahrenheitTemp():
CelsiusFahrenheitTitle="Celsius Fahrenheit"
print(CelsiusFahrenheitTitle)
CTemp = 0
count = 101
while CTemp<count:
FTemp=float(1.8*CTemp+32)
print(CTemp,"C",end=" ")
print(FTemp,"F")
CTemp = ... |
import time
from random import randint
from datetime import timedelta
class Tamagotchi:
def __init__(self, name):
self.name = name
self.kleur = self.kieskleur()
def kieskleur (self):
Kleuren = ["rood","groen","bruin"]
GekozenKleur = Kleuren[randint(0,2)]
ret... |
class Scene:
"""
A scene has a name and a detector function, which returns true if the scene is
detected, false otherwise.
Attributes:
name (string): A descriptive name of what the scene consists of.
detector (function): A function that checks if that scene is present.
"""
def __init__(sel... |
class BaseAlgorithm:
""" Abstract base class meant to be inherited from to implement new algorithms.
Subclasses must implement the schedule method.
Attributes:
max_recompute (int): Maximum number of periods between calling the scheduling algorithm even if no events occur.
If None, the ... |
#!/usr/bin/python3
""" printing a text """
def text_indentation(text):
""" This method prints a text with 2 new lines after each of these
characters: ., ? and : and there should be no space at the begining
or at the end of each printed line.
Args:
text (str): parameter
Raises:
Ty... |
#!/usr/bin/python3
for a in range(97, 123):
if a in [101, 113]:
continue
print("{:c}".format(a), end='')
|
#!/usr/bin/python3
for decimal in range(0, 100):
if decimal < 99:
print("{:02d},".format(decimal), end=' ')
print("{}".format(decimal))
|
#!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
lastDigit = number % 10
if number < 0:
lastDigit = abs(number) % 10 # absolute value first for negative nums
lastDigit = -lastDigit
else:
lastDigit = number % 10
print("Last digit of", number, "is", lastDigit, "and is", end=" ")
if ... |
#!/usr/bin/python3
"""
Python script that takes in a letter and sends a POST request to
http://0.0.0.0:5000/search_user with the letter as a parameter.
The letter must be sent in the variable q
If no argument is given, set q=""
If the response body is properly JSON formatted and not empty,
display the id and name like... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.