text
stringlengths
37
1.41M
""" Задание 1""" my_int = 4 print(type(my_int)) my_float = 1.5 print(type(my_float)) a = input ("Введите число:") print(a) number = int(input('Введите число от 0 до 100: ')) while number >= 100 or number < 0: number = int(input('Введите число от 0 до 100: ')) print('Число введено корректно') real_nam...
import random arrays = [[1,2,4,3],[1,4,2,3],[1,4,3,2],[1,3,4,2],[1,3,2,4],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,1,3],[2,4,3,1],[3,1,2,4],[3,1,4,2],[3,2,1,4],[3,2,4,1],[3,4,1,2],[3,4,2,1],[4,1,2,3],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2],[4,3,2,1]] average = 0 b = 0 while b<23: a = arrays[b] isSorted = False ...
import os import argparse from Crypto.Cipher import AES # Check arguments used parser = argparse.ArgumentParser() parser.add_argument("iv", help="The iv to use to decrypt", type=str) parser.add_argument("key", help="The key to use to decrypt", type=str) parser.add_argument("-d", "--directory", help="Directory ...
def print_two(*args): arg1,arg2,arg3 =args print (f"arg1 :{arg1},arg2 {arg2},arg3 {arg3}.") def print_two_again(arg1, arg2): print(f"arg1: {arg1},agr2: {arg2}") def print_one(arg1): print(f"arg1: {arg1}") def print_none(): print("I got nothing") print_two("shibil","ahamed","just checking") ...
print (""" MULTIPLICATION TABLE BETWEEN 1 & 1OO""") print ("enter the which number multiplication table what display") num=int(input(">>>>")) while num!=0: table=range(0,100,num) list=['multiplication table of - {}'.format(num)] list.extend(table) print (list) exit() if num==0: print("do...
import matplotlib import pandas as pd import matplotlib.pyplot as plt import numpy as np import random import math #Import the dataset df = pd.read_csv("kmeans.csv") #Recording # of rows of the data set rows = df.shape[0] #Recording # of rows of the data set cols = df.shape[1] #Records all the points in the graph ...
from math import log def atwo(n): """If n is power of two, just print it. Otherwise print it with the closest power of two""" if n == 0: print 0, 1 return logn = int(log(n,2)) if 2**logn == n: print n else: print n, 2**(logn+1) if __name__ == '__main__': ...
def binary_to_text(b): def bin_to_char(b): n = int(b,2) if n == 0: return ' ' return chr(ord('A') + n - 1) s = '' for i in xrange(0, len(b), 5): b_char = b[i:i+5] s += bin_to_char(b_char) return s def decrypt(msg, r, c): matrix = [[None for j in...
def amusing(k): num_digits = 1 while 2**num_digits < k: k -= 2**num_digits num_digits += 1 # the number has <num_digits> digits num = '' k -= 1 for i in xrange(num_digits): if k % 2 == 1: num += '6' k -= 1 else: num += '5' ...
if __name__ == '__main__': t = int(raw_input()) for i in xrange(t): n, unit = raw_input().split() n = float(n) print i+1, if unit=='kg': print '%.4f lb' % (n*2.2046) elif unit=='l': print '%.4f g' % (n*0.2642) elif unit=='lb': ...
T = int(raw_input()) while T > 0: T -= 1 N = int(raw_input()) words = raw_input().split() eng_words = [w for w in words if not w.startswith('#')] if not eng_words: print " ".join(words) else: eng_word = eng_words[0] index = words.index(eng_word) for x in xrange(in...
"""http://www.spoj.com/problems/TEST/""" def test(): while True: x = int(raw_input()) if x == 42: break print x test()
# Odd number from 1 to 1000 for i in range(1,1000,2): print i # Multiples of 5 from 5 to 1,000,000 for i in range (5, 1000000, 5): print i # Sum of all in an array a = [1, 2, 5, 10, 255, 3] sum = 0 for data in a: sum = sum + data print "sum:", sum # Average of array avg = sum/len(a) print "Average: ", av...
#coding=utf8 test_str = '[(({[]{}}))]' test_str2 = '[(({[]{}}))]]' def opposite(c): d = {'(': ')', '[': ']', '{': '}'} return d[c] def valid(string): stack = [] for c in string: if len(stack) < 1: stack.append(c) else: if opposite(stack[-1]) == c: ...
def bubble_sort(items): length = len(items) for i in range(0,length): swapped = False for element in range(0,length-i-1): if items[element]> items[element + 1]: hold= items[element + 1] items[element + 1]=items[element] items[element]= ...
#!/usr/bin/env python '''Provides the basic implementation for the pairwise interaction segment activity coefficient (SAC) equations. This code favors readability, please check the accompayning article for the equation numbers cited here. ''' from abc import abstractmethod import math from copy import deepcopy from n...
''' 두 정수(a, b)를 입력받아 a가 b보다 크면 1을, a가 b보다 작거나 같으면 0을 출력하는 프로그램을 작성해보자. 두 정수(a, b)를 입력받아 a와 b가 같으면 1을, 같지 않으면 0을 출력하는 프로그램을 작성해보자. 두 정수(a, b)를 입력받아 b가 a보다 크거나 같으면 1을, 그렇지 않으면 0을 출력하는 프로그램을 작성해보자. 두 정수(a, b)를 입력받아 a와 b가 서로 다르면 1을, 그렇지 않으면 0을 출력하는 프로그램을 작성해보자. ''' a, b = map(int, input().split()) print(int(a>b)) ''' ...
''' 단어를 1개 입력받는다. 입력받은 단어(영어)의 각 문자를 한줄에 한 문자씩 분리해 출력한다. ''' a = input() for i in a: print("\'{}\'".format(i))
''' 두 개의 참(1) 또는 거짓(0)이 입력될 때, 모두 참일 때에만 참을 출력하는 프로그램을 작성해보자. 두 개의 참(1) 또는 거짓(0)이 입력될 때, 하나라도 참이면 참을 출력하는 프로그램을 작성해보자. 두 가지의 참(1) 또는 거짓(0)이 입력될 때, 참/거짓이 서로 다를 때에만 참을 출력하는 프로그램을 작성해보자. 두 개의 참(1) 또는 거짓(0)이 입력될 때, 참/거짓이 서로 같을 때에만 참이 계산되는 프로그램을 작성해보자. 두 개의 참(1) 또는 거짓(0)이 입력될 때, 모두 거짓일 때에만 참이 계산되는 프로그램을 작성해보자. ''' a, b...
''' 실수(float) 1개를 입력받아 저장한 후, 저장되어 있는 값을 소수점 셋 째 자리에서 반올림하여 소수점 이하 둘 째 자리까지 출력하시오. ''' a = float(input()) print('%.2f' %a)
#---------------------------------------------- #--------- Strings methds II ---------- #---------------------------------------------- # Str.split() => devide the string on word based on the space(defultSepartor) between words # # Str.split("Separtor",Number) => Separtor == , or - ... Number == 2, 3, 4... ...
uppercase=0 lowercase=0 result_dict={'Lowercase':0,'Uppercase':0} with open("test.txt",'r') as file1: list1 = file1.read() for i in list1: if i.islower(): lowercase+=1 result_dict['Lowercase']+=1 elif i.isupper(): uppercase+=1 result_dict['Uppercase']+=1 print(uppercase,lowercase) print(result_dict)
l1=[1,2,3,4,5] l2=list([x**2 for x in l1]) print(l2) l3=[1,2,3,4,5] l4=[3,4,5,6,7] set1=set(l3) set2=set(l4) set3=set1.intersection(set2) print(set3)
x=input("Enter word: ") y=[] y=list(x) print(x) z=y[::-1] print(z) a=x[::-1] print(a)
class MyVehicle: def __init__(self,make,model,year): self.make = make self.model = model self.year = year def vehicle_name(self): print("This car is : " + str(self.make) + " " + str(self.model) + " " + str(self.year)) v1 = MyVehicle("Alfa","Milano",1987) print(v1.make,v1.model,v1.year) v1.vehicle_name()
st="nneigheigh" snd = "neigh" x = {v: k for k, v in enumerate(snd)} print(x) for i in range(len(st)): print(str(st[i]) + str(x.get(st[i])))
dict1={} num_stu=int(input("Enter number of students: ")) print(num_stu) for i in range(0,num_stu): stu_name = input("Enter student name: ") stu_age = input("Enter student age: ") stu_grade = input("Enter student grade: ") dict1[stu_name]={stu_age,stu_grade} print (dict1)
#L=[] #print(L) fruit = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] #print(len(fruit)) #print(fruit[1]) #print(fruit[-1]) #print(fruit[2:5]) #print(fruit[-1:-6:-2]) #fruit[1]="pappaya" #print(fruit) #for x in fruit: # print(x) #if "apple" in fruit: ...
maarks=eval(input("enter elements in ():")) sum=0 n=len(marks) for i in range(n): sum=sum+marks[i] print("Sum of all marks=",sum) print("average of the course=",sum/n) print('highest mark=",max(marks)) print('lowest mark=',min(marks))
class School(): okulTuru= "okul tipi" def __init__(self, okulAdı, okulTuru, ogretmen, ogrenci, sınıf): self.okulAdı = okulAdı self.okulTuru = okulTuru self.ogretmen = ogretmen self.ogrenci = ogrenci self.sınıf = sınıf O1 = School("Gazi Şahin", "İlkÖğretim Okulu", 16, 30...
def add(x,y): z=x+y print(z) def sub(x,y): z=x-y print(z) a=100 b=50 add(a,b) sub(a,b)
F = input() C = (float(F)- 32) / 1.8 C_S = str(C) F_S = str(F) print ("{}F is equal to {}C.".format(F,C))
num = input("Enter a number:") word= input("Enter a noun:") space = " " if num == "1": print (num + space + word) elif num > "1" or num < "1": if word[-2:] == "fe": word2 = word[:-2] ves = "ves" print(num + space + word2 + ves) elif word[-2:] == "sh" or "ch": es="es" ...
import time import sys ##setting recursion limit for testing large numbers of n later sys.setrecursionlimit(1000000) ##f, 2**n ##Using recursion for benefit of memoization def f(n): ##anything to power of 0 is 1 if n==0: return 1 ##2 to power of 1 is 2 elif n==1: return 2 ##2 to pow...
# Prompting user for number and then multipies that number by itself user_number = input("Enter a number: ") print("Your number squared is: " + str(int(user_number) ** 2))
#s = "Ivan" #print(s[2::-1]) s = "abcdefigh" for index in range(len(s)): if s[index] == 'i' or s[index] == 'u': print("There is an i or u") for char in s: if char == 'i' or char =='u': print("There is an i or u")
from directions import Directions def introductoryMessage(): print("\n\n") print("Welcome to the python driving directions web service app") print("To get driving directions, enter a starting point and an ending destination") print("\n") def applicationInstructions(): print("Acceptable ...
''' Created on Feb 19, 2015 @author: Ankur ''' import pygame, math,random import numpy as np from sympy.mpmath import unitvector class Color(): white=(255,255,255) blue = (0,255,255) red = (255,0,0) snow = (205,201,201) palegreen= (152,251,152) def __init__(self): pas...
import turtle def draw_snake(rad, angle, len, neckrad): for i in range(len): turtle.circle(rad, angle) turtle.circle(-rad, angle) turtle.circle(rad, angle / 2) turtle.fd(rad) turtle.circle(neckrad + 1, 180) turtle.fd(rad * 2 / 3) def draw_tangle(length,seths): for i in range(...
import threading def add_up(): return local_add.x1 + local_add.x2 def run_thread(x, y): print('Thread {0} is running...'.format(threading.current_thread().name)) lock.acquire() try: local_add.x1, local_add.x2 = x, y print('The finally result is {0} in {1}'.format(add_up(), threading....
from constants import graph1, graph2 def dfs_recursive(graph, start_node, visited=[]): """ * Add to the visited array * Call the dfs method recursively, with the next non-visited node by looping through all the nodes connected to it. """ visited.append(start_node) for next_node in graph...
class c1: def add(self,a,b): """ a,b: int: a+b a,b: str: concate a: int, b:str: None """ try: return a+b except: return None def mul(a,b): return a*b
from random import random import tkinter as tk WIDTH, HEIGHT = 480, 480 x1, y1 = WIDTH // 2, HEIGHT // 2 def create_rectangle(): rectangle = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill='green') return rectangle def move_rectangle(): rnd = random() x = 0 y = 0 pos = canvas.coords(r...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #On Python3,the default input type is str s1 = int(input('输入去年的成绩:')) s2 = int(input('输入今年的成绩:')) delta = (s2 - s1)/s1*100 #print(delta) if delta > 0.0: print('小明今年比去年提升了%.1f%%'%delta) elif delta < 0.0: print('小明今年比去年退步了%.1f%%'%delta) else: print('小明的成绩在原地踏步')
import itertools import itertools as it def erat2a(): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: # old code here: # x = p + q # while x in D or not...
from __future__ import print_function import os def dragon_curve(data): rev_data = ''.join('0' if x == '1' else '1' for x in reversed(data)) return data + '0' + rev_data def calc_checksum(data): checksum = [] for i in range(0, len(data), 2): x, y = data[i], data[i+1] if x == y: ...
#!/usr/bin/python # -*- coding: utf-8 -*- from random import random, randint, uniform from cellVariables import * class Cell(): numCells = 1 ArrayCells = [] deadFactor = 0.1 # kind = tipo de celula # x = posicion X # y = posicion Y # size = area (radio) # veloProg = velocidad de propagacion # colour...
#!/usr/bin/env python from math import * from auxFuncRoots import * # ------------------------------------------------------------ # 1.8 METODO DE STEFFENSEN def steffensen(f,a,printText = 1,tol=1e-7,NMAX=100): if (f(a)-a)==0: return a correct=True for i in range(NMAX): p1 = f(a) p2 = f(p1) if pr...
#!/usr/bin/env python from math import * from auxFuncRoots import * # ------------------------------------------------------------ # 1.11 METODO DE HOUSEHOLDER ( 3er ORDEN ) def householderRoots(f,d1f,d2f,d3f,x0,printText = 1,tol=1e-9, NMAX=100): if f(x0)==0: return x0 n=1 while n<=NMAX: df0 = f(x0) ...
#!/usr/bin/env python from math import * from auxFuncRoots import * # ------------------------------------------------------------ # 1.4 METODO DE NEWTON def newton(f, d1f, x0,printText=1, tol=1e-9, NMAX=100): if f(x0)==0: return x0 n=1 while n<=NMAX: try: dx = f(x0)/d1f(f,x0) except ZeroDivisionErro...
#!/usr/bin/env python from math import * from auxFuncRoots import * # ------------------------------------------------------------ # 1.1 METODO BISECCION def bisection(f, a, b, switch = 0,tol=1e-9): if a>=b: print("Error, a > b") return None if f(a)==0: return a elif f(b) ==0: return b elif f(a...
audi=float(0) visual=float(0) kine=float(0) idk=float(0) print("Bienvenido al programa de la encuestas de este modulo escolar, donde el estudante podra concentrar sus puntos debiles de estudios para que al final el profesor guie al alumno con un nuevo sistema de aprendizaje") print("En caso de no poner los incisos indi...
# Cracking The Coding Interview # Recursion and Dynamic Programming # 8.7: Permutations without Dups ##### First Solution ##### def perm1(listo): if len(listo) == 0: # base case, empty list return [] elif len(listo) == 1: # another simple case, 1 item to permute return listo else: ...
from Tkinter import * class interfaz: def __init__(self,contenedor): self.e1 = Label(contenedor, text="Etiqueta 1",fg = "black", bg = "white") self.e1.place(x=10,y=30,width=120,height=25) ventana = Tk() miInterfaz= interfaz(ventana) ventana.mainloop()
#DAY 16: Exceptions - String to Integer #Read string S, if it has an integer value, print it, if else print 'Bad String'. Must use a error catching, cannot use if/else or loops. I did this in python because it is much easier than JavaScript import sys S = input().strip() try: N = int(S) print(N) ...
import socket import subprocess from util import * # logger for FTP client program clientLogger = setup_logger() class FTPClient(): """ Implementation for FTP client. The command accepted are: get, put, ls and quit. FTP client has two sockets: control socket is used for control channel, data socke...
# Set up your imports here! # import ... from flask import Flask app = Flask(__name__) @app.route('/') # Fill this in! def index(): # Welcome Page # Create a generic welcome page. return "<h1>Welcome! Go to /puppy_latin/name to see your name puppy latin!</h1>" @app.route('/puppy_latin/<name>') # Fill this...
class HashTableEntry: """ Hash Table entry, as a linked list node. """ def __init__(self, key, value): self.key = key self.value = value self.next = None def __str__(self): return f"({self.key}, {self.value})" class HashTable: """ A hash table that with `c...
class rect: l=0 b=0 def __init__(self): self.l=25 self.b=50 def calc(self,a): r=self.l*self.b print(r) a=rect() b=rect() b.calc(a)
import itertools def load_input(fname="input.txt"): with open(fname) as f: return [int(d) for d in f.read().strip()] def pairwise(sequence, offset=1, circular=True): """ Iterator over offset pairs of elements from sequence >>> list(pairwise([1, 2, 3])) [(1, 2), (2, 3), (3, 1)] >>> li...
from collections import Counter def load_points(): points = {} with open("input.txt") as f: for point_id, line in enumerate(f): points[point_id] = tuple(map(int, line.split(","))) return points def md(x1, y1, x2, y2): """ Manhattan distance between two points. """ ret...
a = 5; b=13; sum=a+ \ b print(sum) ##sum raw_input("\n enter key to continue") print("ritesh")
#!/usr/bin/python import random class Generator(): def __init__(self, base, length, amount, encode, decode): '''Base to generate in, the length of the hashes, amount of hashes to generate, conversion function''' self.base = base self.length = length self.amount = amount se...
""" 1.Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. - проверить ввод, если длинна !=3 то повторить ввод - если длинна == 3 - то взять первый символ, сложить его со вторым и с третьим - взять все символы и перемножить """ import sys def num_info(): while True: num = int...
import random print ("Welcome to the guessing game!") computerNumber = random.randint(1,20) enteredNumber=0 totalGuesses=0 while enteredNumber != computerNumber: print("Enter a number between 1 and 20: ", sep='') totalGuesses=totalGuesses+1 enteredNumber=int(input()) if enteredNumber > computerNumbe...
# Create a function that takes 2 positive integers in form of a string as an input, and outputs the sum (also as a string) # sum_str("4", "5") # should output "9" # sum_str("34", "5") # should output "39" # If either input is an empty string, consider it as zero. # my solution def sum_str(a, b): if a == "": ...
def derive(coefficient, exponent): return str(coefficient * exponent) + f"x^{exponent - 1}" #best practiced solution by vote # def derive(coefficient, exponent): # return f'{coefficient * exponent}x^{exponent - 1}' #damn why didn't I just do it like that, not this time. but next time I will be sure to remem...
num=int(input("enter the number")) factorial=1 if num<1: print("No factorial is exist") elif num==0: print("factorial of 0 is 1") elif num >1: for i in range(1,num+1): factorial=factorial*i break print(factorial,"is the factorial of num")
kilometer=float(input("how many kilometer:")) facter=0.62137 mile=kilometer*facter print("{}kilometer is equal to {} mile".format(kilometer,mile))
#inputs #Amusment park height = input("How tall are you? " ) height = int(height) if height >= 160: print("You are tall enough to ride this ride.") else: print("Get out of here halfling.") number = input("Enter to see if your number is even or odd. ") number = int(number) if number % 2 == 0:...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 16 19:22:35 2019 @author: qinyachen """ from Deck import deck from player import Player import random import time class Game: def __init__(self,players): ''' The playerlist contains all players in the game. eg.[player1...
import matplotlib.pyplot as plt import pandas as pd df=pd.read_excel("") fig=plt.figure() #Plots in matplotlib reside within a figure object, use plt.figure to create new figure #Create one or more subplots using add_subplot, because you can't create blank figure ax = fig.add_subplot(1,1,1) #Variable ax.hist(d...
#list a = [1,2,3,4,5] a.append(100) a.remove(4) #print (a) #tuple a = (1,2,3,4) #print (a) #dict #{key:value} a= { 1:True, 2:False } #print (a) #str s1 = '\'string\'' s2 = "\"string\"" #print s1 a = 3 + 4 and 10 - 4 and "1" #print a, type(a) if 5 > 4: print 'Case 1' else: print 'Case 2' for a in range(10): if ...
word = str(input()) number = str(input()) n = (int(number)) c = int(number[len(number) - 1]) d = int(number[len(number) - 2]) if word == 'утюг': if n == 1 or c == 1 and d != 1: print(n, "утюг") elif 2 <= n <= 4 or 2 <= c <= 4 and d != 1: print(n, "утюга") else: print(n, "утюгов") if ...
from binarySearchTree import BST from binarySearchTree import Node class AugmentedBST(BST): def __init__(self): """Initialize a node_class, used in the current implementation of insert""" self.node_class = AugmentedNode def insert_node(self, key): """ Insert node to the tre...
# -*- coding: utf-8 -*- """ Basic unit testing of API @author: NikolaLohinski (https://github.com/NikolaLohinski) @date: 02/02/09 """ def test_get_empty_inventions(client): """After basic creation of DB test if get inventions is empty list""" request = client.get('api/v0/inventions') assert request.statu...
from heapq import heappush, heappop from itertools import count class PriorityQueue: REMOVED = '<removed-task>' def __init__(self): self.elements = [] self.entry_finder = {} self.counter = count() def add_task(self, task, priority=0): """Add a new task or update the prior...
import random class Dice: def roll(self): first = random.randint(1,6) second = random.randint(1,6) return first, second for i in range(3): print(random.random()) for i in range(3): print(random.randint(10,20)) members = ['Carvin', 'Joseph', 'Kyle'] leader = random.choice(members) print(leader) dice = ...
#Program 4-17 #This Program averages test scores. #It askes the user for the number of students #and the number of test scores per students. #Get the number of students. num_students = int(input('How many students do you have?')) #Get the number of test scores per student. num_test_scores = int(input('How many test ...
#This program will split a total bill from a restaurant or whatever establishment and guarantee an even split #import math to use Ceil method (which will round up) import math def split_check(total, number_of_people): #divide the total amongst people #use the ceiling to allow rounding #check if the person is givin...
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> #Floating-point Program example 2-21 >>> monthly_pay = 5000.00 >>> annual_pay = monthly_pay * 12 >>> print('Your annual pay is $',format(annual_pay, ',.2f')...
class Node(object): """ Node contains two objects - a left and a right child, both may be a Node or both None, latter representing a leaf """ def __init__(self, left=None, right=None): super(Node, self).__init__() self.left = left self.right = right def __str__(self): """ Default inorder print """ ...
line = "" for i in range(1, 10): line += "*" * i line += "\n" print(line) line = "" i = 0 while i < 11: line += "*" * i line += "\n" i += 1 print(line)
from collections import defaultdict def PatternCount(genome: str, pattern: str): """ Return count of occurrences of `pattern` in `genome` """ count = 0 k = len(pattern) for x in range(0, len(genome) - k + 1): if genome[x:x+k] == pattern: count += 1 return count def Freq...
import random import copy def crea_puzzle(): puzzle = [[0, 2, 3], [1, 4, 6], [7, 5, 8]] random.shuffle(puzzle[0]) random.shuffle(puzzle[1]) random.shuffle(puzzle[2]) random.shuffle(puzzle[random.randint(0, 2)]) return puzzle def movimientos(puzzle, predecesor): hijos = [] if 0 in pu...
""" Created on Wed Sep 7 22:25:16 2016 @author: James """ import math # We need to import the math module for use in this function def polysum(n, s): """ input : n,s - positive integers where 'n' is the number of sides and 's' is the length of each side. Returns the sum of the perimeter squared and th...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 11 17:15:52 2019 @author: flatironschool """ # import csv text_file = open('top-500-songs.txt', 'r') # read each line of the text file # here is where you can print out the lines to your terminal and get an idea #for how you might...
class HashTable: size = 0 items = [] def __init__(self, size): self.size = size def hash(self, key, size = None): """ - count string, divide length of string by m and return the remainder """ size = size if size else self.size index = len(key) % size return index def add(self, key, value): hash...
import random win = 0 lose = 0 for x in range(0, 1000): flip = random.randint(1, 100) if flip > 49: win += 1 else: lose += 1 print("Wins is: " + str(win)) print("Losses is: " + str(lose)) print("net gain/loss is: $" + str((win - lose) * 100))
# Santa needs help figuring out which strings in his text file are naughty or nice. # A nice string is one with all of the following properties: # It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou. # It contains at least one letter that appears twice in a row, like xx, abcdde (dd), o...
import string import hashlib translator = str.maketrans('','', string.punctuation) with open('titanic_srt.txt', 'r') as file: # read each line for line in file: #read each word which is split by a space for word in line.split(): # turn each word into lowercase lower = word.lower() # remove all punctua...
import random Set_number = random.randint(0,100) print(Set_number) N = 1 try: Guess_number = int(input("输入猜测的数:")) except NameError and ValueError: print("输入内容须为整数!") Guess_number = int(input("重新输入猜测的数:")) N = N + 1 while(Guess_number < Set_number or Guess_number > Set_number): N = N + ...
import numpy as np import pandas as pd import matplotlib.pylab as plt import time as tm """ This code was written as part of a larger project to develope a model that accurately describes the biological interractions between a pest insect and its habitat, namely the eastern spruce budworm and the spruce forests it ...
# CTI-110 # P3HW1 - Age Classifier # 6/19/18 # Connor Naylor #Request age choice="y" while choice=="y": age=float(input("How old are you? ")) #Calculate age classification if age < 0: print("Invalid Number") elif 0<= age <= 1: print("You are an infant.") elif 1 < age < 1...
#Write a subroutine that outputs the following properties of a circle from the the diameter and arc angle. D = int(input("What is the diameter? ")) AA =int(input("What is the arc angle? ")) #Subroutine to find the area and circumference of the circle def Properties(X): return (X * 3.14) #Main Programme R = D / 2 ...
import random def swap(board, r1, c1, r2, c2): t = board[r1][c1] board[r1][c1] = board[r2][c2] board[r2][c2] = t def vLineAt(board, r, c): location = board[r][c] if r-2 >= 0 and location == board[r-1][c] and location == board[r-2][c]: return True if r-1 >= 0 and r+1<len(board) and loca...
import os import time infoFile="/home/pi/firebase/userInfo.txt" while True: print('I am gonna reset all your device info. Are you sure?(y/n)') print('or you can press (ctr+c) to exit') ans = input() if(ans == 'y'): print('removing all your device info.....') a = open(infoFile,"r+") ...
#!/usr/bin/python import sys def add_ranking(): test_filename = sys.argv[1] ranking_filename = sys.argv[2] test_with_ranking_filename = test_filename + ".final_ranking_" + ranking_filename[2:].split("_")[0] print(test_filename) print(ranking_filename) print(test_with_ranking_filename) with...
print("----\n") f = float(input("digite a temperatura em fahrenheit")) c = (f - 32) * 5 / 9 print("a temperatura é de ", c, "graus celcius") print("----\n")
# Ejercicio que define si un estudiante esta aprobado o no #autor: Rose def determinaraprobado(promedio): if promedio >=11: resultado = "aprobado" else: resultado ="desaprobado" return resultado promedio = int(input("promedio valor : ")) print(determinaraprobado(promedio))