text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- # class 派生类名(基类名)://... 基类名写作括号里,基本类是在类定义的时候,在元组之中指明的。 '''在python中继承中的一些特点: 1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。 2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数 3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。 如果在继承元组中列了一个以上的类,那么它就被称...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 25 14:13:42 2019 @author: armand """ import time import numpy as np import random import matplotlib.pyplot as plt import math import collections import string import itertools import copy import hashlib from advent import * def day1(): arg =...
#среднее арифметическое двух чисел a, b = float(input("Введите a: ")), float(input("Введите b: ")) print("Среднее арифметическое a и b = "+str((a+b)/2)
# Votação cand1 = 0 cand2 = 0 cand3 = 0 cand4 = 0 nulo = 0 branco = 0 print() print("------------------------------------------------------------------------------------") print("Segue abaixo a lista dos candidatos dessa eleição e o seu respectivo número: ") print() print(" Candidato número 1 -> Lula do partido PT...
dia = int(input("Informe o dia que você nasceu: ")) mes = int(input("Informe o mês que você nasceu com dois dígitos: ")) ano = int(input("Informe o ano que você nasceu: ")) if (dia < 1) or (dia > 30): print() print("A data não é válida pois o dia informado está incorreto, deve estar entre 1 e 30.") elif (mes <...
#直到使用者輸入對的 flag = True while flag: try: x=int(input("number:")) except ValueError: print("Error!!") else: print(x) flag = False
import re def is_float(val): if isinstance(val, float): return True if re.search(r'^\-{,1}[0-9]+\.{1}[0-9]+$', val): return True return False def is_int(val): if isinstance(val, int): return True if re.search(r'^\-{,1}[0-9]+$', val): return True return False def is_number(val): return i...
def divisor(num): divisors = [] for i in range(1, num+1): if num %i == 0: divisors.append(i) return divisors def run(): try: num = int(input("numero: ")) try: if num < 0: raise ValueError("Debes ingresar un positivo") print(divisor(num)) print("---") except Value...
import time import pandas as pd import numpy as np #Created By Mgaroub CITY_DATA = { 'chicago': 'chicago.csv', 'newyork': 'new_york_city.csv', 'washington': 'washington.csv' } months = ['january', 'february', 'march', 'april', 'may', 'june'] days = ['sunday','monday', 'tuesday', 'wednesday...
""" Chapter Seventeen - Hard """ from random import randint from collections import deque import sys from heapq import heapify, heappop, heappush, nsmallest # 17.1 # Add two numbers without using any arithmetic operators. # # This method has O(1) runtime. def seventeen_one(a, b): # This methods works for posi...
def reverse(s): answer="" for i in range(0, len(s)): answer+=s[len(s)-i-1] return answer print(reverse("Hello world!"))
#!/usr/bin/env python import sys import os # input comes from STDIN (standard input) for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # split the line into words datas = line.split() # access to AVG column if float(datas[7]) > -9999. and (float(datas[7]) > 27...
# Imports the os module for path manipulation import os def file_finder(folder_dir): """ Skims a specified FOLDER for image MEAS .txts and a SummaryMeteorLog.txt. It then passes back a list containing the list of image .txts and the SummaryMeteorLog.txt. This function should be called wit...
# Imports numpy to use the statistics-related # functions in numpy import numpy as np def get_r_squared(x, y, line): """ Calculates the coefficient of determination, or r-squared, between the line generated by the model and the data points composed of x and y. This value indicates how close the...
import turtle import math def draw_shapes (): draw_interior_triangle() def draw_interior_triangles (): m = 3 # order of the gasket brad = turtle.Turtle() brad.shape("arrow") brad.color("blue", "white") brad.speed(3) brad.forward(n/2) brad.fill(True) brad.le...
from matplotlib import pyplot as plt from collections import Counter from numpy.lib.histograms import histogram #----------------Movie Bar Chart---------------------------# movies = ["Annie Hall", "Ben-Hur", "Casablanca", "Gahndi", "West Side Story"] num_oscars = [5, 11, 3, 8, 10] # plot bars with left x-coordinates...
################################################################################ #Collaberation with myself, Justin, Harold, Steven, and Zach # PART #1 ################################################################################ import string import os from os import listdir import csv import json def countWor...
# Katie Brennan, email kmb327@cornell.edu # Python personal project, user-interactive application utilizing random library # to be continuously edited, improved, expanded, and tested. # 12/01/2019 # https://katiebrennan.github.io import random #python random library from random import shuffle #specific random pkg for ...
question=input('Введите возраст, пожалуйста: ') print(question) ask_user=int(question) def age_comparator(ask_user): if ask_user>=3 and ask_user<=6: return "Малыш ходит в садик" elif ask_user>=7 and ask_user<=18: return "Это не малыш, это школьник" elif ask_user>=0 and ask_user<=3: ...
parola=input ("scrivere la parola da processare:") parola1 =parola [::-1] if parola == parola1: print(parola, "è un polindromo") else: print(parola, "non è un palindromo")
# -*- coding: utf-8 -*- name = input('please input your name:') print('hello',name,'let us count your years old') while True: a = input('your year of birth is:') if a.isdigit(): #判断age是否为数字(正整数) b = 2017 - int(a) print(name,'is',b,'years old now!') if int(a) < 2000: ...
# -*- coding: utf-8 -*- # 定制类 # __getattr__ class Student(object): def __init__(self): self.name = 'Marvin' # Python还有另一个机制,那就是写一个__getattr__()方法,动态返回一个属性 def __getattr__(self,attr): if attr == 'score': return 99 #返回一个属性 if attr == 'age': return lambda: ...
# -*- coding: utf-8 -*- # 从0到99的100个数中,删除所有的偶数! r=list(range(100)) for i in range(len(r)//2): r.pop(i) print('循环条件i:',i) print('处理后的list:',r)
# -*- coding: utf-8 -*- # 高阶函数 # 传入函数 def add(x,y,f): return f(x)+f(y) print(add(-5,6,abs)) # 把函数作为参数传入,这样的函数称为高阶函数, # 函数式编程就是指这种高度抽象的编程范式。 #-------------------------------------------------- # 引入数学模块中的方法 from math import sqrt from math import tan # 高阶函数应用,返回一个数字不同方法计算结果 def same(num, *kw): # 参数检查 if no...
# -*- coding: utf-8 -*- # 枚举类 # Python提供了Enum类, # Enum可以把一组相关常量定义在一个class中,且class不可变,而且成员可以直接比较 # 用Enum为枚举类型定义一个class类型,然后每个常量都是class的一个唯一实例 from enum import Enum Month = Enum('Month',('Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec')) # 这样我们就获得了Month类型的枚举类, # 可以直接使用Mont...
# -*- coding: utf-8 -*- def fact(n): if n==1: return 1 return n * fact(n-1) #递归函数 ===> fact(5) ===> 5 * fact(4) ===> 5 * (4 * fact(3)) ===> 5 * (4 * (3 * fact(2))) ===> 5 * (4 * (3 * (2 * fact(1)))) ===> 5 * (4 * (3 * (2 * 1))) ===> 5 * (4 * (3 * 2)) ===> 5 * (4 * 6) ===> 5 * 24 ===> 120 #栈溢出问题 >>> fa...
# -*- coding: utf-8 -*- def volid(pwd): p = bool(pwd) #判断是否为空,为空则返回False e = bool(6<=len(pwd)<=10) a = any(map(str.isupper,pwd)) b = any(map(str.islower,pwd)) c = any(map(str.isdigit,pwd)) d = not all(map(str.isalnum,pwd)) return all([p,e,a,b,c,d]) PW=input('please enter your password:') pr...
# -*- coding: utf-8 -*- # 多重继承 class Animal(object): pass # 大分类 class Mammal(Animal): def base(self): print('Mannal') class Bird(Animal): pass # 各种动物 class Dog(Mammal): # 狗狗 pass class Bat(Mammal): # 蝙蝠 pass class Parrot(Bird): # 鹦鹉 pass class Ostrich(Bird): # 鸵鸟 pass # 按功能,定...
# -*- coding: utf-8 -*- # 函数式编程Functional Programming # ①求和 def sum(start,end,handle): total = 0 for x in range(start,end+1): total += handle(x) return total # 定义处理的handle函数 # 求1到100的和 def ident(n): return n print(sum(1,100,ident)) # 求1到100每项平方加1的和 def square_plus_one(n): return n**2+1 p...
import cv2 # open cv is a open source computer vision library. trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # in we are going to detect face. image = cv2.imread("image3.jpg") # convert in the gray scale grayscaled_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # detect face. fa...
## Advanced Python Decorator Functions class User: def __init__(self, name): self.name = name self.is_logged_in = False def is_authenticated_decorator(function): def wrapper(*args, **kwargs): if args[0].is_logged_in == True: function(args[0]) return wrapp...
import turtle import time from random import randint score = 0 delay = 0.1 # Set up the screen window = turtle.Screen() window.setup(width = 500,height = 500) window.bgcolor("green") window.tracer(0) # Head of Snake head = turtle.Turtle() head.speed(0) head.shape("square") head.color("black") head.penup() head.goto(...
# crie um programa que leia dois numeros e mostre a soma entre eles n1 = int(input("Digite um valor n1:")) n2 = int(input("Digite um valor n2:")) soma = n1+n2 print('{} + {} = {} '.format(n1,n2,soma))
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests return linear_search_iterative(array, i...
"""Utility functions for the potatoes projet.""" import string try: from secrets import choice # Python3.6+ only except ImportError: # pragma: no cover from random import choice def random_key(length): """Return a random alphanumeric string of length 'length'.""" alphabet = st...
class Int_Node(object): """A simple node object that holds an integer""" def __init__(self, n): self.num = n self.kids = set() #no two nodes are alike def children(self): return self.kids def number(self): return self.num def add_child(self, node): self.kids.a...
import random import os import sys # I intended to skip the classes for our group work or group meeting # so we can try working together but they didn't formed a plan to meet. def rules(): # will be shown once per run of the code os.system("cls") sys.stdout.write("\033[1;36m") print('''Greetings! Here ...
numbers = [] input = open("input.txt") for line in input: numbers.append(int(line)) found = False for number in numbers: for number2 in numbers: if (number + number2 == 2020): print("result: " + str(number * number2)) found = True break if found: break ...
def findAndCount(searchedColor, parentsAndTheirChildren, possibleColors): for parent, children in parentsAndTheirChildren.items(): for child in children: if searchedColor == child["color"]: if parent not in possibleColors: possibleColors.append(parent) ...
def isClose(loc1, loc2): if loc1[0] >= loc2[2]: return False elif loc1[2] <= loc2[0]: return False elif loc1[1] <= loc2[3]: return False elif loc1[3] >= loc2[1]: return False else: areaFunc = lambda top, right, bot, left : (bot-top) * (right-left) H = [] V =...
# 老男孩Python全栈13期练习题 考试时间4h # 一、简答题(30) # 1、常用字符串格式化的方式有哪些?并说明他们的区别(4) # '{}'.format('') # s1 = '%s'% '' # s2 = '77' # s3 = f'22{s2}' # print(s3) # 2、L = range(100) (4分) # 1) 取第一到第三个元素_______ # L = range(100) # print(list(L)[0:3]) # 2) 取倒数第二个元素_______ # print(list(L)[-2]) # 3) 取后十个元素_______ # print(list(L)[90:]) # 4) 把L...
import sqlite3 from datamanager import DataManager #turunan dari kelas data manager class Person(DataManager): # untuk memasukkan data baru ke tabel person def setDataPerson(self, Nama, Alamat, NomorHP): # querynya insert val parameter nama, alamat, nohp self.query = 'INSERT INTO Person (Nama, Alamat, No...
#code for printing the extention of the filename entered by the user filename = input("Input the Filename: ") f_ext = filename.split(".") print ("The extension of the file is : " + repr(f_ext[-1]))
import sys row0_cell0 = '-' row0_cell1 = '-' row0_cell2 = '-' row1_cell0 = '-' row1_cell1 = '-' row1_cell2 = '-' row2_cell0 = '-' row2_cell1 = '-' row2_cell2 = '-' def check_winner(): # Check rows. if ( row0_cell0 == 'X' and row0_cell1 == 'X' and row0_cell2 == 'X' ): print "X Wins!" sys....
#!usr/bin/python # -*- coding: utf-8 -*- """Jeu du pendu.""" import fonctions import donnees username = fonctions.get_user() print(('Hello %s!') % (username)) # Recuperation du score courant scores = fonctions.get_scores() if username not in scores.keys(): print "C'est votre premiere partie, bienvenue!" sco...
## 2*rolls in line 58 needs to become dynamic based on the max amount of production per roll ## need to go from raw counts to frequency -- figure out why NewHist is giving me 0's ## also make the product, basket, number of rolls interactive ## make the graph a function of a choice or for all (wood, brick, etc.) impor...
import time from collections import Iterable from collections import Iterator class Classmate(object): """ this is a iterator """ def __init__(self): self.names = list() self.current_num = 0 def add(self, name): self.names.append(name) def __iter__(self): ...
pocketMoney = int (input("enter your pocket money: ")) if(pocketMoney > 500): print("you are a rich kid") elif(pocketMoney > 100): print("you have a good life") else: print("I know what you feel")
import random def alphabet(capitalized = True): """Returns word list of the alphabet. Args: capitalized (bool): Whether the alphabet is capitalized Returns: string: The alphabet string """ return [chr(i) for i in (range(65,91) if capitalized else range(97,123))] def str_to_nu...
a = input() s = input() while True: if len(a) < 8: print("Короткий!") a = input() s = input() elif len(a) > 8 and "123" in a: print("Легкий!") a = input() s = input() elif len(a) > 8 and "123" not in a and s != a: print("Различаются.") a = inpu...
a = int(input()) s = int(input()) d = int(input()) while a != 0 or s != 0 or d != 0: k = int(input()) ka = int(input()) if k == 1: a -= ka print(a, s, d) elif k == 2: s -= ka print(a, s, d) elif k == 3: d -= ka print(a, s, d)
a = int(input()) b = int(input()) if a > b: a = a - (a - b) print(a, b) elif a < b: b = b - (b - a) print(a, b) elif a == b: print(a, b) while a > 0 or b > 0: d = int(input()) g = int(input()) if d == 1: while g > a: g = int(input()) elif d == 2: while g >...
# 終極密碼 from microbit import * import random X = random.randint(0, 10) Y = 0 display.show(Image.HAPPY) while True: if button_a.was_pressed(): Y = Y + 1 display.show(Y) if Y > 10: Y = 0 display.show(Y) if button_b.was_pressed(): Y = Y - 1 display.sho...
""" 堆是一个完全二叉树:完全二叉树要求,除了最后一层,其他层的节点个数都是满的,最后一层的节点都靠左排列。 堆中每一个节点的值都必须大于等于(或小于等于)其子树中每个节点的值 """ class Heap(object): def __init__(self, capacity=64): self._capacity = capacity self._data = [] self._size = 0 # 元素个数 def headpush(self, value): """ :return: """ ...
""" 只出现一次的数字 问题: 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 说明: 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 例如: 输入: [4, 1, 2, 1, 2] 输出: 4 解决思路: 位运算。异或运算有以下三个性质。 1、任何数和 0 做异或运算,结果仍然是原来的数,即 a ^ 0 = a。 2、任何数和其自身做异或运算,结果是 0 ,即 a ^ a = 0。 3、异或运算满足交换律和结合律,即 a ^ b ^ a = b ^ a ^ a = b ^ (a ^ a) = b ^ 0 = b。 """ class Soluti...
""" Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not already p...
#Programmet beräknar avståndet mellan två punkter i ett tvådimensionellt koordinatsystem import math #Användaren skriver in de två första punkterna x1, y1= [float(x) for x in input('Ange första punketns koordinater: ').split()] x2, y2= [float(y) for y in input('Ange andra punketns koordinater: ').split()] #Beräknar avs...
#Programmet konverterar miles/gallon till liter/mil #Användaren skriver in bensinförbrukningen i miles/gallon milesGallon = float(input('Skriv in bensinförburkningen i miles/gallon: ')) #konverterar miles/gallon till km/gallon km = float(milesGallon * 1.609) # milfaktorn = float(10 / km) liter = float(milfaktorn * 3.7...
#Programmet kommer att skriva ut n antal + tecken. För varje rad kommer antalen + tecken minska med 1 tills det bara blir ett + tecken kvar n = int(input("Antal rader? ")) for i in range(n, 0, -1): for j in range(1, i+1): print('+', end='') print()
#Programmet räknar om Fahrenheit till Celsius fahrenheit = float(input('Ange grader i Fahrenheit')) celsius = (fahrenheit - 32) * (5/9) print(f'Antal grader i celsius: {celsius:.1f}C')
# Programmet avgör vilket abonnemang som är mest prisvärt för användaren min = int(input('Hur många minuter ringer du i genomsnitt varje månad? ')) if min < 33: print('Kontant är det bästa alternativet för dig') elif min > 33 and min < 66: print('Normal är det bästa alternativet för dig') else: print('Plus...
import functools import contextlib def to_decorator(wrapped_func): """ Encapsulates the decorator logic for most common use cases. Expects a wrapped function with compatible type signature to: wrapped_func(func, args, kwargs, *outer_args, **outer_kwargs) Example: @to_decorator def foo(...
#!/usr/bin/python3 """ function that writes a string to a text file (UTF8) and returns the number of characters written """ def write_file(filename="", text=""): """ Prototype: def write_file(filename="", text=""): """ with open(filename, "w") as file: return(file.write(text))
#!/usr/bin/python3 """ A base class who can: Returns the JSON string representation. Writes the JSON string representation. Returns the list of the JSON string representation. Returns an instance with all attributes already set. Returns a list of instances. """ import json class Base: """ Base class """ ...
#!/usr/bin/python3 for x in range(122, 96, -2): print("{:c}{:c}".format(x, (x - 1) - 32), end="")
#!/usr/bin/python3 for x in range(99): hx = hex(x) print("{:d} = {}".format(x, hx))
import random def make_sudoku(size): if isinstance(size, int) and size > 0 and size <= 42: flagg = False while flagg == False: matrix = [] x = 0 rand = [] count = 0 for i in range(size**2): mat = [] ...
a1 = 12345 b1 = 567 a2 = 1233211 b2 = 12128 a3 = 123 b3 = 45 def counter(a, b): a = str(a) b = str(b) count = 0 list_a = [] list_b = [] def clean_list(list1): if list1 == []: return (list1) list2 = [] list2.append(list1[0]) for i in range(1, len(list1)): flag = False fo...
import sys n = int(sys.argv[1]) a = 0 b = 1 if n == 0: print (a) else: for counter in range (n-1): b = b + a a = b - a print (b)
import matplotlib.pyplot as plt import numpy as np def canvas (): return plt def plot_points (xs, ys): return plt.scatter (xs, ys) def plot_function (f, a=-10,b=10, den=5): x = np.linspace (a, b, 20 * (b-a)) y = [f (_x_) for _x_ in x] return plt.plot (x, y) def show (): plt.show ()
import os import csv #specify file to pull from: budget_data = os.path.join("Resources", "budget_data.csv") #Name Variables Month=[] Profit_Losses=[] Change_PL=[] #Open CSV with open(budget_data) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvreader) for row in csvr...
import math print("This only works if you have a proper quadratic formula,") print("so make sure you have one") print("also note that if the program returns an error, there is no solution") print(" ") print("what's a?") aVar = input() print("what's b?") bVar = input() print("what's c?") cVar = input() # these outp...
import sys '''This is a simply argument parser, for training purposes''' version = 0.1 def parse_opts(opts): opts = sorted(opts) for opt in opts: if opt == "--help" or opt == "-h": print("""Help Info\n------\nThis program is a simple argument parser\n\n""") elif opt == "--version"...
#!/usr/bin/python print "**************normal varibles **********************" mynumber = 86 # A integer variable assignment myfloatnumber = 86. 11 # A float variable assignment myname = “imran” # A string variable assignment print mynumber print myfloatnumber print myname print "**************string varibles ******...
from itertools import islice, count def is_even(number): return number % 2 == 0 evens = islice((number for number in count() if is_even(number)), 200) executed_evens = list(evens) print(executed_evens) print(any([True, False, False])) print(all([True, False, False])) print(any(is_even(number) for number in range(...
# -*- coding:utf-8 -*- import os fout=open('tree_test.txt','w') def directory_traverse(path,depth=0,isFinal=False): if os.path.isfile(path): try: pass except: pass elif os.path.isdir(path): for i in range(depth): print >>fout,'', for j in range(1): print >>fout,' ', if not isFinal: print >>...
class Qustoin: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer question_prompts = [ "what is the capital of egypt?\n(a) cairo\n(b)alexandra \n(c)giza \n\n", "What is result of 5*5?\n(a) 30\n(b)25 \n(c)30 \n\n", " how is best player?\n(a) tika\n(b)salah\n(c...
import re def arithmetic_arranger(problems, showAnswers = False): if len(problems) > 5: return "Error: Too many problems." line1 = [] line2 = [] line3 = [] answers = [] for problem in problems: match = re.match('^(.+) (.) (.+)$', problem) if match: top = ma...
#taking user inputs.... size_input = input("How big is your house is(in square feet): ") c_meter = float(size_input) s_meter= c_meter/10.8 print(s_meter) h_input = input("Enter your age: ") e_age = int(h_input) age = e_age * 60 * 60 * 60 print(f"your age {e_age} is in seconds is:{age}")
class Person: def __init__(self,name,age): self.name = name self.age = age def __str__(self): return f"hello {self.name}, is {self.age} year old" def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"<P...
num = 10 #user_input = input("Enter (Y/n) if you want to play: ") while True: user_input = input("Enter (Y/n) if you want to paly: ") if user_input == "n": break user_num = int(input("Enter the number: ")) if user_num == num: print("You won") else : print("You loss") ...
class Book: def __init__(self, name: str, page_count: int): self.name = name self.page_count = page_count self.page_read = 0 def __repr__(self): return(f"Book{self.name},read {self.page_read} pages out of {self.page_count}") def read(self, pages: int): if self.pag...
def my_fun(**add): print(add) my_fun(name="Aabid",age=22,dum=45,fun=10) def sum(**add): print(add) details = {"name":"Aabid", "age": 22} sum(**details) def test(**arg): print(arg) def value(**arg): test(**arg) for x, z in arg.items(): print(f"{x}: {z}") value(name="Juned",age="22")...
import math from sets import Set st = 'abcdefghijklm' # input string #st = 'aaaaaaaaaaaaa' # st = '00010101011110' # Shannon entropy for this would be 1 bit/symbol print 'Input string:' print st print stList = list(st) alphabet = list(Set(stList)) # list of symbols in the string print 'Alphabet of symbols in the stri...
#!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): a = min(arr) max_lst = arr[:] max_lst.remove(a) b = max(arr) min_lst = arr[:] min_lst.remove(b) min_lst_sum = 0 max_lst_sum = 0 for i in min_lst: ...
# Name: Jacob Wilson # Course: CS344_400 # Assignment: Program 5 Python Exploration # Due Date: 11/26/16 # Desription: A simple Python program creates three # files containing 10 random lower-case characters # and displys the contents of these files. Also # chooses two random integers and multiplies them # together...
import tkinter as tk from tkinter import font import requests degree_sign = u"\N{DEGREE SIGN}" def format_response(weather): try: name, code = weather["name"], weather["sys"]["country"] desc = weather["weather"][0]["description"] temp = weather["main"]["temp"] final_st...
mybag = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def printInventory(bag): print('Inventory:') itemTotal = 0 for k, v in bag.items(): print(str(v) + ' ' + str(k)) itemTotal += v print('Total ...
#! python3 """ Regex Version of strip() Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in...
def fibo(n): """Calculates n-th fibonacci number""" prev = 0 curr = 1 if n == 0: return prev if n == 1: return curr for i in range(n-1): prev, curr = curr, prev + curr return curr if __name__ == "__main__": """Print first 20 fibonacci numbers""" for n in ran...
gameBoard = [ '-', '-', '-', '-', '-', '-', '-', '-', '-', ] comp = 'x' human = 'o' class Node: def __init__(self, state): self.state = state self.leafs = [] self.value = 2 def addLeafs(self, state): self.leafs.append(Node(state)) def getLeafs(self): return self.leafs def getState(self): return ...
import time time.clock() import queue as Q from Graph import Graph from Solution import Solution def main(): # Initialisation and input data g = Graph('N17.data') #Graph opt_val=0 max_iter=1000 #Max iterations allowed iter = 0 #Iteration indicator tabu...
a = 3 b = 2 if a > 2 else 1 # if a>2: # b = 2 # else: # b = 1 print(b)
#!/usr/bin/env python # -*- encoding: utf-8 -*- from kotonoha import replacer def test_replace_urls_with_a_text_without_url(): text = 'This text does not contain any url' assert replacer.replace_urls(text) == text def test_replace_urls_with_a_text_that_contains_an_url(): text = 'This text contains an ur...
number1 = input("Enter whole number: ") number2 = input("Enter decimal number: ") integerNumber = int(number1) floatNumber = float(number2) roundNumber = int(round(floatNumber)) print(integerNumber) print(floatNumber) print(roundNumber)
good = "Good" day = "Day" name = input("Enter your name: ") print(good + " " + day + " " + name)
int1 = int(input("Enter a whole number: ")) int2 = int(input("Enter another whole number: ")) bool = True if (input("sum? y/n: ") == "y") else False if (bool): print(int1 + int2) else: print(int1 * int2)
from numpy import * from matplotlib import pyplot as plt def mandelbrot( h,w, maxit=40): #20 ''' Returns an image of the Mandelbrot fractal of size (h,w). ''' y,x = ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ] #y,x = ogrid[ -0.25:0.25:h*1j, -1.8:-1.3:w*1j ] #y,x = ogrid[ -0.05:0....
#!/usr/bin/env python3 from turtle import * # Draw a Koch snowflake def koch(a, order): if order > 0: # A line Koch for the first generation for i in [60, -120, 60, 0]: koch(a/3, order-1) left(i) else: forward(a) def koch_curve(size, order): # Choose col...
import turtle iterations = 5 #the number of generations startLength = 200 #Length of the generation 0 line turtle.up() turtle.setpos(-startLength*3/2,0) turtle.speed(0) #Axiom Dragon = "F" #make the L-System we want to process for i in range(iterations): Dragon = Dragon.replace("F","FLFRFRFFLFLFRF") turtle.do...