text
stringlengths
37
1.41M
''' 1431. 拥有最多糖果的孩子 给你一个数组 candies 和一个整数 extraCandies ,其中 candies[i] 代表第 i 个孩子拥有的糖果数目。 对每一个孩子,检查是否存在一种方案,将额外的 extraCandies 个糖果分配给孩子们之后,此孩子有 最多 的糖果。注意,允许有多个孩子同时拥有 最多 的糖果数目。 示例 1: 输入:candies = [2,3,5,1,3], extraCandies = 3 输出:[true,true,true,false,true] 解释: 孩子 1 有 2 个糖果,如果他得到所有额外的糖果(3个),那么他总共有 5 个糖果,他将成为拥有最多糖果的孩子。 孩子 2 有...
def finalcountdown(param1,param2,param3,param4): count=param2 while(count<param3): if count % param1 == 0 and count !=param4: print count count=count+1 if __name__ == '__main__': finalcountdown(3,5,17,9)
def lettergrade(score): if score < 60: print "score:" +str(score)+ ".grade:F" elif score >=60 and score <=69: print "score:{}.grade{}".format(score,"D") elif score >70 and score <=79: print "score:{}.grade{}".format(score,"C") elif score >80 and score <= 89: print "score:{}.grade{}".format(score,...
def negative(arr): newarr=[] for i in range (len(arr)): if arr[i]>0: newarr.append(arr[i]*-1) else: newarr.append(arr[i]) return newarr if __name__ == '__main__': print(negative([2,5,-9,19]))
def MakeItBig(arr): for i in range (len(arr)): if arr[i]>0: arr[i]="big" return arr if __name__ == '__main__': print(MakeItBig([-1,3,5,-5]))
def lowhigh(arr): low=arr[0] high=arr[0] for i in range (len(arr)): if arr[i]>high: high=arr[i] elif arr[i]<low: low=arr[i] print low return high if __name__ == '__main__': print(lowhigh([40]))
def max_of_array(arr): max=arr[0] for i in range (len(arr)): if arr[i]>max: max=arr[i] print max if __name__=='__main__': max_of_array([1,2,3,4,5])
def previouslengths(arr): for i in range (len(arr)): if type(arr[i])is str: arr[i]=len(arr[i]) print arr[i] return arr if __name__ == '__main__': print(previouslengths(["vineel","sindhu",9]))
import unittest from decision_tree.question import Question class QuestionTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.training_data = [ ['Green', 3, 'Apple'], ['Yellow', 3, 'Apple'], ['Red', 1, 'Grape'], ['Red', 1, 'Grape'], ...
def checkio(*args): count = 0 top = 0 bottom = 0 for i in args: i = float(i) if count == 0: count += 1 top = i bottom = i else: if i > top: top = i elif i < bottom: bottom = i retur...
def checkio(number): number = str(number) bignum = 1 for i in number: if i == "0": continue else: bignum *= int(i) return bignum
def checkio(text): alphabet = create_dict(text) print(alphabet) highest = [] q = 0 for k, v in alphabet.items(): if v > q: q = v highest = [] highest.append(k) elif v == q: highest.append(k) highest.sort() print(highest[0]) ...
def i_love_python(): """ Let's explain why do we love Python. """ print('Throw your hands in the air.......') print('B/c Python is the bommmmbb') print('I can read and write w/o a Rosetta Stone') print('It helps me think and get sh** done.') print('3 months in and having too much fun...
def min(*args, **kwargs): key = kwargs.get("key", None) mymin = 'None' if len(args) > 1: for i in args: if mymin == 'None': mymin = i elif key: if key(i) < key(mymin): mymin = i else: if i < mymi...
#!/usr/bin/env python3 ## ## subprograms ## # recursive predicate for checking for sequential increase # is there a more obvious arithmetic test? yes ... see two.f90 def is_increasing ( string_of_digits ): if len( string_of_digits ) == 1: return True i = 0 for a in string_of_digits: i ...
import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import train_test_split from sklearn import preprocessing df = pd.read_csv("profiles.csv") df=df.dropna(axis=0, su...
#largest among 3 numbers #getvalue from user a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) c = float(input("Enter third number: ")) print(max(a,b,c))
import random rn = random.randint(1,10) myn = 0 while myn != rn: myn = input("Guess a number between 1 and 10: ") if type(myn) is int: if myn < rn: print('Too Low :(') if myn > rn: print('Too High :(') else: print("Please type in numbers only") ...
A = 2 B = 4 C = 3 print(A) print(int(B)) #Int foran float, viser dem som Int, men omdifinerer dem ikke print(C) print((str(B)+"\n")*10) #\n i et string felt, skifter linie *10, så sker det ti gange message = ("Hej med jeg") #Det er muligt at ændre en variabel til noget andet undervejs i programmet print(m...
from typing import List def kvadrat(x: float) -> str: return str(x*x) print('Resultatet er: ' + kvadrat(9)) print('----------------------------------------------------------') listen = [1, 2, 3, 4] def minsum(liste: List[int]) -> str: return str(sum(liste)) print(minsum(listen)) print('-------------...
Norden = ['danmark', 'sverige', 'norge', 'finland', 'grønland','færøerne', 'danmark'] if 'danmark' in Norden: print('Ja') else: print('Nej') if 'tyskland' in Norden: print('Ja') else: print('Nej') print('----------------------------------------------------------------') Fundet = False print('Vil ud s...
# Opgave 7-5 side 121 i bogen Entre = True Total = 0 Igen = False print('Velkommen til MegaScope!') while Entre: Flere = '' Alder = int(input('Hvor gammel er du? ')) if Alder < 3: print('Du har gratis entre!') elif 3 <= Alder <= 12: print('Entre koster 100kr') Total += 100 ...
# coding: utf-8 import sys from abc import ABCMeta, abstractmethod import random class Hand(object): HANDVALUE_GOO = 0 HANDVALUE_CHO = 1 HANDVALUE_PAA = 2 class __Hand(object): name = ["グー", "チョキ", "パー"] def __init__(self, hand_value): self.__hand_value = hand_value ...
#Write a Python program to enter decimal number and calculate and display binary eqyivalent of this number def convertToBinary(n): if n > 1: convertToBinary(n//2) print(n % 2,end = '') dec = int(input("Enter number : ")) convertToBinary(dec) print()
#Write a python program to read the email id'email of n users and create a list of user id's email = [] user_id = [] n = int(input("Enter how many strings you want to add : ")) i = 0 for i in range(0,n): t = "Enter string no."+str(i+1)+" : " email.append(str(input(t))) for i in range(0,len(email)): s = e...
#!/usr/bin/env python3 # This is basic HTTP echo server. It is mostly usable for inspecting # incoming requests. Loosely based on this: # https://gist.github.com/huyng/814831 # # curl -s -H "X-Hello: World!" IP:PORT # curl -s -H "X-Hello: World!" -d @some/file IP:PORT # import http.server import logging import argpar...
richest = "none" maxBal = 0 for count in range(1,3): name = input ("Name: ") balance = float (input ("Enter balance: ")) if balance > maxBal : richest = name maxBal = balance print("Richest guy: {0:s} has balance of ${1: ,.2f}" . format(richest, maxBal))
#!/usr/bin/env python2 # # A script to generate random sat formulas inspired from the paper # Achlioptas, Jia and Moore: Hiding Satisfying Assignments: Two are Better than One, # # TODO: sometimes the maximum number of clauses to be generated is lower than # the number of clauses requested and thus the program never f...
# mostrar los multiplos de 3 del 0 al 800 i=0 suma=0 while(i>800): suma =i i =3 #fin_while print("multiplos de 3 son:", multiplo)
import pandas as pd import subprocess, os def df_to_hdfs(df,path,index=False,sep='|',header=False,*args,**kwargs): """ Function to write a pandas dataframe to a specified location in HDFS. If the file already exists, it will be overwritten. """ #delete file if already exists on hdfs os.sy...
# -*- coding: utf-8 -*- """Helper functions to load and save CSV data. This contains a helper function for loading and saving CSV files. """ import csv def load_csv(csvpath): """Reads the CSV file from path provided. Args: csvpath (Path): The csv file path. Returns: A list of lists tha...
""" Day 2 语言元素 """ import math def Fahrenheit_to_Celsius(): f = float(input("请输入华氏温度:")) c = (f - 32) / 1.8 print('%.1f华氏度 = %.1f摄氏度' % (f, c)) def cycle(): radius = float(input('请输入圆的半径:')) perimeter = 2 * math.pi * radius area = math.pi * radius * radius print('周长:%.2f' % perimeter) ...
""" Day 11 读取文件 """ def reading_file(): try: with open('./res/ball.png', 'rb') as file_in: data = file_in.read() print(type(data)) with open('./res/ball-copy.png', 'wb') as file_out: file_out.write(data) except FileNotFoundError as e: print('无法打开指定文件!...
# Створення прикладних програм на мові Python # Лабораторна робота 5 # Chepil Dmytro, 15 print ('Створення прикладних програм на мові Python, Лабораторна 5') print ('Chepil Dmytro, 15') N = int(input ('Введіть число: ')) proste = 0 while proste < N: proste2 = proste + 6 x = 0 y = 0 for j in r...
class Person(): def __init__(self): self.name = None self.sname = None self.byear = None def input(self): self.name = input('Name:') self.sname = input('Surname:') self.byear = input('B.Year:') def __str__(self): return '{},{}'.format...
count=0 while count<=10: count+=1 if count % 2 == 0: continue print(count)
def ProductS_Quant(): while True: NumbApl = input("\nHow many apples would you like to buy? \n> ") NumbOrng = input("\nHow many oranges would you like to buy? \n> ") if NumbApl.isdigit() and NumbOrng.isdigit() == True: InitApl = int(NumbApl) InitOrng = int(NumbOrng) ...
from tkinter import * from functools import partial # clculator # https://www.youtube.com/watch?v=_1tTS638xUQ root = Tk() root.title('First Program') frame = Frame(root) frame.pack(side=TOP) num_input = Entry(frame,border=10,width=25,insertwidth=1,font=30) num_input.pack(side=TOP) def Calculator(num): if num == ...
num = [0,1,2,0,13,44,0,56] print(num) index_0 = [] count = 0 for i in range(len(num)): if num[i] != 0: index_0.append(num[i]) else: count += 1 for j in range(count): index_0.append(0) print(index_0)
import random play = [] deal = [] for i in range(0,2): player = random.randint(1,10) dealer = random.randint(1,10) play.append(player) deal.append(dealer) print('You drew {} and {}.'.format(play[0], play[1])) print('Your Total is ',(play[0]+play[1])) print('The Dealer has',deal[0],'and',deal[1]) print...
tup = tuple(range(10)) #print(tup) l = list(tup) #print(l) l2 = l[::-1] #print(tuple(l2)) # replace last value of tuples in a list(my way) tulps = [] for i in range(5): tulps.append(tuple(range(1,5))) print(tulps) for j in range(len(tulps)): arr = list(tulps[j]) arr[-1] = 'gg' tulps[j] = tuple(arr) pr...
# https://www.codewars.com/kata/decoded-string-by-the-numbers string = 'abc\\5defghi\\2jkl' ch_holder, spot1, spot2 = [], 0, 0 for i in range(0,len(string)): if string[i] == '\\': spot1 = i+2 spot2 = (i+2) + int(string[i+1]) ch_holder.append(string[spot1:spot2]) else: if i >= s...
def addition(a,b): return a+b def subsraction(a,b): return a-b def division(a,b): return a/b def multiplication(a,b): return a*b while True: string = str(input('>')) if string[0] == '0':break else: if string[1] == '+': print(addition(int(string[0]),int(string[2])))...
num = 26 isNot = False for i in range(num): if i*i == num: isNot = True print(num,'is a square Number!') if isNot == False: print(num,'is Not a square Number!')
num = int(input()) if num % 2 != 0: print("Weird") if num % 2 == 0: if 2 <= num: if num <= 5: print("Not Weird!") if num % 2 == 0: if num >= 6: if num < 20: print("Weird!") else: print("Not Weird!") """ tab = [1,2,5,8,6,65,5,4,54,5,56,8,7,4,21,2...
string = 'fun time' ch = list(string) print(string) for i in range(0,len(ch)): ch[i] = chr(ord(ch[i])+1) print(''.join(ch))
import random arr = [] for i in range(15): arr.append(random.randint(4,23)) print(arr) #get the lowest number temp = 0 for j in range(len(arr)): if arr[0] > arr[j]: temp = arr[0] arr[0] = arr[j] arr[j] = temp print('lower number = ',arr[0]) #get the highst number for x in range(len(...
print("Hello %s %s! You just delved" " into python " % (str(input("enter ur name :")) ,str(input("enter ur last name:")))) string = "this is a srting" string = string.split(" ") print("-".join(string)) #string = "-".join(string) #print(string) #another solution print(*input().split(" "), sep='-') #anothe...
x,y=map(int,input().split()) x1=list(map(int,input().split())) if y in x1: print("yes") else: print("no")
x123=list(input()) for i in range(0,len(x),2): c123=x[i] x123[i]=x123[i+1] x123[i+1]=c123 for i in x123: print(i,end="")
string=(input()) string2=string[0: :2] string3=string[1: :2] print(string2,string3,end=" ")
x=(int(input())) temp=x sos=0 while(x!=0): temp=x%10 sos+=temp*temp x=x//10 print(sos)
import os from Board import Board def start_mastermind(): temp_difficulty_select = 0 ant = " "; #setting up the game by selecting a difficulty while temp_difficulty_select != 1: if temp_difficulty_select == -1: print("That was not a valid number") print("Difficulty options:...
''' This program loads a list of the most common python libraries and allows the user to select a library, view its methods, select one and see the help documentation on it. It also allows the user to see the list of others that are installed and then to enter ones not in the pre-populated list. ''' # import the thing...
""" Helper Methods """ import numpy as np from statistics import variance, stdev, mean ## Plot Libraries import matplotlib.pyplot as plt import numpy as np from math import exp, sqrt def same(population): m = [] def med(population): """ population med """ m = [] for c in population: ...
#定义一个函数 def get_name(first_name,last_name,middle_name=''): if middle_name: full_name=first_name.title()+middle_name+last_name else: full_name=first_name.title()+last_name return full_name user1=get_name('wang','qing','yong') print(user1) user2=get_name('bralan','jaery') print(user2) friend=...
b = int(input("Enter the number of inputs : ")) name = [] for x in range(b): n = str(input()) name.append(n) for o in name: print(o.capitalize())
""" Problem 001 - Multiples of 3 and 5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :description: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. :url: https...
#!/usr/bin/env python # coding: utf-8 # In[71]: from splinter import Browser from bs4 import BeautifulSoup from selenium import webdriver import pandas as pd import time # In[4]: def init_browser(): executable_path = {'executable_path': 'chromedriver.exe'} return Browser("chrome", **executable_path, head...
myfunc = lambda x,y:x+y res = myfunc(1,2) print(res) myfunc1 = lambda x,y=1:x+y res1 = myfunc1(2) print(res1) mylist = [lambda x:x**2,lambda x:x**3,lambda x:x**4] res2 = mylist[0](2) print(res2) print('----------------') for var in mylist: print(var(2)) print('----------------') #跳转表 #func #函数对象 #func() #函数调用 def...
# 异常处理 # 捕捉异常可以使用try/except语句。 # # try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。 # # 如果你不想在异常发生时结束你的程序,只需在try里捕获它。 # # 语法: # # 以下为简单的try....except...else的语法: # # try: # <语句> #运行别的代码 # except <名字>: # <语句> #如果在try部份引发了'name'异常 # except <名字>,<数据>: # <语句> #如果引发了'name'异常,获得附加的数据 # else: # <语句> ...
import re example="hello world this is 2019" print(re.findall("\w\w",example)) print(re.findall("\w(\w)",example)) print(re.findall("(\w)\w",example)) print(re.findall("(\w)(\w)",example)) ''' ['he', 'll', 'wo', 'rl', 'th', 'is', 'is', '20', '19'] ['e', 'l', 'o', 'l', 'h', 's', 's', '0', '9'] ['h', 'l', 'w', 'r', 't',...
#coding=utf-8 def printme(parameters ): "打印传递进函数的字符串" print(parameters) return printme("Hello Python !") # python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。 # 不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如fun(a),传递的只是a的值,没有影响a对象本身。 # 比如在 fun(a)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。 # # 可变类型:类似 c++ 的引用传递,如 ...
''' 引用与拷贝 浅拷贝的方式: 浅拷贝 不会拷贝数据中的子对象 import copy 切片,copy() 深拷贝: 深拷贝 会拷贝数据中的子对象 import copy copy.deepcopy() ''' mylist=[1,2,3] mylist1=mylist[:] mylist1[0]=3 print(mylist,mylist1)
#登录 user_file = open(r'C:\Users\Administrator\Desktop\文件操作续集\user_info.txt') islogin = 0 #标志位 while True: if islogin == 0: account = input('请输入你要登录的帐号:') user_file.seek(0,0) for user in user_file: if user.split(':')[0] == account: passwd = input('请输入你要登录的密码:') #做密码核对的功能 if user.split(':')[1].strip...
#HATALAR #print(sayi) > NAME ERROR değişken tanımlanmadı #sayi1 = int ("1,2,3asd") > VALUE ERROR değerde hata var #sayi3 = 5/0 > ZeroDivisionError #print("merhaba"dünya) > SyntaxError #HATA AYIKLAMA try: sayi1=int("1,2,3asd") print("try bloğu içerisinde") except ValueError: print("hata oluştu")#direkt ...
#FONKSİYONLAR #def FonksiyonAdi (par1,par2,....): # fonksiyonunKodları def karsilama(isim): print("Merhaba ben Siri , Hoşgeldin", isim) karsilama("Yaren") def karesiniAl(sayi): print(sayi*sayi) karesiniAl(10) def topla(sayi1,sayi2,sayi3): print("sonuç : ", sayi1+sayi2+sayi3) topla(10,20,30) ...
class Libro: def __init__(self, codigo_ISBN = '', titulo = '', genero = 0, idioma = 0, precio = 0.0): self.codigo_ISBN = codigo_ISBN self.titulo = titulo self.genero = genero self.idioma = idioma self.precio = precio # Muestra el libro con los idiomas y generos en palabra...
from functools import wraps import time def Calculate_Time(function): @wraps(function) def wrapper(*args,**kwargs): print(f'Executing.....{function.__name__}') T1 =time.time() returned_value = function(*args,**kwargs) T2 = time.time() Total_Time = T2-T1 print(f'Th...
import re def clean_word(word): word = re.sub(r'[^A-Za-z]', "", word.lower()) return word
#Code to count number of inversions #Author: Taruna Agrawal countInv = 0 # Merge Sort def mergeSort( num ): n = len(num)//2 if len(num) < 2: return else: leftArr = num[:n] rightArr = num[n:] mergeSort( leftArr ) mergeSort( rightArr) def merge(): nL = len(leftArr) nR = len(rightArr) i = 0; j = 0...
""" listas: son colecciones de datos bajo un unico nombre , y para acceder esos nombres se utiliza un indice numerico """ pelicula = "Batman" #print(pelicula) #definir lista peliculas = [ "barman","spiderman", "El senor de los anillos"] cantantes= list(("2pac","Drake","Dualipa")) #transforma una tupla a lista year = ...
# operador de aisganacion edad = 26 print(edad) edad+= 5 edad = edad + 5 edad-= 5 print(edad) #operador de incremento y decremento year = 33 year = year +1 print(year) # Decremento year = year - 1
""" Ejericico 6 Mostrar todas las tablas de multiplicar del 1 al 10 , mostrando el titulo de la multiplicacion y luego las multiplicaciones """ numero = 1 while numero <= 10: print(f"###Tabla del {numero}###") for contador in range(1,11): print(f"{numero} x {contador} = {numero * contador}") num...
""" Ejericio 2 Escribir un script que nos muestre por pantalla todos los numeros pares del 1 al 120 """ numero = 1 # con while while numero <=120: numero_par = numero % 2 if numero_par == 0 : print(numero) numero+=1 # con for for contador in range(1,121): if contador % 2 == 0: print...
print("What is your weight?") weight = int(input('> ')) print("How many feet tall are you? For instance, if you're 5 feet and 11 inches tall, enter '5'") feet = int(input('> ')) print("And how many inches tall are you? For instance, if you're 6 feet and 2 inches tall, enter '2'") inches = int(input('> ')) height = (fee...
import itertools import random def deck(): color = ['pik', 'kier', 'karo', 'trefl'] value = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jupek', 'Królowa', 'Król', 'As'] deck = list(itertools.product(value, color)) return deck def shuffle_deck(decko): random.shuffle(decko) ...
def inputFunc (): userInput = input() return(userInput) def inputFuncValidation (userInput): if userInput == '1' or userInput == '2' or userInput == '3' or userInput == '4' : valid = userInput else: valid = 0 return(valid)
# Given a positive integer num, output its complement number. # The complement strategy is to flip the bits of its binary representation. class Solution: def findComplement(self, num: int) -> int: a = format(num, 'b') op = '' for x in a: if x == '0': op += '1' ...
# Given an arbitrary ransom note string and another string containing letters from all the magazines, # write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. # Each letter in the magazine string can only be used once in your ransom note. cl...
u"""This is the naive implementation of a server handling many concurrent connections at once.""" import itertools, socket HOST = '127.0.0.1' PORT = 9001 def reverse(data): return ''.join(reversed(data)) commands = {'reverse' : reverse } def dispatcher(data): u"""Receives data, parses command and the paylo...
#!/usr/bin/env python """ Usage example employing Lasagne for digit recognition using the MNIST dataset. This example is deliberately structured as a long flat file, focusing on how to use Lasagne, instead of focusing on writing maximally modular and reusable code. It is used as the foundation for the introductory La...
filename = "file.txt" ## Writing file = open(filename, 'w') for i in range(1, 11): file.write("This is line %i \n" % i) file.close() file = open(filename, 'r') for line in file: print(line, end = '') file.close()
letters = {"A": "E", "B": "F", "C": "G", "D": "H", "E": "I", "F": "J", "G": "K", "H": "L", "I": "M", "J": "N", "K": "O", "L": "P", "M": "Q", "N": "R", "O": "S", "P": "T", "Q": "U", "R": "V", "S": "W", "T": "X", "U": "Y", "V": "Z", "W": "A","X": "B", "Y": "C", "Z": "D"} message = input("Enter your...
# This program calculates the shift of characters (the key) that has been used # when a message has been decrypted by a substitution cipher. sentance = "amrwxsr xli hsk jsyklx sjj e fiev" sentance = sentance.lower() sentanceList = sentance.split(" ") # sorts the list into order using the sorted function. # lo...
#Decrypts it with key of 3 #Also works around z #Ascii number for z is 122 #Ascii number for a is 97 #when DECRYPTING only have to care about a #when ENCRYPTING have to care about z #Word is phenomenal. key = 4 sentance = 'the world can be one together cosmos without hatred' sentanceList = sentance.split("...
from random import shuffle class Card: suits = ["spades", "hearts", "diamonds", "clubs"] # first two items are None so that index matches card value values = [None, None, "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] def __init__(self, value, suit): # suits and values shoul...
user_number = int(input("Enter a number of three digits:")) array = list() i= 0 while user_number >= 0: array[i] = user_number%10 user_number = user_number /10 i+= 1 array.sort(reverse=True) # Lets do some sorting to get second largest temp = array[0] array[0] = array[1] array[1] = temp # now we ar...
with open("Input.txt") as file: linebuffer = file.read() lines = linebuffer.split(" ") max_occurence = max(lines, key=lines.count) print("The no occured max is :", max_occurence) print("The no of time this word occured :", lines.count(max_occurence))
num1,num2 = map(int,input("Enter two numbers to find out HCF:").split()) if num1 > num2: smaller = num2 if num1 % smaller == 0: print("The HCF of both the numbers is:",smaller) else: for i in range(2,(smaller//2)+1): if num1% i == 0: ...
import unittest from queue import Queue class QueueTest(unittest.TestCase): def test_object(self): """ - test if queue object has been implemented - returns true for the correct name """ queue = Queue() self.assertEqual(type(queue).__name__, 'Queue') def te...
#!/usr/bin/python #!encoding: UTF-8 import moduloerror import sys if((len(sys.argv)==1) or (len(sys.argv)==2)or(len(sys.argv)==3)): print ("No se han introducido los valores necesarios. Se utilizarán los valores predeterminados:") print("Intervalos= 10 Veces=10 umbral 0.1") k=10 n=10 umbral=0.1 else: n= i...
# -*- coding: utf-8 -*- """ Created on Sat Jun 2 14:18:37 2018 @author: cherylK """ from matplotlib import pyplot as plt import pandas as pd import numpy as np species=pd.read_csv('species_info.csv') #print species.head() # "How many different species are in the `species` DataFrame?" 5541 num_species=species.scie...
''' Polling places Evelyn Dang, Corry Ke Main file for polling place simulation ''' import sys import random import queue import click import util class Voter: def __init__(self, arrival_time, voting_duration): ''' Constructor for the Voter class Inputs: arrival_time: (float) ...
""" Added a store. The hero can now buy a tonic or a sword. A tonic will add 2 to the hero's health wherease a sword will add 2 power. """ import random import time class Character(object): def __init__(self): self.name = '<undefined>' self.health = 10 self.power = 5 self.coins = 20...
# age = int(input("Enter your age: ")) # if age >= 18: # print("You are of age") # else: # print("You are a minor") # password = "456m789D123".lower() # ask_password = str(input("Enter your password: ")).lower() # if password == password1: # print("Valid password") # else: # print("Invalid password") ...
# Task # A Node class is provided for you in the editor. A Node object has an integer data field,data, and a Node instance pointer,next , # pointing to another node (i.e.: the next node in a list). # # A removeDuplicates function is declared in your editor, which takes a pointer to the head node of a linked list as a ...
# Given a base-10 integer,n , convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of # consecutive 1's in n's binary representation. if __name__ == '__main__': n = int(input()) rmd = [] while n > 0: rm = n % 2 n = n // 2 rmd.append(rm...
# Printing the Number of Swaps taken and also the first and last element of an array sorted using Bubble Sort. n = int(input().strip()) a = list(map(int, input().strip().split(' '))) # Write Your Code Here swaps = 0 for i in range(len(a)): for j in range(1, len(a)): if a[j - 1] > a[j]: swaps +=...
import sys import time import RPi.GPIO as GPIO import datetime import w1thermsensor import os os.system('modprobe w1-gpio') os.system('modprobe w1-therm') # Note GPIO module uses Physical PIN as reference. Physical PINs are numbered in order # Note Adafruit_DHT uses BCM PIN as reference. BCM PINs are the numbers on t...