text stringlengths 37 1.41M |
|---|
# Program to return the sum of the numbers in the list
def sumList(nums):
count = 0
for i in nums:
count += i
return count
def main():
nums = [1, 2, 133]
print(sumList(nums))
main()
|
# c11ex05.py
# various list algorithms
def count(myList, x):
ans = 0
for item in myList:
if item == x:
ans = ans + 1
return ans
def isin(myList, x):
for item in myList:
if item == x:
return True
return False
def index(myList, x):
for i in range(len(myL... |
# c13ex05.py
# recursive algorithm for base conversion
def baseConversion(num, base):
# PRE: num and base are integers with num >= 0 and base > 1
if num < base:
# base case is left most digit
print(num, end=' ')
else:
#remove last digit, recurse and then print last digit
l... |
def fibo():
n = int(input("Enter a positive integer: "))
total = 0
i = 0
while i <= n:
if i % 2 != 0:
total += i
i += 1
print(total + 2 * n - 1)
fibo()
|
# c08ex11.py
# heating/colling degree-days
def main():
print("Heating and Cooling degree-day calculation.\n")
heating = 0.0
cooling = 0.0
tempStr = input("Enter an average daily temperature: ")
while tempStr != "":
temp = float(tempStr)
heating = heating + max(0, 60-temp)
... |
# c06ex08.py
# square roots
def nextGuess(guess, x):
return (guess + x/guess) / 2.0
def sqrRoot(x, iters):
guess = x / 2.0
for i in range(iters):
guess = nextGuess(guess, x)
return guess
def main():
x = float(input("Enter the value to take the root of: "))
n = int(input("Enter t... |
# c07ex12.py
# Date validator
from c07ex11 import isLeap
DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isValidDate(month, day, year):
if 1 <= month <=12:
# month OK, check day
# determine last day of month
if month == 2:
if isLeap(year):
... |
# c11ex02.py
# A program to sort student information into GPA order.
from gpa import Student, makeStudent
def readStudents(filename):
infile = open(filename, 'r')
students = []
for line in infile:
students.append(makeStudent(line))
infile.close()
return students
def writ... |
# c13ex03.py
# A recursive palindrome checker
#
def isPalindrome(s):
# The base case
if len(s) < 2:
return True
elif not s[0].isalpha():
# ignore s[0] if non-letter
return isPalindrome(s[1:])
elif not s[-1].isalpha():
# ignore s[-1] if non-letter
return isPalin... |
# c13ex06.py
# digits in english
# global list of words
engDig = ["Zero","One","Two","Three","Four","Five",
"Six","Seven","Eight","Nine"]
def digitsToWords(num):
# base case is left most digit
if num < 10:
print(engDig[num], end=' ')
else:
currentDigit = num % 10
dig... |
import math
hydrogen = float(input("Enter the number of hydrogen atoms: "))
carbon = float(input("Enter the number of carbon atoms: "))
oxygen = float(input("Enter the number of oxygen atoms: "))
hydrogen = 1.00794 * hydrogen
carbon = 12.0107 * carbon
oxygen = 15.9994 * oxygen
print("The molecular weight o... |
# c10ex10.py
# Cube class
class Cube:
def __init__(self, side):
self.side = side
def getSide(self):
return self.side
def surfaceArea(self):
return 6 * self.side ** 2
def volume(self):
return self.side ** 3
def main():
print("This program computes the volume a... |
import math
diameter = float(input("Enter the diameter of your pizza: "))
price = float(input("Enter the price of your pizza: "))
def areaOfPizza(diameter):
return math.pi * (diameter/2)**2
def costSquareInch(diameter, price):
return price / areaOfPizza(diameter)
def main():
print("The area ... |
# c04ex09.py
# creates a rectangle
from graphics import *
import math
def main():
win = GraphWin("Rectangle!",500,500)
win.setCoords(0,0,10,10)
msg = Text(Point(5,1),"Click opposite corners of a rectangle").draw(win)
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
... |
# c05ex07.py
# Caesar cipher (non-circular)
def main():
print("Caesar cipher")
print()
key = int(input("Enter the key value: "))
plain = input("Enter the phrase to encode: ")
cipher = ""
for letter in plain:
cipher = cipher + chr(ord(letter) + key)
print("Encoded message follow... |
#Given February 16, 2020
#Suppose an arithmetic expression is given as a binary tree.
#Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'.
#Given the root to such a tree, write a function to evaluate it.
#For example, given the following tree:
# *
# / \
# + +
# / \ / ... |
import random
import math
def remove(newrow,keep,discard):
vertex = newrow[0]
i =1
while(i<len(newrow)):
if((newrow[i] == keep)|(newrow[i] == discard)):
del(newrow[i])
else:
i=i+1
def replace(row2,replace_var):
delete_var = row2[0]
numofneigh = len(r... |
def lb_to_kg(input1):
output=[]
print("Weight in Lb's:",input1)
for i in range(0,len(input1)):
i = round(input1[i]*(0.453592),2)
output.append(i)
return output
def string_alternative(input2):
x=[]
y=''
for i in input2:
x.append(i)
for i in range (0,len(x)):
... |
'''
Dynamic Programming(Tabularization)
There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter... |
def reverse(S):
#Add code here
st=[]
for i in S:
st.insert(0,i)
ans = ""
for i in st:
ans+=i
return ans
|
# 당신은 택시기사이고, 어플로 손님을 매칭할 수 있다.
#50명의 승객과 매칭 기회가 있다. 이때 총 탑승 승객 수를 구하는 프로그램을 작성하시오.
#조건1: 승객별 운행 소요 시간은 5분~50분 사이의 난수로 정해진다.
#조건2: 당신은 소요 시간이 5분~15분 사이의 손님만 태울수 있다
from random import *
customers = range(1,51)
customers = list(customers)
num = 0
count = 0
for info in range(50):
minute = randrange(5,51)
num += ... |
// Calculate Factorial Example
number = int(input("Number : "))
factorial = 1
if number<0:
print("The factorial of negative numbers cannot be calculated.")
elif number == 0:
print("Result : 1")
else:
for i in range(1,number+1):
factorial = factorial * i
print("Result : ", factorial) |
'''
| Write a program that replaces all vowels in the with ‘* |
|---------------------------------------------------------|
| Using re module. |
'''
import re
string = input("Enter the string\n")
print(re.sub('[aeiouAEIOU]','*',string))
|
'''
| Write a program to read two strings and perform concatenation and comparison operations on it |
|-----------------------------------------------------------------------------------------------|
| We use the input() function to receive input from the user and print() function to print it |
'''
f1 = input("Strin... |
"""
|-------------------------------------------|
| Problem 3:⦁ Write a program to find the |
| largest of three numbers |
|-------------------------------------------|
| Approach: |
| We use the max() function |
|---------------------------------------... |
"""
|-------------------------------------------|
| Problem 4: Write a program to find whether|
| the year is a leap year or not. |
|-------------------------------------------|
| Approach: |
| First, check if the year is divisible by |
| 100. If so, check is the year is ... |
"""
|-------------------------------------------|
| Problem 3:⦁ Write a program to find the |
| largest of three numbers |
|-------------------------------------------|
| Approach: |
| We use the max() function |
|---------------------------------------... |
#!/usr/bin/python3
############################################################################################################################
#
#
# To Find the number of Characters, Words and Lines in test.txt as input file, and storing output in output.txt
#
#
#############################################... |
########################################################
#
# Program to perform CRUD operation on a table named
# "registration" in the database "student"
#
#######################################################
import mysql.connector
from mysql.connector import Error
import logging
# create the logging object
log... |
def main():
print("Enter the no")
numb=list(input())
# checking whether the input is a whole number
assert int(''.join(numb))>-1, 'Enter positive number'
sum=0
for i in numb:
sum=sum+pow((int(i)),len(numb))
if sum== int(''.join(numb)):
print ("Armstrong number")
else:
print ("Non Armstrong number")
ma... |
import sqlite3
connection = sqlite3.connect("addressbook.db")
print("Database opened successfully")
cursor = connection.cursor()
#delete
cursor.execute('''DROP TABLE Address;''')
connection.execute("create table Address (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, address TE... |
from tkinter import *
master = Tk()
x = Entry()
x.pack(pady=10,padx=10)
x.insert(END, "a default value!")
def ok():
t = x.get()
print(t.capitalize())
def delt():
x.delete(0, END)
b = Button(master, text="ok", command=ok)
c = Button(master, text="delete", fg="red", command=delt)
b.pack()
c.pack()
master.mainl... |
#-*- coding: utf-8 -*-
from collections import namedtuple
from collections import defaultdict
Grade = namedtuple('Grades',('score', 'weight'))
def fake():
pass
class Subject(object):
def __init__(self):
self._grade = []
self.count = 0
def Gen(self):
self.count += 1
... |
from datetime import datetime
from model.Despesa import Despesa
from linkedList.LinkedList import LinkedList
import locale
import time
import os
class TelaDespesas:
# Criando método para padronizar os dados em moeda real:
locale.setlocale(locale.LC_MONETARY, "pt_BR.UTF-8")
def __init__(self):
li... |
import time
# Reference: https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/
# Reference: https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/
# class for Prim's algorithm
class PrimGraph:
def __init__(self, vertices):
self.vertices = vertices
... |
# function for demonstrating the insertion sort algorithm
def ins_sort(arr):
count = 0
# iterate through the length of the list
for i in range(1, len(arr)):
count += 1
key = arr[i]
j = i - 1
# Swap the elements in the list if the preceding element exceeds the succeeding elem... |
# Using a base class to initialize the id of the nodes and the size for the weighted quick union
class UF:
# referred the documentation for __init__ and self
def __init__(self, size):
self.id_no = list(range(size))
self.sz = list(range(size))
# Class quick find from the base class
# constructo... |
import re
with open("python_07.fasta","r") as f:
for line in f:
line=line.rstrip()
found=re.search(r">",line)
if found:
# print(line)
match=re.search(r">(\S+)",line)
if match:
print(match.group(1))
#group1 specifies everything inside the parentheses
# startMatch=match.start()
# endMatch=ma... |
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self, node=None):
self.head = node
def insert(self, value):
node = Node(value)
node.next = self.head
self.head = node
return se... |
left = {
"fond": "enamored",
"wrath": "anger",
"diligent": "employed",
"outfit": "garb",
"guide": "usher",
}
right = {"fond": "averse", "wrath": "delight", "diligent": "idle", "guide": "follow", "flow": "jam"}
def left_join(hashmap1, hashmap2):
result = []
values1 = list(hashmap1.values(... |
class Node:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
class K_aryTree:
def __init__(self, root=None):
self.root = root
def pre_order(self):
pre_order_list = []
def traverse(root):
... |
####################################
# Author: Amber Lee #
# Email: cryptoboxcomics@gmail.com #
# Info: A choose-your-own #
# adventure game #
####################################
player_name = ""
player_health = 100
player_money = 50
player_species = "Human"
player_weapons = ... |
fhand = open(input('Enter a filename (recommended mbox-short.txt): '))
count = (0)
for line in fhand:
print(line.upper()) |
from karel.stanfordkarel import *
def turn_around():
"""
Makes Karel rotate 180 degrees/
"""
turn_left()
turn_left()
def turn_right():
"""
Makes Karel rotate 90 degrees clockwise.
"""
turn_left()
turn_left()
turn_left()
def plant_garden():
"""
Pre-condition: Kar... |
"""
File: complement.py
-----------------------
This file should define a console program that prompts a user for
a strand of DNA and displays the complement of that strand of DNA.
Further details and output format can be found in the Assignment 2
handout.
"""
def build_complement(strand):
"""
This function t... |
from simpleimage import SimpleImage
def red_channel(filename):
"""
Creates an image for the given filename.
Changes the image as follows:
For every pixel, set green and blue values to 0
yielding the red channel.
Return the changed image.
"""
image = SimpleImage(filename)
for pixel ... |
''' QUESTION:
Greedy person:
The owner of the shopping complex is a greedy person. The owner is very lazy to do anything and so felt lazy to count the number of digits in profit.
Also, he doesn't believe in anyone to assign that job. So he wants to make someone write a program to count the number of digits in the... |
import re
pattern = r's\S*'
string = 'smr tki yki smr ski' # 検索対象文字列
# 全て検索し、文字列リストを返す
result = re.findall(pattern, string)
print(result) # ['smr', 'smr', 'ski'] |
import time
starttime = time.clock()
a = []
for i in range(1,100):
if i % 3 ==0 and i % 5 == 0 :
a.append("fizzbuzz")
if i % 3 == 0 :
a.append("fizz")
elif i% 5 ==0 :
a.append("buzz")
else:
a.append(i)
print(a)
endtime = time.clock()
print("Duration {}".format... |
#Ask the user to input the temperature
temp = input("Please enter the current temperature (°F): ")
#Convert the input string temperature to an integer
temp = int(temp)
#Set up the equality statement for the input temperature
if temp >= 70:
print ("No jacket required")
else:
print ("Wear a jacket")
|
import numpy as np
'''
TAKEN FROM UDACITY - ARTIFICIAL INTELLIGENCE FOR ROBOTICS, LESSON 2, SEBASTIAN THRUN
# Write a program that will iteratively update and
# predict based on the location measurements
# and inferred motions shown below.
#1D KALMAN FILTER
def update(mean1, var1, mean2, var2):
new_mean = f... |
from collections import deque
class DAG(object):
"""Directed Acyclic Graph"""
def __init__(self, nodes = None):
"""
Init the graph.
If nodes is given, it should be a mapping {node_id: {children}}
"""
self._nodes = nodes if nodes else {}
self._properties = {n: {}... |
def is_prime(x):
# check if x is prime
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(2,int(x)):
rem = x % i
if rem == 0:
return False
else:
return True
def inputfac(num):
# return list of prime factors of num
primelist = []
nonlist = []
... |
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(2,x):
rem = x % i
if rem == 0:
return False
else:
return True
def findprimes(w,x):
primes = []
for i in range(w,x+1):
... |
# import pygame
# start drawing
# lines 8 - 21 displays pygame window
import pygame
import sys
BOARD_SIZE = WIDTH, HEIGHT = 640, 480
DEAD_COLOR = 0, 0, 0
ALIVE_COLOR = 0, 255, 255
class LifeGame:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode(BOARD_SIZE)
# ball = p... |
'''def ecrit():
a=-1
while(a<0):
a=input("donnez number positive a")
return (a)
def puissance(x,n):
if(n==0):
return(1)
else:
x=x*puissance(x,n-1)
return(x)
x=ecrit()
y=puissance(x,3)
print(x,y)'''
def saisi():
n=input("donnez n")
b=0
while(b<2)and(b>8)... |
#fortune cookie bot
#before we start the programme, we ask python to get all the packages we need
#random allows us to pick a random fortune later
#time allows us to pause between outputs
#pyttsx3 is the package that does speech for us. We will ask it to start up and will close it down later
import random
import ... |
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for row in range(len(A)):
A[row] = A[row][::-1]
for col in range(len(A[row])):
A[row][col] ^= 1
return A
... |
class Solution:
def isToeplitzMatrix(self, matrix: 'List[List[int]]') -> 'bool':
for i in range(len(matrix) - 1):
for j in range(len(matrix[0]) - 1):
if matrix[i][j] != matrix[i + 1][j + 1]:
return False
return True
def main():
input = ... |
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums) <= 0:
return 0
if len(nums) == 1:
return nums[0]
dp = [0]*len(nums)
for i, num in enumerate(nums):
dp[i] = max(dp[i-1] + num, num)
return ... |
from typing import List
class Solution:
def lengthOfLastWord(self, s: str) -> int:
word_list = s.split()
return len(word_list[-1])
def main():
# Example:1
s = "Hello World"
print(Solution().lengthOfLastWord(s))
# Input: s = "Hello World"
# Output: 5
# Explanation: The las... |
class Solution:
def findLUSlength(self, a: str, b: str) -> int:
if a == b:
return False
return max(len(a), len(b))
def main():
print(Solution().findLUSlength("aba","cdc"))
# Output: 3
# Explanation: The longest uncommon subsequence is "aba" (or "cdc"),
... |
class Solution:
def findWords(self, words: 'List[str]') -> 'List[str]':
a = set('qwertyuiop')
b = set('asdfghjkl')
c = set('zxcvbnm')
ans = []
for word in words:
loWordList = set(word.lower())
if set(a) - (set(a) - set(loWordList)) == loWordLis... |
import random
import string
from words import words
def get_valid_word(words):
word = random.choice(words) # randomly select a word from words list
while '-' in word or ' ' in word:
word = random.choice(words)
return word
def hangman():
word = get_valid_word(words).upper()
word_letter... |
class AbstractAngle(object):
__slots__ = ['atom1', 'atom2', 'atom3']
def __init__(self, atom1, atom2, atom3):
self.atom1 = atom1
self.atom2 = atom2
self.atom3 = atom3
def __eq__(self, object):
if ((self.atom1 == object.atom1 and
self.atom2 == object.atom2 and
... |
a=input("enter the first number : ")
b=input("enter the second number : ")
print("the first number is", a.replace(a,b))
print("the second number is", b.replace(b,a))
|
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n is 0:
return []
result = []
curr = ""
self.backtrack(result, n, curr, 0, 0)
return result
def backtrack(self, result, n, curr, op, cl):
if len(curr) is 2*n:
... |
# person3 = {'Name': 'Ford Prefect',
# 'Gender': 'Male',
# 'Occupation':'Researcher',
# 'Home Planet':'Not Earth'
# }
#
#
# print(person3['Gender'])
# person3['Age'] = 33
# print(person3['Age'])
found = {}
found['a'] = 0
found['e'] = 0
found['i'] = 0
found['o'] = 0
fou... |
#Cálculo de la potencia. Calcular a^n cuando n es potencia de 2
def calcularPotencia(a,n):
if n==2:
b=a
else:
b=calcularPotencia(a,n//2)
return b*b
def __main__():
print(calcularPotencia(5,4))
if __name__=="__main__":
__main__() |
import tkinter
from tkinter import *
from tkinter.ttk import *
import os
import sqlite3
conn=sqlite3.connect('My.project12.db')
window=Tk()
window.title("ACCOUNT LOGIN")
window.geometry('550x300')
#window.configure(background="orange")
#window.configure(highlightbackground="#d9d9d9")
#window.configure(hi... |
# Escreva um programa para aprovar o emprestimo bancario para a compra de uma casa. O programa vai perguntar o valor da casa, o salario do comprador e em quantos anos ele vai pagar
# Calcule o valor da prestação mensal sabendo que ela não pode exeder 30% do salario ou entãoo emprestimo será negado
valor = float(input(... |
from datetime import date
year = date.today().year
age = int(input('Digite seu ano de nascimento: '))
age = year - age
if(age <= 9):
print('Mirim')
elif((age > 9) and (age <= 14)):
print('Infantil')
elif((age > 14) and (age <= 19)):
print('Junior')
elif((age > 19) and (age <= 20)):
print('Sênior')
el... |
# Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo
from random import randint
from time import sleep
c = 0
ppt = 'PEDRA, PAPEL, TESOURA'
print('-' * 30)
print(ppt.center(30))
p... |
#Peça dois valores e escreva na tea o maior ou diga se os dois são iguais
n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
n = [n1, n2]
n.sort()
print('')
if(n[0] == n[1]):
print('Os numeros são iguais!')
else:
if(n[1] == n1):
print('O primeiro valor é maior... |
# Desenvolva um programa que leia duas notas de um aluno, calcule e mostre sua media
n1 = float(input('Nota 1: '))
n2 = float(input('Nota 2: '))
x = (n1 + n2) / 2
print('Media: {:.1f}' .format(x))
|
# Faça um programa que leia um número qualquer e mostre o seu fatorial
num = int(input('Digite um numero: '))
result = 1
print(f'Calculando {num}! = ', end='')
while(num != 0):
result = result * num
if(num == 1):
print(num, end=' = ')
print(result)
else:
print(num, end=' x ')
... |
# Desenvolva um programa que pergunte a distancia de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por km para viagens de ate 200km e R$0,45 para viagens mais longas
km = int(input('quantos km teve a viagem: '))
if(km <= 200):
price = km * 0.5
elif(km > 200):
price = km * 0.45
print('O preço... |
#Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
# A) Quantos números foram digitados.
# B) A lista de valores, ordenada de forma decrescente.
# C) Se o valor 5 foi digitado e está ou não na lista.
num = list()
print('\nDigite uma letra para parar')
print('-=-' * 10)
while T... |
# Converta uma temperatura de C° para F°
c = float(input('C° = '))
f = (c * 9/5) + 32
print('{}F°' .format(f)) |
# Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles
end = False
times = 0
add = 0
while(end == False):
n = int(input(f'Digite o {tim... |
# Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores ‘M’ ou ‘F’. Caso esteja errado, peça a digitação novamente até ter um valor correto
loop = True
while(loop == True):
gender = str(input('Qual é o seu sexo?(M, F): '))
if gender.lower() in('m', 'f'):
loop = False
else:
... |
# Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente
lnum = list()
print('Digite um numero para adicionalo na lista')
print('Digite ... |
def has_even_neg_numbers(array):
neg_num = 0
for num in array[-3:]:
if num < 0:
neg_num = neg_num + 1
if neg_num == 0:
return None
if neg_num % 2 == 0
return -3
def solution(array):
sorted_array = sorted(array, key=lambda num: abs(num))
print(sorted_array... |
from collections import deque
def solution(array, cycles):
if len(array) == 0:
return []
new_list = array
for _ in range(cycles):
queue = deque(new_list)
queue.appendleft(de.pop())
new_list = list(de)
return new_list |
from .factory import *
"""
This module handles taking an external file and parsing out youtube links.
This will be used on an extract of a bookmarks.html from mozilla.
"""
"https://www.youtube.com/watch?v=U18Ru3k5HrM"
def find_url(string):
count, url, array = 0, "", []
index = string.find("https://www.yout... |
#!/usr/bin/env python
# coding: utf-8
# # 1. Conditional Basics
# In[73]:
# a. prompt the user for a day of the week, print out whether the day is Monday or not
input_day = input("Please type a day of the week: ")
if input_day.capitalize() == "Monday":
print("It is Monday")
else:
print("It is not Monday")
... |
import threading
import time
import random
semaphore = threading.Semaphore(0) # 创建信号量
def producer():
global item
time.sleep(3)
item = random.randint(1, 1000)
print("product : 生产 %s." % item)
semaphore.release()
def consumer():
print("consumer : 挂起")
semaphore.acquire()
print("cons... |
# you can add imports but you should not rely on libraries that are not already provided in "requirements.txt #
from collections import deque
import copy
def breadth_first_search(stack):
flip_sequence = []
# --- v ADD YOUR CODE HERE v --- #
visited = deque()
deq = deque()
traverse = []
counte... |
import random
count = 0
f = open("highscore.txt", "r")
currentHigh = int(f.read())
f.close()
guessed = False
print("The current high score is: {}".format(currentHigh))
difficulty = int(input("What do you want the difficulty to be (Number)"))
guessNumber = random.randint(0,difficulty+1)
while (guessed == False):
gue... |
import numpy as np
import matplotlib.pyplot as plt
### Uncomment each section and play with the variables marked as hyper-parameters
###
###grid search and random search
'''
n_search = 10 #hyperparameter #how many values should we search
x_plot = np.linspace(0.001, 2.5, 400)
y_plot = (np.sin(10*np.pi*x_plot)/(2*x_p... |
# STAT/CS 287
# HW 01
#
# Name: Cecily Page
# Date: September 11 2018
import urllib.request
from os import path
from string import punctuation
import collections
import operator
def words_of_book():
"""Download `A tale of two cities` from Project Gutenberg. Return a list of
words. Punctuation has been remove... |
# Understanding
# * can we count
# solution: build count var
# * ONE pass, not FIRST pass
# sol: setup for the one pass
# turns out ^^^ was incorrect :grin:
# c
# [h/1] [2] [3] [4] [5] [6] [7] [t/8]
# m
# m = c // 2 + 1
# when (count reaches tail || next == null)
# return m
# class Node:
# ... |
name=input("enter your name:")
surname=input("enter your surname:")
deneme=3
failed=0
while True:
if deneme==0:
print("please try again later..")
break
if name=="Yusuf" and surname=="Volkan":
print("Welcome {} {}".format(name,surname))
deneme-=1
bre... |
def is_palindrome(n):
return str(n) == str(n)[::-1]
largest = 0
for n in range(100,1000):
for m in range(100,1000):
number = n * m
if is_palindrome(number) and number > largest:
largest = number
print largest
|
print("Happy 2021!!!")
# variables
secret_of_life = 42
gst_percentage = 0.07
# BMI Calculator
weight = float(input("Please enter your weight in kg"))
height = float(input("Please enter your height in metres"))
bmi = weight / (height * height)
if bmi < 18.5:
print("underweight")
# else if bmi < |
# Programming Exercise 2-3
#
# Program to convert area in square feet to acres.
# This program will prompt a user for the size of a tract in square feet,
# then use a constant ratio value to calculate it value in acres
# and display the result to the user.
# Variables to hold the size of the tract and number of... |
#WRITE YOUR CODE IN THIS FILE
def greaterThan (x,y):
if x > y:
return True
else:
return False
print(greaterThan(52, 2))
def lessThan (x,y):
if x < y:
return True
else:
return False
print(lessThan(52, 2))
def equalTo (x,y):
if x == y:
return ... |
"""
- 숫자 야구
해당하는 케이스를 확인하는 작업이 필요
remove 해서 남은 원소 파악하기
그러나 remove를 하면 인덱스가 조정이 된다는 사실을 인지하고
remove 후 인덱스를 옮겨야함
"""
from itertools import permutations
num_list = list(permutations([1, 2, 3, 4, 5, 6, 7, 8, 9], 3))
N = int(input())
# asdf = []
for _ in range(N):
test, s, b = [int(x) for x in input().split()]
tes... |
"""
- 절댓값 힙
힙에 넣을 때 크기만 필요하지만 출력시 부호를 고려해야 하므로
힙은 tuple을 원소로 가질 수 있음을 이용하여 tuple에 부호를 넣기
"""
import sys # input으로 했더니 틀림...
import heapq
input = sys.stdin.readline
N = int(input().rstrip())
heap = []
for _ in range(N):
num = int(input().rstrip())
if num != 0:
heapq.heappush(
heap, (abs(num... |
#Peter Tran
#1104985
#this program calculates stock transactions
#input
stockName = input("Enter Stock name: ");
numShares = int(input("Enter Number of shares: "));
purchasePrice = float(input("Enter Purchase price: "));
salePrice = float(input("Enter Selling price: "));
brokerCommission = float(input("Enter ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.