text stringlengths 37 1.41M |
|---|
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# TODO: Count the number of occurences of each word in s
a = dict()
split_s = s.split()
for sp in split_s:
a[sp] = a.get(sp,0) + 1
# TODO: Sort the occurences in descending order (alphabetically in c... |
num1=int(input("enter the first number"))
num2=int(input("enter the second number"))
num3=int(input("enter the third number"))
sum=num1+num2+num3
print(sum) |
# Parent Class
class User:
name = "Bill"
email = "bill@aol.com"
phone = "321-456-7544"
password = "abcde1234"
def getLoginInfo(self):
entry_name = input("Enter your name: ")
entry_email = input("Enter your email: ")
entry_phone = input("Enter your Phone Number: ")
... |
#Written by: Adrian Sanchez
#Prof: Diego Aguirre
#Class: Data Structures 2302
#Lab: 1
#Date completed: 9/12/19
import hashlib
def hash_with_sha256(str):
hash_object = hashlib.sha256(str.encode('utf-8'))
hex_dig = hash_object.hexdigest()
return hex_dig
#compares generated string after being hashe... |
def max_num(num1, num2, num3):
if num1>= num2 and num1>= num3:
return num1
elif num2>= num1 and num2>= num3:
return num2
else:
return num3
print(max_num(30, 4, 57))
# new code starts here
# float immediately converts into a number instead of the conventional stri... |
"""
DYNAMIC
Dynamic programming stuff
Stefan Wong 2019
"""
from pylc import stack
# debug
#from pudb import set_trace; set_trace()
# ======== Compute Fibonacci Sequence ======== #
def fibonacci(i:int) -> int:
if i == 0 or i == 1:
return i
return fibonacci(i - 1) + fibonacci(i - 2)
# ---- Memoized... |
"""
QUESTIONS
Answers to specific Leetcode questions
Stefan Wong 2019
"""
from typing import List, Optional
from pylc.tree import TreeNode, BinaryTreeNode
# debug
#from pudb import set_trace; set_trace()
# leetcode 3
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
def longest_uniqu... |
# python3
def linear_search(keys, query):
for i in range(len(keys)):
if keys[i] == query:
return i
return -1
def binary_search(keys, query, final_position, checker):
checker_position = len(keys) // 2
checker_value = keys[checker_position]
#print('Query:', query)
#print('... |
import tkinter as tk
from tkinter import *
from tkinter import messagebox
from googletrans import Translator
import pyperclip
#Creating the Frontend by using Tkinter
app = tk.Tk()
app.title('Tanslator')
app.geometry('500x350')
app.configure(bg="#eaeaea")
#String Variables
ent_var = StringVar()
out_var = StringVar()
... |
"""The interface used by user"""
from tkinter import *
class Interface:
"""The main interface"""
def __init__(self):
global root
root = Tk()
root.title("Expense Tracker")
mybutton1 = Button(root,text="Start", command = self.mybutton,width = 25, height = 5)
mybutton1.p... |
#add any 2 numbers
a=int(input("enter value of a"))
b=int(input("enter value of b"))
sum=a+b
print(sum) |
def tree(tpl):
dct = {} # словарь, где ключ - родитель, значение - множество детей
for index, apex in enumerate(tpl):
if apex not in dct:
dct.update({
apex: {index},
})
else:
dct[apex].add(index)
return dct
def height_tree(dct):
hei... |
A = int(input ("Could I ask you for a number? "))
k = 0
for i in range(A//2, 0, -1):
if A % i == 0:
k = k + i
if A == k:
print ("It is a perfect number")
else:
print ("It is not a perfect number")
|
# У меня большие проблемы с тем, чтобы сосолаться на функцию из другого модуля!
# Я умею импортировать модуль, но он у меня тогда его начинает запускать полностью!
# А если я ему пишу так: from Task_1 import factorial ()
# он меня не понимает! Поэтому пришлось копировать!
def factorial(x):
mult = 1
for i in r... |
import csv
def list_to_dict(l1: list, l2: list) -> dict:
result = {}
for index in range(len(l2)):
result[l2[index]] = l1[index]
return result
def csv_to_dict(file: str, dictKeyList: list) -> dict:
result = {}
open_file = open(file, 'r')
read_file = csv.reader(open_file)
... |
import math
func = lambda x: 2*math.sin(x) - x**2
fp = lambda x : 2*math.cos(x)-2*x
g = lambda x: math.sqrt(2*math.sin(x))
X = 1.3
root = 1.404418240924343641
def biseccion(a,b,n):
print("Bisección")
aN = a
bN = b
for i in range(1,n+1):
m_n = (aN+bN)/2
f = func(m_n)
print("a_N... |
import math
root1 = 0.22849140
root2 = 2.69682
def serie():
print('Serie de MacLaurin para ln((1+x)/(1-x)), evaluada en 0.75 para obtener ln(7)')
S = 0
x = .75
real = 1.94591014906
i = 0
while abs(S-real)>=0.00001:
S += 2*(x)**(2*i + 1) / (2*i +1)
print("S:", S, "error: "+"{:3... |
"""
Math 560
Project 3
Fall 2020
Partner 1: George Lindner (dgl12)
Partner 2: Ezinne Nwankwo (esn11)
Date: October 28, 2020
"""
# Import math and p3tests.
import math
from p3tests import *
################################################################################
"""
detectArbitrage
"""
def detectArbitrage(... |
l1=[10,20,30,40]
l1.append(40)
print(l1)
print("appending one list to another list")
l2=[300,400,500]
l1.append(l2)
print("append=",l1)
print("----------------------","ExtendMethod","----------------")
l2=[300,400,500]
l1.extend(l2)
print(l1)
l3=[10,20]
l2.extend(l3)
print(l2)
print("-------------","Insert Method ",... |
# Fitness Data Class.
# Create a class that has the properties:
# 1.) name (Constructor set)
# 2.) step count
# 3.) height (Constructor set)
# 4.) miles walked.
#
class FitnessData:
def __init__(self, name, height):
self.name = name
self.stepCount = 0
self.he... |
def RenjieWen():
print("he is cool")
def printLess100(n):
for x in n:
if x < 100:
print(x)
else:
print("something larger than 100")
def defineRange(n):
for x in n:
if x < 0:
print(x,'is a negative number')
elif x >= 43 and x < 100:
... |
#Proyecto final - Minijuego TATETI (Grupo: Juan Cruz - Mirko)
'''Reglamento:
1. Cantidad de jugadores: 2.
2. Objetivo: Formar TA-TE-TI en el tablero de juego.
3. El jugador que inicia el juego lo define el sistema en forma aleatoria.
Como jugar:
- Al inicio el sistema define en forma aleatoria cual de los 2 jugadores ... |
'''
A suite of functions to make eda plots with baseball data
'''
import matplotlib.pyplot as plt
import pandas as pd
from pymongo import MongoClient
def plot_stats_over_time(year_index, df, stats_to_plot, games_per_year):
'''
Parameters:
----------
Input:
year_index {list-like}: list of years co... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import numpy as np
def sigmoid(z):
p = 1 / (1 + np.exp(-z))
return p
def predict(x, theta):
m, n = x.shape
theta = theta.reshape((n, 1))
z = x * theta
a = sigmoid(z) > 0.5
return a |
def guess(num, k):
if num < k:
return -1
elif num > k:
return 1
else:
return 0
class Solution(object):
def guessNumber(self, n, k):
"""
:type n: int
:rtype: int
"""
l, r = 0, n
while l <= n:
mid = (l + r + 1) >> 1
... |
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def binary_search(self, array, target):
length = len(array)
l, h = 0, length - 1
while l <= h:
mid = l + (h - l) // 2
print(l, mid, h)
if array[mid] < target:
l = mid + 1
... |
#!/usr/bin/python
import socket
#from Tkinter import *
class player:
def __init__(self, n):
self.name = n
port = int(raw_input("define port: "))
conn = socket.socket()
host = socket.gethostname()
#port = 12345
conn.connect((host,port))
while True:
print "***MENU***"
print "1 - Enter names"
print "2 - Get na... |
import math
class SolutionTest(object):
def reverse(self, x):
ret = 0
mul = 1
sign = x/abs(x) if x is not 0 else 0
log = int(math.log(abs(x))/math.log(10)) if x is not 0 else 0
#maxmul = 10**log if x is not 0 else 0
for mul in [10**d for d in range(log + 1)]:
... |
def get_indices_of_item_weights(weights, length, limit):
"""
YOUR CODE HERE
"""
# Add all items to a hash table with weight: index
table = {}
for i in range(len(weights)):
# store indices in arrays so that we can handle duplicate weights
if weights[i] in table:
table[... |
import sqlite3 as sq
db = sq.connect('data/mydb')
cursor = db.cursor()
rowNumbers = 32
def createTable(headers):
#headers = [ "name" , "phone", "email" , "password" ]
try:
## connects to the database
#db = sq.connect('data/mydb')
# get a cursor object
#cursor = db.cursor()
# check... |
# Second Engeto project Bulls and Cows
import random
def welcome() -> None:
print("Hi there!")
separator()
print("I've generated a random 4 digit number for you. \nLet's play a bulls and cows game.")
separator()
def generate_number() -> (list, int):
number = [random.randint(1, 9)]
for i in ... |
""" False 包括:
1) None
2) 数值中的0(包括0.0)
3) 空序列,包括空字符串(""),空元组(()),空列表[]
4) 空字典{} """
# and - 与,or - 或,not - 非
user_gender = input("请输入您的性别(F/M): ")
user_is_student = input("您是学生吗?(Y/N): ")
if user_gender == 'F':
if user_is_student == 'Y':
print("你是萌妹子学生")
elif user_is_student == 'N':
... |
# 自己实现链表
class IntList(object):
def __init__(self, f, r):
self.first = f
self.rest = r
#获取链表长度,通过递归实现
""" def size(self):
if self.rest is None:
return 1
else:
return 1 + self.rest.size() """
#获取链表长度,通过循环实现
def size(self):
p = ... |
#字典(无序),可变的
#字典中的key类型必须是不可变的,例如数值,字符串或元组
#dict查找和插入的速度极快,不会随着key的增加而变慢。但其需要占用大量的内存,内存浪费多
#如果key重复,以最后一个的数据为准
user1 = {'name':'李雷','numbers':'1234',"name":'李四'}
print(user1['name'])
#使用列表和元组的组合,创建字典
message = [('lilei',98),('hanmeimei',99)]
d = dict(message)
print(d)
#根据关键字参数新建字典
d1 = dict(lilei = 98, hanmeimei = 99... |
#给定一组数字,将他们用链表的形式进行存储。另外再给一个数字,将它插入到链表的末尾。输出这个链表
#创建一个节点元素类
class IntNode(object):
def __init__(self, i, n):
self.item = i
self.next = n
#创建一个列表类
class SLList(object):
def __init__(self, x):
#两个下划线表示把变量或者方法设置成私有
self.__first = IntNode(x, None)
self.__last = self.__first
... |
import numpy as np
import matplotlib.pyplot as plt
# Load the data in format (energy,frequency)
data = np.loadtxt('results.csv',delimiter=',')
"""
We produce a plot of the hamming distance from our initial state against the frequency with which we measure these states
This is to demonstrate that we can measure states ... |
print("WELCOME TO MY CALCULATOR")
while True:
welcome_input = str(input("TO ENTER PROGRAMMING MODE 1 ENTER P. \nTO ENTER PROGRAMMING MODE 2 ENTER M \nTO ENTER SCIENTIFIC MODE ENTER S \nOR press any key TO EXIT: ").capitalize())
if (welcome_input == "P"):
print("You have entered programming mode 1.... |
import logging
def add (num1, num2):
return num1 + num2
def substr (num1, num2):
return num1 - num2
def multip (num1,num2):
return num1 * num2
def divid (num1, num2):
return num1/num2
print ("Podaj działanie, posługując się odpowiednią liczbą:")
print ("1 Dodawanie, 2 Odejmowanie, 3 ... |
"""
Tests the add() function of the calculator
"""
from calculator import add
def test_two_plus_two():
"""
If given 2 and 2 as parameters, 4 should be returned
"""
assert add(2, 2) == 4
def test_three_plus_three():
assert add(3, 3) == 6
def test_no_parameter():
assert add() == 0
def test_one... |
def is_palindrome(s, lo, hi):
while lo < hi:
if s[lo] != s[hi]:
return False
lo += 1
hi -= 1
return True
def solve(s):
lo, hi = 0, len(s) - 1
while lo < hi:
if s[lo] != s[hi]:
return is_palindrome(s, lo + 1, hi) or is_palindrome(s, lo, hi - 1)
... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
# File Name: test_sql2.py
# Author: Feng
# Created Time: Tue 30 Oct 2018 05:37:06 PM CST
# Content:
import sqlite3, os
db_file = os.path.join(os.path.dirname(__file__), 'test.db')
if os.path.isfile(db_file):
os.remove(db_file)
#初始数据
conn = sqlite3.connect(db_file)
... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
# File Name: test2.py
# Author: Feng
# Created Time: Tue May 8 19:40:17 2018
# Content: https://www.w3cschool.cn/python/python-exercise-example2.html
total = int(input("Enter a number: "))
arr = [1000000, 600000, 400000, 200000, 100000, 0]
rat = [0.01, 0.015, 0.03, 0.05,... |
'''
Created on Aug 27, 2016
@author: Sudeep
'''
#Normal print function
print ("Hello World")
#print using a custom function
def print_function(string):
print(string)
print_function("What a day")
#Perform normal numerical functions
a = 8
print(a*10) #Multiplication
print(a**10) #Exponential
|
import math as mt
from operator import itemgetter
# Report functions
def insertion_sort(lst):
for i in range(1, len(lst)):
current = lst[i]
j = i - 1
while j >= 0 and current < lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = current
return lst
def s... |
# Declaring a class
class lotteryPlayers():
def __init__(self): # init method which has sone variables which is
## available to all the objects
self.name = "Test"
self.numbers = (10,23,1,234,2)
def total(self):
return sum (self.numbers)
# Creating a player object
player = lotte... |
from flask import Flask, jsonify, request, render_template
app = Flask (__name__)
stores = [
{
"name" : "My store",
"items" :[
{
"name" : 'book',
"price": 10
}
]
}
]
@app.route("/")
def home():
return render_template("index.html")
#... |
name = 'Oladimeji Oladepo'
other_name = 'Akinlabi Ishola'
print(name[2])
print(name[2:4])
print(name[2:])
print(name[0:7:2])
print(len(name))
print(name.index('j'))
print(name.upper())
print(name.lower())
print(name.split())
print(name.split('O'))
print(f"My name is {name} and my other name is {other_name}")
|
#you cant use index, rather use the keys or put the dictionary in a List
salary = {'deji':400, 'enitan':500, 'bolu':350}
salaries = {'ayo':[20,30,40], 'dele':[25,35,45]}
print(salary)
print(salary['enitan'])
salary['kenny'] = 800
print(salary['kenny'])
salary['enitan'] = salary['enitan'] + 100
print(salary)
salary['dej... |
# age=input("请输入年龄")
# age=int(age)
# if(age<20):
# print("小孩")
# elif(age<40):
# print("青年")
# else:
# print("old")
for i in range(1,10,3):
print(i)
for i in "abc","def","jks":
print(i)
# 9*9乘法表
# i=1
# while i<10:
# j=1
# while j<=i:
# print("%d*%d=%d"%(j,i,j*i),end="\t")
# ... |
import sys
order = int(input(
"""
Bem vindo a Loja de Vendas!!!
1.Guaraná Antarctica - $1.00
2.Coca-Cola - $ 1.50
3.Energético RedBull - $2.00
Escolha o numero do pedido (1, 2, 3...)
"""
))
if order == 1:
disPrice = 1.00
print("Você escolheu Guaraná Antarctica.")
elif orde... |
#public => memberName
#protected => _memberName
#private => __memberName
class Car:
numberOfWheels = 4 #accesible anywhere within the program
_color = 'Black' #can be accessed within the class and within its derived classes. also outside of the classes
__yearOfManufacture = 2017 #cannot be accessed outside... |
import csv
from datetime import datetime
try:
with open('testdata.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter='-')
voltages = []
time = []
for row in readCSV:
print(row)
#time.append(row)
print("\n")
print(voltages)
print("... |
# try:
# for i in ['a','b','c']:
# print(i**2)
# pass
# except:
# pass
# try:
# x = 5
# y = 0
# z = x/y
# print (z)
# pass
# except:
# print ("Error")
# pass
# finally:
# print ("All Done")
def ask():
while True:
try:
val = int(input("Ple... |
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
median = None
nums = nums1+nums2
nums = sorted(nums)
median = nums[int((len(nums)-1)/2)] if len(nums)%2 == 1 els... |
#!/usr/bin/python
import sys
for line in sys.stdin:
# Input of the form "word docname count"
word, docname_count = line.strip().split(" ")
docname, count = docname_count.strip().split("\t")
# Output of the form "docname word count"
print"{0}\t{1} {2}".format(docname, word, count)
|
import pandas as pd
import csv
with open("height-weight.csv", newline = '') as f:
reader = csv.reader(f)
filedata = list(reader)
filedata.pop(0)
newdata = []
for i in range(len (filedata) ):
num = filedata[i][2]
newdata.append(float(num))
n = len(newdata)
newdata.sort()
if n % 2 =... |
__author__ = "ResearchInMotion"
# Write a Python program to sum all the items in a dictionary.
dicto = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
sum = 0
for values in dicto.values():
sum += values
print(sum)
|
__author__ = "ResearchInMotion"
arr = [2, 7, 11, 15, 6, 4]
maxElement = max(arr)
for i in range(len(arr)):
for j in range(len(arr)):
if arr[i] + arr[j] == maxElement:
print(arr[i], arr[j])
|
__author__ = "ResearchInMotion"
from collections import Counter
nums = [2,2,1]
def singleNumber(nums):
result = Counter(nums)
for key, value in result.items():
if value == 1:
return key
print(singleNumber(nums))
|
__author__ = "ResearchInMotion"
def insertionSort(arr):
indexing_len = range(1,len(arr))
for i in indexing_len:
values_sort = arr[i]
while arr[i-1] > values_sort and i > 0:
arr[i-1] , arr[i] = arr[i] , arr[i-1]
i = i-1
return arr
print(insertionSort(arr=[24... |
__author__ = "ResearchInMotion"
nums = [9,6,4,2,3,5,7,0,1]
def missingNumber(nums):
for value in range(0, len(nums) + 1):
if value not in nums:
return value
print(missingNumber(nums))
|
__author__ = "ResearchInMotion"
def searchInsert(nums, low, high, target):
if (high >= low):
mid = int(low + (high - low) / 2)
if nums[mid] == target:
return mid
elif nums[mid] > target:
return searchInsert(nums, low, mid - 1, target)
else:
retur... |
__author__ = "ResearchInMotion"
import math
nums = [1, 2, 3, 4]
newnums = []
maxval = max(nums)
for values in nums:
if values < maxval:
newnums.append(values)
for vals in newnums:
if vals+vals > maxval:
print("-1")
else:
print(maxval)
|
def txttolist(filename):
"""Takes a txt file and makes a list with each line being an element"""
return [line.split("\n")[0] for line in open(filename, "r")]
def isstrlessthan(string, length):
"""Checks if string is below length"""
return len(string) < length
def errormsg(e):
"""Generates an error... |
print(range(5))
for i in range(5):
print(i)
p = list(range(0, 5))
print(p)
q = list(range(5, 10))
print(q)
r = list(range(0, 10, 2))
print(r)
# range(5) --- 5 is the stop argument
# range(5, 10) --- 5 is start, 10 is stop, although the values move from 5 to 10 as 5,6,7,8,9
# range(10, 20, 2) --- 10 is start,... |
# a method is different from a function in a sense that it can
# only be called from within a class by the help of an object.
# A Method is a function associated with a class.
class Human:
def __init__(self, name, gender):
self.name = name
self.gender = gender
def speak_name(self):
... |
import math
class Circle:
def __init__(self, radius=1.0):
self.__radius = radius
def setRadius(self, r):
self.__radius = r
def getRadius(self):
return self.__radius
def calcArea(self):
area = math.pi*self.__radius*self.__radius
return area
def calcCircum(self):
circumference = 2.0*math.pi*self.__rad... |
class Student:
def __init__(self, name=None, age=0):
self.__name = name
self.__age = age
def getAge(self):
return self.__age
def getName(self):
return self.__name
def setAge(self, age):
self.__age=age
def setName(self, name):
self.__name=name
obj=Student("Hong", 20)
obj.getName()
|
class Student:
def __init__(self, name=None, age=0):
self.__name = name
self.__age = age
obj=Student()
print(obj.__age)
|
from tkinter import *
from tkinter import messagebox
from math import hypot
from PIL import ImageTk, Image
import os
def circle_area():
name = radius_vvod.get()
name = int(name)
name = name*name*3.14
name = str(name)
messagebox.showinfo('Circle Area', 'Area is: ' + name)
def length_area():... |
countries_information={}
countries_information["Polska"] = ("Warszawa" ,37.97)
for country in countries_information.keys():
print(country)
country=input("Info o jakim kraju chcesz zobaczyć ")
country_informaction=countries_information.get(country)
print("-")
print("country")
print('--')
print('stolic... |
# Uses python3
import sys
def get_majority_element(a, left, right):
if left == right:
return -1
if left + 1 == right:
return a[left]
#write your code here
return -1
def recursive_majority(A,len_,array,n):
if len_ == 1:
print(A)
array[A[0]]+=1
if array[A[0]]... |
# Uses python3
import sys
def get_number_of_inversions(a, b, left, right):
number_of_inversions = 0
if right - left <= 1:
return number_of_inversions
ave = (left + right) // 2
number_of_inversions += get_number_of_inversions(a, b, left, ave)
number_of_inversions += get_number_of_inversions(... |
def binary_search_recursive(array,item,high,low):
if low > high:
return "ELEMENT NOT FOUND"
mid = low + (high-low)//2
if array[mid]==item:
print("array[{}] = {}".format(mid,array[mid]))
return mid
elif array[mid]<item:
return binary_search_recursive(array,item,high,mid+1)
else:
return binary_search_rec... |
s = "aaAAwe Cc crwwwww wwBBbber WEr "
k = 3
def chars_met_counter(s, k):
refactored_string = s.lower().replace(' ', '')
chars_cout_dict = { chr(character): refactored_string.count(chr(character))
for character in range(ord('a'), ord('z')+1)}
final_string = ''.join('{}'.format(key) for key, val in sorted(
cha... |
zin = input('vul een zin in: ')
woorden = zin.split()
acroniem=''
for woord in woorden:
acroniem = acroniem + woord[0].upper()
print(acroniem)
|
from tkinter import *
import json
window = Tk()
window.title("친구관리")
address_book = {} # 공백 딕셔너리를 생성한다.
def add() :
name = e1.get()
phone = e2.get()
address = e3.get()
print(name)
info = [phone, address]
print(address_book)
print("추가")
t.insert(END, "이름:" +name+ "을 추가 했습니... |
class Calculadora:
def calcular_soma(self, numero1, numero2):
soma = numero1 + numero2
print("A soma é:", soma)
def calcular_subtracao(self, numero1, numero2):
subtracao = numero1 - numero2
print("A Subtracao é:", subtracao)
def calcular_multiplicacao(self, numero1, numero2... |
for numero in range(1, 11):
print('{0} x {1} = {2}'.format(8, numero, 8*numero))
|
num=int(input())
tree={'0':[1,0]}
for i in range(num-1):
parent,children=input().split()
if parent in tree and tree[parent][1]<2:
tree[children]=[tree[parent][0]+1,0]
tree[parent][1]+=1
depth=[x[0] for x in tree.values()]
print(max(depth)) |
import sqlite3
connection = sqlite3.connect("passwords.db")
cursor = connection.cursor()
masterPassword = "3141592"
cursor.execute('CREATE TABLE IF NOT EXISTS passwords (accounts text, password text)')
cursor.execute('SELECT * FROM passwords WHERE accounts = "masterPassword"')
connection.commit()
checker =... |
# Run this code to play Nim :)
import random as r
print("Welcome to Nim.")
player_type_input = raw_input("Please choose singleplayer (1) or multiplayer (2): ")
try:
value = int(player_type_input)
except ValueError:
print("Invalid input, please try again.")
player_type_input = raw_input("Please choose singleplayer... |
class beautyConsole:
"""This class defines properties and methods to manipulate console output"""
colors = {
"black": '\33[30m',
"red": '\33[31m',
"green": '\33[32m',
"yellow": '\33[33m',
"blue": '\33[34m',
"magenta": '\33[35m',
"cyan": '\33[36m',
... |
from random import shuffle
import time
'''Write a Java program that uses a Monte Carlo algorithm to calculate the
probability that next week's lottery draw won't have any consecutive
pairs of numbers (eg 8 and 9 or 22 and 23). Six numbers are drawn
from 1 to 45.'''
a = time.clock()
n = range(1,46)
times =1000000
count ... |
#
# problem_id_4.py
# Problem: Largest palindrome product
# Last Modified: 8/14/2017
# Modified By: Andrew Roberts
#
def largest_palindrome():
largest_product = 0
palin = None
for i in range(100, 1000):
for j in range(100, 1000):
prod = i * j
if str(prod) == str(prod)[::-1]:
if prod > largest_product:
... |
class Address:
def __init__(self, country, city, street):
self.country = country
self.city = city
self.street = street
def __str__(self):
result = ''
for k,v in self.__dict__.items():
result += f'{k} : {v}\n'
return result
class AddressPars... |
# Question 1 :
# Consider one string as input. You have to check whether the strings obtained from the input string with single backward and single forward shift are the same or not. If they are the same, then print 1; otherwise, print 0.
# Hint:
# Backward Shift : A single circular rotation of the string in which... |
x=int(input("Give an integer:"))
while x > 1000000:
x=int(input("Give another number:"))
#checks if the number given is already prime
if x%2==1:
print ("The number is already prime!")
if x%2==0:
i=0
j=0
k=0
z=0
tot=0
#does the modification with 2
while x%2==0 :
... |
# implementation of correlation of given two signals
import numpy as np
import matplotlib.pyplot as plt
a=[5,2,3]
b=[2,4,1]
def convolution(a,b):
m=np.size(a)
n=np.size(b)
c=np.zeros(m+n-1)
for i in range(m):
for j in range(n):
c[i+j]=c[i+j]+a[i]*b[j]
return c
x=list()
p=input... |
from random import randint
from gameComponents import gameVars
def compare(status):
# this will be the AI chiice -> random pick from the choices array
computer = gameVars.choices[randint(0, 2)]
#validate that the random choice worked for the AI
print("AI chose: " + computer)
# adding in separation
print("_____... |
# Got help from Jake Shams
def knapsack(items, capacity):
'''inputs:
an array of tuples with weights and values
maximum capacity of the bag
output:
the max value that can fit in the bag
'''
if len(items) == 0 or capacity == 0:
return 0
weight, val... |
from util import file_to_graph
from sys import argv
if __name__ == '__main__':
assert argv[1] is not None, "Data file path is required."
assert argv[2] is not None, "'From' vertex is required."
assert argv[3] is not None, "'To' vertex is required."
graph = file_to_graph(argv[1])
start, stop = argv... |
name = input("Enter your name -> ")
age = input("Enter your age -> ")
age = int(age)
if name == 'Kyle' and age == 29:
print('You must be ' + name + ' because that info is correct.')
elif name != 'Kyle' and age == 29:
print('You must be someone else.')
elif name != 'Kyle' and age != 29:
print('So ' + name, '... |
# create a function named 'collatz' which accepts 1 argument - 'number'
import sys
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 != 0:
odd_result = 3 * number + 1
print(odd_result)
return odd_result
try:
value = int... |
def sqrt(n):
if n == 0 or n == 1:
return n
if n < 0:
return None
start = 0
end = n
return _find_root(n, start, end)
def _find_root(n, start, end):
mid = (start+end) // 2
mid_sq = mid*mid
if mid_sq == n or abs(mid_sq-n) < 5:
return mid
elif mid_sq < n:
... |
from Trees import *
class With_Stacks:
def __init__(self, tree):
self.tree = tree
def pre_order(self, debug_mode = False):
tree = self.tree
node = tree.get_root()
visit_order = []
state = State(node)
stack = Stack()
stack.push(state)
count = 0
... |
class DoubleNode:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DoubleLinkedList:
def __init__(self, value=None):
self.head = value
self.tail = None
def append(self, val):
if self.head is None:
self.head ... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:... |
class Heap:
def __init__(self, initial_size=10):
self.cbt = [None for _ in range(initial_size)] # initialize arrays
self.next_index = 0 # denotes next index where new element should go
def insert(self, data):
# insert element at the next index
self.cbt[self.next_index] = data
... |
class GraphEdge(object):
def __init__(self, destinationNode, distance):
self.node = destinationNode
self.distance = distance
class GraphNode(object):
def __init__(self, val):
self.value = val
self.edges = []
def add_child(self, node, distance):
self.edges.append(Gra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.