text
stringlengths
37
1.41M
""" Dictiobnaries are unordered mappings for storing objects. previously we saw how lists store onjects n an unordered sequence dictionaries use a key value pair instead This key value pair allows users to quickly grab objects without needing to know an index location Dictionaries use curly braces and colo...
n=int(input("Digite o valor de n:")) if(n==0): print(1) else: fatorial=1 while(n>0): fatorial=fatorial*n n-=1 print(fatorial)
# -*- coding: utf-8 -*- import math a=float(input("Digite a:")) b=float(input("Digite b:")) c=float(input("Digite c:")) if(b**2 < 4*a*c): print("esta equação não possui raízes reais") else: if(b**2 == 4*a*c): x1=(-b + math.sqrt(b**2-4*a*c))/(2*a) print("a raiz desta equação é %0.2f" % x1) el...
''' Exercicios da seção 7 do curso pt1 ''' ''' # exercicio 1 total = 0 vetor = [1, 0, 5, -1, -5, 7] total = vetor [0] + vetor[1] + vetor[5] print(total) vetor[4] = 100 print(vetor[4]) print(*vetor, sep= '\n') # exercicio 2 valores = [] for i in range(0,6): print(input('Insira um valor')) valores...
variable = "hola" variable = 2 # el nombre de una variale puede ser la misma # pero se ira sustituyendo a medida se cambie su valor, al final va tener el valor ultimo que se le dio a = 9 b = 8 c = 7 suma = a + b resta = a - c multiplicacion = c*a division = b/b divisionEntera = b//c # para conocer el tipo de una v...
#! /usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Tokuume Shinya<g1244785@cc.kyoto-su.ac.jp>" __status__ = "production" __date__ = "22 December 2014" class Tuple(object): """タプル:総理大臣の情報テーブルの中の各々のレコード。""" def __init__(self, attributes, values): """属性リストと値リストからタプルを作るコンストラクタ。""" self.attributes = attr...
""" Project Euler Problem 3 Largest Prime Factor: what is he largest prime factor of 600851475143 https://projecteuler.net/problem=3 """ num = 10 prime_list = [] def is_it_prime(number): """ function to check if a number is a prime number """ counter = 2 while counter <= round(number/2): ...
def DikdortgenAlanCevreHesapla(): uzun_kenar = int(input("Uzun kenarı girin:")) kisa_kenar = int(input("Kısa kenarı girin:")) alan = uzun_kenar * kisa_kenar cevre = (uzun_kenar * 2) + (kisa_kenar * 2) print ("Alanı: ", alan) print ("Çevresi: ", cevre ) while True: DikdortgenAlanCevreHesapla(...
import random import numpy as np import matplotlib.pyplot as plt x = [i for i in range(200)] total_cost = [] for i in range(250): if i < 50: cost = random.uniform( (200 - i) * 900, (200 - i) * 1000) total_cost.append(cost) elif i >= 50 and i < 100: cost = random.uniform( (200 - i) * 80...
def average(numbers): ave = 0 count = 0 for number in numbers: ave = ave + number count = count + 1 return ave/count print(average([1, 5, 9])) print(average(range(11)))
with open('input.txt') as my_file: lines = list(map(lambda x: x.strip('\n'), my_file.readlines())) lines = [line.split(')') for line in lines] planets = {line[1]: line[0] for line in lines} # child: parent santa_ancestors = ['COM'] you_ancestors = ['COM'] '''return a count of objects a planet is directly...
# -*- coding: utf-8 -*- """ Created on Thu Sep 2 18:51:42 2021 @author: lemit """ #Condiciones #En un while siempre hay ciclos dependiendo la condicion c=2 d=2 if c>d: print ('Esto es lo correcto') elif c<d: print('Esto es incorrecto') elif c==d: print ('me da igual') c=2 d=5 if c>d: print ('...
# -*- coding: utf-8 -*- """ Created on Wed Nov 13 18:05:09 2019 @author: emeka """ # !/usr/bin/env python # -*- coding: utf-8 -*- """ Lesson 9 - Temperature Conversion ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In this homework, you will write a program which will convert a temperature given by the user into Fahrenheit or Ce...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Lesson 9 - Pair Programming ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Exercise 3 Write a Python program to get the Fibonacci series between 0 to 50. Note: The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, .... Every next number is found by adding up the...
print(f'Welcome to my temperature converter!') users_temp = int(input('what is your prefered temperature?')) users_temp_scale = input('what temperature scale would you prefer?') valid_temperature_scales = ('Fahrenheit', 'F', 'Celsius', 'C') while users_temp_scale not in valid_temperature_scales: users_temp_scale = ...
class Solution(object): def canPartition(self, nums): lookup = set([0]) for n in nums: new_lookup = set() for lookup_sum in lookup: new_lookup.add(lookup_sum + n) new_lookup.add(lookup_sum - n) lookup = new_lookup ...
""" Palindromes are strings that read the same from the left or right, for example madam or 0110. You will be given a string representation of a number and a maximum number of changes you can make. Alter the string, one digit at a time, to create the string representation of the largest number possible given the limit...
''' 316. Remove Duplicate Letters Medium 2640 193 Add to List Share Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Note: This question is the same as 1081: https://leetco...
''' 332. Reconstruct Itinerary Medium 2793 1293 Add to List Share You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus...
# 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 pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[i...
""" 501. Find Mode in Binary Search Tree Easy 1893 518 Add to List Share Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it. If the tree has more than one mode, return them in any order. Assume a BST is defined as follows: The l...
""" 241. Different Ways to Add Parentheses Medium 3068 157 Add to List Share Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. Example 1: Input: expression = "2-1...
import datetime dt = datetime.datetime.today() days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: target = datetime.date(year = year, month = month, day = day) days_diff...
''' 582. Kill Process Medium 683 14 Add to List Share You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process's parent process. Each process has only one parent process but may have multi...
""" 95. Unique Binary Search Trees II Medium 4296 282 Add to List Share Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. Example 1: Input: n = 3 Output: [[1,null,2,null,3],[1,null,3,2],[2...
""" 89. Gray Code Medium 1286 2160 Add to List Share An n-bit gray code sequence is a sequence of 2n integers where: Every integer is in the inclusive range [0, 2n - 1], The first integer is 0, An integer appears no more than once in the sequence, The binary representation of every pair of adjacent integers differ...
""" 96. Unique Binary Search Trees Medium 6472 255 Add to List Share Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= ...
''' 162. Find Peak Element Medium 2973 2725 Add to List Share A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] ...
def permute(ls): l = len(ls) if l == 0: return [] if l == 1: return [ls] sol = [] for i in range(l): sub = permute(ls[:i] + ls[i+1:]) for x in sub: sol.append(x + [ls[i]]) return sol print(permute([1,2,3]))
from bisect import bisect class Solution: def heightChecker(self, heights: List[int]) -> int: lst = [] count = 0 for x in heights: i = bisect(lst, x) lst.insert(i, x) for i, x in enumerate(heights): if lst[i] != x: count +...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def leafSimilar(self, root1: 'TreeNode', root2: 'TreeNode') -> bool: leaves1 = [] leaves2 = [] self.g...
class StockSpanner(object): def __init__(self): self.stack = [] self.i = 0 def next(self, price): """ :type price: int :rtype: int """ if not self.stack: self.stack.append( (price,0) ) self.i += 1 return 1 ...
from Board import Board board = Board() # board.saveLoad = '' board.toggleGameStatus(1) # board.printPiles() # board.saveLoad = 'l' while board.playing: # if board.saveLoad == 's': # board.saveGame() # break if board.winning_player != 0: if board.winning_player == 3: pri...
""" Omat Gonzalez web scraper python project """ import urllib.request from bs4 import BeautifulSoup class Scraper: """ Object Scraper takes in a website to scrape from as a parameter for example : "https://news.google.com/" """ def __init__(self,site): self.site=site def scrape(self): #urlopen() makes re...
class StoreItem: TAX = 0.13 def __init__(self, name, price): self.name = name self.price = price self.after_tax_price = 0 self.set_after_tax_price() def set_after_tax_price(self): self.after_tax_price = round(self.price * (1 + self.TAX), 2) def __sub__(self...
class Inventory: def __init__(self): self.slots = [] def add(self, item): self.slots.append(item) # to use len on an object, the object must # have a method named __len__ def __len__(self): return len(self.slots) def __contains__(self, item): ...
def rev(name): ptr = len(name) - 1 letters = [] while ptr >= 0: letters.append(name[ptr]) ptr -= 1 return "".join(letters) def rev2(name): res = '' for c in name: res = c + res return res def rev3(name): return name[::-1] print(rev('miles')) print(r...
""" 1. create a fruit_basket list 2. prompt user to enter in fruit or 'q' to quit 3. check if fruit was entered, if so add fruit to fruit_basket list and then ask again for another fruit. 4. if 'q' was entered end program and display fruits in alphabetically order provided there is at least 1 fruit. """...
# Credit goes to Websten from forums # # Program defensively: # # What do you do if your input is invalid? For example what should # happen when date 1 is not before date 2? # # Add an assertion to the code for daysBetweenDates to give # an assertion failure when the inputs are invalid. This should # occur when the fir...
"""this is our little calculator to work with functions.""" def add(num1, num2): """add num1 with num2 and return the results.""" return num1 + num2 def subtract(num1, num2): """subtract num1 with num2 and return the results.""" return num1 - num2 def multiply(num1, num2): """multiply num1 wit...
#!/usr/bin/env python3 """ Copy the messages.py. Write a function called send_messages() that prints each text message and moves each message to a new list called sent_messages as it's printed. After calling the function, print both of your lists to make sure the messages were moved correctly. ...
class Student: all_students = [] def __init__(self, name, grade): self.name = name self._grade = grade Student.all_students.append(self) @property def grade(self): return self._grade @grade.setter def grade(self, grade): if grade not in range(0, 10...
def main(): """ variable - container that stores a value. container is a section in the computers memory. ex: color = "blue" Rules to Naming Variables: * cannot start with a number - ex: 5color = "blue" * cannot contain any special ...
class Group: def __init__(self, name, members=[]): self.name = name self.members = members def add(self, name): self.members.append(name) def delete(self, name): if name in self.members: self.members.remove(name) else: raise Exception("Member...
#------------------------------------------------------------------------------- # Name: parse_DB_line # Purpose: The purpose is stated below. The robustness is decreased with # this module due to the strictness of the arg line's structure. # # Author: jkougl # # Created: 29/08/2014 ...
''' Exercice IV : Un cycliste souhaite s'entrainer pour une compétition. Il prépare un programme d'entrainement de 3 semaines. Le premier jour, il parcourt 30km puis il décide d'augmenter la distance parcourue de 10km chaque jour. 1) Ecrire un programme python qui calcule et affiche le nombre de kilometres par...
""" Saisie N nombre qui affiche si ce nombre est pair ou impair. Le programme s'arrete des qu'on saisit un nombre négatif """ i = True while i == True: """ print("Saisi un nombre entier") nb = input() nb = int(nb) """ # OU nb = int(input('Saisie un nombre entier :')) # test de coherenc...
''' Programme python qui saisit N nombres et qui affiche si ce nombre est pair ou impair. Le programme s'arrete des qu'on saisit un nombre negatif ''' # Booleen encore = True while encore == True: ''' print("Saisir un nombre entier ") nb = input() nb = int(nb) ''' # OU nb...
# ------------------------------- # Listes necessaires au programme # ------------------------------- # Liste des employes hommes hommes = list() # Liste des employes femmes femmes = list() # Liste des employes dont le salaire est # compris entre 1000 et 1500 euros salaireInf = [] # Liste des employes...
from statistics import mean numbers = [] number = input("Please enter a number (0 to quit)") list_lenth = len(numbers) while number != "0" : print(number) numbers.append(float(number)) number = input("Please enter a number") print(numbers) average = sum(numbers)/len(numbers) print(...
import math userNumber = input("Enter a float number") floatingNumber = float(userNumber) wholeNumber = round(abs(floatingNumber)) print(str(floatingNumber) + " rounded is "+ str(wholeNumber) + " ")
months = ("January", "Feburary", "March", "April", "June", "July", "August", "Sept", "Äug", "Nov", "Dec") for month in months [4:7]: print(month)
def multiplicar_por_dos(n): return n * 2 def sumar_dos(n): return n + 2 def aplicar_operacion(f, numeros): resultados = [] for numero in numeros: resultado = f(numero) resultados.append(resultado) print(resultado) # Funciones en estructuras de datos # Las funciones también se...
import copy class Board(): def __init__(self, player1, player2): self.initial_state = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] self.player1 = player1 self.player2 = player2 self.current_player = self.player1 self.state = copy.deepcopy(...
input() A = input() A1 = A.split() a = int(A1[0]) for i in A1: x = int(i) if x >= a: a = x bul = True else: bul = False break if bul: print("Yes") else: print("No")
import random from math import sqrt, acos def normalize(vector): v_sum = vector.x + vector.y return Vector2D(vector.x / v_sum, vector.y / v_sum) class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y ...
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print("Rayon") Rayon >>> arr1=[1,2,3,4,5,6,7] >>> i=0 >>> while(i<7): print(arr1[i]) i=i+1 1 2 3 4 5 6 7 >>> while(i<7): ar...
text = "paralelepípedo" for letra in text: if letra == 'a': print(letra*2) else: print("Não é a letra 'a'") var = input() print("O número é {}".format(var)) meses = {1: 'Janeiro', 2: 'Fevereiro', 3: 'Março', 4: 'Abril', 5: 'Maio', 6: 'Junho', 7: 'Julho', 8: 'Agosto', 9: 'Setembro', ...
# https://www.geeksforgeeks.org/merge-sort/ def sort(arr, leftIndex, rightIndex): if (rightIndex > leftIndex): midIndex = leftIndex + (rightIndex - leftIndex) / 2 sort(arr, leftIndex, midIndex) sort(arr, midIndex + 1, rightIndex) def merge(arr, leftIndex, rightIndex, midIndex): length1...
# -*- coding: utf-8 -*- import math class Neuron(object): def __init__(self, w, a, c): self.w, self.a, self.c = w, a, c def __call__(self, point): distance = sum(map(lambda x, y: math.pow(x - y, 2.0), point, self.c)) return self.w * math.exp(-1.0 * distance / math.pow(self.a, 2.0)) ...
# !usr/bin/env python3 # -*- coding:utf-8 _*- # author: Alfa # file: PythonTraining_string.py # time: 2018/04/11 23:06 """ 练习字符串的各种方法 """ # join 拼接方法 a = '' a1 = '---' b = '3456' c = 'abcd' d = 'ttee3344' e = 'a is A b is {name}' f = 'a is A b is {name} c is {age}' print(a.join([b, c])) # 3456abcd print(a1.join...
# a121_catch_a_turtle.py #-----import statements----- import turtle as trtl import random #-----game configuration---- turtleshape = "turtle" turtlesize = 3 turtlecolor = "blue" counter_interval = 1000 #1000 represents 1 second timer_up = False timer = 10 score = 0 #-----initialize turtle----- bob = ...
from random import randint def sortColor(list): head = 0 tail = len(list)-1 while head < tail: if list[head] is not 0: while list[tail] is not 0: tail-=1 print(head, tail) print("switch") if head>tail: break ...
class Node: def __init__(self, d=None, n=None): self.data = d self.next = n def __str__(self): return "(" + str(self.data) + ")" class CircularlinkedList: def __init__(self, r=None): self.head = r self.size = 0 def add(self, d): if self.size == 0: ...
# input basics a = input("??") print(a) # print print("Hello" "I" "am") print("Hello" + "I" + "am") # , == space print("Hello" , "I" , "am") for i in range(0, 10): print(i, end = ' ')
money = True if money: print("I have money") else: print("I don't have money") money = 2000 if money <=1000: print("cannot buy anything") elif money <=2000: print("can buy one drink") else: print("you are rich") # and or not card = True if money >= 2000 and card: print("okee") else: print(...
from random import randint def partition_mid(arr, middle): quickSort(arr, 0, len(arr)-1) print("Sorted", arr) key = find(arr, middle) print(key) return arr[:key], arr[key:key+count(arr, middle)+1], arr[key+count(arr, middle)+1:] def partition(arr, low, high): # print("low:", str(low), "high:",...
# !usr/bin/python # usage: results announcement print "Enter user name r qualified or not:::" name=raw_input() list1=['kalyan','supraja','mahindra','anil','siva','ajay','haritha','keerthi','suhashini','subhashini','nariyan','manoj','santhosh','kumar','niveda','thomos','rasii'] if name in list1 : print 'Qualified i...
#usr/bin/python a=int(raw_input("please enter the n value we can show uuu 1--->N values:::")) for i in range(a): if i%2==0 : print "even",i else : print "odd",i
#!/usr/bin/env python import pandas as pd # We only need these attributes to contribute attributes = [ "Endurance", "Strength", "Power", "Speed", "Agility", "Flexibility", "Nerve", "Durability", "Hand-Eye Coordination", "Analytical Aptitude" ] # Handles inputting for valid and invalid values. ...
# -*- encoding: utf-8 -*- # 2018-04-22 from __future__ import print_function import tensorflow as tf import numpy as np # Print 10 random numbers. for step in range(10): # https://www.tensorflow.org/api_docs/python/tf/random_uniform # https://crypto.stackexchange.com/questions/20839/what-is-the-difference-be...
names_list = [["Ellen", "Betty", "Diana"], ["Fox", "Helen", "Andy"], ["Ian", "Glen", "Carol"]] for names in names_list: for i, name in enumerate(names): if i != len(names) - 1: print(name, end=",") else: print(name)
def calc_item(price, count): return price * count def calc_total(items): total = 0 for item in items: total += calc_item(**item) return total items = [{"price": 100, "count": 3}, {"price": 200, "count": 2}, {"price": 300, "count": 1}] total = calc_total(items) print(f"{tota...
names = ["Andy", "Betty", "Carol"] for i, name in enumerate(names): print(f"{i+1}:{name}")
def append_list(list1, list2): return list1 + list2 names1 = ["Andy", "Bob", "Carol"] names2 = ["Alice", "Betty", "Charlie"] print(append_list(names1, names2))
scores = [90, 95, 80, 85, 80, 95, 80, 90, 100] score_count_dict = {} for score in scores: count = 1 if score in score_count_dict.keys(): count = score_count_dict[score] count = count + 1 score_count_dict[score] = count for score, count in score_count_dict.items(): print(f"{score:3}:", ...
some_string = "Hi, hello how are you doing. My name is Sandeep Siddapureddy. Some people call me Sandy or Deep. I don't rly care what you call me." count = {} for char in some_string: count.setdefault(char, 0) count[char] = count[char] + 1 for k, v in count.items(): print(k,v) # a = count.keys() # pri...
# https://www.practicepython.org/exercise/2014/05/21/15-reverse-word-order.html #write a program to reverse order of a stentence def reverse(string): #init final list rev_string = [] #sep initial string sep_string = string.split() for w in sep_string: rev_string.append((sep_string[(...
from threading import Thread, Lock import os import time from queue import Queue if __name__ == "__main__": q = Queue() q.put(1) q.put(2) q.put(3) first = q.get() print(first) q.task_done() #tells that the task is done after u call q.get() q.join() # blocks until all items in queue h...
import sys def sum_of_num_gen(n): num = 0 while n>0: yield n num = num + n n -= 1 def sum_of_num_list (nu): count = nu listed = [] while count > 0: listed.append(count) count -=1 return listed print (sum(sum_of_num_list(10000000))) print (s...
#multiplication operation mult = 2*4 print (mult) #power operation power = 2 ** 4 print(power) #list/tuple/str duplication operation zero = [1, 5] * 10 print(zero) #* args and **kwargs def somefunc(a, b, *args, **kwargs): print(a, b) for arg in args: print(arg) for k in kwargs: print(k ...
class CountCalls: def __init__ (self, func): self.func = func self.num_calls = 0 #call method allows you to exceute a object of this class, just like a funciton. # For eg if this method has a print function, and you create a class like cc = CountCalls(None), every time you execute (or call?) the...
def permutation(combo: str): length = len(combo) for i in range(length): for j in range(length): swap(combo, i, j) pass pass def swap(combo: str, i, j): temp = combo[i] combo[i] = combo[j] combo[j] = temp
def merge_sort(arr): length = len(arr) if length == 1 or length == 0: return arr mid = (length // 2) left = arr[:mid] right = arr[mid:] left_arr = merge_sort(left) right_arr = merge_sort(right) return merge(left_arr, right_arr) def merge(left_arr, right_arr): arr = [] ...
""" function: arithmetic_arranger: takes a list with up to five entries of "number +- number" prints them in columns formatted according to the specifications found in proj_desc.txt Author: Kai Ellis Date: 2020-09-16 """ import re def arithmetic_arranger(l,tf = False): if len(l) > 5: #check to see if th...
""" lots of exercises for this one: 1): modify the socket program to prompt the user for a url of interest that you can connect to 2) change the program so it counts the number of characters and stops displaying text after it's shown 3000. all should be recieved but only 3k printed 3) change the socket program so...
""" reading files: bringing the secondary memory into the equation! we will later be getting to databases etc. Text files are just sequences of lines of text separated by newline characters \n (this is recognized as one character not two in python) note: print() always adds a \n to the end of a print statement...
import copy import random # Consider using the modules imported above. class Hat: def __init__(self,**kwargs): #on initialization, will take any number of keywords and append them into a list based on thier value self.contents = [] for arg in kwargs.items(): #...
# -*- coding: utf-8 -*- """ Created on Thu Sep 17 09:44:38 2020 Bot which asks the user what year they were born, and tells them their horoscope. @author: Randy Zhu """ # Data of the horoscopes. # I wonder how much RAM this uses. rat = [ 1996, 1984, 1972, 1960, 1948 ] ox = [ 19...
# -*- coding: utf-8 -*- """ Created on Mon Oct 5 09:02:50 2020 evaluates city bliss. @author: Randy Zhu """ # Ask about which city to evaluate. city = input("What city would you like to evaluate?: ") # Tell the user which city they are evaluating. print("Okay, we are evaluating " + city + ".\n") # Make a...
# -*- coding: utf-8 -*- """ Created on Fri Sep 18 09:27:56 2020 @author: Randy Zhu """ X = 10 Y = 5 print("x is: " + str(X)) print("y is: " + str(Y)) # nah. print("Is x equal to y?: " + str(X == Y))
# -*- coding: utf-8 -*- """ Created on Fri Nov 6 08:47:46 2020 @author: 1257035 """ import turtle from random import randint anna = turtle.Turtle() anna.speed(0) def draw_cookie(x: int, y: int) -> None: """ Draw a cookie. """ # Draw cookie outside anna.penup() anna.goto(-...
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 09:16:26 2020 Calculate age in 2051. @author: Randy Zhu """ CURRENT_YEAR = 2020 current_age = int(input("How old are you right now?: ")) print("You wil be " + str(2051 - CURRENT_YEAR + current_age) + " years old in 2051!")
""" Author: Randy Zhu Purpose: Determine whether the user is in the dark or light. Date: 09-30-2020 """ # Introduce yourself. print("I will decide whether you can join the Dark Side.") # Set variables. IN_DARK = False # Ask user for input. user_likes_red_input = input("Is red your favorite color?: ") user_...
# -*- coding: utf-8 -*- """ Created on Wed Oct 14 09:01:13 2020 Produce an amortization chart for a mortage. @author: Randy Zhu """ # Import higher precision math library to prevent weird rounding errors with floating points from decimal import Decimal # Ask the user for inputs on purchase price of the home...
from threading import Thread # a. Run the following concurrent program. Are there any particular patterns in # the output? Is the interleaving of the output from the two threads # predictable in any way? # # Ans a). # No, there is no particular pattern in the output. Also, there is no # predictabilty in t...
#!/usr/bin/env python # -*- coding=utf8 -*- import chardet import sys # print sys.argv filelist=sys.argv[1:] # print filelist # exit() # open file not_converted=[] for ifile in filelist : # print ifile try: inputfile=open(ifile, 'r') except IOError: print "can not open file ", ifile ...
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ product = 0 for a in range(1000): for b in range(a, 1000): c = (1000 -...
#!/usr/bin/python from core_tool import * def Help(): return '''List up the attributes or assign value to an element. Usage: attr attr 'list' [MAX_LEVEL] List up the attributes MAX_LEVEL: Maximum level of printed attribute attr 'keys' [MAX_LEVEL, ] [KEY1 [, KEY2 [, ...]]] List up the k...
class Product(object): def __init__(self, price, item_name, weight, brand, status="for sale"): self.price = price self.item_name = item_name self.weight = weight self.brand = brand self.status = status # print self def display_all(self): print self return self def __repr__(self): return "Price: ${}...