text
stringlengths
37
1.41M
print("Welcome to rollercoaster") height = int(input("Please tell me your height in cm: ")) bill = 0 if height >= 120: print("You may ride") age = int(input("Please tell me your age: ")) if age < 12: bill = 5 print(f'Your price is {bill}') elif age <= 18: bill = 7 print(...
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
def format_name(f_name, l_name): """Take a first and last name and format it to return the title case version of the name.""" if f_name == "" or l_name == "": return "You did not provide a valid input" formated_f_name = f_name.card_title() formated_l_name = l_name.card_title() return f"{...
"""This module handles everything having to do with aligning models and solving temporal word analogies. The `Alignment` class takes two models and fits a linear regression transformation between them, and also applies this transformation to produce a third model. The `Analogy` class solves a temporal word analogy. I...
""" This is the `twapy` module for computing temporal word analogies in Python (twa+py). The code in this module facilitates aligning and comparing independent vector space models. This module does not help with the task of training those models: you can use the `gensim` module, the original word2vec implementation, o...
__author__ = 'Peter' sales = float(input("Enter sales: $")) while sales >= 0: if sales < 1000: bonus = sales * .1 else: bonus = sales * .15 print(bonus) sales = float(input("Enter sales: $"))
import math class ConstantAnnealing: """ Constant annealing schedule: set β to a constant fixed value during training Args: kl_weight: β value """ def __init__(self, nr_warmup_iterations=0, kl_weight=1): self.kl_weight = kl_weight self.nr_warmup_iterati...
def left(text, width): ''' Return a string left-aligned within the given width ''' words = text.split() # Check longest word against width longestWord = '' for word in words: if len(word) > len(longestWord): longestWord = word assert len(longestWord) <= width, 'Longest word cannot exceed width.' # Left-...
# Files ques 1 name_file = "name.txt" file_name = open(name_file, "w") name = str(input("Enter your name: ")) print(name, file=file_name) file_name.close() # Files ques 2 name_in_file = open(name_file, "r") name = name_in_file.read() print("Your name is", name) name_in_file.close() # Files ques 3 number_file =...
# Rahul Thapa def minimum_path_triangle(n): import time def make_triangle(n): triangle = [] import random for i in range(n): temp_list = [] for j in range(0, i+1): temp_list.append(random.randint(1, n**2)) triangle.append(temp_list) return triangle triangle = make_tr...
def times10(x): return x * 10 print (times10(3)) def firstA(w): word = w if w[0] == "a": return True else: return False print (firstA("pple")) def sizer(n): if n <= 10: return "small" if n == 67: return "medium" if n > 100: retu...
from operator import add, mul def process(operator, address1, address2, target_address, memory): operand1 = memory[address1] operand2 = memory[address2] # print(operator, (address1, address2), (operand1, operand2), target_address, memory) memory[target_address] = operator(operand1, operand2) opcodes...
from operator import add, mul def process(operator, address1, address2, target_address, memory): operand1 = memory[address1] operand2 = memory[address2] print(operator, (address1, address2), (operand1, operand2), target_address, memory) memory[target_address] = operator(operand1, operand2) ...
class Car: def __init__ (self,make,model): self.make = make self.model = model def __repr__(self): return f'<Car {self.make} {self.model}' class Garage: def __init__(self): self.cars = [] def __len__(self): return len(self.cars) def add_car(self,car): ...
import pygame import random pygame.init() #colours white = (255,255,255) red = (255,0,0) black =(0,0,0) screen_width = 900 screen_height = 600 gamewindow=pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption('SnakesWithHarry') pygame.display.update() #games specific varibales exit_g...
class college: no_of_branches=8 def __init__(self,aname,asid,abranch): #constructor to construct class object and assign their variables easily self.name=aname self.sid=asid self.branch=abranch def printdetails(self): return f'Name is {self.name}.\nSID is {self.sid}.\n...
print('enter your first number') num1=int(input()) print('enter your second number') num2=int(input()) print('select your operation : ') print("1 = addition \n","2 = subtraction \n","3 = multiplicatoin \n","4 = division \n") op=int(input('enter your choice : ')) print('your answer is : ') if (num1 == 45 and num2==...
import pygame x = pygame.init() #creating window gamewindow = pygame.display.set_mode((1200,500)) #tuple : width and height pygame.display.set_caption("My First Game") #game screen title #game specific variables exit_game = False #will make it true in future so that user can quit the game game_o...
#dictionary is nothing but key values pair d1={} print(type(d1)) d2={"harry":"burger","rohan":"fish","binnnu":"roti","shubham":{"b":"roti","l":"fish","d":"chicken"}} print(d2["harry"]) #it will print burger print(d2["shubham"]) #it will print the dictionary print(d2["shubham"]["b"]) # t...
s = set() # print(type(s)) # print(len(s)) #max , min s_from_list = set([1,2,3,4]) print(s_from_list) print(type(s_from_list)) s.add(1) #to add element in set s.add(1) #will only show 1 element as it only holds unique elements s.add(2) print(s) s1 = s.union({1,2,3,4}) print(s,s1) print(s.isdisjoint(s1)) s.r...
import random WORDS = ("SLAVES","FUCK","order","this","shit") i = 0 u = [] used = [] print("welcome") input("Нажмите кнопку для продолжения") while i < len(WORDS): lent = len(WORDS) - 1 rand = random.randint(0, lent) if rand not in u: print(WORDS[rand]) used.append(WORDS[rand]) ...
user1 = ['/home', '/register', '/login', '/user', '/one', '/two'] user2 = ['/home', '/red', '/login', '/user', '/one', '/pink'] def find_longest_common_sequence(sequence1, sequence2): longest_sequence_length = -1 longest_sequence = None def find_indices_of_word_in_sequence(sequence, word): return ...
import time fee = 2 def calculate_optimal_purchases(stock_prices, fee = fee): profit = 0 num_transactions = 0 buy_index = 0 while buy_index < len(stock_prices) - 1: buy_price = stock_prices[buy_index] highest_sell_index = None highest_sell_price = -1 for sell_index in ra...
import math class Node: def __init__(self, value, left, right): super().__init__() self.value = value self.left = left self.right = right def __str__(self): return "Node(value=%s, left=%s, right=%s)" % (self.value, self.left.__str__() if self.left != None else None, self...
import turtle import pandas turtle_writer = turtle.Turtle() turtle_writer.hideturtle() screen = turtle.Screen() screen.title("US State Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) data = pandas.read_csv("50_states.csv") states = data["state"].to_list() while len(states) > 0: ...
"""Use this file after get_senders_list.py, to filter out repeat senders while also prioritizing based on how many time a particular sender occurs in senders_list.txt. Note: If writing this again, I'd include this functionality in get_senders_list.oy""" def occurrence(pair): """Used later as a sor...
p=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] c=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] m="YMJHFJXFWHNUMJWNXTSJTKYMJJFWQNJXYPSTBSFSIXNRUQJXYHNUMJWX" #input("enter the ciphertext") s=list(m) #...
def patternCount(): genome = raw_input("Please enter the strand: ") pattern = raw_input("Please enter the pattern: ") count = 0 for i in range(len(genome) - len(pattern)): if genome[i:].startswith(pattern): count += 1 print count patternCount()
import operator import random class Player: def __init__(self, name, active=True, games_played=0): self.name = name self.active = active self.games_played = games_played def sit(self): self.active = False def unsit(self): self.active = True def play(self): ...
import numpy as np import random as r from timeit import Timer def insertionSort(array): for j in range(1,len(array)): key = array[j] i = j-1 while (i > -1) and key < array[i]: array[i+1] = array[i] i=i-1 array[i+1] = key return array start = ...
from collections import Iterable # 迭代 # Python的for循环抽象程度要高于C的for循环,因为Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上。 # # list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代: d = {'a': 1, 'b': 2, 'c': 3} for key in d: print(key) # 因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。 # # 默认情况下,dict迭代的是key。如果要迭代...
# https://leetcode.com/problems/remove-linked-list-elements/ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: if head is None:...
# https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/ class Solution: def tictactoe(self, moves: List[List[int]]) -> str: dp = {'X':'O', 'O':'X'} matrix = [[None] * 3 for _ in range(3)] char = 'X' for x, y in moves: matrix[x][y] = char char = dp[c...
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ # Solutions one, two pointers. Better performance class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: start, end = 0, len(numbers) - 1 while start < end: if numbers[start] + numbers[end] == targ...
# https://leetcode.com/problems/to-lower-case/ class Solution: def toLowerCase(self, str: str) -> str: res = '' lbase = ord('a') ubase = ord('A') for char in str: if 'A' <= char <= 'Z': res += chr(lbase + ord(char) - ubase) else: ...
# https://leetcode.com/problems/find-leaves-of-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # Runtime: 24 ms, faster than 96.09% of Python3 online submissions f...
# https://leetcode.com/problems/regular-expression-matching/submissions/ class Solution: def isMatch(self, s: str, p: str) -> bool: i, j = 0, 0 if len(s) == 0: return self.checkempty(p) if len(p) == 0: return False f1, p1 = s[0], p[0] if len(p) > 1: ...
# https://leetcode.com/problems/rectangle-overlap/ class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: def isOverlap(rec1, rec2): minx1, miny1 = rec1[0], rec1[1] maxx1, maxy1 = rec1[2], rec1[3] minx2, miny2 = rec2[0], rec2[1] ...
# https://leetcode.com/problems/sort-array-by-parity/ class Solution: # Solution One: # Runtime: 80 ms, faster than 58.99% of Python3 online submissions for Sort Array By Parity. # Memory Usage: 15 MB, less than 55.95% o def sortArrayByParity(self, A: List[int]) -> List[int]: return [k for k in ...
# https://leetcode.com/problems/clone-graph/ # Runtime: 84 ms, faster than 12.22% of Python3 online submissions for Clone Graph. """ # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ from...
# https://leetcode.com/problems/reverse-words-in-a-string-iii/ class Solution: def reverseWords(self, s: str) -> str: return ' '.join([k[::-1] for k in s.split()])
# here we import the argv module # run this script by typing python exercise_13.py first 2nd 3rd from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third prin...
def multiplier(lst,numero): risultato = [] for i in lst: x = i * numero risultato.append(x) return risultato tpl = (4,2,3,5) #print tpl x = [2,5,7,9] y = [3,7,9,10] def mult (a,b): return a*b print mult (7,8)
class ATM: def __init__(self,ATMcard,pinNumber): self.ATMcard=ATMcard self.pinNumber=pinNumber def Balance(self): print("User Balance is 5000$") def BankEnquiry(self,amount): new_amount=5000-amount print("You Have Withdrawn"+ str (amount)+"Remaining Balance is...
# high_income = True # good_credit = False # if high_income and good_credit == True: # print('ok') # age = 10 # if age >=18 and 65<=age: # print('accepted') # else: # print("not accepted")
# class Person: # def __init__(self,name,age,country): # self.name = name # self.age = age # self.country = country # p1 = Person("junya","20","japan") # p2 = Person("karthik","24","india") # print(p1.name) # print(p1.age) # print(p1.country) # print(p2.name) # print(p2.age) # ...
age = 10 # if age == 22: # print('eligible') # elif age<=18: # print('not child') # else: # print('child')
def invert(A): ''' Returns the inverse of A, where A is a square matrix in the form of a nested list of lists. ''' A = [A[i]+[int(i==j) for j in range(len(A))] for i in range(len(A))] for i in range(len(A)): A[i:] = sorted(A[i:], key=lambda r: -abs(r[i])) A[i] = [A[i][j]/A[i][i]...
# Experimenting with a neural network consisting of a single neuron import random import time from tkinter import * class Perceptron: def __init__ (self, numberOfInputs): self.weights = [None] * numberOfInputs self.learningConstant = 0.01 for i in range(0, numberOfInputs): self.weights[i] = random.unifor...
age = 10 if age == 10: print("What's the best way to speak to a monster?") print("From as far away as possible!") age = '10' if age == 10: print("What's the best way to speak to a monster?") print("From as far away as possible!") age = '10' converted_age = int(age) age = 10 converted_ag...
# PROJECT 2 - File separator using OS Module. import os , shutil dict_extension={ "audio_ext": (".m4a",".flac",".mp3",".mp4",".wav",".wma",".aac"), "video_ext": (".mov", ".wmv", ".flv", ".mp4", ".avi", ".avchd", ".mkv",".mpeg"), "doc_ext" : (".doc", ".pdf", ".txt",".jpj",".docx",".3gp",".pdf") } ...
from Bio import Entrez #Initialize Library from Bio import Medline import time Entrez.email = "yousefa@colorado.edu" #Always tell biopython who you are name = "" #User input for their choice of author print("Choose faculty member:\n") #Display choices print("1: Natalie Ahn\n") print("2: Kristi Anseth\n") print("3: St...
#-*- coding: utf-8 -*- #!/usr/bin/python #Filename: insert_sort.py #Author: Boyce #Email: boyce.ywr@gmail.com import randata ''' 被注释掉的部分是c语言数组普通的插入方式 未被注释的部分则是使用python列表的插入和删除特性改善的 ''' def insertSort(arr): print(arr) for i in range(1,len(arr)): j=i print(arr[i]) while j>0 and arr[j-1]>arr[i]: j-=1 print(j...
"""Simple reader-writer locks in Python Many readers can hold the lock XOR one and only one writer http://majid.info/blog/a-reader-writer-lock-for-python/ """ import threading version = """$Id: 04-1.html,v 1.3 2006/12/05 17:45:12 majid Exp $""" class RWLock: """ A simple reader-writer lock Several readers ca...
from Document.Interval import Interval class Token(Interval): """ A Interval representing word like units of text with a dictionary of features """ def __init__(self, document, start: int, end: int, pos: str, shape: int, text: str): """ Note that a token has 2 text representations. 1)...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[in...
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ result = [] parsed_path = path.split('/') for pp in parsed_path: if pp == '.' or pp == '': continue elif pp == '..': ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if(head == None): ...
########################################### # Author: Sudeshna Pal # SBU ID: 110938222 ########################################### from pyspark import SparkContext from operator import add # Creating Spark Context sc = SparkContext(appName="Word Count") text_file = sc.textFile("SampleFileWordCount.txt") counts = text...
# First draft of .py file # from urllib2 import urlopen # from bs4 import BeautifulSoup # html = urlopen("http://www.pythonscraping.com/pages/page1.html") # bsObj = BeautifulSoup(html.read(), "html5lib") # print(bsObj.h1) from urllib2 import urlopen from urllib2 import HTTPError from bs4 import BeautifulSoup def getT...
amount = int(input("")) if (amount >= 100 and amount <= 100000): n_t = amount / 1000 n_f = (amount - n_t * 1000) / 500 n_h = (amount - n_f * 500 - n_t * 1000) / 100 print(str(n_t) + " of 1000 Rupees") print(str(n_f) + " of 500 Rupees") print(str(n_h) + " of 100 Rupees") else: print("Amount...
from random import randint vetor = [randint(1,100) for x in range(10)] # gera um lista com numeros aleatorios def meuQuickSort(lista): if not lista: return [] menores = meuQuickSort([x for x in lista if x < lista[0]]) iguais = [x for x in lista if x == lista[0]] maiores = meuQuickSort([x for x...
from sheldonchess.piece import Pawn, Horse, King, Bishop, Queen, Rook class Field(object): def __init__(self, color, x, y): self.color = color self.x = x self.y = y self.piece = None class ChessBoard(object): def __init__(self): self.width = 8 self.height = ...
''' Brute-force implementation of DictionaryWithLast using Python's OrderedDict ''' from collections import OrderedDict class DictionaryWithLast: ''' /// Space Complexity? O(...) See implementatin of _map here - https://github.com/python/cpython/blob/master/Lib/collections/__init__.py ''' ...
#!/usr/bin/python3 n = 1 for i in range(9): for j in range(n, 10): if n != 9: print('{:d}{:d}, '.format(i, j), end="") else: print('{:d}{:d}'.format(i, j)) n += 1
#!/usr/bin/python3 """ Module """ def read_lines(filename="", nb_lines=0): """ FileName """ with open(filename, "r", encoding="UTF-8") as f: """ IF """ if nb_lines <= 0: print(f.read(), end="") else: for l in f: print(l, end="")
import re import sys with open("input.txt", "r") as f: data = f.read().splitlines() def isSumOfTwoIn(target,numberSet): isSum = False for number in numberSet: firstNumber = int(number) secondNumber = int(target) - firstNumber if str(secondNumber) in numberSet: isSum = T...
with open("input.txt", "r") as f: data = f.read().splitlines() requiredFields = { "byr" : "Birth Year", "iyr" : "Issue Year", "eyr" : "Expiration Year", "hgt" : "Height", "hcl" : "Hair Color", "ecl" : "Eye Color", "pid" : "Passport ID", "cid" : "Country ID" } def parsePassportData...
"""Using rjust(), ljust(), and center() lets you ensure that strings are neatly aligned, even if you aren’t sure how many characters long your strings are.""" def print_picnic(itemsDict, leftWidth, rightWidth): print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-')) for k, v in itemsDict.items(): ...
from tkinter import * window_name = Tk() # Assigns window name. Make sure 'T' is capital. window_name.title('Put title here') lbl_name = Label(window_name, text='Hello') # Assigns label name. Make sure 'Label' is capitalized. lbl_name.grid(column=0, row=0) window_name.mainloop()
import sqlite3 conn = sqlite3.connect('demo_data.sqlite3') cursor = conn.cursor() cursor.execute('''CREATE TABLE demo ( s VARCHAR(1), x INT, y INT )''') cursor.execute('''INSERT INTO demo VALUES ('g', 3, 9), ('v', 5, 7), ...
#!/bin/python3 import math import os import random import re import sys def dectobin(n): binary = '' while(n>=1): if n==1: binary = ''.join([binary,str(n)]) return binary else: r = n%2 binary = ''.join([binary,str(r)]) n = n//2 re...
import numpy as np class nn_neuron(): ''' class nn-neuron: neuron class oo-implementation of a neuron for a neural network with this implementation it is possible to make a neuron with inputs(with there weights). ''' def __init__(self,activation = 1.0,weigths = []): """ de...
import numpy as np from math import * import random ''' Funcion desarrollada para realizar la sustitucion hacia atras en una matriz triangular inferior. Entradas: a=Matriz de coeficientes. b=Vector de terminos independientes. Salidas: xk=Vector columna de soluciones que s...
#Animal is-a object (yes, sort of confusing) look at the extra credit # OO Concepts # ex42.py print "======================== Exercise 42: Is-A, Has-A, Objects, and Classes =====================" # Base Class Animal class Animal(object): pass ## Is-A class Dog(Animal): def __init__(self, name): ## ...
# Exercise 33: While Loop print "================ Exercise 33: While Loop ======================" i = 0 numbers = [] ''' while i < 6: print '\n' print "At the top i is %d" % i numbers.append(i) i = i+1 print "Numbers now:", numbers print "At the botton i is %d" % i pr...
import unittest # This is our unit testing class called FruitSortTests. It inherits from one of unittest's classes, unittest.TestCase. # There are 7 test cases below. One is functional which you can reference. I would like you to each develop the rest of the test cases. At least one of the test cases for compareFruit...
# Paths to files path = 'day5AoCinput.txt' ex_path = 'example.txt' # Open files with open(path, 'r') as file: day5AoC_inputs = file.read().splitlines() with open(ex_path, 'r') as ex_file: example_inputs = ex_file.read().splitlines() #######PART 1########## def boarding_pass(lst_of_passes): """This funct...
from sys import stdin mydict = {} alph = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" idx = 1 for c in alph: mydict[c] = idx idx+=1 def isPrime(i): i = int(i) if i >= 1: if i==4: return False for x in range(2, i//2): if i%x == 0: ...
def add(x, y): """Add two numbers""" return x+y def substract(x, y): """Substract two numbers""" return y-x
#Assignment of Ahmad Kamal Baig (BS CIS 18-22) Implementation of Neural Networks using Backpropagation import numpy as np import random inputs = np.array([[0.4, -0.7],[0.3, -0.5],[0.6, 0.1],[0.2, 0.4],[0.1, -0.2]]) outputs = np.array([[0.1],[0.05],[0.3],[0.25],[0.12]]) learning_rate = 0.1 eta = 0.5 error = 1...
import time def Knapsack(W, wt, val, n): K = [[0 for x in range(W+1)] for x in range(n+1)] for i in range(n+1): for w in range(W+1): if i==0 or w==0: K[i][w] = 0 elif wt[i-1] <= w: K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) ...
import time graph={ 1:{ 2:10, 5:100}, 2:{ 1:10, 3:50}, 3:{ 2:50, 4:20, 5:10}, 4:{ 3:20, 5:60}, 5:{ 1:100, 3:10, 4:60} } def Dijkstra(s): d,visited=[float('inf')]*len(graph),[0]*len(graph) d[s-1]=0 visited[s-1]=1 vertices=[s] print "\nStart --> ", print s," --> ", #printing start node path={} ...
def cmdLS(): print('''SqrRt(outprint) -- returns the square root of a number by N dimensions (outprint can only be 1 or 0!) \nONEoutofZERO -- tells you the value of 1/0''') def SqrRt(outprint): N = int(input('What is your number of dimensions?')) C = int(input('What is the squared output (NO FLOAT NUMBERS!!)?'...
mystr = "hello" mystr.encode("utf-8") print(mystr) print(type(mystr)) mystr2 = u'mystr' print(type(mystr2)) print(mystr2)
a = 1 while a == 1: darling_said = input("You say that you love.....(from the clouds?): ") if darling_said == "rain": print("But you open your umbrella when it rains.") a = 0 a = 1 while a == 1: darling_said = input("You say that you love the.....(shines in the sky?): ") if da...
# Blackjack Rules """ Conditions - One deck of 52 cards - Ace counts as 1 or 11 - Face cards are 10 Some exceptional cases to consider: - More than 1 ace Logical Flow - Player places bet - Give player hand - Give dealer hand - Player's turn to choose from the following options: -- HIT = get another c...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 19 17:49:27 2021 @author: matthewayala """ import pandas as pd import numpy as np # Reading in the file birth_data = pd.read_csv('LowBirth.csv') # Checking the first 5 rows and the shape of the data. print(birth_data.head()) print(birth_data.sh...
#!/usr/bin/python3 # 다음 코드를 실행하기 위해서는 lxml 모듈이 필요합니다. from lxml import etree def read_xpath(tree, xpath): tags = tree.xpath(xpath) if tags and len(tags) > 0: return True, tags[0] else: return False, None def read_all(tree, xpath): for tag in tree: if len(tag) > 0: ...
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ start = 0 end = 0 longest = 0 for i in range(0, len(s)): # for palindromes like 'aba' length1= 1 left = i right...
class ListNode(object): def __init__(self, val): self.val = val self.next = None class Solution(object): def mergeKLists(self, lists): list1 = lists[0] list2 = lists[1] head = self.merge2Lists(list1, list2) self.printList(head) def merge2Lists(self, list1, l...
# python 3 import pandas as pd import numpy as np import random as rand from pprint import pprint, PrettyPrinter import logging pp = PrettyPrinter(width=100, indent=5, compact=False) class Game: """ Initialize a new game by passing a game name and player names as string arguments. e.g. : my_game = Game(...
a=int(input('Введите первое целое значение')) b=int(input('Введите второе целое значение')) c=int(input('Введите третье целое значение')) #Если нет ни одого нуля - вывести: "Нет нулевых значений!!!"(Без if - использовать лень) z=a==0 or b==0 or c==0 or 'Нет нулевых значений!!!' print(z) #Вывести первое ненулевое ...
tuple1=('a','m','v','p','m','n','s') for x in tuple1: a=tuple1.count(x) if (a>1): print (x)
j=0 n=int(input()) for i in range(1,n): if(n%i==0): j=j+1 if (j==2): print("prime") else: print("not prime")
# Dette programmet lar brukeren legge inn en fahrenheit temperatur som den ønsker å få omregnet til Celcius temperatur. fahrenheit = input("Skriv inn et tall: ") # Først laget jeg en variabel der bruker legger inn det tallet den ønsker å konvertere. omregning = float(fahrenheit) -32 * (5/9) # Siden "fahrenheit" input ...
""" Module to read data from CSV files and HTML file to populate an SQL database ITEC649 2018 """ import csv import sqlite3 from database import DATABASE_NAME import sqlite3 from bs4 import BeautifulSoup as BS """Importing all the necessary modules like CSV, SQLite, Beautiful Soup. """ # define your functions t...
# Uses python3 def calc_fib(n): if (n <= 1): return n else: a = [] a.append(0) a.append(1) for i in range(2, n+1): a.append(a[i-1]+a[i-2]) return a[n] n = int(input()) print(calc_fib(n))
from math import log10, floor def get_number_of_digits(n): return long(floor(log10(n))) + 1 def list_of_digits(n): r = [] while n > 9: n, x = divmod(n, 10) r.append(x) r.append(n) return r def fib(): yield 0; yield 1; yield 1 a = b = 1 while True: yield a + b...
from itertools import count # The solvig algorithim goes as follows # At every round we compute the number of squares of a certain size # For example (1, 1) which is n*m. Every time we increase the # size of one of the sides we decrease it from the bigger side. # For example the number of squares of size (2, 2) on a n...