text
stringlengths
37
1.41M
# CN_Mobile=['131','132','133','134'] #移动 # CN_Unicorn=['147','199','188'] #联通 # CN_telecon=['156','158','157'] #电信 # # mobile=input('请输入11位的手机号码:')#输入11位手机号码 # mobile_s = mobile[:3] #截取前三位手机号码 # if mobile.isdigit(): # if len(mobile)!=11: # print('号码位数不对') # else: # if mobile_s in CN_Mobile: # ...
# author:JinMing time:2020-05-16 # -*- coding: utf-8 -*- import threading import time def foo(something, num): # 定义每个线程要执行的函数 for i in range(num): print("CPU 正在", something) time.sleep(1) # 创建线程实例,target 指向任务函数,args 为 target 指向的函数传参 t1 = threading.Thread(target=foo, args=("看电影", 2)) # 生成了一个线程实...
#Ingresar nombres en una lista, luego buscar un nombre y de encontrarlo decir en qué posición está. lista_nombres = [] nombre = input("\nIngresar nombre (0 para finalizar): ") while (nombre != "0"): lista_nombres.append(nombre) nombre = input("\nIngresar nombre (0 para finalizar): ") print("\n ---...
#Dada una lista cargada con 7 números enteros, obtener el promedio. Mostrar por pantalla dicho promedio y los números de la lista que sean mayores que él. lista_numeros = [0 for x in range(7)] print("A continuación, se calculará el promedio de siete números") # numero = int(input("\nIngresar número: ")) for i...
#Transformar la cadena "River vuelve a las copas", en la cadena "River vuelve a la copa". Resolverlo recorriendo la cadena original como si fuera una lista. cadena = 'River vuelve a las copas' cadena3 = cadena.replace("s", "") # print(cadena2) print(cadena3) cadena2 = cadena.split('s') for i in range(len(...
#Determinar cuál es la vocal que aparece con mayor frecuencia. s = "Quiero comer manzanas, solamente manzanas." # s = s.replace(",", "") # s = s.replace(".", "") # lista_s = s.split() s.lower() # cantidad_a = s.count("a") # cantidad_e = s.count("e") # cantidad_i = s.count("i") # cantidad_o = s.count("o") # cantidad_u ...
##Nombre de alumno: Leonardo Roman Leonhardt #Pedir un nombre y una opción ('>' o '<') y según esta mostrar por ejemplo.: Juan es menor de edad nombre = input("\n Ingrese un nombre: ") opcion = input("\n Ingrese un signo mayor que ( > ) o menor que ( < ) para definir si " + nombre + " es mayor o menor de edad : ")...
#Pedir el ingreso de 10 números. Contar los mayores de 23. Mostrar el resultado. datos = [0 for x in range(10)] for i in range(0,len(datos)): datos[i] = int( input( "Ingrese número {}: ".format(i+1) )) print ("Los números mayores que 23 son: ") for i in range(0, len(datos)): if datos[i] > 23: ...
test_string = "I am a NOUN " test_string = test_string.replace("NOUN","Rafeeq") print test_string
from datetime import datetime class Node: def __init__(self, name, date, clickCount): """Represents a generic object in the bookmark manager Keyword Args: name -- name of the node date -- date the node was added clickCount -- frequency of node clicks """ ...
a = int(input("성적을 입력하세요 : ")) if a>= 90 : print("A") elif a>=80: print("B") elif a>=70: print("C") elif a>=60: print("D") else : print("F")
# a1에 한행씩 리스트 생성해서 a2로 한줄씩 통째로 복사하는 다중리스트 a1 = [] # 1줄 (행)용 리스트 a2 = [] # 최종목표인 다중리스트(이차원) # 다중리스트 생성 v = 1 for i in range(0, 3): # 3행 for j in range(0, 4): # 4열 a1.append(v) v += 1 print(a1) a2.append(a1) # 배열 <- 배열 print(a2) a1 = [] # 다중리스트 출력 for i in range(0, 3): # 3행 ...
print(2**3) print(pow(2,3)) print(100 ** 100) print(9/2) print(9//2) #몫 구하기 print(9%2) #나머지 구하기 print(3.14E5) print(0xff, 0o77, 0b1111) #16/8/2진수를 10진수로 변환 print(hex(255), oct(63), bin(15)) #10진수를 다른진수로 변환 print() a = (100 == 100) print(a) #True b = "파이썬\n만세" print(b) b = """파이썬 만세""" #"""(겹따옴표 세개) -> 화면에 보이는 그대로 출력 ...
import re import nltk nltk.download('stopwords') nltk.download('punkt') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize def clean_text(text_string): text_string = text_string.lower() text_string = re.sub(r'[^\w\s]', '', text_string) # Removes punctuations from test query. ...
__author__ = 'dario' def main(): pass def print_columns(data): print "\nCOLUMNS IN DATA SET ARE:" for x in data.columns: print x def append_squared_value_for_columns(data, columns_to_square): added_column_names = [] for column in columns_to_square: squared = data[column] * data[co...
# -*- coding: utf-8 -*- """Collecting multiple drivers in a database.""" import json from .driver import Driver class DriverDB(list): """Representing the database (inherits from ``list``).""" def __init__(self): """Create an empty database. Take a look at ``from_file`` for loading an existin...
animals = [ {'name':'cow', 'size':'large'}, {'name':'bird', 'size':'small'}, {'name':'fish', 'size':'small'}, {'name':'rabbit', 'size':'medium'}, {'name':'pony', 'size':'large'}, {'name':'squirrel', 'size':'medium'}, {'name':'fox', 'size':'medium'}] import itertools from operator im...
# -*- coding: utf-8 -*- """ Created on Mon Apr 13 10:05:21 2018 @author: souravg To do : Accept First and Last name and print them in reverse order. """ fname = input("Enter your First Name : ") lname = input("Enter your Last Name : ") print("Your FullName is %s and the reverse order of your FullName is %s" %(f...
DECREASING_POWER_OF_10 = [1000, 100, 10, 1] ROMAN_TO_NUMERAL = {1000: 'M', 500: 'D', 100: 'C', 50: 'L', 10: 'X', 5: 'V', 1: 'I'} def convert(number): assert isinstance(number, int) and 0 < number < 3000 decreasing_remain_list = [int(number % (power_of_10 * 10) / power_of_10) for power_of_10 in DECREASING_POW...
import random DESCRIPTION = "Answer yes if given number is prime. Otherwise answer no." RANDOM_NUMBER_MIN = 2 RANDOM_NUMBER_MAX = 100 def get_question_answer(): """Function to create random number and return result(prime or no)""" question = random.randint(RANDOM_NUMBER_MIN, RANDOM_NUMBER_MAX) ...
class Board(object): def __init__(self, boardSize, playerNum): self.__boardSize = boardSize self.__playerNum = playerNum self.__gameBoard = [] self.__CandLmap = {} self.__player_loc = {} self.__delimeter = '-' self.__initBoard() # PROPERTIES @prope...
# Simple finite while loops n = 5 while n > 0: n -= 1 print(n) a = ["foo", "bar", "baz"] while a: # != [''] print(a.pop(-1)) # while loop with an else statement # while <expr>: # <statement(s)> # else: # <additional_statement(s)> n = 5 while n > 0: n -= 1 print(n) else: print("Loop ...
def quick_sort(arr): """[3, 8, 2, 5, 1, 4, 7, 6] pick pivot, put smaller on the left, larger on the right, keep doing these for the subset of the array:left, right """ if len(arr) <= 1: return arr k = choose_pivot(arr) left, right = partition(arr, k) l = quick_sort(left) r = ...
class Node(object): def __init__(self, val): self.val = val self.next_ = None def __repr__(self): val = str(self.val) if self.next_ is None: return val return val + ',' + str(self.next_) def _is_head(pre): return pre is None def _is_tail(cur): retur...
# Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input()); A = set() B = set() sum1=0; A = input(); #print(A) A = A.split(" "); #print(A) for i in range(n): A[i]=int(A[i]); A = set(A) #print(A) #print(A); op = int(input()); for i in range(op): a = input().split(' '); B = inp...
# 32ms/98.63% class Solution: def countSegments(self, s: str) -> int: count = 0 flag = True for i in s: if i == " ": flag = True else: if flag: count += 1 flag = False
# 36ms/94.95% class Solution: def isValid(self, s: str) -> bool: stack = [] for symbol in s: if symbol == "(" or symbol == "[" or symbol == "{": stack.append(symbol) else: if stack == []: return False char =...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 56ms/100% class Solution: def findTilt(self, root: TreeNode) -> int: # return sum and tilt simutaneously def _findTilt(root): if root...
''' When working with iterators, henerators, etc. look at the documentation for the itertools module ''' from itertools import islice, count from itertools import chain from list_comprehension import is_prime def main(): thousand_primes=islice((x for x in count() if is_prime(x)), 1000) print(thousand_prime...
rows = 'ABCDEFGHI' cols = '123456789' def cross(a, b): return [x + y for x in a for y in b] boxes = cross(rows, cols) row_units = [cross(x, cols) for x in rows] column_units = [cross(rows, y) for y in cols] square_units = [cross(xs, ys) for xs in ['ABC', 'DEF', 'GHI'] for ys in ['123', '456', '789']] unitlist ...
# Python program to find out # Sum of elements at even and # odd index positions separately # Function to calculate Sum def SumEvenOdd(a, n): even = 0 odd = 0 for i in range(n): # Loop to find even and odd Sum if i % 2 == 0: even += a[i] else: odd += a[i] print ("Even index positions sum ...
def postorder_traversal(root): if root: left = postorder_traversal(root.left) right = postorder_traversal(root.right) return left + right + [root.val] else: return [] def postorder_traversal_iteratively(root): if not root: return [] result, queue = [], [(root,...
import unittest from trees.treenode.treenode import TreeNode from .postorder_traversal import postorder_traversal, postorder_traversal_iteratively class PreorderTraversalTestCase(unittest.TestCase): @classmethod def setUpClass(cls): a = TreeNode('a') b = TreeNode('b') c = TreeNode('c')...
""" Write a Python program to print the following string in a specific format Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are" Output : Twinkle, twinkle, little star, How I wonde...
# Tyler Hedegard 5/13/2016 # Thinkful.com Python Introduction Lesson 3 # Pirate Bartender questions = { "strong": "Do ye like yer drinks strong?", "salty": "Do ye like it with a salty tang?", "bitter": "Are ye a lubber who likes it bitter?", "sweet": "Would ye like a bit of sweetness with yer poison?"...
from random import shuffle import itertools palo = "C D P T".split() rank = "2 3 4 5 6 7 8 9 10 J Q K A".split() def shuffleDeck(): # Función para barajear y repartir deck = list(itertools.product(rank, palo)) shuffle(deck) return deck[:26], deck[26:] def compareCards(card1, card2): # Co...
# Import the random module so we can randomly generate numbers # Import time module for dramatic pausing effect import random import time # Create a Superhero class that will act as a template for any heroes we create class Superhero(): # Initializing our class and setting its attributes def __init__(self): ...
import time def PowSum(numbers): Sum=0 New_list=iteration(numbers) x=digits(numbers) for n in range(0,x): Sum=int(New_list[n])**x+Sum return Sum def flower(Numbers): if PowSum(Numbers)==Numbers: print(Numbers,'\n') def iteration(numb): # Origin_list=[]...
# Create a function called calculate_avg_rating # Parameters: the function should have one argument of type list of Review (i.e., the arg should be a list of Review objects) # Returns: the function should return a float: the average of all review ratings that are given in the list as an argument to this function. # ...
""" 1. Szukanie min i max [1,23] | 2. a = |0-1|/|1-23| = a = |0 - 1| / |min - max| 3. b = 1 - 1/22 * 23 = b = 1 - (a * max) 4. y = a*x + b -> 1/22*x - 1/22 | min - max """ def findMinimum(data): return min(data) def findMaximum(data): return max(data) def findExtrema(data): return min(data), max(data) ...
#CLI - command line interface #GUI - graphical user interface from d3_2_objects.p67_pwn.student_controller import StudentController # utworzenie obiektu zawierającego metody obsługi dziekanatu dziekanat = StudentController() while(True): menu = input("APLIKACJA DZIEKANAT\n" "(D)-dodaj nowego stude...
# P 55 # Woda zamarza przy 32 stopniach Fahrenheita, a wrze przy 212 stopniach Fahrenheita. # Napisz program, który wyświetli tabelę przeliczeń stopni Celsjusza na stopnie Fahrenheita # w zakresie od –20 do +40 stopni Celsjusza (co 5 stopni). Pamiętaj o wyświetlaniu znaku plus/minus przy temperaturze. print(" C |...
# Napisz program zliczający liczbę wartości unikatowych wprowadzonych przez użytkownika # P44 slowo = input("Pdaj co kolwiek: ") zbior = set(slowo) print(sorted(zbior)) for index, element in enumerate(sorted(zbior)): print(element + ":=", index, end=" ")
# P59 # Napisz funkcję, która wygeneruje losowe zdanie zawierające podaną liczbę (domyślnie 5) losowo wygenerowanych wyrazów. from random import sample, choice, randint, random, randint, choices names = ["Ala","Ola","Ela", "Andrij", "Agni", "Andrij"] # print(sample(names, 5)) for element in sample(names, 5): prin...
a = "sample text" b = [1,2,3,1,1,2] # lista c = (1,2,1,2,1) # krotka d = {1,2,3,4,5} # zbiór e = {'a':1,'b':2,'c':3} # Słownik print() ############ Napisy print("# napisy = Tekst") a_tekst = "tekst" print(a_tekst.capitalize()) print(a_tekst) print(a_tekst[1]) print ('a' and 'b', "'a' and 'b‘# 'b'") print ('a' or 'b',"...
from math import exp, log deltas = [0.41, 0.49, 0.55, 0.65, 0.73] # for the first time we are calling get_diffs, we use 100. For the second stage, we use the calculated diff def check_diff(diffs, diff): if diff in diffs: return diffs[diff] return 100 def intermediate_func(delta, velocityOne, veloci...
#!/bin/python3 import math import os import random import re import sys #import numpy as np # # Complete the 'numbersSquare' function below. # # The function accepts following parameters: # 1. INTEGER n # 2. INTEGER s # def numbersSquare(n, s): # Write your code here #rs = [[0,0],[0,0]] rs = [[0 for j i...
# -*- coding: utf-8 -*- """ Created on Thu May 6 22:13:38 2021 @author: sh010 """ class Node: def __init__(self,elem, link = None): self.data = elem self.link = link class LinkedList: def __init__(self): self.head = None def isEmpty(self): return self.head == None def cle...
# -*- coding: utf-8 -*- """ Created on Thu Apr 29 11:56:16 2021 @author: sh010 """ class Node: def __init__(self,elem, link = None): self.data = elem self.link = link class LinkedList: def __init__(self): self.head = None def isEmpty(self): return self.head == None def cle...
# -*- coding: utf-8 -*- """ Created on Tue Apr 13 15:46:22 2021 @author: sh010 """ MAX_QSIZE = 10 class CircularQueue: def __init__(self): self.front = 0 self.rear = 0 self.items = [None] * MAX_QSIZE def isEmpty(self):return self.front == self.rear def isFull(self): return self.fro...
# Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. salario + (salario*15/100) salario = float(input("Informe o salário: ")) aumento = salario + (15 / 100) novo_salario = salario + aumento print(f"Seu salário com aumento é R${novo_salario}")
# Faça um programa que receba um valor, e traga informações sobre esse valor, dizendo se é alfanumérico, numérico e etc. num = input("Informe um valor: ") if num.isalpha() and num.isupper(): msg = "é letra do alfabeto e está em maiúsculo" elif num.isalpha() and num.islower(): msg = "é letra do alfabeto e est...
fruits = ["apple", "banana", "cherry", "guava"] print(fruits) print(type(fruits)) print(fruits[2]) print(fruits[-2]) print(fruits[0:]) if "banana" in fruits: print("Exist!") fruits[0] = "sev" fruits[2] ="deshi" print(fruits) newfruits=["aam", "jamun", "amrood"] print(fruits[0:2]) fruits[0:2] = newfruits fruits.inse...
#x = 32 #txt = """My name is rohit and my age is {} #Also i am leving in Pune since {} years""" #print(txt.format(32,3)) #y = "welcom to \"Python\" world" #print(y) #y="Welcome to Python World.\n with Rohit Shukla" #for new line #print(y) #y="welcome" #print(y.capitalize()) #Capitlize function in string #y="welco...
def solution(A): """ A sorted array has been rotated so that the elements might appear in the order 3, 4, 5, 6, 7, 1, 2. How would you find the minimum element? You may assume that the array has all unique elements. >>> solution([3, 1, 2]) 1 >>> solution([2, 3, 4, 6, 1]) 1 >>> solu...
def solution(stairs): """ A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. >>> solution(5) 13 >>> solution(3) 4 >>> solution(7) 44 """ ...
# Real Mini Project from selenium import webdriver from bs4 import BeautifulSoup import time import tkinter as tk from tkinter import ttk import pandas as pd # import requests # from_city = input("Flying from: ") # to_city = input("Flying to: ") # day = input("What date (dd/mm/yyyy): ") def popup(msg): popup = t...
# search and count the words in file count = 0 with open("/home/anil/Desktop/py_file.txt") as file_data: file_content = file_data.read() file_data.seek(0) for line in file_data: for s in line.rstrip().split(" "): count += 1 # print(line.rstrip()) # for line in file_content: # ...
def sort_dict_list(dict): values = [] sorted = [] for entry in dict: for key, value in entry.items(): values.append(value) values.sort(key=lambda x: x, reverse=True) for number in range(len(values)): for entry in dict: for key, value in entry.items(): ...
import json import csv import io ''' creates a .csv file using a Twitter .json file the fields have to be set manually ''' data_json = io.open('bigtweets_2.json', mode='r', encoding='utf-8').read() #reads in the JSON file data_python = json.loads(data_json) csv_out = io.open('bigtweets_2_out_utf8.csv', mode='w', enc...
#!/usr/bin/python3 ''' say_my_name function ''' def say_my_name(first_name, last_name=""): ''' Print first and last name Parameters: first_name (str) last_name (str) Returns: void ''' if type(first_name) is not str: raise Typ...
#!/usr/bin/python3 ''' write_file function ''' def append_write(filename="", text=""): ''' write in a file and appends in file ''' with open(filename, 'a', encoding="utf-8") as file: return file.write(text)
#!/usr/bin/python3 """ pascal triangle""" def pascal_triangle(n): """ return pascal triangle """ pascal_list = [] new_list = [] pascal_number = 0 if n <= 0: return pascal_list for i in range(0, n): pascal_number = 11 ** i pascal_list.append(str(pascal_number)) for...
#!/usr/bin/python3 for i in range(0, 90): if i % 10 != i / 10 and i % 10 > i / 10: print("{:02d}{}".format(i, ", " if i < 89 else '\n'), end='')
while True: #Taken if User Want to play game again v=1 #Counter how many values are filled in board board=[' ']*10 #Setting all values to blank in board player='' #Will store which player is playing val=False #For Checking if any player won or not def printTable(): for i in range...
print(sorted([9, 1, 3, 2, 7, 5])) # 使用sorted对字典进行排序 from random import randint names = ['bruce', 'john', 'lili', 'cindy', 'tony'] d = {x: randint(60, 100) for x in names} print(d) # 1.转换成元祖 print(sorted(zip(d.values(), d.keys()))) # 2. print(d.items()) print(sorted(d.items(), key=lambda x: x[1]))
import sqlite3 from sqlite3 import Error import os class Database: """Handles simple sqlite database to keep track of urls already visited. We want to avoid having to check for changes on each individual listing so urls visited can be stored with flags indicating whether the listing has been visited o...
# -*- coding: utf-8 -*- """ Model related functions defined on analysis To train the best model on new data, add the data to the raw csv data and use train_model function Otherwise, use predict to predict new data @author: icaromarley5 """ from sklearn.tree import DecisionTreeClassifier from joblib import dump,load ...
#write a function which take the given array and find and return the #second biggest number import time start = time.time() #write a function that takes two strings and returns True if they are reverse def sum_array(list_array): total=0 list_array=sum(list_array) total+=list_array return to...
age = 31 if age>= 35: print('You are old enough to be president!') elif age >=30: print('You are old enough to become Senator!') else: print('You are not old enough to be elected') print('Have a nice day!!')
""" Basic implementation of a binary tree. Author: Xavier Cucurull Salamero <xavier.cucurull@estudiantat.upc.edu> """ class Node: """ Implementation of a binary tree to use with CART. """ def __init__(self, predicted_class, gini, data_idx=None): self.predicted_class = predicted_class self....
n = int(input("Enter Your Number :")) for i in range(n): for j in range(i+1): print(" ",end = '') for j in range(n-i ): print(i+j+1,end = " ") print("") for p in range(n): for q in range(n-p): print(" ",end = '') for q in range(p+1): print(n-p+q,end = ' ') print(...
#if we decide to do things locally check this out #http://zetcode.com/db/mysqlpython/ #http://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html import mysql.connector from mysql.connector import errorcode class users: def __init__(self, dbname, username , password , host , connection =...
# In Python, there are not built in Arrays, # The default data type is Lists. Check more # On that. However, we can also use arrays # Good old boi # Tho, not exactly, the are different that in Java # ARRAYS # All data must be of the same kind # You can only sotre simple types of data # Has an index # Storage order g...
# DICCIONARIES # Its similar to JSON # It stores values as # pairs by key/value # The items order is not guaratee* dic = {"primero": "Christopher"} # To add: dic["last"] = "Harrison" #To delete: #del dic['last'] print(dic) print(dic["primero"]) # Returns a list of all keys in a dict print(dic.keys()) # Returns a ...
from Mascota import * from Vete import * listaDeDueños = [] listaDeMascotas = [] pepe = Dueño() pepe.Nombre = "pepe" jose = Dueño() jose.Nombre="jose" listaDeDueños.append(pepe) listaDeDueños.append(jose) a = Pajarito("pepe", jose) listaDeMascotas.append(a) while True: print("1)Agregar Mascota") print("2)Borra...
import cv2 as cv import numpy as np def find_faces_haar(img, face_cascade): """ Find all the regions in the image that have faces. Parameters ---------- img : The input image. face_cascade : A pre-trained face detector API. Returns ------- The final image, and the list of faces d...
# 冒泡排序可以记住交换次数,这样一旦有一轮全程没有进行交换,那就表示已经排好序了,可以结束了。 # 所以最好的时间复杂度就是数列直接就是有序的,时间复杂度为O(n). # 因为存在两层for循环,所以时间复杂度平均和最坏都为O(n^2). # 未使用多余空间,空间复杂度为O(1)。 class Sorting: def bubbleSort(self, s): # 正确 for i in range(0,len(s)): # 这里的i并不是控制从前往后的,而是控制后面每次该减几个 for j in range(0,len(s)-i-1): # 每一轮的最后面一个元...
import math as mt r=input("Radio: ") r=float(r) theta=input("Ángulo [Rad]: ") theta=float(theta) x=r*mt.cos(theta) y=r*mt.sin(theta) print("x es: ",x) print("y es: ",y)
from itertools import combinations def main(): data = [] with open("data/data_1.txt", "r") as f: for line in f: data.append(int(line)) for x, y, z in combinations(data, 3): if x + y + z == 2020: return x * y * z if __name__ == "__main__": print(main())
import random def jogar_adivinhacao(): print("----------------------------------\n") print("Bem vindo ao jogo de adivinhação!\n") print("----------------------------------\n") secret_number = int(random.randrange(1,101)) print(secret_number) cont = 1 while cont == 1: print("Nive...
#!/usr/bin/env python # coding: utf-8 # In[ ]: get_ipython().run_line_magic('mathplotlib', 'inline') import mathplotlib.pyplot as plt import np as numpy # In[ ]: def function_to_integrate(x): # e^(-2x)*cos(10x) return math.e**(-2*x)*math.cos(10*x) # In[ ]: def trapazoid core(f,x,h) return math.e**(-2*x)*...
#!/usr/bin/python3 import random numbers=[i+1 for i in range(45)] for i in range(5): random.shuffle(numbers) print(sorted(numbers[:6])) input()
# Filename: classes.py # Name: Chua Yu Peng # Description: Implements suitable class relationship for Staff, between Teaching and Support Staff. class Staff(): ''' superclass for staff ''' def __init__(self, StaffID, Name, EmployeeType): ''' define variables ''' self.__StaffID = StaffID ...
# def operasiBilangan(): # a = 7 # b = 8 # yield a + b # x = 19 # y = 90 # yield x - y # z = 80 # w = 90 # yield z * w # c = 999 # k = 10 # yield c / k # oprGen = operasiBilangan() # for i in oprGen: # print(i) def operasiBilangan(): yield "Hello World" ...
import Helper nama = "" umur = 0 tinggi = 0.0 tryAgain = True print("software perkenalan : ") print("==============================") while tryAgain: #input case nama = str(input("masukkan nama : ")) umur = Helper.inputInteger("masukkan umur : ",0,100) tinggi = Helper.inputFloat("masukkan tinggi ba...
#!/usr/bin/env python # coding: utf-8 # ## 目標:在一list中的連續整數,有一個數字重複、且因此該數字的下一個數字沒有成功加入list中。此題需要找出重複之數, 未出現之數,並以陣列方式返回出來 # #### Leetcode題目位置:https://leetcode.com/problems/set-mismatch/ # In[1]: class Solution: def findErrorNums(self, nums): n = len(nums) # 全部總和 nums_sum = sum(num...
#!/usr/bin/env python # coding: utf-8 # # 法一:偷吃步 # ###直接應用python的既有函式,如append、pop等 # In[50]: class MyLinkedList1(object): def __init__(self): self.linkedlist = list() def get(self, index): if index < 0 or index >= len(self.linkedlist): return -1 else: return...
import sys import time class parking: S_count = 0 L_count = 0 M_count = 0 slot_id = 0 id = "0" t = "V" slot_id = 0 slot = [] slot[0:9] = ['S'] * 10 slot[10:16] = ['M'] * 7 slot[17:19] = ['L'] * 3 def vehicle_details(self): parking.id = str(input("Pl...
def has_negatives(a): """ YOUR CODE HERE """ # Your code here result = [] a_dict = dict.fromkeys(a, 'I exist') for num in a: if num < 0: pos_num = 0 - num if a_dict.get(pos_num) is not None: result.append(pos_num) return result if __name...
class Cat: # A Cat class. def __init__( self, name, preferred_food, meal_time ): # Every Cat has attributes name, preferred_food, and meal_time. self.name = name self.preferred_food = preferred_food self.meal_time = meal_time def __str__(self): return f'''The cat {...
from urllib import request as req from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup # get profile id and privacy settings print("https://steamcommunity.com/id/[THIS PART IS WHAT YOU ENTER]") print('Check for spelling / case mistakes!') print('Avatar will be downloaded to folder directory...
def listToTuple(list): odd_sum = 0 product = 1 for item in list: if item % 2 == 0: product *= item else: odd_sum += item return (odd_sum, product) # print(listToTuple([4,2,5,7,3,6,9])) def kebabToScreamingSnake(str): str = str.upper().replace('-',...
n = 5 longest = 0 nlong = 0 while n < 1000000: terms = 1 m = n while m > 1: if m % 2: m = 3 * m + 1 else: m = m / 2 terms += 1 if terms > longest: longest = terms nlong = n print nlong, "took", longest, "steps" n += 1 print nlon...
import turtle t = turtle.Turtle() t.reset() t.color("red") for angle in range(0, 360, 15): t.seth(angle) t.circle(100)
#!/usr/bin/python3 # guess what this program doess???? import random r=random.randint(67,89) # gives random num print(r) if r<50: print(r) print(":is less than 50") elif r==45:
import pygame.font class Help: """Class used to render how to play text as an image.""" def __init__(self, ai_game): self.screen = ai_game.screen self.screen_rect = self.screen.get_rect() self.settings = ai_game.settings self.finder = ai_game.finder # Font settings for...
import unittest from classes import Customer, Amazon, Book, CoffeeMachine class TestCustomer(unittest.TestCase): def setUp(self): pass def test_deposit(self): cust = Customer("Sarah") self.assertEqual(cust.balance, 0) cust.deposit(1000) # This is where we call the method to...
class Shape(): def what_am_i(self): print("I am a Shape.") class Square(Shape): def __init__(self, s1): self.s1 = s1 def calculate_perimetre(self): print(self.s1*4) class Rectangle(Shape): def __init__(self,w,l): self.w = ...
o_list = [3,2,7,5,6] n_list = [c for c in o_list if c % 7 == 0] print(n_list)