text
stringlengths
37
1.41M
a, b = map(int, input().split()) hantei = (a*b) % 2 print(("Odd" if hantei else "Even"))
class temp(object): def __init__(self, from_value, to_value, temp_value): self.from_value = from_value self.to_value = to_value self.temp_value = temp_value def c_to_c(self, temperature): return temperature def c_to_k(self, temperature): return temperatu...
def funcs(x, y, z): m = z a = x b = y rem = -1 while(rem!=1): temp1 = m temp2 = a quot = m//a rem = m%a print(m,"=", a, "(", quot, ") + ", rem) m = a a = rem return -(temp1//temp2) def GCD(x, y): while(y): x, y = y, x % y return x print("Enter the values of a, b, m for the equation ...
import socket import os s = socket.socket() print "Socket successfully created" port = 12345 s.bind(('', port)) print "socket binded to %s" %(port) s.listen(5) print "socket is listening" def comp_cube(n): return n**3 while True: c, addr = s...
#cuvant = "a _ _ a _ _ t" #alfabet #word = "address" import random from random_word import list_of_random_word word = random.choise(list_of_random_word) word_list = [] unique_letter = set(word) for item in word: if item != word[0] and item != word[-1]: word_list.append('_') else: word_list.appe...
import csv from datetime import datetime import logging import os """ The str(f|p)time format used in the database files and the expected length of the formatted strings. """ CURRENT_DT_FORMAT = '%Y-%m-%d %H:%M:%S' CURRENT_DT_FORMAT_LEN = 19 ARCHIVE_DT_FORMAT = '%Y-%m-%d %H:%M' ARCHIVE_DT_FORMAT_LEN = 16 class D...
# Standard Calculator # from tkinter import * import math import parser import tkinter.messagebox root = Tk() root.title("Standard Calculator") root.configure(background = 'white') root.resizable(width=False, height=False) root.geometry("480x568+450+90") calc = Frame(root) calc.grid() # =======...
import csv,json,sys def menteeCleaner(fileName): try: menteeCsv = csv.reader(open(fileName, 'rb')) mentees = list(menteeCsv) dictmentees = [] for row in mentees: tempDict={} tempDict['name'] = row[0] tempDict['rollNo'] = row[1] tempDict...
""" Create Tony's tic-tac-toe board. Creates Tony's tic-tac-toe board. """ import tkinter as tk root = tk.Tk() win = tk.Canvas(root ,width = 320, height = 320) root.title = ("tic tac toe") win.pack() win.create_line(10,110,310,110,fill="black",width = 2) win.create_line(10,210,310,210,fil ="black", width ...
# NumPy # numpy is used for scientific computing. # contains array objects (for vectors, matrices, images, more) and linear algebra functions # the array object lets you do important operations like matrix multiplication, transposition, solving equation systems, vector multiplication, normalization - needed for things ...
def knapsack(a, target): if len(a) == 0: return 0 if len(a) == 1: if a[0] <= target: return a[0] else: return 0 if a[0] <= target: return max(a[0] + knapsack(a[1:], target - a[0]), knapsack(a[1:], target)) else: return knapsack(a[1:], target) if __name__ == '__main__': n = int(input().strip()) l...
def main(): n = int(raw_input()) team_wise_problem_solved = [] for i in range(n): temp = raw_input() temp = temp.strip().split() team_wise_problem_solved.append((int(temp[0]), int(temp[1]))) team_standings = sorted(team_wise_problem_solved, key = lambda x: x[1], reverse=True) for i in team_standings: ...
n = int(raw_input()) if n == 1: print 1, 2, 3 elif n == 2: print 3, 4, 5 else: print -1
testlist = [1,24,3,5,6,8,11,13,16,19] def bubble_sort(l): swap = False while not swap: print ("bubble sort: " + str(l)) swap = True for j in range (1, len(l)): if l[j-1] > l[j]: swap = False temp = l[j] l[j] = l[j-1] l[j-1] = temp print ("") print (bubble_sort(testlist)) print (testlist)
#square numbers using list comprehension numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] squared_numbers = [n*n for n in numbers] print(squared_numbers) #filter even numbers numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] even_numbers = [n for n in numbers if n % 2 == 0] print(even_numbers) #compare two docs, and com...
#new_dict ={new_key: new_value for item in list} names = ['Alex', 'Brad', 'Chelsea', 'Don', 'Edward', 'Fred'] import random student_scores = {student:random.randint(1, 100) for student in names} #check out which students passed the test, got over 60 points #passed_students = { int(student) > 60 for student in student...
try: a=str() print(a.append()) x=int(input('Enter a first number')) y=input('Enter a second number') print('result',x//y) print('result',x+y) except AttributeError: print('Error') except TypeError: print('Not possible') except ValueError: print('E...
import pandas as pd from mysql.connector import Error from mysql_tutorial.coffee_sale.connection_pool import DatabaseConnectionPool from mysql_tutorial.query.fetch_query import query_with_fetchall2 def delete_product(sql, code): try: conn = DatabaseConnectionPool.get_instance().get_connection() c...
import random as rnd def random_number(): return rnd.randint(1, 46) def bubble_sort(generate_list): for cnt in range(len(generate_list)): for i in range(len(generate_list) - 1): if generate_list[i] > generate_list[i + 1]: # generate_list[i], generate_list[i + 1] = generat...
#-*- coding:utf-8 -*- # Fibonacci series: # the sum of two elements defines the next a, b = 0, 1 while a < 10: print(a) a, b = b, a+b print('>>>>>>>>') a, b = 0, 1 while a < 1000: print(a, end=', ') a, b = b, a+b print() print('>>>>>>>>') print(2+2) # 나눗셈 (/) 은 항상 float를 돌려줍니다. 정수 나눗셈 으로 ...
import sqlalchemy from sqlalchemy import Table, Column, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() """ many to one 관계에서 1. parent 테이블을 참조하는 child 테이블에 외부 키를 배치 2. 하위 항목이 나타내는 항목 모음을 참조하여 상위에 relationship()를 지정 1. cla...
# str.format() 메서드의 기본적인 사용법 print('We are the {} who say "{}!"'.format('knights', 'Ni')) # 중괄호와 그 안에 있는 문자들 (포맷 필드)은 str.format() 메서드로 전달된 객체들로 치환 # 중괄호 안의 숫자는 str.format()메서드로 전달된 객체들의 위치를 가리키는데 사용 print('{0} and {1}'.format('spam', 'eggs')) print('{1} and {0}'.format('spam', 'eggs')) # str.format() 메서드에 키워드 인자가 사용...
import matplotlib.pyplot as plt from matplotlib_tutorial.graph_bar.bar import graph_config class HistoDraw(): def __init__(self): self._math = [76, 82, 84, 83, 90, 86, 85, 92, 72, 71, 100, 87, 81, 76, 94, 78, 81, 60, 79, 69, 74, 87, 82, 68, 79] graph_config('히스토그램 예제', 18) def simple_histo1(s...
""" namedtuple() collections.namedtuple() 함수는 필드명과 클래스명을 추가한 튜플의 서브클래스를 생성하는 팩토리 함수로서 디버깅할 때 유용 """ from collections import namedtuple City = namedtuple('City', 'name country population coordinates') tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) print(tokyo) print(tokyo.population, '\n', tokyo[1], '\n'...
import collections Card = collections.namedtuple('Card', ['rank', 'suit']) print(type(Card), Card, dir(Card)) ranks = [str(n) for n in range(2, 11)] + list('JQKA') print(ranks) suits = 'spades diamonds clubs hearts'.split() print(suits) card_list = [Card(rank, suit) for suit in suits for rank in ranks] ...
""" Project 3: Problems vs Algorithms Problem 6. Max and Min in a Unsorted Array We look for smallest and largest integer from a list of unsorted integers. Time: O(n), where n is the input size. It scans the array of int once. Space: O(1) """ def get_min_max(ints): """ Return a tuple(mi...
for i in range(1, 1000, 2): number = i ** 3 summa = 0 j = 1 while True: temp = number % 10**j // 10**(j-1) summa += temp if number // 10**(j-1) == 0: break j += 1 if summa % 7 == 0: print("число:", number, "sum:", summa)
def best_result(line, time_stamp): bus_found = False wait_time = 0 while not bus_found: for b in line: if time_stamp % b == 0: print(wait_time, b) return wait_time * b wait_time += 1 time_stamp += 1 def main(): line = [] ...
class Solution(object): def clock(self, S, T): count = 0 startSec = self.tranToSec(S) endSec = self.tranToSec(T) print("startSec:{}, endSec:{}".format(startSec, endSec)) for sec in range(startSec, endSec+1): hour = self...
#PROGRAM TO PRINT TRIANGULAR STAR PATTERN row = int(input("Enter number of rows: ")) for i in range(1,row+1): print("*"*i) ''' OUTPUT: Enter number of rows: 10 * ** *** **** ***** ****** ******* ******** ********* ********** ''' """ Points to look for: 1. for loop 2. 'in' keyword 3 range() funct...
#PROGRAM TO FIND IF NUMBER IS EVEN OR ODD num = int(input("Enter any number to check: ")) if (num % 2 == 0): print(f"{num} is an EVEN number") else: print(f"{num} is an ODD number") """ points to look for: 1. input() function 2. if-else statement 3. f- strings (in line 6 and line 9) """
hexa = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "A", 11: "B", 12: "C", 13: "D", 14: "E", 15: "F", 16: "G" } class Restas(object): def __init__(self): pass def restas(sel...
x = input().split() if(x[1] == "+"): if(x[0] == "x"): print(int(x[2]) + int(x[4])) elif(x[2] == "x"): print(int(x[0]) + int(x[4])) elif(x[4] == "x"): print(int(x[0]) + int(x[2])) elif(x[1] == "-"): if(x[0] == "x"): print(int(x[2]) + int(x[4])) elif(x[2] == "x"): ...
import category def main(): header() menu() def header(): print(""" --------------------------------------- ---------Financial Application--------- ---------------------------------------""") def menu(): while True: print(""" ...
perguntas = { 'Pergunta 1': { 'p': 'Quanto é 1x2', 'respostas': {'a': '5', 'b': '6', 'c': '2', 'd': '1'}, 'respCerta': 'c', }, 'Pergunta 2': { 'p': 'Quanto é 3x5', 'respostas': {'a': '5', 'b': '15', 'c': '21', 'd': '9'}, 'respCerta': 'b', }, ...
def mean(value): if isinstance(value, dict): average = sum(value.values()) / len(value) else: average = sum(value) / len(value) return average student_grades = {"Jonson": 91, "Terry": 88, "Sims": 75} print(mean(student_grades)) monday_temperatures = [9.1, 8.8, 7.6] def weather_condition(...
class Employee: raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = "{}.{}@gmail.com".format(first, last) #------------------------------------------------------------- class Developer(Employee): raise_amt = 1.10 def __init__(self, first...
from matplotlib.pyplot import draw_if_interactive from intruder import V_INTR from constants import DECIMAL_PLACES from math import fmod, isclose, sqrt, sin, cos, atan2 # Average drone flies ~12mph and a human walks at 3-4mph, jogs 4-6mph, and runs 8-10mph. # These are very loose values though and have quite a bit of ...
def greeting(language: str = "en") -> str: """ Return a greeting """ if language == "da": return "Hej Moneyflow!!" else: return "Hello Moneyflow!!"
#!/usr/bin/python import sys import math def find(j): ''' This functions takes an incoming value 'j' and calculates the numberof divisors j has. ''' s=2 value=0 while s <= math.floor(math.sqrt(j)): value+=((math.floor(j/s))-(math.floor((j-1)/s))) s+=1 return value if __name__ == '...
#!/usr/bin/python import sys import generateprimes def newfunc(m): m=int(m) for eachnum in range(2, m): k=3/2 compareme=(eachnum**k) print "here is the 'compare-me' to the power of 3/2: ", compareme comparemeagain=compareme/2 comparemeagain=int(comparemeagain) g...
#!/usr/bin/python import math def Is_Prime(p): ''' This function determines if a given number 'p' is a prime number or not. ''' p = int(abs(p)) x = math.floor(math.sqrt(p)) a = 3 #z=x if p == 0: return False elif p == 1: return False elif p == 2: return ...
#this function will take and return the #first letter of the name def get_initial(name): initial = name[0:1].upper() return initial # Ask for someone's name and return the initials first_name = input('Enter your first name: ') middle_name = input('Enter your middle name: ') last_name = input('Enter yo...
a = float(input("Enter a number. ")) b = float(input("Enter a number to divide by. ")) print(f"The answer is {a/b}.")
def subtotal(orderAmt, salesTax): subtotal = float(orderAmt) * (1 + float(salesTax)) return subtotal firstOrderTotal = subtotal(300, .08) secondOrderTotal = subtotal(400, .06) thirdOrderAmount = input("What was the order amount? ") thirdTax = input("Enter your Sales tax rate.") thirdOrderTotal = su...
a=[-1,-2,-3,0,1,2,3] print(a) for i in a: if(i<0): print(i) print("negative") if(i>0): print(i) print("positive") if(i==0): print(i) print("zero")
import tkinter def main(): widget = tkinter.Tk() widget.title("Sample") button = tkinter.Button(text = "hello", command = display_button_message) button.place(x = 100, y = 50) label = tkinter.Label(text = "click here") label.place(x=35, y = 50) widget.mainloop() def display_button_mess...
class Combinacion: def __init__(self, nombreobjeto, objeto1, objeto2, descripcion): self.nombreobjeto = nombreobjeto self.objeto1 = objeto1 self.objeto2 = objeto2 self.descripcion = descripcion def getObjetosComp(self): return [self.objeto1, self.objeto2] ...
""" This is a very brief introduction to numpy. Some examples are adapted from [here](https://cs231n.github.io/python-numpy-tutorial/#numpy). For a much more comprehensive introduction, see the [official quickstart guide](https://numpy.org/devdocs/user/quickstart.html). What is numpy? In [it's own words](https://numpy...
class Tree: """Abstract base class representation a tree structure""" class Position: """An abstraction representing the location of a single element""" def element(self): """Return the element stored at this position""" raise NotImplementedError('must be im...
"""Class and methods for handling ingredient information.""" from datetime import date class Ingredient: """Class that holds the ingredient information. Attributes: ingr_id: Ingredient's id in the database. content: Ingredient's name. date_added: The date the ingredient was added to th...
""" Build a dataframe in pandas """ import pandas as pd def test_run(): start_date = '2010-01-22' end_date = '2010-01-26' # this creates an array of dates in the range given: dates = pd.date_range(start_date, end_date) print dates # print the array elements like any array print dates[0]...
n = input("nhap phan tu :") j=[] for i in range(2, n/2): if (n%i == 0): print("snt") print("not SNT")
answers = { "qYesNo": { "label": 's/n', "true": ["s", "S", "y", "Y", "si", "Si"], "false": ["n", "N", "No", "no"] } } def qYesNo (label): ans = None answersYesNo = answers["qYesNo"]["true"].copy() answersYesNo.extend(answers["qYesNo"]["false"]) while ans not in answersYe...
from interface import Interface class MainMenu: def __init__(self): self.choices = { "1": self.run_daily_test, "2": self.run_emergency_test, "3": self.run_history, "4": self.run_appeal, "5": self.run_quit } def display_menu(self): ...
# 拼装一个文字游戏 # 名词 形容词 动词 who = input("please input a name") something = input("please input what do you want create") describe = input("please descirbe your create with a word") print(who, "use python build a ", something, ". it's very ", describe, ". i will be a cool geek!")
# we use return statement in the function when we use print statement outside from the function #it basically return the value of function which can be print outside from the function def cube(num): num*num*num print(cube(2)) #above code give the result none because we print the function outside the fu...
secrate_word= "rocket" print("Hint: fly over sky with fast speed") guess="" guess_count=0 guess_limit=4 out_of_guess=False while guess!=secrate_word and not(out_of_guess): if guess_count<=guess_limit: guess = input("enter guess: ") guess_count += 1 else: out_of_guess = True...
# Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. # An input string is valid if: # Open brackets must be closed by the same type of brackets. # Open brackets must be closed in the correct order. # Note that an empty string is also considered valid...
class Solution: """ @param A: sorted integer array A @param B: sorted integer array B @return: A new sorted integer array """ def mergeSortedArray(self, A, B): # write your code here C = [] left, right = 0, 0 while left < len(A) and right < len(B): if ...
import collections #栈这种数据结构满足LIFO后进先出的规则,如果想要首先处理最后一个元素那么就可以考虑栈的结构 import copy class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] #用队列实现栈 #方法1:用一个队列暂存元素 class MyStack: def __init__(self): """ ...
#外函数返回内函数的引用 def out_fuc(): out_params = 1 def in_fuc(): print(out_params) return True return in_fuc b = out_fuc() b() #内函数对外函数的临时变量进行调用 def out_fuc(): out_params = 1 def in_fuc(): # out_params = out_params + 1 print(out_params) return True return in...
class Solution: # 给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。 #方法1:使用求和 def missingNumber(self,nums): len_num = len(nums) sum = (1+len_num)*len_num/2 for i in range(len_num): sum = sum-nums[i] return int(sum) #*方法2:位运算 def missingNumber...
from time import time, localtime, sleep class Clock(object): """数字时钟""" def __init__(self, hour=0, minute=0, second=0): self._hour = hour self._minute = minute self._second = second @classmethod def now(cls): ctime = localtime(time()) return cls(ctime.tm_h...
import random from game_files.game_config import (STARTING_BUDGET, PURCHASE_PRICE_ICE, PURCHASE_PRICE_CONE, OPERATING_COST) def get_weather(): """Weather Is randomly generated integer between -10 and 40""" ...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv from collections import defaultdict with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务1: 短信和通话记录中一共有多少电话号码?每个号码只统计一次。 ...
# -*- coding: utf-8 -*- __author__ = 'Anders Mølmen Høst' __email__ = 'anderhos@nmbu.no' """ From Book: A Primer on Scientific Programming with Python Author: Hans Petter Langtangen Editition: 5th Edition Year: 2016 Ex 3.23: Wrap a formula in a function """ from math import * """ M_s = 47 # mass of small egg m...
# -*- coding: utf-8 -*- __author__ = 'Anders Mølmen Høst' __email__ = 'anderhos@nmbu.no' """ From Book: A Primer on Scientific Programming with Python Author: Hans Petter Langtangen Editition: 5th Edition Year: 2016 Exercise 4.4: Read and write several numbers from and to file """ from pprint import * fahrenheit =...
# -*- coding: utf-8 -*- __author__ = 'Anders Mølmen Høst' __email__ = 'anderhos@nmbu.no' """ From Book: A Primer on Scientific Programming with Python Author: Hans Petter Langtangen Editition: 5th Edition Year: 2016 Exercise 2.20: Explore what zero can be on a computer """ """ 1: Storing 1.0 as a value for eps...
import os import random clear = lambda: os.system('cls') def display_board(board): clear() print(' | |') print(board[7]+' | '+board[8]+' | '+board[9]) print(' | |') print('-----------') print(' | |') print(board[4]+' | '+board[5]+' | '+board[6]) print(' | |') ...
# basic neuron information inputs = [1.0, 2.0, 3.0, 2.5] weights = [0.2, 0.8, -0.5, 1.0] bias = 2.0 def calc_neuron(): output = ( inputs[0]*weights[0] + inputs[1]*weights[1] + inputs[2]*weights[2] + inputs[3]*weights[3] + bias ) return output print(calc_neuron())
country_names = ["India","Singapore","Malaysia","Thailand","Sri lanka"] for country in country_names: print("country names is {0}".format(country)) ##break and continue country_names = ["India","Singapore","Malaysia","Thailand","Sri lanka"] for country in country_names: if country=="India": continue; ...
#!/usr/bin/env python3 # By Elias Goodale import sys def ft_bin(n): if n == 0: return '' else: return ft_bin(n // 2) + str(n % 2) def is_integer(n): try: int(n) return True except: print('Not an Integer!') return False def main(argv): if len(argv) == 2 and is_integer(argv[1]): print(ft_bin(int(ar...
#!/usr/bin/env python3 # By Elias Goodale import sys def print_colorful_text(string, style=0, foreground=0, background=7): form = ';'.join([str(style), str(foreground), str(background)]) print("\x1b[%sm%s" % (form, string), end="") def main(argv): rbow = [' R ', ' A ', ' I ', ' N ', ' B ', ' O ', ' W '] for i in...
i=1 print('{0}.TITLE() FUNCTION'.format(i)) word='i am Martian' print(word.title()) i=2 print('{0}.TITLE() WITH APOSTROPHES'.format(i)) word="they don't know" print(word.title()) i=3 print('{0}.STARTSWITH() WITHOUT START AND END PARAMETERS'.format(i)) result=word.startswith('they') print(result) i=4 print('{0}.STAR...
import sqlite3 from sqlite3 import Error conn = sqlite3.connect('passwords.db') cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS passwords ( id integer primary key, website text not null, email text not null, username text not null, password text not null ); ''' ) conn.commit() conn....
from functools import reduce def AcceptData(): arr = list() size = int(input("Enter the no of element")) for i in range(0, size, 1): print("Enter the no", i + 1) no = int(input()) arr.append(no) return arr def PrimeNo(no): if no > 1: for i in range(2, no, 1): ...
def main(): print("In Main") num1 = int(input("Enter the No of Element 1 :")) num2 = int(input("Enter the No of Element 2 :")) result = multiply(num1, num2) print(result) multiply = lambda no1, no2: no1 * no2 if __name__ == '__main__': main()
import sys import copy def main(): while(True): print("==========================虚拟内存调度==========================") choose = int(input("请选择调页算法:\n1-FIFO \n2-OPI\n3-LRU\n")) pageNum = int(input("请输入页面个数:\n")) #pageOrder = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1] ...
def convert(s): try: number ='' DIGIT_MAP = str for token in s: number += DIGIT_MAP[token] x = int(number) print(f"conversion failed x = {x}") x = -1 except KeyError: print("conversaion failed") x = -1 return x
# Tuples are a sequence of values. They are Immutable. # Tuples are work faster than lists. # Hence are used in places where objects need to be immutable like dictionaries # Syntax of tuple functions example_tuple = tuple([i for i in range(10)]) print(example_tuple) # integer = tuple.index(x, start, stop) print("tupl...
#!/usr/bin/python python # author='Kalyan Sankar' from decorator import * #----- generate fibonacci series for a given 'n' number using generator ----- @generator_next # use any one decorator @generator_forloop # use any one decorator def Fib(n): count=0 a,b=0,1 while True: yield a ...
import sys if len(sys.argv) < 2: print("error") else: inputNum = sys.argv[1] n1=int(3*inputNum) n2=int(2*inputNum) n3=int(inputNum) print(n1+n2+n3)
#shapeCalculator.py from math import pi def rectArea(length, width): area=length * width return area def circleArea(radius): area=pi*radius*radius return area def welcome(): print("Welcome to the shape calculator!") name=input("What is your name? ") return name def askDimension(dimension...
import unittest def merge_sorted_arrays(arr1, arr2) -> [str]: if not arr1 and not arr2: # Return empty array if both lists are empty return [] elif not arr1: return arr2 elif not arr2: return arr1 else: # Merge arrays result = arr1 + arr2 # Ret...
class Node: def __init__(self, value): self.value = value self.next = None class Queue: def __init__(self): self.first = None self.last = None self.length = 0 def peek(self): ''' Looks up the first element of the queue :rtype: self.first...
# # print("Victor Nara") # fullname = "Victor Nara" # age = 100 # married = False # hobbies = ['football', 'singing', 'dancing'] # kids = { # "paul": "male", # "maurice": "male", # "ama":"female" # } # # print(hobbies) # # if statement # if (married == True): # print("Happy marriage") # else: # p...
# parent class to Wheel and Frame classes class BikePart: # weight is weight of BikePart, expects float # cost is production cost of BikePart, expects float def __init__(self, weight, cost): self.weight = weight self.cost = cost class Wheel(BikePart): # all valid types of of wheel ...
'''Tree iterator in pre-order''' def tree_iter(tree): # tree format: ('a', ('b', None, None), None) if tree: name, child_left, child_right = tree yield name for left in tree_iter(child_left): yield left for right in tree_iter(child_right): yield right
import string import random RANDOM_CANDIDATE = string.ascii_letters + string.digits RANDOM_STRING_DEFAULT_LENGTH = 10 def random_string(length: int = RANDOM_STRING_DEFAULT_LENGTH) -> str: return "".join(random.choices(RANDOM_CANDIDATE, k=length))
import gpxpy def get_gpx_tracks( gpx_file_names ): """ Parses one or more GPX files into a list of GPX objects. Invalid GPX files are handled, the failure is logged to standard error, and a placeholder None is inserted into the created list. Takes 1 argument: gpx_file_names - A list of GPX...
def fact(n): if n == 0: return 1 else: return n * fact(n-1) print(fact(0)) print(fact(5)) #print(fact(2000)) import sys sys.setrecursionlimit(3000) def fact(n): if n == 0: return 1 else: return n * fact(n-1) print(fact(2000)) foo = 100 def hello(): print...
#STACK IMPLEMENTATION def push(list1,element): list1.insert(0,element) display(list1) def pop(list1): if len(list1)==0: print("No element is present in the stack!!!") else: del(list1[0]) display(list1) def display(list1): if len(list1)==0: print("No element is present...
#You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. #Find the maximum profit you can achieve. You may complete at most k transactions. #Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy agai...
from typing import List import re import collections class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: # re.sub \W : 단어문자가 아닌 경우 공백으로 substitute # lower() 소문자 변환 # 공백단위로 split print("Asis paragraph :", paragraph) print(re.sub(r'[^\w]', ' ...
n = 1234.56789 print(format(n, '0.2f')) print(format(n, '>10.1f')) # right align print(format(n, '<10.1f')) # left align print(format(n, '^10.1f')) # center align print(format(n, '^10,.1f')) # center align with thousands separator swap_separators = { ord('.'):',', ord(','):'.' } print(format(n, ',').translate(swap...
from collections import namedtuple # create a class that takes 2 arguments (like a record) Subscriber = namedtuple('Subscriber', ['addr', 'joined']) # Subscriber objects do everything a tuple can do # eg. len() - unpacking - is immutable # instantiate an object (of the named tupled class) sub = Subscriber('test@examp...
s = 'Hello World!' print(s.ljust(20)) # prints 'Hello World! ' print(s.rjust(20)) # prints ' Hello World!' print(s.center(20)) # prints ' Hello World! ' print('') print(s.ljust(20, '*')) # prints 'Hello World!********' print(s.rjust(20, '-')) # prints '--------Hello World!' print(s.center(20, '=')...
a1=list() a2=list() for i in range(0,5): x=input("İsim: ") y=input("soyisim:") z=input("Takım:") if z=="Barcelona": a1=[x,y,z] a2.append(a1) print(a2)
#!/usr/bin/env python2 """ Logpuzzle exercise Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0 Google's Python Class http://code.google.com/edu/languages/google-python-class/ Given an apache logfile, find the puzzle urls and download the images. He...