text
stringlengths
37
1.41M
# Date: 06.01.2021. # Author: Sherzod Oltinbpoyev. # Theme: Ro'yxatlar bilan ishlash. # 1. Har bir odamga alohida xabar yuboruvchi dastur ismlar=['Anvar','Islom','Lochin','Abdurasul','Ulug\'bek'] for ism in ismlar: print(f"Salom {ism}") print(f"Kod {len(ismlar)} marta takrorlandi") # 2. 10 dan 100 gacha bo'lgan ...
n=int(input("Enter days number: ")) result = [] for i in range(n): v=[] m=int(input("Enter running number: ")) for i in range(m): TimeS=input() TimeS = TimeS.split() v.append(int(TimeS[1])/int(TimeS[0])) result.append(sum(v)) result.sort() for i in range(len(result)-1,-1,-1): print(result[i])
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import class CuentaAtras: def __init__(self, tope): self.tope = tope def __iter__(self): self.counter = s...
# Очередь на основе двух стеков # Операции empty, size и push не имеют циклов и не зависят от длины подаваемого списка => выполняются за O(1) # Операция pop имеет 1 цикл и в лучшем случае она выполняется за O(1), но если self.leftStack # не пустой, то операция pop может выполняться за O(n) class Queue: def __...
# 위상 정렬하여 각 선수 노드의 값을 누적한다. # 그래프에 넣을때는 해당 인덱스를 선수로 하는 노드를 이중 배열로 from collections import deque import copy n = int(input()) graph = [[] for _ in range(n+1)] indegree = [0]*(n+1) times = [0]*(n+1) result = [] for i in range(1,n+1): tmp = list(map(int,input().split())) times[i] = tmp[0] for j in tmp[1:len(tm...
import os import pandas as pd def get_WH_data_for_given_year(data_path: str, year: int) -> pd.DataFrame: ''' Extract World Happiness data for a given year Parameters ---------- data_path path to the CSV data file year year for which to select the data ...
#!/usr/bin/python import random import sys try: num_flips = int(raw_input("Enter number of times to flip coin: ")) except: print "Please try again and enter an integer" sys.exit() heads = 0 tails = 0 while num_flips > 0: flip = random.randint(1,2) if flip == 1: print "Heads!" heads += 1 else: print "Tails...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys import webbrowser pm = sys.argv[1] input = sys.argv[2:] args = (' '.join(input)) def usage(): print("srch - search from the commandline \n") print("python srch <platform> <query> \n") print('''platforms to search for wiki Search Wikipe...
# Write a Python program to remove duplicates from a list. def remove_duplicates_from_list(arg): ''' :param arg: list of numbers :return: arg:list ''' return list(set(arg)) if __name__ == '__main__': print(remove_duplicates_from_list([2, 1, 8 ,4, 8, 3, 2, 1, 5, 4]))
# Create a function, is_palindrome, to determine if a supplied word is # the same if the letters are reversed. def is_palindrome(word): ''' :param word: string :return: boolean ''' return word == word[::-1] print(is_palindrome('dad')) print(is_palindrome('mom'))
# Write a Python program to remove an item from a tuple. def remove_item_from_tuple(tup, item): ''' :tup: tuple :item: element of tup :return: tuple ''' temp = list(tup) temp.remove(item) return tuple(temp) if __name__ == '__main__': t = (2,3,4,5) print('tuple: ', t) print...
# Create a list with the names of friends and colleagues. Search for the # name ‘John’ using a for a loop. Print ‘not found’ if you didn't find it. friend_list = ['Ram', 'Jesus', 'Allah', 'Budha'] print('List of names:\n', friend_list) print('Searching for John...') flag = 0 for name in friend_list: if name == 'J...
# Write a Python program to reverse a string. def reverse_str(arg): ''' :param arg: string :return: string ''' return arg[::-1] if __name__ == "__main__": print(reverse_str('apple'))
# create a word which is made up of first and last two characters of a given string def create_word(original_word): if len(original_word)<2: return '' else: new_word = original_word[:2] + original_word[-2:] return new_word if __name__ == "__main__": print(create_word('Python')) ...
# replace the all the occurences of the first character of a given string with $. # Note that first character itself should not be changed. def replace_occurence(original_word): first_char = original_word[0] return first_char + original_word[1:].replace(first_char, '$') if __name__ == "__main__": ...
# Write a Python program to unpack a tuple in several variables. def tuple_to_list(arg): ''' :arg: tuple :return: list ''' return list(arg) def tuple_to_set(arg): ''' :arg: tuple :return: set ''' return set(arg) def tuple_to_string(arg): ''' :arg: tuple :return:...
# Write a Python program to change a given string to a new string where the first # and last chars have been exchanged. def rearrange_characters(arg): ''' :param arg: word:String :return: word:String ''' return arg[-1] + arg[1:(len(arg)-1)] + arg[0] if __name__ == '__main__': print(rearrange...
# Write a Python program to find the length of a tuple def tuple_length(arg): ''' :arg: tuple :return: number ''' return len(arg) if __name__ == '__main__': t = (2,3,4,5) print('given tuple: ', t) print('legth: ', tuple_length(t))
# Write a Python program to convert a list to a tuple. def list_to_tuple(arg): ''' :arg: list :return: tuple ''' return tuple(arg) if __name__ == '__main__': t = [2,3,4,5] print('list: ', t) print('tuple: ', list_to_tuple(t))
# use if statements to make decisions in code # ask user for their age age = int(input("What is your age?")) # check if person is old enough to drive if age >= 16 : print("You can get your driver's licence") else: print("You will be old enough in {} year(s)".format(16-age))
# converts a mark to a grade try: #ask the user for their mark mark = int(input("Enter your mark")) # tell user their grade # check if mark is >= 0 and <= 100 if mark >= 0 and mark <= 100: # calculate grade # check if grade in A range if mark >= 90: print("A") ...
## Test for grn1 = kop50 = kop25 = kop5 = kop1 = 0.00 money_list = [100, 50, 25, 5, 1] answer_list = ["1 grn", "50 kop", "25 kop", "5 kop", "1 kop"] try: amount = float(input("Input amount of your money: "))*100 if amount < 0: raise ValueError except: print("Error! Wrong input.") else: for i,...
#Function fabric def f(n): def g(x): return n * x return g double = f(2) triple = f(3) l = [] # Not closed, because depends on i value for i in range(10): def f(x): return x * i l.append(f) #closed for i in range(10): def f(x, i=i): return x * i l.append(f) # map f...
#a = int(input('Primeiro valor: ')) #b = int(input('Segundo valor: ')) #c = int(input('Terceiro valor: ')) #if a > b and a > c: # print('O maior número é {}'.format(a)) #elif b > a and b > c: # print('o maior número é {}'.format(b)) #else: # print('o maior número é {}'.format(c)) #print('final do programa') ...
# ten_x_plus1(7) -> 71 # ten_x_plus1(1) -> 11 # print ten_x_plus1(121) -> 1211 def ten_x_plus1(x): '''Takes the value x and computes (10 * x ) + 1 ''' return (10 * x ) + 1 #EVAL FUNCTION FOR EVALUATING A ONE LINE IF_ELSE CONDITION def if_else(condition, trueVal, falseVal): if condition: return ...
'''ss377KINAROW.py This module contains a player for K-in-a-row. It's personality is Mr T. It takes a given game stage and computes moves, and comments accordingly. ''' import copy import time import random ## ## Returns Introduction of the personality of this Player ## def introduce(): output = "When I was g...
# PdfFileWriter 可以分割寫入 PDF 檔 from PyPDF2 import PdfFileReader, PdfFileWriter # 設定讀取 PDF 檔案,獲取 PdfFileReader 物件,此處增加宣告 strict = False # 是因為所讀取 PDF 混用了不同的編碼方式,因此直接讀取發生 error 而無法執行, # 宣告此一參數將使 error 改為 warning 方式出現,使程式仍能繼續。 readFile = 'E1-1-2-2-input.pdf' pdfFileReader = PdfFileReader(readFile, strict=False) # pdfFileRe...
import re, os, argparse import random import check from fractions import Fraction '''' print 语句是为测试用,已注释掉 len_bag_randint = random.randint(2,len(bag)) 目的是为了取数,生成1个符号的式子,需要2个数, 生成3个运算符的式子需要4个数 create_expression函数目前只能生成整数式子,没有判断功能:判断式子是否合法——结果负值,除法有0等,只能简单生成式子 ''' def create_expression(erange=10): ope...
import multiprocessing def motion(data): return data+2 if __name__=="__main__": pool = multiprocessing.Pool() for i in range(10): if (i % 2) == 0: # use mod operator to see if "i" is even #result.put(i) print(pool.apply(motion,(i,))) else: ...
import csv import json import re def get_country_name(name): german_countries = ['Germany', 'West Germany (Germany)', 'Germany (Poland)', 'Prussia (Germany)', 'Federal Republic of Germany'] #Countries with instances of birth and organization country (combined) that is <= 10 other_countries = ['Mexico', 'Morocco', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' * * * * * * * * * * * * * * * ''' # 打印上边的图形 # while 循环 treeheight = int(input('输入打印的高度: ')) #高度 hashes = 1 while treeheight != 0: for i in range(hashes): print('*',end=' ') print() treeheight -= 1 hashes += 1 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # L1 = ['Hello', 'World', 18, 'Apple', None] # L2 = [s.lower() for s in L1 if isinstance(s, str)] # print(L2) # if L2 == ['hello', 'world', 'apple']: # print('测试通过!') # else: # print('测试失败!') # ---------------------------------------------- # def...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 字符串拼接,最好用.format方式,其次用%s方式,最好不要用‘+’号, # 万恶的‘+’,会把每个符符串都开辟内存空间,不高效! name = input('name: ').strip() # .strip() age = input('age: ').strip() job = input('job: ').strip() print('InFomation of \n{}\n{}\n{}\n'.format(name, age, job)) # 函数原型 # 声明:s为字符串,rm为要删除...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 常用模块 # calendar # time # datetime # timeit # os # shutil # zip # math # string # 上述所有模块使用,得先导入,string是特例 # calendar, time, datetime 的区别参考中文意思 # calendar # 跟日历相关的模块 import calendar # calendar: 获取一...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 函数 # 函数是代码的一种组织形式 # 函数应该能完成一项特定的工作,而且一般一个函数只完成一项工作 # 有些语言,分函数和过程两个概念,通俗解释是,有返回结果的叫函数,无返回结果的叫过程, # python 不加以区分 # 函数的使用 # 函数使用需要先定义 # 使用函数,俗称调用 # 定义一个函数 # 只是定义的话不会执行 # 1. def关键字,后跟一个空格 # 2. 函数名,自己定义,起名需要遵循便令命名规则,约定俗成,大...
#!/usr/bin/env python # -*- coding: utf-8 -*- # str 字符串 # str # 转义字符 # 格式化 # 内建函数 # 字符串 # 表示文字信息 # 用单引号,双引号,三引号括起来 s = 'i love lao wang' print(s) s = 'i love lao wang' print(s) s = ''' i love lao wang ''' print(s) # 转义字符 # 用一个特色的方表示一系列不方便写出出的内容,比如:回车键,换行符...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 作业一 # 写一个程序,判断给定年份是否为闰年 # 闰年的定义:能够被 4 整除的年份就是闰年 year = input('请输入年份===>') # type: str if year.isdigit(): # isdigit() 方法检测字符串是否只由数字组成。 year = int(year) if year % 4 == 0: print('{} 是闰年'.format(year)) else: print('{} 不是闰年'.fo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 什么是柯里化 # 指的是将原来接受两个参数的函数变成新接受一个参数的函数的过程。新的函数返回一个以原有第二个参数为参数的函数。 # 如:z = f(x, y) 转换成 z = f(x)(y) # 实例 def add(x, y): return x + y # z = f(x, y) print(add(4, 5)) def new_add(x): return inner # 方便记忆的写法,先写一个函数,接受第一个参数,然后返回一个新的函数, 如,返回了一个新的函数 in...
import random # set balance for testing purpose balance = 10 rounds_played = 0 play_again = input("Press <Enter> to play... ").lower() while play_again == "": # increase # of rounds played rounds_played += 1 # Print round number print() print("*** Round #{} ***".format(rounds_played)) ...
def getalpha(prompt: str) -> str: while True: string = input(prompt) if not string.isalpha(): print("Invalid input. Please only enter English letters.") else: break return string name = getalpha("Please enter your name: ").lower() other = getalpha("Please enter another word: ").lower() ...
##Intro to functions def theTruth(): """displaying a statement""" print ( 'Existance is pain.' ) theTruth()
## Or Condition yourAge = input("How old are you?\n") friendAge = input("Yeah but how old is your friend? haha\n") if int(yourAge) >= 18 or int(friendAge) >=18: print ( "Congrats. Welcome to the rest of your life." ) else: print ("You're both so young and naive.")
##Function with multiple parameters/arguments: Keyword Arguments def bookInfo(bookName, bookType, bookAuthor): """This function displays information about the book""" print ( bookName.title() + ' is a(n) ' + bookType.lower() + ' book, that was written by ' + bookAuthor.title()) name = input( "Please enter a b...
#finding length daysOfWeek = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ] print (len(daysOfWeek) )
##Passing a list to a function and modifying it def showNotCheckedInPassengers(notChecked): """Display not checked in passengers""" print ( 'These passengers are not yet checked in: ' ) for passenger in notChecked: print(' -' + passenger.title()) def checkInPassengers(notChecked,checked): """...
from random import choice import json choices = ["Rock", "Paper", "Scissor"] def game(played,p1_won,cmp_won): played+=1 print("ROCK!! PAPER!! SCISSOR!!") print("1. Rock") print("2. Paper") print("3. Scissor") player_choice = choices[int(input("Choose:")) - 1] computer_choice = choice(choic...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import os def process_data(data_file): df = pd.read_csv(os.getcwd() + "/data/" + data_file) df = df.loc[df["death_count"] >= 100, ] return df["death_count"].values def compute_death_rate(population, case_array): daily_new_death =...
def is_palindrome(n) -> bool: """ Functia determina daca un numar este palindrom sau nu Metoda: verificarea elemtelor simetrice din lista, in functie de mijlocul listei :param n: variabila de tip string ce poate contine un numar :return: True daca elementul este palindrom, False daca nu este palindr...
# -*- coding:utf-8 -*- #直接按价格排序语句 #search food class search_food(): def __init__(self,destination): self.destination = destination #按降序 self.sql1 = "select * from food where price != -1 and (city like '%{0}%' or area like '%{0}%') order by price desc".format(self.destination) #按升序...
from generate_list import generate_random_list from time import sleep lista = generate_random_list(10) for slow in range(len(lista)): print("---" * 6) print(f"Ordering position: {slow}") for fast in range(slow, len(lista)): if lista[fast] < lista[slow]: aux = lista[fast] li...
#Question 1 my_list = ['this', True, 'student', 45, 66, 43] new_list = my_list.copy() print(new_list) #Question 2 color_list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] color_list.remove('Red') color_list.remove('Pink') color_list.remove('Yellow') print(color_list) #Question 3 color_list = ['Red', 'Gr...
nombre = {"giraffe":3, "singe":5} emplacement = {"giraffe":"Cage nord-ouest"} nombre['dahu'] = 1 nombre["singe"] = 6 print nombre print 'singe' in nombre print 'ornithorynque' in nombre print nombre.keys() print nombre.values() print nombre.items() liste_de_paires = nombre.items() print dict(liste_de_paires) for cle in...
import sys #perform caterpillar method On^2 def solution(sum, array): minimum_sum = -1 minimum_distance = -1 for i in range (0, len(array)): j = i + 1 k = len(array) - 1 while j<k: current_sum = array[i] + array[j] + array[k] if minimum_sum == -1: ...
#!/usr/bin/python # WBKoetsier 9Jul2015 # very short script that uses selenium to fire up Google Chrome, get the # Google search page, send a search term and print the full plain text # html to stdout. # install selenium: pip install selenium # get the Chrome driver: http://chromedriver.storage.googleapis.com/2.16/ch...
# import the random and string packages to help generate passwords import random import string # Asks the user for the length of their desired password passLength = int(input("Welcome to my password generator! \n" "Please enter the length of the desired password: ")) # Collects all po...
from graph_search import bfs, dfs from vc_metro import vc_metro from vc_landmarks import vc_landmarks from landmark_choices import landmark_choices # stations under construction to be taken out of dfs and bfs vertexes stations_under_construction = ["Olympic Village"] landmark_string = "" for letter, landmark in landm...
#get the total charge of food. food= float(input('enter the total charge for food: ')) #get the percentage they want to tip of travel. tip=.18 #get the sales tax %. sales_tax=.07 #Get the total amount of bill with tip. whole_bill = (food+ (food *18))*.07 #display total distance. print('The total bill...
''' Creating a linked list using iteration Previously, we created a linked list using a very manual and tedious method. We called next multiple times on our head node. Now that we know about iterating over or traversing the linked list, is there a way we can use that to create a linked list? We've provided our solut...
# Priority Queues - Intuition ''' Consider the following scenario - A doctor is working in an emergency wing at a hospital. When patients come in, a nurse checks their symptoms and based on the severity of the illness, sends them to the doctor. For e.g. a guy who has had an accident is sent before someone who has come...
''' Breadth First Search: Visits the tree one level at a time. BFS in graph structure (shortest path). Traverse a Tree (breadth first search): You'll see breadth first search again when we learn about graph data structures, so BFS is very useful to know. ''' class Node(object): def __init__(self, val...
''' Problem Statement Previously, we considered the following problem: Given a positive integer n, write a function, print_integers, that uses recursion to print all numbers from n to 1. For example, if n is 4, the function should print 4 3 2 1. Our solution was: ''' def print_integers(n): # Base Case. if n <= 0:...
''' Reversing a String: The goal in this notebook will be to get practice with a problem that is frequently solved by recursion: Reversing a string. Note that Python has a built-in function that you could use for this, but the goal here is to avoid that and understand how it can be done using recursion instead. ''' # ...
# Binary Search First and Last Indexes ''' Problem statement Given a sorted array that may have duplicate values, use binary search to find the first and last indexes of a given value. For example, if you have the array [0, 1, 2, 2, 3, 3, 3, 4, 5, 6] and the given value is 3, the answer will be [4, 6] (because the val...
''' Reversing a linked list exercise: Given a singly linked list, return another linked list that is the reverse of the first. ''' #Begin helper code class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = No...
# Build a Red-Black Tree ''' In this notebook, we'll walk through how you might build a red-black tree. Remember, we need to follow the red-black tree rules, on top of the binary search tree rules. Our new rules are: - All nodes have a color - All nodes have two children (use NULL nodes) - All NULL node...
# Complete Binary Trees Using Arrays ''' Although we call them complete binary trees, and we will always visualize them as binary trees, we never use binary trees to create them. Instead, we actually use arrays to create our complete binary trees. Let's see how. [0][1][2][3][4][5][6][7][8] An array is a contiguous bl...
from __future__ import print_function, division from sympy import (degree_list, Poly, igcd, divisors, sign, symbols, S, Integer, Wild, Symbol, factorint, Add, Mul, solve, ceiling, floor, sqrt, sympify, simplify, Subs, ilcm, Matrix, factor_list, perfect_power) from sympy.simplify.simplify import rad_rationalize fr...
import random computer_number = random.randint(1, 10) win = 0 while win != 1: input_value = int(input('Imput your guss: ')) if input_value == computer_number: print('Congratulations! You have win the prize! Your guess is correct!!!') win = 1 elif input_value < computer_number: pri...
class PQ: class Node: def __init__(self, ele, parent = None, left = None, right = None): self._data = ele self._p = parent self._l = left self._r = right def __init__(self): self._root = None self._size = 0 def fuck_merge(...
class PositionalList: class Node: __slots__ = ('_prev','_next','_data') #Saves space and stores data def __init__(self, prev, data, nxt): #This is what Node looks like self._prev = prev self._next = nxt self._data = data class Position: def __init__(se...
#crear ciclo for que permita ingresar n temperaturas donde n es un numero ingresado por teclado #mostrar cuantas temperaturas estan por sobre cero y cuantas estan bajo o igual a cero. sobrecero=0 bajocero=0 veces= int(input("Cuantas temperaturas quiere ingresar ? : ")) for i in range(veces): tempe= float(input("Ing...
from db import Db class Customer: def __init__(self, first_name, last_name, phone, email, address1, address2, postal_code, city, country, customer_id=None, added_by=None): self.first_name = first_name self.last_name = last_name self.phone = phone s...
from sign import Sign class Board: ''' generic board of 3X3 which can represent a classic tic tac toe board and also a board made of other boards which used in super tic tac toe ''' def __init__(self, empty_square_generator): '''function builds new board empty_square_generator -- funct...
""" Given a tuple of numbers, iterate through it and print only those numbers which are divisible by 5 """ myTuple = (5, 6, 20, 33, 45, 62) print("Given list is ", myTuple) for element in myTuple: if (element % 5 == 0): print (element)
import bike_db_access import kiosk_db_access import datetime # Handles most of the logic of the bike rental program Bikes can be checked out # from a kiosk if the kiosk is not empty. Bikes can be returned to a kiosk if # the kiosk is not full. Bikes can also be in transit, meaning that the bike is # not at any kiosk ...
# Program 2: Vypocet faktorialu (rekurzivne) #navratova hodnota 0 def factorial(n): if n < 2: result = 1 else: # else cast prikazu vetveni, jednoradkovy komentar, negeneruje DEDENT decremented_n = n - 1 temp_result = factorial(decremented_n) result = n * temp_result return re...
class Circle(): # class object attribute pi = 3.14 # user defined attribute def __init__(self,radius = 1): self.radius = radius # method def circumference(self): cir = 2 * Circle.pi * self.radius # you can call pi using class becau...
# Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another class Animal(): # perent class def __init__(self): print('Animal created !!') def eat(self): print('I eat grass.') # Ani = Animal() # Ani.eat() class Do...
# How to use python in a console: # python can be executed directly from the command line using "py" or "python" # when wanting to exit python, use exit() # How to run python programs: # py "PATH TO PROGRAM.py" # How Python works: # Python is an Interpreter based language. # Python Code -> Interpreter -> Machine Code...
"""To Define Methods""" # def num_sum(): # print(3 + 2) # num_sum() # # """With Argument""" # def sum_num(n1 , n2): # print (n1 + n2) # # sum_num(3,4) # # """Return Value""" # def sum_num(n1,n2): # """Get some of two numbers # :param n1: # :param n2: # :return : # """ # return n1 + n2 ...
"""Nested Dictionary is a data type which store the another dictionary on a single key d = {'k1' : {'nestk1': 'newvalue1', 'nestk2' : 'newvalue2'}} d['k1']['nestk1'] """ cars = {'BMW':{'model' : '550i', 'year': 2016},'benz':{'model' : 'E350', 'year': 2018}} bmw_model = cars['BMW']['model'] print(bmw_model) print(cars[...
from jogo_da_velha import JogodaVelha humano_escolha, bot_escolha, dificuldade = '','','', while humano_escolha != 'O' and humano_escolha != 'X': # escolha do x ou o e dificuldade try: print('') print('Bem vindo ao jogo da velha, professor Allan!') humano_escolha = input('Escolha X or O: '...
"""Template code for M3C 2016 Homework 3 """ import numpy as np import matplotlib.pyplot as plt def visualize(e): """Visualize a network represented by the edge list contained in e """ def degree(N0,L,Nt,display=False): """Compute and analyze degree distribution based on degree list, q, co...
import copy #Flight Itinerary #Done by: Chiew Jun Hao and Zhang Hao class Flight: def __init__(self, start_city, start_time, end_city, end_time): self.start_city = start_city self.start_time = start_time self.end_city = end_city self.end_time = end_time def __str__(self): ...
board=[["-" for i in range(3)] for i in range(3)] def alleq(l,player=False): return l[0]==l[1]==l[2]==player def myinput(x,y): return (x,y) if board[x][y]=='-' else myinput(int(input("Enter an x value\n")),int(input("Enter a y value\n"))) def gameplay(player): (x,y)=myinput(int(input("Enter an x value\n...
import math number = int(input(" Please enter any Number to find factorial : ")) fact = math.factorial(number) print("The factorial of %d = %d" %(number, fact))
from turtle import * mode('logo') speed(1) shape('turtle') for i in range(5): forward(100) right(72) mainloop()
''' # 1 for number in range(1,11): print(number) #2 start = int(input('Start from: ')) end = int(input('End from: ')) for number in range(start,end + 1): print(number) #3 for number in range(1,11): if number %2 != 0: print(number) #4 size = 5 for i in range(size): print('*' * size) #5 s...
import urllib.request import json def display_album(id): """photo album - take the id from the keyboard and print photo id and titles on the console :param id: An integer id :return: """ with urllib.request.urlopen("https://jsonplaceholder.typicode.com/photos?albumId=" + str(id)) as url: ...
import turtle def circle_for_turtle(): for i in range(4): turtle.fd(x) turtle.rt(90) turtle.shape("classic") x = 40 for i in range(10): circle_for_turtle() turtle.lt(135) turtle.penup() turtle.fd((20**2*2)**0.5) turtle.pendown() turtle.rt(135) x += 40
Chemistry_theory = int(input("Enter your Chemistry Theory Marks (out of 75): ")) if Chemistry_theory > 0 or Chemistry_theory < 75: Chemistry_practical = int(input("Enter your Chemistry Practical Marks (out of 25): ")) Biology_theory = int(input("Enter your Biology Theory Marks (out of 75): ")) Biology_pract...
from sys import argv user_range = int(argv[1]) def demo_range(num): for i in range(num): print i def print_all_evens(num): """Print all even numbers between 0 and num.""" for i in range(2, num, 2): print i def count_down(num): """Count down from num to 0.""" for i in range(num, -...
def sum_of_digits(n): n = str(n) if n[0] == '-': n = n[1::] #m = 0 #for i in range(len(n)): # m += int(n[i]) return sum([int(i) for i in n]) return m print(sum_of_digits(-10))
def is_number_balanced(number): number = str(number) half_n = len(number)//2 if len(number) % 2: number = number[:half_n:] + number[half_n + 1::] left = number[:half_n:] right = number[half_n::] left = [int(i) for i in list(left)] right = [int(i) for i in list(right)] return sum(left) == sum(right) print(i...
import unittest from sort_array import sort_fractions class TestSortFractions(unittest.TestCase): def test_with_two_fractions(self): fractions = [(2, 3), (1, 2)] excpected = [(1, 2), (2, 3)] fractions = sort_fractions(fractions) self.assertEqual(fractions, excpected) def test_with_descending_argument_gi...
_userArray = list() while True: _userinput = input('Please enter a number. Type "Done" when finished') if _userinput == 'Done': break try: _userinput = float(_userinput) except: print('You entered a invalid number') continue _userArray.append(_userinput) print('The l...
# tree.py # Constructor def tree(value, branches=[]): for branch in branches: assert is_tree(branch), 'branches must be trees' return [value] + list(branches) # Selector def root(tree): return tree[0] def branches(tree): return tree[1:] def is_leaf(tree): return not branches(tree) def i...
import unittest from user import User class Test(unittest.TestCase): """ Testing users """ def setUp(self): """Setup method creating user instance""" self.user = User() #User Registration tests def test_registration_empty_name(self): """test account creation with a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # check################################## age = 1 if age >= 18: print('adult'); else: print('teenager'); #变量 #变量的概念基本上和初中代数的方程变量是一致的,只是在计算机程序中,变量不仅可以是数字,还可以是任意数据类型。 #变量在程序中就是用一个变量名表示了,变量名必须是大小写英文、数字和_的组合,且不能用数字开头 a = 123 # a是整数 print(a) a = 'ABC' # a变为字符串 print(a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # check################################## # 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数。可以直接从Python的官方网站查看文档: # http://docs.python.org/3/library/functions.html#abs print(abs(100)); print(abs(-105)); print(abs(12.34)); # print(abs(1, 2));调用函数的时候,如果传入的参数数量不对,会报TypeError的错误,并且Py...