text stringlengths 37 1.41M |
|---|
a = 0
A = 0
B = 0
C = 0
def FindABC():
for c in range(1000, 3, -1):
C = c
for b in range(c, 2, -1):
B = b
a = 1000 - b - c
if a ** 2 + b ** 2 == c ** 2 and a > 0:
return print(a * b * c)
FindABC()
|
# -*- coding: utf-8 -*-
# Typoglycemia
import random
def Typoglycemia(text):
words = text.split()
result = ""
for word in words:
wordList = list(word)
if len(word) >= 4:
tmp = wordList[1:-1]
random.shuffle(tmp)
result += wordList[0] + "".join(... |
# -*- coding: utf-8 -*-
# n-gram
def nGram(inStr, n):
l = len(inStr)
for i in range(l):
print(inStr[i:i+n])
if __name__ == "__main__":
s = raw_input(">")
print(s)
nGram(s.replace(" ", ""), 2)
s = s.split()
nGram(s, 2)
|
#%%
class Polygon:
def __init__(self, sides):
self.sides = sides
def display_info(self):
print("A polygon is a two dimensional shape "
"with straight lines")
def get_perimeter(self):
perimeter = sum(self.sides)
return perimeter
class Triangle(Polygon):
de... |
from tkinter import *
#definicion de clase App y sus miembros.
class App:
#miemros de App
def __init__(self, master):
#instancia de widget frame, cuyo contenedor debe ser enviadoo como argumento
frame = Frame(master)
#organizacion en bloques
frame.pack()
#instancia de boton
self.button = Butto... |
import sys
#input: list of tuples of data returned by read_data
#process: calculates the counts and total certified, percentage certified. Also sorts the list in decreasing order of number of certifieds and alphabetically for ties.
# Same function used to calculate top 10 states as well as occupations (inputs modi... |
first_name = "Eric"
last_name = "Weidman"
age = 28
print "Hello, world!"
print "My name is " + first_name +" " + last_name + ". " "I am " + str(age) + " " + "years old!"
print "Python is neat!"
#This is a comment.
"""This is a comment too.
So is this.
Also this."""
|
# add dependencies
import csv
import os
# assign variable to load a file from path
path1 = "/Users/michaelmanthey/Documents/Bootcamp/Module_3_Python/Challenge/election_results.csv"
path2 = "/Users/michaelmanthey/Documents/Bootcamp/Module_3_Python/Challenge/"
file_to_load = os.path.join(path1)
file_to_save = os.path.... |
class Tree:
def __init__(self, root = None):
self.root = root
def insert(self,val,current = None):
new_node = Node(val)
if current is None:
current = self.root
if self.root is None:
self.root = new_node
return
if val <= ... |
#from the search options of the site- like product name, its description- which is available on the website, and then the image url.
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
#Url who's information you want to scrape
url = "https://www.flipkart.com/search?q=iphone&sid=tyy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 9 17:44:18 2021
@author: alok
"""
import os.path
import pandas as pd
import random
from Hangman_parts import parts #to call teh Hangman_parts file
from Hangman_words import words
picked_l = random.choice(words)
picked = picked_l.upper()
nam... |
import sqlite3, datetime
connection = sqlite3.connect('data.db')
def create_tables():
with connection:
connection.execute(
"CREATE TABLE IF NOT EXISTS movies ("
"id INTEGER PRIMARY KEY,"
" title TEXT,"
" release_timestamp REAL)")
connection.execute(... |
#!/usr/bin/python3
import sys
import unittest
def max(x, y):
"""An auxiliary function that returns the maximum of 2 values.
:rtype: int
"""
if x >= y:
return x
return y
def cut_rod( p, n ):
""" Cutting rod problem: the naive, recursive solution that returns the maximum price.
:param ... |
from random import *
from src.card import *
class Player:
def __init__(self, charac, real):
"""
Class initialiser
:param charac: Selected character
:param boolean real: True if the character is human
"""
self.cards = []
self.character = charac
self.... |
from src.player import *
from src.card import *
from random import randint, choice, shuffle
class Game:
def __init__(self):
self.curPlayer = None
self.players = []
self.murderCards = None
def addPlayer(self, character):
"""
Adds a player to the current game
:pa... |
import sys
# dictionaries
# creating new dictionary
# the order of items in dictionary is unpredictable
# items might not retrieved in the same order we inserted
allStatesAndZipCodes = dict()
allAreasAndZipCodes = { 'Washtenaw': 48197, 'Ann Arbor': 48105, 'Ypsilanti': 48198 }
# print(allAreasAndZipCodes['Washtenaw'])... |
import math
import random
# function example - no arguments
def printName():
print('Karthik here')
printName()
# function with one argument
def welcomeUser(name):
print('Hello', name, 'welcome to the world of Python')
welcomeUser('Karthik')
# void functions return a special value called 'None' which of typ... |
import sys
# Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages.
# The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail.
# The program creates a Python dictionary that maps the sender's mail addre... |
import sys
# Variables, Expression and Statements
message = 'This is Python 3.7.x'
print(message)
#to know the type of varaible use type function
print(type(17))
print(type('Hello Python'))
# Operators and Operands
# Opeators are: + - * / // **
# ** is 'to the power of'
# // is to tell python to ignore decimal part ... |
import socket, sys#, threading, time
#from queue import Queue
"""
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
queue = Queue()
all_connections = []
all_address = []
"""
#Create a socket (connecting two or more computers)
def socket_creation():
try:
global host
global port
global s
host... |
import math
#valueSplit is a list of 2 items. The first is number of positive examples,
#the second is the number of negative examples
def calcEntropy(valueSplit):
h = 0.0
probabilityP = valueSplit[0]
probabilityN = valueSplit[1]
totalValues = probabilityN + probabilityP
probabilityP = probabilityP... |
#values we have
radius=20.0
PI=3.14
#computer area of the circle
area=PI*radius*radius
#print the results
print("area of circle=",area) |
# Print Fibonacci series upto n
a = 0
b = 1
n = 25
while a < n:
print(a)
(a, b) = (b, a + b) |
# insertion sort in increasing order
A = [1, 2, 4, 6, 3, 20]
j = 1
while j < len(A):
key = A[j]
i = j - 1
while i > -1 and A[i] < key:
# swap A[i] and A[i+1]
A[i+1] = A[i]
i -= 1
A[i+1] = key
j += 1
print(A)
|
def main():
# my_list = [8, 7, 6, 5, 4, 3, 2, 1]
my_list = [6, 2, 8, 3, 1, 7, 9, 5, 4]
quick_sort(my_list, 0, len(my_list)-1)
print(my_list)
def quick_sort(numbers, i, j):
if i < j:
l = pivot(numbers, i, j)
print(l)
print(numbers[i:l])
quick_sort(numbers, i, l-1)
print(numbers[l:j])
quick_sort(numbe... |
import random
print('This is a book recommendation application')
print('Genres available: history, autobiography, science fiction, non-fiction, children')
selection = input('Please select one of the listed genres to recieve a recommendation: ')
history = ['history book 1', 'history book 2', 'history book 3']
autobiog... |
#!/usr/bin/env python3
# Write a program that given a text file will create a new text file in
# which all the lines from the original file are numbered from 1 to n (where n is
# the number of lines in the file). [use small.txt]
def numbered_lines():
with open("small.txt", "r") as doc:
text = doc.readlin... |
from typing import List
class Solution:
def longestMountain(self, A: List[int]) -> int:
left, mid, right = 0, 0, 0
n, res = len(A), 0
while left < n:
# 寻找升序
mid = left
while mid < n - 1 and A[mid + 1] > A[mid]:
mid += 1
if mid... |
from typing import List
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) == 1:
return
last_up = len(nums) - 2
while last_up >= 0 and nums[last_up] >= nums[last_... |
from typing import List
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordSet = set(wordList)
if endWord not in wordSet:
return 0
stack1 = [beginWord]
stack2 = []
step = 1
visited = {w: False for w in w... |
def get_rps(player):
while True:
choice = input(f'Player {player}, choose (R)ock/(P)aper/(S)cissors\n').upper()
if choice in ['R', 'S', 'P']:
print('\n'*100)
break
else:
print('Your choice was not R/S/P.')
return choice
p1_wins = 0
p2_wins = 0
play_to... |
# Get word to be guessed, and then hide it
# While user has more guesses:
# Ask for user to guess a letter or entire word,
# show word guessed until now and show him number of guesses left
# if letter - reveal letters in word
# if all letters in original word were guessed - notify and end game
... |
from argparse import ArgumentParser
from magic_formatter import MagicFormatter
if __name__ == '__main__':
"""
if you are running from the terminal you can either pass a text as a String
or a file location, if on the same path just pass the file name.
Also, you need to pass the width of the text yo... |
type = 7
# Python Strings https://www.w3schools.com/python/python_strings.asp
if type == 1:
a = """test
123""" # multi line strings
print(a)
print(a[0]) # strings are arrays
if len(a) > 1: # length of a string, use the len() function.
for x in a: # Since strings are arrays, we can loop... |
"""
Inventory
---------
Calculate and report the current inventory in a warehouse.
Assume the warehouse is initially empty.
The string, warehouse_log, is a stream of deliveries to
and shipments from a warehouse. Each line represents
a single transaction for a part with the number of
parts delivered or shipped. It... |
b=input("enter a string\n")
rev=""
for i in range(len(b)-1,-1,-1):
rev=rev+b[i]
if rev==b:
print("string is palindrome")
else:
print("string is not palindrome")
|
b=input("enter a first string\n")
c=input("enter a second string\n")
x=sorted(b)
y=sorted(c)
if x==y:
print("two string are anagram")
else:
print("two strings are not anagram")
|
from constants import GENDER_MALE
from constants import GENDER_FEMALE
class Member(object):
def __init__(self, founder, gender):
"""
founder: string
Initializes a member.
Name is the string of name of this node,
gender specifies the gender of the member
mother, fath... |
# -*- coding:utf-8 -*-
# __author__ :kusy
# __content__:文件说明
# __date__:2018/9/30 17:28
class MyStack(object):
def __init__(self, alist=None):
if alist == None:
self.stack_list = []
self.count = 0
else:
self.stack_list = alist
self.count = len(alist)... |
str = ''
length = 0
while (length < 1):
str = input("Enter any valid string\n")
length = str.replace(" ","").__len__()
if length == 0:
print("Entered String length is zero\n")
print("Length of '",str,"' is (excluding spaces):",length) |
import json
print(json.dumps([1, 'simple', 'list']))
with open('file1') as f:
json.dump(x, f)
#To decode the object again, if f is a text file object which has been opened for reading:
x = json.load(f)
print(x) |
strs = ["flower","flow","flight"]
# First approach: 36 ms, 14.2 mb
common_word = ''
def LCP(strs):
if strs == None or len(strs) == 0:
return ''
for letter in range(len(strs[0])): # For each letter in the first word (strs[0])
current_letter = strs[0][letter] # First word, current letter
... |
# Ejercicio 1: Mision TIC Colombia
calificaciones = list()
# Ingresar 10 calificaciones:
for i in range(10):
while True:
try: # Verifica que el input sea correcto
calificacion = int(input(f'Ingrese la calificacion {i}: '))
break
except:
print('Ingrese un valor c... |
from vartree import *
from linkedlist import *
def eval_postfix(tree, iterator):
vartree = tree
stack = LinkedList()
current = (next(iterator))
while current is not None:
current = str(current)
if current.isdigit():
stack.push((current))
try:
current = next(iterator)
except StopIter... |
from random import choice
score=[0,0]
direction=['left','center','right']
def kick():
print'======YOU KICK====='
print'CHOOSE ONE SIDE TO SHOOT'
you=raw_input()
print'YOU KICKED'+you
com=choice(direction)
print'COMPUTER SAVED'+com
if you!=com:
print'GOAL'
score[0]+=1
el... |
from heapq import heappush, heappop
import enum
class Node():
def __init__(self, id=None):
self.id = id
self.neighbors = {}
def __repr__(self):
return str(self.id)
def __lt__(self, other):
# this is only implemented so that heappop can run
# the actual i... |
# def convert(hex_number):
#
# result = int(hex_number, 16)
#
# return result
#
#
# hex_number1 = input("Please enter a hex number.")
# hex_number2 = input("Please enter a hex number.")
# #print(convert(hex_number))
# print(convert(hex_number1) + convert(hex_number2))
# score = 10
# answer = 9
# if answer == ... |
from tkinter import *
import tkinter as tk
def hello(e=None):
print('Hello')
tk.Button(root, text='say hello', command=hello).pack()
root.bind('<Escape>', lambda e: root.quit())
root.bind('h', hello)
root.mainloop() |
# CODE for EXERCISE 1
# -------------------
#
# Import the Tkinter package
# Note in Python 3 it is all lowercase
import tkinter as tk
from tkinter import *
# This method is called when the button is pressed
def clicked():
print("Clicked")
# Create a main frame with
# - a title
# - size 200... |
# CODE for EXERCISE 6
# -------------------
# This exercise introduces
# * The radio button widget
#
# MAKE THE FOLLOWING CHANGES
# * change the text of the radio buttons to colours
# * when the selection is made, change th background colour of the label
#
from tkinter import *
root = Tk()
# ... |
## validate tutor group name function
def check_tutor_group_name(tutor_group_name):
validated = True
## it has to have 2 or 3 characters
if len(tutor_group_name) < 2 or len(tutor_group_name) > 3:
validated = False
print("The length of the tutor group name is incorrect.")
## it has to hav... |
class Person:
department = 'School of Information' #a class variable
def set_name(self, new_name): #a method
self.name = new_name
def set_location(self, new_location):
self.location = new_location
person = Person()
person.set_name('Christopher Brooks')
person.set_location('Ann Arbor, MI,... |
import time
import turtle
class Stack:
def __init__(self):
self.items = []
self.height = 50
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return sel... |
import os # listing directory contents, determining files from directories
import argparse # CLI
import sys # get command-line arguments with sys.argv
from typing import List, Iterator # type hinting
argparser = argparse.ArgumentParser(description="pypree - A partial Python tree command implementation")
argparser.add_... |
from operator import itemgetter
from collections import Counter
import random
class NoMoveSet(Exception):
pass
class Player(object):
"""
Default type of player, is human.
Needs input
"""
next_move = None
def __init__(self, symbol, opponent_symbol, player_type="human"):
self... |
#!/usr/bin/python3
a = 1
b = 2.0
c = 10000000000000000000000000000000000000000
d = "what's your problem"
e = " There is a space "
print("Hello world")
print (a)
print ("a = %d" % a)
print (b)
print ("\tb^3 = %f" % b**3)
print (c+1)
print (d + " fuck off")
print (d.upper())
print (d.title())
print (e.rstrip())
print (... |
# BlueOrange -- Tania Cao, Jack Lu
# SoftDev1 pd8
# K06 -- StI/O: Divine your Destiny!
# 2018-09-13
import csv
import random
# Chooses random occupation based on percentage of US workforce comprised of it.
def choose(fileName):
# Builds a dictionary of careers occupations and percentage of US workforce.
dict... |
def findNonRepeatedChar (string):
stringList = list(string)
charMap = {}
for char in stringList:
if char not in charMap:
charMap[char] = 1
else:
charMap[char] += 1
for char in stringList:
if charMap[char] == 1:
return char
print(findNonRepeate... |
import random
def hangMan(guessCount):
if guessCount == 0:
print("|----|")
print("| ")
print("|")
print("|")
print("|______")
print("|______|")
elif guessCount == 1:
print("|----|")
print("| O")
print("|")
print("|")
print("|______")
print("|______|")
elif guessCount == 2:
prin... |
def add(a):
anssign=""
num1=""
num2=""
num1sign="+"
num2sign="+"
sum=0
if a.startswith("-"):
num1sign="-"
a=a[1:]
d=a.split("-")
e=a.split("+")
if len(d)>1:
num2sign="-"
num1=d[0]
num2=d[1]
elif len(e)>1:
num1=e[0]
num2=e[1]
if num1sign=="-" and num2sign=="-":
anssign="-"
sum=anssign+ad... |
age = 69
if age < 2:
print('You are kinder!')
elif age >= 2 and age < 4:
print('You are baby!')
elif age >= 4 and age < 13:
print('You are child!')
elif age >= 13 and age < 20:
print('You are teenager!')
elif age >= 20 and age < 65:
print('You are adult!')
else:
print("You are too old!") |
def country_city(country, city, population=''):
"""Получаем страну и город"""
if population:
formatted_name = f'"{city.title()}, {country.title()} - population {population}"'
else:
formatted_name = f'"{city.title()}, {country.title()}"'
return formatted_name |
import unittest
from survey import AnnonymousSurvey
class TestAnnonymousSurvey(unittest.TestCase):
"""Тесты для класса AnnonymousSurvey"""
def setUp(self):
"""
Создание опроса и наборов ответов для всех тестовых методов.
"""
question = "What language did you first learn to speak?"
self.my_survey = Annonym... |
cities = {
'Minsk': {
'country': 'Belarus',
'population': '2 million',
'fact': '1067',
},
'Moscow': {
'country': 'Russia',
'population': '12 million',
'fact': '1147',
},
'Warsaw': {
'country': '... |
for value in range(1, 6):
print(value)
numbers = list(range(6))
print(numbers)
even_numbers = list(range(2, 12, 2))
print(even_numbers) |
responces = {}
polling_continue = True
while polling_continue:
name = input("\nWhat's your name?\n")
responce = input("\nWhat country would you like to visit in vacation?\n")
responces[name] = responce
new_name = input("\nWould like to get new answer from another person? (yes/no)\n")
if new_name... |
import unittest
from city_functions import country_city
# country_city('belarus', 'minsk')
class CountryCity(unittest.TestCase):
"""Тесты для 'city_functions.py'."""
def test_city_country(self):
"""Страна и город отображаются правильно?"""
formatted_name = country_city('chile', 'santiago')
self.assertEqual(... |
menu = ('sushi', 'pasta', 'pizza', 'pancakes', 'burger')
for meal in menu:
print(meal)
print('*' * 10)
menu = ('cruton', 'hot dog', 'pizza', 'pancakes', 'burger')
for meal in menu:
print(meal) |
filename = 'guest.txt'
name = input('Enter your name:\n')
with open(filename, 'a') as file_object:
file_object.write(f"Your name is {name}.\n") |
tupleList = (1, 2, 3)
print(tupleList)
# Dictionary with tuples insite
day_temperatures = {'morning': (1.0, 2.0, 3.0), 'noon': (
3.0, 4.0, 5.0), 'evening': (6.0, 7.0, 8.0)}
print(day_temperatures)
|
mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
# prints out 1,2,3
for x in mylist:
print(x)
numbers = [1, 2, 3]
strings = ["hello", "world"]
names = ["John", "Eric", "Jessica"]
# write your code here
second_na... |
import random
import time
def OneDie(trials):
c1=time.clock()
print("====================")
print("One die with 6 sides")
print("Number of trials = ", trials)
sides = 6
histogram = [0, 0, 0, 0, 0, 0]
print(histogram)
j = 0
r = 0
while j < trials :
r = int(random.random... |
# To calculate the square root
num = 9
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) |
import numpy as np
import matplotlib.pyplot as plt
def display_image(img):
""" Show an image with matplotlib:
Args:
Image as numpy array (H,W,3)
"""
plt.figure()
plt.imshow(img)
plt.title("Image")
plt.show()
def save_as_npy(path, img):
""" Save the image arr... |
f = open('MyData.txt','r')
# to open file for reading as r
#print(f.readline(), end='') # for reading
#print(f.readline())
f1 = open('abc','w') # for writing w and appending a for reading r ,
#f1.write('Laptop')
# copying one file to another
for data in f:
f1.write(data)
|
from random import randint
import random as rand
from pythonds.basic.stack import Stack
import numpy
import sys
import signal
def handler(signum, frame):
print 'Time\'s up!!'
exit(0)
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
def Xor(x):
sum=0
i=0
s=""
bin=Stack()
while x >= 1:
bin... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
from hashlib import sha256
from hmac import HMAC
def encrypt_password(password, salt=None):
"""Hash password on the fly."""
if salt is None:
salt = os.urandom(8)
for i in range(10):
try:
... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
def get_filtered_words(file_name='filtered_words.txt'):
with open(file_name, 'r') as fp:
filtered_words = [word.strip() for word in fp]
return filtered_words
def get_user_input():
return raw_input('Input: ')... |
from battleships import *
from random_guessing import *
from search_guessing import *
from probabilistic_guessing import *
from statistics import mean, stdev
def simulate_battleships():
while True:
method = input("Select guessing method: random (r), search (s), probabilistic (p): ").lower()
if m... |
import numpy as np
# numpy arange fumction similar to range available in the python
arr = np.arange(10)
# numpy reshape function
reshape_arr = np.reshape(arr, (2, 5))
print(repr(arr))
print("arr shape: {}".format(arr))
print(repr(reshape_arr))
print("reshape_arr : {}".format(reshape_arr.shape))
areshape = np.reshape(re... |
from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Arial", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0 # initialize score to 0
# self.high_score = 0
with open("data.txt") as data:
self.high_score = int(data.read()) #... |
"""
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to
the left, 1 position to the right in the array or stay in the same place (The pointer should not be
placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that you... |
dogs = ['border collie', 'australian cattle dog','labrador retriever']
name = input('What is your favourite type of dog? ')
number = ''
while not number in ('0','1','2'):
number = input('pick a number between 0 and 2 ')
number = int(number)
dogs[number] = name
print(dogs) |
def main():
import os
print('List_Hard')
menu = ('{:>30}'.format('Shark Regatta'),
'1...add a boat to list',
'2...remove a boat from lit',
'3...print a list of boats by sign up order',
'4...print a list of boats sorted alphabetically',
'5...print a list of boats sort... |
num = []
for n in range(4):
inpu = int(input('What is thr No.'+str(n+1)+' number. '))
num.append(inpu)
num = sorted(num)
print(num) |
n1 = ''
n2 = ''
while not n1.isdigit() and not n2.isdigit():
n1 = input('What is your first natural number? ')
n2 = input('What is your second natural number? ')
n1 = int(n1)
n2 = int(n2)
print('The first number is',n1)
print('The second number is',n2)
if n2 > n1:
change = n2
n2 = n1
n1 = change... |
print('x','y')
for x in range(-10,11):
y = 5*x +3
print(x,y) |
n1 = int(input('What is your first natural number? '))
n2 = int(input('What is your second natural number? '))
print('The first number is',n1)
print('The second number is',n2)
sum = n1+n2
print('The sum of',n1,'and',n2,'is',sum)
product = n1 * n2
print('The product of',n1,'and',n2,'is',product)
difference = n1 - ... |
c = 3
while c>=1:
print(c)
c -= 1
for n in range(3,0,-1):
print(n) |
dog_name = input("What is youe dog's name? ")
dog_age = int(input("Whai is your dog's age? "))
human_age = dog_age * 7
print('Your dog',dog_name,'is', human_age,'years old0 in human years ') |
dogs = ['border collie', 'australian cattle dog','labrador retriever']
dogs.append('poodle')
dogs.append('dog A')
dogs.append('dog B')
for dog in dogs:
print(dog.title() + 's are cool.') |
def main():
import time
print('Getting Old Hard')
print()
go = True
while go:
try:
age = int(input('How old you you? '))
except:
pass
else:
if age >= 0:
go = False
gender = ''
while not (gender == 'f' or gender... |
from typing import Tuple
def should_board_front(seat: Tuple[int, str]) -> bool:
return seat[0] < 13
def upgrade_passenger(name: str, current_seat: Tuple[int, str]) -> Tuple[int, str]:
if name == "Sander G. van Dijk":
return 1, "A"
else:
print("Nice try")
return current_seat
|
class EmptyCollection(Exception):
pass
class EmptyTree(Exception):
pass
class LinkedBinaryTree:
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
if (self.left is not None):
self.left.parent = self
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 20 19:41:18 2017
@author: Zhoukx.joseph
"""
def fibs(n):
i = 0
q = 1
count = 0
while count < n:
c = i+q
i = q
q = c
count+=1
yield i
for i in fibs(9):
print(i) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 09:21:51 2017
@author: Zhoukx.joseph
"""
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self.data = []
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self) ==... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 19 20:47:04 2017
@author: Zhoukx.joseph
"""
class BinarySearchTreeMap:
class Item:
def __init__(self, key, value=None):
self.key = key
self.value = value
class Node:
def __init__(self, item):
... |
import sys
import pandas as pd
from sklearn.model_selection import train_test_split
def filter_df(df):
"""
Remove the unwanted samples from the dataframe
"""
df = df[(df.native_language == 'english') | (df.length_of_english_residence < 10)]
return df
def split_data(df, test_split=0.2):
"""
... |
# Helpful functions for interacting with the Twitter API using Python
def tweet_to_string(tweet):
"""
Takes Tweet text in JSON format (dictionary) and converts it to a useful string output.
Parameters
---------
tweet: dictionary
Tweet in JSON format as returned by requests.get(...).js... |
import math
height = 10
def ReturnAngles(X, Y):
hypot = math.sqrt((X*X) + (Y*Y))
if X == 0:
degX = 0
else:
degX = math.degrees(math.atan(X / Y))
if Y <= 0:
degY = 0
else:
degY = math.degrees(math.atan(hypot / height))
return degX, degY
def CalcSteps(X, Y, curDe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.