text
stringlengths
37
1.41M
numbers = [int(n) for n in input().split()] average = sum(numbers) // len(numbers) top_5 = [] for n in numbers: if n > average: top_5.append(int(n)) if len(top_5) > 1: a = list(reversed(sorted(top_5))) print(*a[:5]) else: print(f'No')
rooms = int(input()) free_chairs = 0 if_enough = True for room in range(1, rooms+1): each_room = input().split() chairs = each_room[0] people_taken_places = int(each_room[1]) if len(chairs) == people_taken_places: continue elif len(chairs) > people_taken_places: free_chairs += len(...
a = int(input()) b = int(input()) c = int(input()) def smallest_of_number(a, b, c): smallest_number = 0 if a <= b and a < c: smallest_number = a elif b <= a and b <= c: smallest_number = b else: smallest_number = c return smallest_number print(smallest_of_number(a, b, c))
# LAB 1 # 1.1 Part A temperature_F = float(input("Please enter the temperature in Fahrenheit: ")) temperature_C = (temperature_F - 32) * 5/9 print("The temperature in Celsius is", temperature_C) # 1.2 Part B height = float(input("Please enter the height of the trapezoid: ")) bottom = float(input("P...
a=int(input()) if 100 >= a >=90:print('A') elif 90 > a>=80:print('B') elif 80 > a>=70:pirnt('C') elif 70 > a>=60:print('D') elif 60 > a >= 0:print('F') print('FFFFFFDCBAA'[a//10])
#listing 4-26 def step_to(factor, stop): step = factor start = 0 while start <= stop: yield start start += step for x in step_to(2, 10): print(x)
#Listing 4-39 #Decorators enhances the action of the function that they decorate #We have the ability to change the inner-working of the function without #adjusting the original decorated function at all def plus_five(func): def inner(*args, **kwargs): x = func(*args, **kwargs) + 5 return x ...
""" The camera module is used to calculate positions of everything thats going on a map. Use this pygame.rect to draw everything in relative positions to the tracked object's position. """ # dependencies from .utils import validateDict import pygame as pg # classes class Camera(pg.Rect): """ The camera is used ...
"""find the median of two sorted arrays: median is the number which in the middle number of a sequence of sorted numbers (x) if len(x) is odd, the median is kth value, k = (len(x) + 1) / 2 if len(x) is even, the median is (x[len(x)/2] + x[len(x)/2+1]) / 2 author: Yi Zhang <beingzy@gmail.com> date: 20...
"""create a function to return n-th fibonacci number """ def fib(n): if n == 1 or n == 2: return 1 else: return fib(n-1) + fib(n-2) def dynamic_fib(n): """dynamic programming implementation of fib() """ raise NotImplementedError
favorite_foods = [] #Start a loop to ask user to enter their favorite foods repeat = True while repeat == True: food = input("Please enter a favorite food or 'done' to end input: ").strip().lower() #Check if user has entered done so that loop can be stopped if so if food == 'done': repeat = False...
class Trie: '''Reperesents a Trie data structure''' def __init__(self): self.root = dict() def add(self,s): ### Defining a helper method def add_helper(s): if s == "": return {"" : None} return {s[0] : add_helper(s[1...
class Luhn: @classmethod def checkdigit(cls, card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ _sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for i in range(0, num_digits): try: digit = int(c...
''' Read, combine and write excel sheets with pandas Just a test script ''' import pandas as pd # Read the input excel files seen = pd.read_excel('pandas_in.xlsx', sheet_name='seen', index_col='license') owners = pd.read_excel('pandas_in.xlsx', sheet_name='owners', index_col='license') # Create a result from seen a...
# ------------------------Download and read MNIST data-------------------------- from tensorflow.examples.tutorials.mnist import input_data # mnist is a lightweight class that stores training, validation and testing sets # as NumPy arrays. Also provides function for iterating through data # minibatches mnist = in...
m = int(0) x = int(input ("Digite um número: ")) m = m+1 x = x+ int(input ("Digite um numero: ")) m = m+1 x = x+ int(input ("Digite um numero: ")) m = m+1 print ("Soma total : ",x) Media = x/m print ("média : ",Media) print ("Deu certo")
import os import re def get_filenames(): folder = "./prank_after" all_files = os.listdir(folder) # current directory print all_files def rename_files(): print "Inside rename_files" # 1) Get file names from folder folder = "./prank_after" all_files = os.listdir(folder) # current direct...
from tkinter import * import random class Window(): def __init__(self): self.WIDTH = 800 self.HEIGHT = 600 self.block_size = 20 self.IN_GAME = True self.root = Tk() self.c = Canvas(self.root, width=self.WIDTH, height=self.HEIGHT, bg="#819ca3") def create_window(...
#2.To count the unique words in a file(use set) # f=open("a_new.txt","w") # f.write("one two two") # f.close() # # f=openf=open("a_new.txt","r") # data=f.read() # print(data) unique = set(["one","two","two","three","three"]) print(len(unique))
# #print ([i if i%2==0 else "Odd" for i in range(10)]) # #print ([ letter for letter in 'Python class' ]) # # #iterator # a=[2,4,5,7] # i=iter(a) # print(next(i)) # print(next(i)) # # class Hotel(): # def__init__(self) # self.menu=['assad','bdas','cftsrf'] # self.index=-1 # def__iter__(self) # ...
import time from threading import Thread #-----------------------------------------------------Sort Class------------------------------------------------------ class Sort(Thread): def __init__(self, func, name): Thread.__init__(self) self.func = func self.name = name def read_from_fi...
import os as system from time import * class menu(): def men(): print("Witaj w moim notatniku!") print("[1] Zapisać") print("[2] Odczytać") odpowiedz = input("Napisz tutaj ---> ") zapisywanie class kot(): def zapisywanie(): if menu....
name = input("enter a name:") marks = input ("enter a marks:") print("name:{} \nmarks:{}".format (name,marks))
import sys class Ipv4Address(): def __init__(self): self.octets = 4 self.max_of_octets = 3 #maximum number of digits of a single octet self.min_of_octets = 1 #minimum number of digits of a single octet self.notation = "." #dot notation is always used in IP address se...
#Creating a Cryptocurrency On Python And Testing It On Postman #Getting Started #Importing the libraries import datetime import hashlib import json from flask import Flask, jsonify, request ''' From flask lbrary we are not just importing the flask class and jsonify file but also request module this time because we ...
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here if pRoot is None or k == 0: return None def kth...
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here if n <=1: return n pre = 0 cur = 1 cnt = 1 ans = 1 while cnt <n: ans = cur + pre pre = cur cur = ans cnt += 1 r...
# coding=utf-8 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @param {integer} m # @param {integer} n # @return {ListNode} def reverseBetween(self, head, m, n): if not m or not n or m>n: return h...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def addTwoNumbers(self, l1, l2): if l1 is None: return l2 ...
# coding=utf-8 import unittest class Solution: def solve(self, nums): return self.candy(nums) # @param {integer[]} ratings # @return {integer} def candy(self, ratings): length=len(ratings) if length<2: return length candies=[1]*length for i in range(...
class Solution: # @param {string} s # @return {boolean} def isValid(self, s): stack=["+"] for p in s: if p in "([{": stack.append(p) else: if (p==")" and stack[-1]=="(") or (p=="]" and stack[-1]=="[") or (p=="}" and stack[-1]=="{"): ...
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ strs = str.split(" ") if len(pattern)!=len(strs): return False dic1={}# pattern to str dic2={}# str to pattern ...
#separador de tags e palvras: corpus = "((S (UBK re) (UBK re) (UBK re) (ARK re) (SBJ I) (NOUN uh) (NOT don't) (NOT don't) (NEXP like) (NEXP like) (OBJ it) (UNK re) ))" corpus = corpus.replace("(", "").replace(")", "").replace("S", "").split() #definidas as duas listas que serão utilizadas pelo codigo para ter acesso a...
import microbit import random submarine_life = 5 submarine = {} life = {} x = {} y = {} def dictionnary(nb_submarine): """Specification of the function Parameters: ----------- nbr_submarine : the number of submarine for a game (int) Note: ----- The function will generate a dictionnary with the subm...
# -*- coding: utf-8 -*- """ Created on Tue Aug 11 14:09:44 2020 @author: Charlie """ import numpy as np import matplotlib.pyplot as plt import statistics as stat import math import scipy import itertools as itr xticks = np.linspace(0.01, 720, 2000) fig = plt.figure(figsize=(10,7)) ax1 = fig.add_subpl...
# -*- coding: utf-8 -*- """ Created on Thu Jul 9 16:16:13 2020 @author: Charlie """ import statistics as stat import scipy.stats as sci import numpy as np import matplotlib.pyplot as plt import math import scipy import itertools as itr # Python function to print permutations of a given list def permu...
# -*- coding: utf-8 -*- """ Created on Wed Jun 24 15:08:11 2020 @author: Charlie """ import statistics as stat import scipy.stats as sci import numpy as np import matplotlib.pyplot as plt ''' so we are gonna get 2 strings of binary digits, and combine them into a new string of binary digits using a logi...
import numpy as np import matplotlib.pyplot as plt #define our functions, using def. x, y, z are our variables. s, r, b, are our #are our parameters. Return must be used toto give back results. def lorenz(x, y, z, s=10, r=28, b=8/3.): x_dot = s*(y - x) y_dot = r*x - y - x*z z_dot = x*y - b*...
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 11:25:04 2020 @author: Charlie """ import statistics as stat import scipy.stats as sci import numpy as np import matplotlib.pyplot as plt from matplotlib import cm import math import scipy import itertools as itr from mpl_toolkits.mplot3d import Axes3D ...
def rational_to_decimal(n,d): # returns the decimal expression of the rational as a string #if n%1!=n or d%1!=d: #return 'That is not a rational number!' dec_expr='' # it will store n/d = d0.d1 ... dn ( period ) r=[] q=int(n/d) dec_expr+=str(q) dec_expr+='.' r.append(n-d*q) n=r[-1]*10 while True: #This will ...
def Collatz_seq(n): l=[] l.append(n) if l[-1]==1: return l else: if l[-1]%2==0: return l+Collatz_seq(n/2) else: return l+Collatz_seq(3*n+1) def LengthCollatz(n): count=1 a=n while a!=1: if a%2==0: a=a/2 else: a=3*a+1 count+=1 return count MaxLength=1 index=0 memory={} for i in rang...
def number_name(n): #gives the names of numbers between 1 and 999 included. if n>1000: return 'Too big!' if n==1000: return 'one thousand' s=str(n) if len(s)==1: if s[0]=='0': return 'zero' if s[0]=='1': return 'one' if s[0]=='2': return 'two' if s[0]=='3': return 'three' if s[0]=='4':...
lowers = 'abcdefghijklmnopqrstuvwxyz' caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Read from file, check if binary or nor and print mesage accordingly def binReadWrite(): message = readFile() if(checkBinary(message)): # Converting to alphabet if message binary print(binToAlpha(message)) else: # Converting to binary ...
caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def removeSpecials(message): #make a list of individual characters from message lettersOnly = '' for symbol in message: if symbol in caps: lettersOnly = lettersOnly+symbol # return the modified, letters-only message return lettersOnly def vig...
import read as R import datetime import display as D import list2d as L import write as W import returnbook as RB try: # first it is read from the file. def initialtable(): lists=[ ] lists_1= R.read_information(lists) list_2d=L.arrange(lists_1) # the read data which is in list ...
#5622 import sys alphabet = input() num_word = ['','','ABC', 'DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ'] time = len(alphabet) for i in alphabet: for j in range(len(num_word)): if i in num_word[j]: time += j print(time)
"""Module containing the descriptions that make up Shadow House's story. This module is made up of several classes that contain descriptions of each room a player can enter. Within each room choices can be made and each corresponding class has descriptions of those as well. Rooms such as Basement, DiningRoom, etc., al...
# Code from project compressed down to one file for ease of use # Note: As the project grows, this file will become less viable import pandas as pd file_path = input("File path: ") table_name = input("Table name: ") schema = input("Schema name: ") type_dict = {"object": "TEXT", "int64": "NUMERIC", "float64": "REAL", ...
# OPERATORS IN PYTHON # Arithmatic operator """ + - * / ** power a^b // flor value % """ # Assignment operators """ = += -= *= /= """ # Comparison operator """ == <= >= """ # Logical operator """ and or """ # Identity operator """ is nor """ # Membership operator """ in not in """
# lambda function or anonymous function def add(a,b): return a+b minus = lambda x, y: x+y print(add(2,4)) print(minus(3,8)) list = [[11,41],[5,6],[8,23]] list.sort(key=lambda x:x[0]) print(list)
# f string - inserting variables in string me ="mohan" a1 = 3 a ="this is %s %s"%(me,a1) aa = "This is {} {}" b = aa.format(me ,a1 ) print(b) aaa = f"this is {me} {b} {a1} {4+5}" print(aaa)
#A prime number is a whole number greater than 1 whose only factors are 1 and itself. #Write a program using a while statement, that given an int as the input, #prints out "Prime" if the int is a prime number, otherwise it prints "!Prime". n = int(input("Input a natural number: ")) counter = 2 #ég byrja á 2 því þa...
#Write a Python program using a for loop that, # given the number n as input, # prints the first n odd numbers starting from 1. num = int(input("Input an int: ")) for i in range if i % 2 != 0
#Write a Python program using a for loop, tthat given two integers as input, prints the greatest common divisor (gcd) of them. #GCD is the largest integer that divides each of the two integers. for i in range (1, n+1): n % i== 0 and m % i == 0 gcd = i print (gcd)
#!/usr/bin/python3 # A function to output all of the English words that are being picked up from # Newspapers, checking which ones have Māori format and if they exist in Māori # Dictionary. This is best run after changes to taumahi have been made. from taumahi import * import csv def hihira_kupu_pākehā(tāuru_kōnae_i...
from database import add_entry, view_entries menu = """Please select one of the following options: 1. Add new entry for today. 2. View entries. 3. Exit. Your selection: """ welcome = "Welcome to the programming diary!" print(welcome) user_input = input(menu) while (user_input :=input(menu)) != "3": if user_inpu...
def single_bit_or(a, b): ''' a: single bit, 1 or 0 b: single bit, 1 or 0 ''' if a == 1 or b == 1: return 1 else: return 0 def single_bit_not(a): ''' a: single bit, 1 or 0 ''' if a == 1: return 0 elif a == 0: return 1 def single_bit_and(a, b): ''' a: single bit, 1 or 0 b: single bit, 1 or 0 ''...
""" =================================================================== Decision Tree Regression =================================================================== 1D regression with :ref:`decision trees <tree>`: the decision tree is used to fit a sine curve with addition noisy observation. As a result, it learn loca...
import pdb import os class Stack: def __init__(self): self.items = [] def push(self, val): self.items.append(val) def pop(self): return self.items.pop() def top(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def...
from random import * def msg(txt): print('=' * (len(txt) + 4)) print(f'| {txt} |') print('=' * (len(txt) + 4)) def tela(): print(''' Existe um super prêmio de uma destas 3 portas! Adivinhe qual é a porta certa para ganhar o prêmio!''') for c in range(1,4): print(''' ______ ...
class Tree: def __init__(self, num): self.__elements = [] for a in range((2**(num+1))-1): self.__elements.append( [True, False] ) def close(self, index): element = self.get_elements()[index] if element[0]: element[0] = False ...
# # File: Prac2Exc12.py # Author: Ethan Copeland # Email Id: copey006@mymail.unisa.edu.au # Version: 1.0 16/03/19 # Description: Practical 2, exercise 12. # This is my own work as defined by the University's # Academic Misconduct policy. # temperature = int(input("Please enter the temperature: ")) if temp...
# # File: Prac2Exc2.py # Author: Ethan Copeland # Email Id: copey006@mymail.unisa.edu.au # Version: 1.0 15/03/19 # Description: Practical 2, exercise 2. # This is my own work as defined by the University's # Academic Misconduct policy. # width = int(input("Enter the width: ")) length = int(input("Enter the ...
# # File: Prac5Exc2.py # Author: Ethan Copeland # Email Id: copey006@mymail.unisa.edu.au # Version: 1.0 12/04/19 # Description: Practical 5, exercise 2. # This is my own work as defined by the University's # Academic Misconduct policy. # import random rolls = 0 pairs = 0 while rolls != 10: die1 =...
def determine_grade(): testScore = int(input("Please enter the test score")) if testScore >= 0 and testScore <= 39: grade = "F2" elif testScore > 39 and testScore <= 49: grade = "F1" elif testScore > 49 and testScore <= 54: grade = "P2" elif testScore > 54 and testSco...
print((lambda n: 'Weird' if n % 2 or 5 < n < 21 else 'Not Weird')(int(input("Enter a number:"))))
from random import randrange min=1 max=49 length=6 ticket_num=[] for i in range(length): r= randrange(min,max+1) while r in ticket_num: r= randrange(min,max+1) ticket_num.append(r) ticket_num.sort() print("ticket numbers are:") for i in ticket_num: print(i)
def charcount(s): count={} for ch in s: if ch in count: count[ch]=count[ch]+1 else: count[ch]=1 return count def main(): s1=input("first string:") s2=input("second string:") counts1=charcount(s1) counts2=charcount(s2) if counts1==cou...
import math a = 1 b = 5 c = 6 # To take coefficient input from the users # a = float(input('Enter a: ')) # b = float(input('Enter b: ')) # c = float(input('Enter c: ')) # calculate the discriminant d = (b ** 2) - (4 * a * c) sol1 = (-b - math.sqrt(d)) / (2 * a) sol2 = (-b + math.sqrt(d)) / (2 * a) print('The solu...
from collections import deque class binaryTree: def __init__(self,value): self.value = value self.left_child = None self.right_child = None def insert_right(self,val): if self.right_child == None: self.right_child = binaryTree(val) ...
#!/usr/bin/env python x = int(raw_input("Enter number to square: ")) ans = 0 itersLeft = x while(itersLeft != 0): ans = ans + x itersLeft = itersLeft - 1 print(str(x) + "*" + str(x) + " = " + str(ans))
from datetime import datetime class Node(object): """This is a coordinate node for the TimeList class.""" __slots__ = ( "x", "y", "timestamp" ) def __init__(self, timestamp, value): self.x, self.y = value self.timestamp = timestamp def __lt__(self, other): return self.timestamp < other def ...
# Universidad del Valle de Guatemala # Cifrado de información 2020 2 # Grupo 7 # Implementation RSA.py import random from sympy import mod_inverse from Crypto.Util.number import bytes_to_long ,long_to_bytes import binascii # First Alice and Bob will communicate thru RSA # STEPS FOR RSA # 1. Generate two big random pr...
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。 如果不存在则输出0。 思路: 1、用字典设置计数,超过一半则返回 2、采用阵地攻守的思想: 第一个数字作为第一个士兵,守阵地;count = 1; 遇到相同元素,count++; 遇到不相同元素,即为敌人,同归于尽,count--;当遇到count为0的情况,又以新的i值作为守阵地的士兵,继续下去,到...
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点, 重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5 思路: 用lst删除重复结点,再重建链表''' class Solution: def deleteDuplication(self, pHead): if not pHead: return None lst1=[] while pHea...
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 给定一个double类型的浮点数base和int类型的整数exponent。 求base的exponent次方。 思路: 递归,注意指数是负数的情况''' class Solution: def Power(self, base, exponent): s = 1 if exponent == 0: return 1 elif exponent >= 1: s = base * self...
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。 我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 思路: 需要考虑排序的实现''' class Solution: def __init__(self): self.stack = [] def GetMedian(sel...
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 输入一个链表,反转链表后,输出新链表的表头。 思路: tmp记录下一个要反转的结点,pre指向反转后的首结点,pHead始终指向要反转的结点 每反转一个结点,把pHead结点的下一个结点指向pre,pre指向反转后首结点, 再把pHead移动到下一个要反转的结点(=tmp)。直至None结束 需要考虑链表只有0 or 1个元素的情况。''' class Solution: # 返回ListNode def ReverseList(self, pHead): i...
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Author: SONG '''题目描述: 把只包含质因子2、3和5的数称作丑数(Ugly Number)。 例如6、8都是丑数,但14不是,因为它包含质因子7。 惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 思路: 1、判断丑数:除以2 直到无法整除then除以3直到无法整除then除以5直到无法整除 余数为0则为丑数 2、丑数的生成:对现有的丑数列表里各数,min(num*2,num*3,num*5) 注意有可能重复''' # -*- coding:utf-8 -*- class Solution: d...
class Person: def __init__(self, person_id, first_name, last_name, age, race): self.person_id = person_id self.first_name = first_name self.last_name = last_name self.age = age self.race = race def __repr__(self): return (f"{self.first_name}, {self.last_name}...
#Extract information about various US colleges # #Computational steps of the code: # #Part 1: Import relevant python modules #Part 2: Define the URL of the Site and Get the (clean) data as a long list #Part 3: Extract 1D data from the long list #Part 4: Create pandas dataframe #Part 5: Save data in a csv file #Pa...
# Common mathematical functions from math import * def combinations(n, k): num = factorial(n) den = factorial(k) * factorial(n - k) return num // den # n-th fibonacci, 1 indexed def fibonacci(n, a0=0, a1=1): if n == 1: return a0 if n == 2: return a1 for i in range(3, n + 1): ...
# Learning a communication channel # This model shows how to include synaptic plasticity in Nengo models using the # hPES learning rule. Here we implement error-driven learning to learn to # compute a simple communication channel. This is done by using an error signal # provided by a neural ensemble to modulate th...
# Adaptive motor Control # Now we use learning to improve our control of a system. Here we have a # randomly generated motor system that is exposed to some external forces # (such as gravity acting on an arm). The system needs to learn to adjust # the commands it is sending to the arm to account for gravity. # The ...
def validateIP(ip): "aaaaaaaaaaaaaa...." numbers_list = ip.split(".") # "X.X.X.X"["X", "X", "X", "X"] # X -> [0, 255] if len(numbers_list) != 4: return False for i in range(len(numbers_list)): if not (isValid(numbers_list[i])): return False return True def isValid(myNum...
def newKey(str1, str2): if len(str1) == 0: return str2 if len(str2) == 0: return str1 return(str1 + "." + str2) def helper(initial_key, obj, output): if type(obj) is dict: for key, value in obj.items(): helper(newKey(initial_key, key), value, output...
# for loops in python for x in range(1, 10): print(x) for letter in "budi": print(letter)
# Create basic paper rock scissors games player1 = input("Enter Player 1's choice: ") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") print("* * * NO CHEATING * * *") pr...
import random import math random_number = random.randrange(1,100) def guess(x): num = input(x) number = int(num) if number==random_number: print("Your guess was correct") elif(number is not random_number): diff = random_number - number difff = abs(diff) print("you lost by "+ str(difff)) pr...
#getting numbers between 1000 and 3000 that have an even number in them items = [] for i in range(1000, 3001): x = str(i) if (int(x[0])%2==0) and (int(x[1])%2==0) and (int(x[2])%2==0): items.append(x) print(items)
from collections import OrderedDict import random food_list = OrderedDict() food_list["한식"] = ["김밥천국","장충동왕족발","엄마밥상"] food_list["중식"] = ["복성각","차우차우","베이징덕"] food_list["일식"] = ["갓덴스시","아비꼬","아리가또"] selected_food_type = input("{} 중 한가지를 고르시오.\n".format(",".join(food_list.keys()))) while selected_food_type not in foo...
# Leia um vetor de 10 posições e verifique se o número digitado ja foi armazenado, se sim, leia novamente. No final mostre todos os números. # Use lista. num = [] for i in range(0, 10): while True: if len(num) == 10: break num2 = int(input('Informe o número: ')) if num2 not in ...
# Jogo da Forca: A palavra é adicionada pelo jogador e verifica se já escreveu uma letra. # Para o sorteio usei o módulo random, que é um módulo builtins do próprio python. import random as rd print('=============================') print(' JOGO DA FORCA') print('=============================') palavras = ['Coel...
def controle(): mouses = [0]*4 calculo = [] while True: menuEntrada = int(input("Situação do mouse: " + "\n1 - Necessidade de esfera \n2 - Necessidade de limpeza \n3 - Necessita troca de cabo ou conector" + "\n4 - Quebrado ou inutilizado \n0 - Sair: ")) if me...
#!/usr/bin/python3 """ pascal triangle module """ def pascal_triangle(n): """ return ist that represent pascal's triangle""" my_list = [] if n <= 0: return my_list for i in range(1, n + 1): value = 1 tmp_list = [] for j in range(1, i + 1): tmp_list.append(st...
# -*- coding: utf-8 -*- #Take note #Purpose:Python code to convert Hex code to Text as per Grade 1 Braille #@author Manikandan V #@version 1.0 #@date 09/01/18 from __future__ import print_function import os,sys #****** Declaration of Alphebets and corresponding Hex codes *********** alp = ['a','b','c','d','e','...
### # Google Hash Code 2020 # This code aims at solving the practice problem - more pizza # # Author: Teki Chan # Date: 28 Jan 2020 ### import sys def read_file(in_file): """ Read Intput File Args: in_file: input file path Returns: Maximum number of slices allowed , Number...
def latest(scores): return scores[-1] def personal_best(scores): scores.sort() return scores[-1] def personal_top_three(scores): scores.sort() scores.reverse() l = len(scores) if l == 0: return "input is a empty list" if l <= 3: top = scores[0:l] print(top) ...
import sqlite3 class Database: def __init__(self, db): self.conn= sqlite3.connect(db) self.cur= self.conn.cursor()#쿼리 접속 self.cur.execute("CREATE TABLE IF NOT EXISTS part (id INTEGER PRIMARY KEY, part text, customer text, retailer text, price text)") # create table : db 만들기 ...
class BST: """ Binary Search Tree Properteis left and right are a reference to another Node """ def __init__(self, value = None): self.value = value self.left = None self.right = None def insert(self, value): ''' Add a Node with the given value in the BST :type value: integer or any :rtype: void ...