text stringlengths 5 121k |
|---|
"""
Question 1
1.1) Create a list called 'friends' containing the first names of 5
friends of yours, ranked in ascending chronological order based on
when you met them. (The oldest friend goes first; the most recent one
goes last.) Print that list.
1.2) Suppose you realize that you have recently mad... |
import numpy as np
import tensorflow as tf
import constants
from tensorflow.python.framework import ops
def initialize_parameters():
l1_weights = tf.get_variable("l1_weights", [constants.HIDDEN_LAYER_1_SIZE, constants.NN_INPUT_SIZE], initializer = tf.contrib.layers.xavier_initializer())
l1_biases = tf.g... |
"""
Module for storage enum classes
"""
from enum import Enum
class ItemOption(str, Enum):
"""
This class represents all options available
"""
office = 'office'
home = 'home'
travel = 'travel'
|
lstring = s[0]
cstring = s[0]
for char in s[1::]:
if char >= cstring[-1]:
cstring += char
if len(cstring) > len(lstring):
lstring = cstring
else:
cstring = char
print(lstring)
|
import math
def polysum(n, s):
area = (.25 * n * s**2) / (math.tan(math.pi / n))
perimeter = n * s
return round((area + perimeter ** 2), 4)
|
print('\n\t\tCLASS\n')
class Enemy:
life = 3
def attack(self):
print('\tOuch -> life -1')
self... |
class Stack(list):
def push(self, item):
self.append(item)
print(self)
def pop(self):
try:
super().pop()
print(self)
except IndexError:
print("stack is empty")
def peek(self):
try:
print(self[-1])
except... |
import math
numberofB =int(input ("How many bowling balls will be manufactured? "))
ballD = float(input ("What is the diameter of each ball in inches? "))
ballR = float(ballD / 2)
coreV = int(input("What is the core volume in inches cubed? "))
fillerA = (4/3) * (math.pi * (ballR ** 3))- coreV
print("You will need",fil... |
import random
with open('d.txt','r') as f:
store=f.read()
store=store.split(" ")
word_store=('choose','convert','glory','MIGHTY','NATION')
choose_word=random.choice(word_store)
choose_word=choose_word.lower()
length_choose=len(choose_word)
show_word={}
index={}
for i in range(length_choose):
show_word[i]... |
import sys
input = sys.stdin.readline
def find_parent(x):
if parent[x] != x:
parent[x] = find_parent(parent[x])
return parent[x]
def union_parent(x,y):
x = find_parent(x)
y = find_parent(y)
if x < y:
parent[y] = x
else:
parent[x] = y
v, e = map(int, input().split())
p... |
from collections import defaultdict as ddict
def solution(clothes):
answer = 1
look = ddict(list)
for cloth in clothes:
look[cloth[1]].append(cloth[0])
for category in look.keys():
answer *= (1+len(look[category]))
return answer-1 |
class Node:
def __init__(self):
self.value = None
self.next = None
def display(head):
if head is not None:
print(head.value, end=' ')
display(head.next)
def insertNode(head, element):
while head.next is not None and head.next.value < element.value:
head = head.... |
"""
file: Passenger.py
description: class to represent passenger
language: python3
author: Abhijay Nair, an1147@rit.edu
author: Sushruth Beeti, sb3112@rit.edu
"""
class Passenger:
__slots__ = "name", "ticket_number", "has_carry_on"
def __init__(self, name, ticket_number, has_carry_on):
... |
from Gate import Gate
from MyStack import MyStack
from Passenger import Passenger
"""
file: Aircraft.py
description: Class to represent aircraft
language: python3
author: Abhijay Nair, an1147@rit.edu
author: Sushruth Beeti, sb3112@rit.edu
"""
class Aircraft:
__slots__ = "passengers_with_carry... |
num =float(input())
metric = str(input())
output_metric =str(input())
if metric == 'mm':
num = num / 1000
elif metric == 'cm' :
num = num /100
if output_metric == 'mm':
num = num * 1000
elif output_metric == 'cm':
num = num * 100
print(f'{num:.3f}') |
import math
count_people = int(input())
tax = float(input())
price_chaise_lounge = float(input())
price_for_umbrella = float(input())
total_taxes = count_people * tax
using_umbrella = math.ceil(count_people / 2) * price_for_umbrella
using_chaise_lounge = math.ceil(count_people * 0.75) * price_chaise_lounge
total = t... |
n = int(input())
p1_count = 0
p2_count = 0
p3_count = 0
for i in range(n):
maimuna=int(input())
if maimuna % 2 == 0 :
p1_count += 1
if maimuna % 3 == 0 :
p2_count += 1
if maimuna % 4 == 0 :
p3_count += 1
percentage_p1 = p1_count / n * 100
percentage_p2 = p2_count / n * 100
pe... |
import math
name = input()
games = int(input())
sum_points = 0
volleyball_point = 0
v_games = 0
tennis_point = 0
t_games = 0
bardminton = 0
b_games = 0
for i in range(games):
game_name = input()
points = int(input())
if game_name == "volleyball":
points *= 1.07
sum_points += points
... |
start_hour = int(input())
start_minutes = int(input())
time_in_minutes = start_hour * 60 + start_minutes
time_plus_15_min = time_in_minutes + 15
final_hour = time_plus_15_min // 60
final_min = time_plus_15_min % 60
if final_hour > 23:
final_hour = final_hour - 24
if final_min < 10:
print(f'{final_hour}:0{fi... |
meters = float(input())
total_price = meters * 7.61
discount = total_price * 0.18
total_price_with_discount = total_price - discount
print(f'The final price is: {total_price_with_discount:.2f} lv.')
print(f'The discount is: {discount:.2f} lv.')
|
width = int(input())
length = int(input())
height = int(input())
packet = 0
space = width * length * height
new = input()
while new != 'Done':
pack = int(new)
packet += pack
if space < packet:
break
new = input()
if space < packet:
print(f'No more free space! You need {packet - space} Cu... |
start = int(input())
end = int(input())
for num in range(start, end + 1):
num_as_string = str(num)
even_sum = 0
odd_sum = 0
for i in range(len(num_as_string)):
digit = int(num_as_string[i])
if (i + 1) % 2 == 0:
even_sum += digit
else:
odd_sum += digit
... |
import sys
goal = 10000
goal_for_day = False
while goal > 0:
steps = input()
if steps != 'Going home':
goal -= int(steps)
else:
goal -= int(input())
if goal> 0 :
goal_for_day = False
sys.exit()
if goal_for_day == False:
print(f'{(goal)} more steps to reach g... |
dogs_count = int(input())
other_animals_count = int(input())
price_per_dog = 2.5
price_per_animal = 4
dogs_total_price =dogs_count * price_per_dog
animal_total_price =other_animals_count*price_per_animal
total_price= dogs_total_price + animal_total_price
print(f'{total_price:.2f} lv.') |
word = input()
word_len = len(word)
sum = 0
for i in range(0, word_len):
letter = word[i]
if letter == 'a':
sum += 1
elif letter == 'e':
sum += 2
elif letter == 'i':
sum += 3
elif letter == 'o':
sum += 4
elif letter == 'u':
sum += 5
print(sum)
|
income = float(input())
count_mouth = int(input())
costs = float(input())
another_costs = income * 0.3
saving = income - costs - another_costs
total_saving = count_mouth * saving
print(f"She can save {(saving / income) * 100:.2f}%")
print(f"{total_saving:.2f}")
|
count_days = int(input())
count_food = float(input())
cookies = 0
total_food = 0
dog_food = 0
cat_food = 0
for i in range(1, count_days +1):
dog = int(input())
cat = int(input())
if i % 3 == 0:
cookies += (dog + cat) * 0.10
total_food += dog + cat
dog_food += dog
cat_food += cat
pri... |
from random import randint
class Skeleton(object):
def __init__(self):
self.health = 13
self.power = 6
self.armor_class = 13
self.name = "Skeleton"
self.xp_value = 8
def __repr__(self):
return self.name
def is_alive(self):
if self.health > 0:
... |
"""
Implementations of Gaussian elimination.
"""
import numpy as np
def gaussian_elimination(A, b):
"""General Gaussian elimination. Solve Av = b, for `v`.
`A` is a square matrix with dimensions (n,n) and `b` has dim (n,)
Parameters
----------
A : np.ndarray
(n,n) matrix
b : np.ndarr... |
array = [0,1,43,-4,2]
def finder(array):
setOfArray = set(array)
i=1
while i in setOfArray:
i += 1
return i
print(finder(array))
|
import multiprocessing as mp
from multiprocessing import Process
import sys
from CNN import CNN
class CNN_adjusted:
"""
This class can be substituted by the CNN class in the code whenever the used GPU card has enough
memory to save multiple instances of the data. If not (in our case for example a... |
import sqlite3
conn = sqlite3.connect("Online_Shopping.db")
cur = conn.cursor()
'''
prodID = "PID0000003"
cur.execute("SELECT category FROM product where prodID = ? ", (prodID,))
print(cur.fetchall()[0][0])
# cur.execute("SELECT prodID FROM product WHERE sellID = {}".format(sellID))
'''
cur.execute("SELEC... |
from __future__ import print_function
from time import sleep
def myfun1():
print (" myfun1")
sleep(0.25)
myfun3()
def myfun2(n):
print (" myfun2")
sleep(0.15)
if n == 0:
return
else:
myfun3()
myfun2(n-1)
def myfun3():
print (" myfun3")
sleep(... |
__author__ = 'thecreator232'
from exceptions import UserNotFoundException
class Tweet(object):
def __init__(self, tweet):
self.tweet = tweet
@staticmethod
def text(self):
"""Returns the text of a tweet.
Returns:
unicode formatted string.
"""
return se... |
a = [3, 6, 8, 2, 78, 1, 23, 45, 9]
print(sorted(a))
"""
Sorting a List of Lists or Tuples
This is a little more complicated, but still pretty easy, so don't fret!
Both the sorted function and the sort function take in a keyword argument called key.
What key does is it provides a way to specify a function that return... |
from collections import deque
def parse(line):
parts = line.split()
if 'move' in parts:
return ('move', int(parts[2]), int(parts[5]))
elif 'swap letter' in line:
return ('swap', parts[2], parts[5])
elif 'swap position' in line:
return ('swap_pos', int(parts[2]), int(parts[5]))
... |
def not_prime(n):
for i in range(2, n):
if n % i == 0:
return True
return False
def run(debug=True):
if debug:
b = 65
c = 65
return (b - 2) * (c - 2)
else:
return sum(not_prime(b) for b in range(106500, 123500 + 1, 17))
def main():
print('... |
def seat_id(seat):
rows = list(range(128))
for k in seat[:7]:
n = len(rows)
if k == 'F':
rows = rows[:n // 2]
elif k == 'B':
rows = rows[n // 2:]
cols = list(range(8))
for k in seat[7:]:
n = len(cols)
if k == 'L':
cols = cols[:n... |
def reallocate(memory):
n = len(memory)
blocks = max(memory)
i = memory.index(blocks)
memory[i] = 0
while blocks > 0:
memory[(i + 1) % n] += 1
blocks -= 1
i += 1
return memory
def redistribute(memory):
count = 0
seen = set()
while True:
seen.add(... |
deltas = {
'R': (1, 0),
'L': (-1, 0),
'U': (0, 1),
'D': (0, -1),
}
def get_steps(moves, grid, junctions):
""" Calculate the steps it takes to get to each junction. """
x, y = 0, 0
steps = 0
taken = {}
for d, dist in moves:
dx, dy = deltas[d]
for i in range(1, dis... |
"""
Created on Mon Jan 13 18:16:35 2020
@author: Aakash
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv("./Datasets/admissions.csv")
x=np.array(data["TOEFL Score"])
y=np.array(data["CGPA"])
def gradient_descent(x,y,learning_rate=0.0001,num_iterations =... |
example = """nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6"""
def execute():
with open('2020/input/8.txt') as inp:
lines = inp.readlines()
code = [l.strip() for l in lines if len(l.strip()) > 0]
return run_until_loop_or_exit(code)["accumulator"], flip_until_halt(code)
tests_fai... |
def execute():
with open('2015/input/9.txt') as inp:
lines = inp.readlines()
data = create_graph([l.strip() for l in lines if len(l.strip()) > 0])
return shortest_distance(data), longest_distance(data)
tests_failed = 0
tests_executed = 0
distances = """London to Dublin = 464
London to Belfast = ... |
def execute():
with open('2022/input/day.3.txt') as inp:
lines = inp.readlines()
data = [l.strip() for l in lines if len(l.strip()) > 0]
return total_priority(data), total_badge_priority(data)
tests_failed = 0
tests_executed = 0
sample_input = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZS... |
def execute():
with open('./input/day.13.txt') as inp:
lines = inp.readlines()
data = [l.strip() for l in lines if len(l.strip()) > 0]
paper = fold_paper(parse_origami(data))
render(paper)
return count_dots(paper)
tests_failed = 0
tests_executed = 0
def verify(a, b):
global tests_exe... |
class Card:
def __init__(self, value, suit):
if value >= 1 and value <= 13:
self.value = int(value)
else:
self.value = 1
if self.validSuit(suit):
self.suit = suit
else:
self.suit = "Spades"
def getFaceValue(self):
retu... |
import random
print(random.randrange(1, 100))
x = 5
y = 7.2
z = 4j
a = float(x)
b = int(y)
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
|
nums = [1, 2, 3]
for num in nums:
for letter in 'abc':
print(letter, nums)
for i in range(10):
print(i)
for i in range(1, 11):
print(i)
x = 0
while x < 10:
print(x)
x += 1
x = 0
while x < 10:
if x := 5:
breakpoint()
print(x)
x += 1
a = 0
while True:
pr... |
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
x = abs(-98.3)
print(x)
x = pow(5, 4)
print(x)
|
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(student. keys())
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(student. values())
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(student. items())
|
def primeNumbers(limit):
for i in range(2,limit+1):
for j in range(2,i):
if i%j==0:
break
else:
print(i)
limit = int(input())
primeNumbers(limit) |
number=int(input())
rev=0
while number!=0:
digit=number%10
rev=(rev*10)+digit
number//=10
print(rev) |
c = int(input('Enter temperature in Centrigrade'))
f = ((9*c)/5)+32
print('Temperature in Fahrenheit is: ',f)
|
List=[1,2,3,4,5,6,7,8]
flag=0
search=int(input('Enter num to search'))
for i in range(len(List)):
if List[i]==search:
print('Element is found')
flag=1
break
if flag==0:
print('Element is not found') |
def sumOfMultiplesOf3and5(limit):
l = []
i = 1
while True:
l.extend([3*i,5*i])
if 3*i==limit or 5*i==limit:
break
i+=1
return sum(l)
limit = int(input())
print(sumOfMultiplesOf3and5(limit)) |
first_number = int(input("Enter first Number: "))
second_number = int(input("Enter Second number: "))
x = first_number - second_number
print()
print("The Diffrence between first and second number is: ", x) |
"""
Created on Wed Nov 6 19:10:34 2019
@author: SampadAcharya
"""
if __name__ == '__main__':
n = 5
arr = [-7,-7,-7,-7,-6]
index=[]
def indexVal(arr, maxVal,n):
for i in range(n):
if arr[i]==maxVal:
m=i
index.append(m)
return inde... |
def __is_permutation(string1, string2):
if len(string1) != len(string2):
return False
set = {}
for i, v in enumerate(string1):
v = v.lower()
if v not in set:
set[v] = 1
else:
set[v] += 1
for i, v in enumerate(string2):
v = v.lowe... |
from collections import defaultdict
with open("Day06_Input") as f:
orbits = f.readlines()
orbits = list(map(lambda x: x.strip(), orbits))
print(len(orbits))
edges = defaultdict(list)
vertices = set()
for orbit in orbits:
orbitee, orbiter = orbit.split(")")
edges[orbiter].append(orbitee)
vertices... |
print("Павловська Катерина. КМ-93. Варіант 14. ")
print("Task2: Given an integer N (> 0), which is a degree of 2: N = 2K. Finding an integer K is an exponent of this degree.")
print()
import re
re_integer = re.compile("^[-+]?\d+$")
def validator(pattern, promt):
text = input(promt)
while not bool... |
print('Павловська Катерина. КМ-93. Варіант №14.')
print('You are welcomed by the guessing program')
Petails=int(input("Number of petails: "))
while Petails<=3:
print("The given values are incorrect, which flower does not exist, please try again")
Petails=int(input("Number of petals: "))
Version=int(input("... |
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
sbg = ['69', '88','11', '96', '00']
if n == 0:
return []
if n == 1:
return ['0', '8', '1']
if n == 2:
return sbg[:4]
... |
class Solution(object):
def countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
def dfs(root):
if root.left is None and root.right is None:
return 1, True
... |
def bis(a,b,func):
if (func(a) * func(b)>=0):
print("wrong assumption")
return
c=a
while((b-a)>=0.01):
c= (a+b)/2
if(func(c) == 0.0):
break
if(func(c)*func(a)<0):
b=c
else:
a=c
return (a+b)/2 |
import random
randNo = random.randint(1,100)
userGuess = None
totalGuesses = 0
while randNo!=userGuess:
try:
userGuess = int(input("Guess the number between 1 to 100: "))
if randNo != userGuess:
if userGuess>randNo:
print("Your guess is wrong, Select the smaller numbe... |
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while True:
ret,frame = cap.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
k = cv2.waitKey(0)
if k == 27:
cv2.destroyAllWindow... |
from PIL import Image
from numpy import *
from scipy.ndimage import filters
from pylab import *
im = array(Image.open("riaz.jpg"))
blur2 = zeros(im.shape)
for i in range(3):
blur2[:,:,i] = filters.gaussian_filter(im[:,:,i],2)
blur2 = uint8(blur2)
blur5 = zeros(im.shape)
for i in range(3):
blur5[:,:,i]... |
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
from scipy.ndimage import filters
im = np.array(Image.open("lena_noisy.png").convert("L"))
blur = filters.gaussian_filter(im,10)
sharp = im - blur
plt.figure("Unsharp masking Example")
plt.gray()
plt.subplot(131)
plt.title("Original")
p... |
i = 0
while(i<8):
print(i)
i = i + 1
|
list1 = ['Vivek', 'Larry', 'Carry', 'Marie']
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
for item in list1:
print(item)
list1 = ('Vivek', 'Larry', 'Carry', 'Marie')
for item in list1:
print(item)
list1 = [["Vivek", 1], ["Larry", 2],
... |
lis = ["john","cena","khali","randy","ortan","sheamus","jinder mahal"]
a = " and ".join(lis)
print(a)
b = " , ".join(lis)
print(b)
|
def print_2(str):
print("This is",str)
print_2("kajal")
def factorial_iterative(n):
'''
:param n: integer
:return: n * n-1 * n-2.....1
'''
fac=1
for i in range(n):
fac=fac*(i+1)
return fac
def factorial_Recursion(n):
'''
:param n: Inte... |
class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
n = len(points)
if n <= 1:
return n
points.sort(key=lambda a: a[1])
count = 1
curr_s... |
def add(x: float, y: float) -> float:
return x + y
add(3, 4)
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def isVal... |
class Solution:
def convert(self, s: str, numRows: int) -> str:
if (numRows == 1) or (numRows > len(s)):
return s
rows = [''] * numRows
row = 0
increment = 1
for c in s:
rows[row] += c
row +=... |
class Solution(object):
valid_filed = {str(i) for i in range(256)}
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
n = len(s)
if n == 0:
return []
ans = set()
address = ['' fo... |
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
n = len(intervals)
if n == 0:
return 0
intervals.sort(key=lambda a: a[1])
... |
class Solution:
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
r, c = len(matrix), len(matrix[0])
low, high = 0, r * c - 1
while low <= high:
mid = low + (high - low) // 2
m, n = mi... |
class Solution:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
def canBreak(s, memory, wordDict):
if s in memory:
return memory[s]
if s in wordDict:
memory[s] = True
return True... |
class Solution:
def triangleNumber(self, nums: list[int]) -> int:
res = 0
l = len(nums)
if l < 3:
return res
nums.sort(reverse=True)
for loc_c, c in enumerate(nums):
loc_b = loc_... |
import math
vel = float(input("Velocity (m/s): "))
mass = float(input("Mass (kg): "))
energy_kinetic = 0.5*mass*(math.pow(vel, 2))
print("The Kinetic Energy is " + str(energy_kinetic) + " Joules.")
|
import time
import threading
def calc_square(num):
print("Calculating squares")
for n in num:
print("Square", n*n)
def calc_cube(num):
print("Calculating Cubes")
for n in num:
print ("cube", n*n*n)
number = [1,2,3,4]
t = time.time()
t1 = threading.Thread(target = calc_square,args=(ra... |
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
dic = {}
for k,v in zip(keys,values):
dic[k] = v
print(dic)
|
test1 = input("Are you craving spicy food? (Y/N) :")
test2 = input("Are you craving sweets? (Y/N) :")
test3 = input("Are you suffering from extreme morning sickeness or hyperemesis (Y/N) :")
test4 = input("Is the baby's heart rate above 150 beats per minute? (Y/N) :")
if test1.upper() == "N" and test2.upper() == "N"... |
"""
Created on Fri Nov 15 15:33:08 2019
@author: yousuf
"""
import numpy as np
from datetime import datetime
from sklearn.linear_model import LinearRegression
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
'''
predictLinear takes in a ticker, a start date, and the number... |
"""
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows
like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
================================================
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINA... |
values = '6 12 8 10 20 16'
frequency = '5 4 3 2 1 5'
values = values.split()
frequency = frequency.split()
values = [float(x) for x in values]
frequency = [float(x) for x in frequency]
index_median = 0
def create_list(values, frequency):
arr = []
for i in range(len(values)):
for freq in range(in... |
def describe_city(city, country="China"):
print(str(city).title() + " is in " + country.title())
describe_city("Shanghai")
describe_city("Beijing")
describe_city(city="Chongqing")
describe_city("London", "England")
describe_city(city="California", country="America")
|
with open("guest.txt", "a") as file_obj:
while True:
name = input("What is your name please? ")
file_obj.write(name + "\n")
repeat = input("Add other guest? (yes / no) ")
if repeat.lower() == "no":
break
|
favorite_places = {
'William': ["Hainan", "Guangzhou", "Yunnan"],
'Sunna': ["Shanxi", "Greece", "London"],
'Wilson': ["Shanghai", "Beijing", "Hong Kong"]
}
for name, places in favorite_places.items():
print(name.title() + " likes following places:")
for place in places:
print("\t" + place... |
visit_places = {}
poll_active = True
while poll_active:
name = input("What is your name? ")
place = input("If you could visit one place in the world, where would you go? ")
visit_places[name] = place
repeat = input("Would you like to let another person respond? (yes / no)")
if repeat.lower() == ... |
with open("survey.txt", "a") as survey:
while True:
reason = input("Why do you want to learn Python? ")
survey.write(reason + "\n")
repeat = input("Continue? (yes / no) ")
if repeat.lower() == "no":
break
|
class Restaurant:
def __init__(self, restaurant_name, cuisine_type, number_served=0):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = number_served
def describe_restaurant(self):
print(self.restaurant_name + " is a " + self.cuisin... |
rivers = {
'Nile': 'Egypt',
'Changjiang': 'China',
'Ganges River': 'India'
}
for river, location in rivers.items():
print("The " + river + " runs through " + location + ".\n")
for river in rivers.keys():
print(river)
print()
for location in rivers.values():
print(location)
|
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def _rob_range(nums, i, j):
last = now = 0
for x in range(i, j):
last, now = now, max(now, last + nums[x])
return now
if not num... |
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return
odd = even = even_head = None
cur = head
while cur:
if odd:
odd.next = cur
o... |
class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
bil = [0, 0]
for b in bills:
if b == 5:
bil[0] += 1
elif b == 10:
if bil[0] < 1:
return Fal... |
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head:
return
fast, slow = head, head
while fast and fast.next and fast.next.next:
... |
class Solution(object):
"""
Python can do it directly by str(int(num1)*int(num2))
"""
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = [0] * (len(num1) + len(num2))
lengh = len(res)
for i, n1 in en... |
def guess(num: int) -> int:
if num == 6:
return 0
elif num > 6:
return -1
return 1
class Solution:
def guessNumber(self, n: int) -> int:
l = 1
r = n
while True:
if l == r:
return l
mid = (l + r) // 2
ret = gu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.