text stringlengths 37 1.41M |
|---|
def create_cubes(n):
for x in range(n):
yield x ** 3
for x in create_cubes(10):
print(x)
print(list(create_cubes(10)))
def gen_fibon(n):
a = 1
b = 1
for i in range(n):
yield a
a, b = b, a + b
for number in gen_fibon(10):
print(number)
def simple_gen():
for x in... |
# Problem 1
def gensquares(N):
for i in range(N):
yield i**2
for x in gensquares(10):
print(x)
import random
random.randint(1,10)
def rand_num(low,high,n):
for i in range(n):
yield random.randint(low, high)
for num in rand_num(1,10,12):
print(num)
s = 'hello'
s_iter = iter(s... |
def is_greater(a, b):
if a > b:
return True
else:
return False
print(is_greater(1,2))
print(is_greater(2,1))
|
from collections import Counter
list = [1,1,1,1,12,2,2,2,2,3,4,4,5,6,6,6]
print(Counter(list))
string ='asdihsdiuhsiughsdbadkjn'
print(Counter(string))
string_word = 'How many times does each word show up in this sentence word word shoe up up'
words = string_word.split()
c = Counter(words)
print(c)
print(c.most... |
def name_of_function():
"""
Docstring explains funtion, this function only print Hello
:return:
"""
print("Hello")
def name_of_function2(name):
"""
Docstring explains function, this function only print Hello
:return:
"""
print("Hello" + name)
def add_function(num1, num2):
... |
berthaVonSuttner = {'belderberg_Ampeln':'green', 'platz_Ampeln':'red'}
def switchLights(intersection):
for key in intersection.keys():
light = intersection[key]
if light == 'green':
intersection[key] = 'yellow'
elif light == 'yellow':
intersection[key] = 'red'
... |
"""
"""
import traceback
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('The symbol needs to be a string of length 1.')
if (width<2) or (height<2):
raise Exception('Width and height need to be greater than 2.')
print(str(symbol)*width)
for i in range(heigh... |
#! C:/Users/VSENTH17/AppData/Local/Programs/Python/Python36-32/python
'''
Retrieve and print words from a URL.
Usage:
python WordsV4_DocStrings.py <URL>
Created on Jan 12, 2018
@author: VSENTH17
'''
from urllib.request import urlopen
import sys
def fetch_words(url):
"""Fetch a list of words from a URL.
... |
'''
Created on 18-Jan-2018
@author: senthilkumar
'''
from math import sqrt
from pprint import pprint as pp
if __name__ == '__main__':
pass
def is_prime(x):
if(x < 2):
return False
for i in range(2, int(sqrt(x))+1):
if x % i ==0:
return False
return True
print([x for x in... |
'''
Created on Jan 12, 2018
@author: VSENTH17
'''
from urllib.request import urlopen
def fetch_words(self):
with urlopen('http://public.oed.com/how-to-use-the-oed/what-is-the-oed-online/') as story:
story_words = []
for line in story:
line_words = line.decode("UTF-8").split()
... |
import time
import os
def _generate_sequence(difficulty):
# Generate 5 Random numbers, creates a list and prints it
import random
random_numbers = []
for number in range(difficulty):
random_numbers.append(int(random.uniform(1, 101)))
print(random_numbers)
time.sleep(0.7)
os.system(... |
def convertString(a, b):
mang = []
for x in a:
mang.append(x)
i = 0
j = 0
kt = 0
while(i < len(mang)):
if(j == len(b)):
k = i
kiemtra = 1
while(k < len(mang)):
if('A' <= mang[k] <= 'Z'):
kiemtra ... |
fruits = ['apple', 'banana', 'orange']
fruits.append('grape')
print(fruits)
fruits[0] = 'cherry'
print(fruits[0]) |
# Assign 'Bob' to the my_name variable
my_name = "Bob"
# Print 'I am Bob' by combining the my_name variable and a string
print("I am "+my_name)
|
from menu_item import MenuItem
menu_item1 = MenuItem('Sandwich', 5)
menu_item2 = MenuItem('Chocolate Cake', 4)
menu_item3 = MenuItem('Coffee', 3)
menu_item4 = MenuItem('Orange Juice', 2)
menu_items = [menu_item1, menu_item2, menu_item3, menu_item4]
index = 0
for menu_item in menu_items:
print(str(index) + '. ' ... |
"""
Takes text document and stores content as a string
"""
import os
input_string = open("input.txt", "r")
input_transfer = input_string.read()
input_string.close()
|
import numpy as np
class operation:
def blend(self, image, logo, x=None, y=None, alpha=None):
'''
Use logo and blend it on the image at location (x, y)
image: the original image
logo: the logo to blend on to the image
x: topleft coordinate x
y: topleft coordinate y
... |
data = """.#..#
.....
#####
....#
...##"""
map = data.splitlines()
for row in map:
print(row)
asteroids = {}
for y in range(len(map)):
for x in range(len(map[0])):
if map[y][x] == '#':
asteroids[(x,y)] = []
# Need to make a list of asteroids that current asteroid can see
# Only add an a... |
celcius = int(input("Enter a temperature in celcius: "))
Fahrenheit = 9/5 * celcius + 32
print(Fahrenheit)
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
get_ipython().magic(u'tensorflow_version 2.x')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
# In[ ]:
mnist = tf.keras.datasets.mnist # mnist data of grayscale images of handwritten digits
(x_tra... |
"""
Inlucde code related to how to read data from text and generate batch training
data from dataset
"""
import numpy as np
import copy
import pickle
def batch_generator(arr, batch_size, n_steps):
"""
Generate a batch of training samples
:param arr: shape(none, 1), the whole training data, each int numb... |
"""Python 3.7 dataclass example.
Dataclasses are classes that implement very few (public) methods
and are instead used for instantiating objects with specific attributes
this is particularly common in ORM(Object relation mapping).
Python 3.7 includes the `dataclasses` module with the `dataclass`
decorator that... |
# -*- coding:utf-8 -*-
# @Author: Marie
# @Time: 2018/10/29 10:25 PM
# @Software: PyCharm
import time
def do_time():
print(time.ctime(time.time()))
print(time.asctime(time.localtime(time.time())))
print(time.gmtime(time.time()))
def do_test():
start = time.time()
for i in range(3000):
prin... |
from functools import reduce
def sum(x,y):
return x+y
a = reduce(sum,[1,2,3,4,5])
print(a)
def str_float(s):
s = s.split('.')
def fn(x,y):
return x*10+y
def dn(x,y):
return x/10+y
def str2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, ... |
"""
List of quick helper functions
"""
import os
LOWER_IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.bmp', '.pgm', '.ppm', '.gif']
IMAGE_EXTENSIONS = LOWER_IMAGE_EXTENSIONS + list(map(lambda x: x.upper(), LOWER_IMAGE_EXTENSIONS))
def ir(some_value):
""" Because opencv wants integer pixel values"""
return i... |
# s = input("Enter the string")
# def uniqueCharacters(str):
# for i in range(len(str)):
# for j in range(i + 1,len(str)):
# if(str[i] == str[j]):
# return False;
# return True;
# if(uniqueCharacters(s)):
# print("The String ", s," has all unique characters")... |
import sqlite3
class Banco:
con = sqlite3.connect('pizza.db')
cursor = con.cursor()
tabela1 = """
create table if not exists cliente (idcliente integer not null primary key autoincrement,
nome text,
telefone txt,
... |
suma=float(input("Сумма заказа?"))
tea=float(input("Сколько чая дадите нашим официантам?(Общее число)"))
people=int(input("Сколько вас(колличество человек)"))
sumageneral=suma+tea
suma2=suma/people
sumaeach1=suma/people+tea/people
teaeach=tea/people
prozentsuma=suma/100
prozenttea=tea/prozentsuma
print("-----... |
#!/usr/bin/python -tt
from __future__ import print_function
import nltk
# Given a file in which each line contains a polar term followed by a polar value,
# creates a polar_value_dict in which each polar term is mapped to a polar value.
def polar_value_dict_maker(filename):
polar_value_dict = {}
f = open(filename, '... |
# -*- coding: utf-8 -*-
#Menu Principal
def menu():
print("***************************************************************** ")
print(" ")
print(" ..:: Bemvindo a Calculadora ::..")
print(" ")
print(" ")
op = int(input(''' Digite o número da operação desejada:
************************... |
#método que compara la primera letra del parametro
def obtener_primer_letra(pais):
pais = "quito"
letra = (pais[0])
return letra
#método que calcula el valor del promedio
def obtener_promedio_notas(a, b, c):
promedio = (a + b + c)/3
#retorno del valor para realizar el test
return promedio
#metodo pa... |
#! /usr/bin/python
import re
targ = "the 1337 brown 420 jumped over the lazy dog"
search = re.search(r".*([0-9]*).*", targ)
|
att = int(input())
eyes = int(input())
#1
if att >= 3 and eyes <= 4:
print('TroyMartian')
if att <= 6 and eyes >= 2:
print('VladSaturnian')
if att <= 2 and eyes <= 3:
print('GraemeMercurian') |
age = int(input("How old are you? "))
def what_to_do():
if age <= 6:
print ("you should go to kindergarten")
elif 6 < age <= 19:
print ("you should go to school")
elif 19 < age <= 24:
print ("you should go to university")
elif 24 < age <= 65:
print ("work work work!"... |
import turtle
from random import *
from math import *
import tkinter
turtle.colormode(255)
turtle.hideturtle()
robot = turtle.Turtle()
#robot.hideturtle()
screen_dimension = turtle.screensize()
x_origin = screen_dimension[0]//2
y_origin = screen_dimension[1]//2
robot.penup()
robot.goto((-1*x_origin),-1*y_origin)
n1=80
... |
#! /usr/bin/env python
# coding:utf-8
import random
RANGE_COUNT = 40
RANGE_LIMIT = 100
# lst = []
i_count = 0
# for x in list(range(RANGE_COUNT)):
# lst.append(random.randint(0,RANGE_LIMIT))
# 下面脚本是上面循环的优化结果
lst = [random.randint(0,RANGE_LIMIT) for x in list(range(RANGE_COUNT))]
i_sum = sum(lst)
i_avg = i_... |
# coding:utf-8
# 题目:打印出所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个“水仙花数”,因为153=1的三次方+5的三次方+3的三次方。
import math
for i in range(100,1000):
totle = math.pow(int(i / 100),3) + math.pow(int(i / 10) % 10,3) + math.pow(int(i % 10),3)
if i == totle:
print(i) |
class GrandParents(object):
def __init__(self):
super(GrandParents,self).__init__()
print("this is GradParents")
class Parent1(GrandParents):
def __init__(self):
super(Parent1,self).__init__()
print("this is Parent1")
class Parent2(GrandParents):
def __init__(self):
s... |
# coding:utf-8
# 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
string = str(input("请输入字符串:"))
d = 0 # 数字
c = 0 # 字母
o = 0 # 其它
s = 0 # 空格
for i in string:
if str.isalpha(i):
c += 1
elif str.isnumeric(i):
d += 1
elif str.isspace(i):
s += 1
else:
o += 1
print("输入的字符串中有 {0} 个字... |
def login():
with open('passwd') as f:
lines = f.readlines()
lines = [line.split() for line in lines]
pwds = dict(lines)
i = 0 #三次登录验证
while i<3:
username=input('username:') #获取 用户名
if username not in pwds: #用户名不存在
print('invalid username')
... |
# 一个小小的四则运算器~
# 基本思路:基本运算顺序是先乘除后加减,乘除顺序是从左到右,加减没有顺序,有括号的先把括号里的拿出来,按照基本运算顺序计算再返回结果。
# 考虑到会有负数,而负号和减号的符号是相同的,所以需要优先区分出来,我的做法是将运算符号两边都加上空格,而负号直接连着数字以将两者区分开来。
# 没有做太多的测试,可能还有bug,还请各位大大们指出~~
# !/usr/bin/env python3
# coding:utf8
def error():
print('不合法的算术式子!')
exit()
def calculate(formula): # 四则运算
dict_op... |
# coding:utf-8
"""
题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
"""
def main():
num = int(input("输入重复的数字:"))
count = int(input("输入要重复的次数:"))
totle = 0
basis = num
if count >= 1:
for i in range(1,count + 1):
if i == count:
p... |
def lcm(a, b):
assert a > 0 and b > 0
mult = a * b
while (a % b!=0) and (b % a!=0):
if a > b:
a = a % b
else:
b = b% a
return mult/min(a,b)
|
# This library should import for work with regular expression
import re
# we know that in python string can holder any character as string
# set but '\+cmd' symbol that only way to give commads to string
# eg:- '\n' , '\t' ...ect
#$print('we\nSriLanka')
print('Sri\tLanka')
# but we are using row String in this case ... |
# In this code we implement a simple Q based learning example in AIgym
# Importing the required libraries
import gym
import random
import numpy as np
import time
from gym.envs.registration import register
from IPython.display import clear_output
# The register class in the gym has default setting of is_slippery
# va... |
''' Program tests whether Monty Hall problem is real.
link to paradox: https://en.wikipedia.org/wiki/Monty_Hall_problem
Dependency:
random
python 3.x.x
How to run:
python3 zonk.py
'''
import random as r
class gen_obj:
def __init__(self, **kwds):
self.__dict__.update(kwds)
def gen_gates():
... |
import math
def FixFunction(function):
function = function.replace("ln","math.log")
function = function.replace("Ln","math.log")
function = function.replace("e","math.e")
function = function.replace("π","math.pi")
function = function.replace("cos","math.cos")
function = function.replace("sen","... |
import cs50
def checksum(card):
sum=0
while card>0:
sum+=card%10
card//=10
sum+=(((card%10)*2)%10)+(((card%10)*2)//10)
card//=10
return sum%10
def main():
card=cs50.get_int("Number: ")
if(not(checksum(card))):
if card//(10**13) in (34,37):
print(... |
import unittest
class FizzBuzzTest(unittest.TestCase):
def test_divisible_by_3_returns_fizz(self):
fizzbuzz = FizzBuzz()
result = fizzbuzz.take(3)
self.assertEqual(result, "fizz")
def test_divisible_by_5_returns_buzz(self):
fizzbuzz = FizzBuzz()
result = fizzbuzz.take(... |
n = input('Digite algo: ')
print(type(n))
print('alphanumerico ',n.isalnum(),'\ndecimal ', n.isdecimal(),'\nmaiusculo ',n.isupper())
print('digito',n.isdigit(),'\nidentidade',n.isidentifier(),'\nprint',n.isprintable())
print('decimal',n.isdecimal(),'\nminusculo', n.islower(),'\nnumeral', n.isnumeric())
print('espa... |
from math import hypot
def catetos_hipotenusa(co,ca):
hi = (co**2 + ca**2) ** (1/2)
print('A hipotenusa é {:.2f}'.format(hi))
def hipcat_math(co,ca):
hi = hypot(co,ca)
print('A hipotenusa é {:.2f}'.format(hi))
co = float(input('Digite cateto oposto: '))
ca = float(input('Digite cateto adjace... |
from random import randint
from time import sleep
sorte = randint(0,5)
#print(sorte)
n = int(input('TENTE ACERTAR UM NÚMERO ENTRE 0 E 5:'))
print('PROCESSANDO...')
sleep(2)
if sorte == n:
print('PARABENS VOCE ACERTOL! {}'.format(sorte))
else:
print('QUE PENA O NÚMERO CERTO É {}'.format(sorte))
|
saque = int(input('Qual valor quer sacar? '))
reais_50 = reais_20 = reais_10 = reais_1 = 0
while saque > 0:
print('='*40)
if saque >= 50:
reais_50 = saque // 50
saque = saque % 50
print(f'{reais_50} cédulas de R$50')
if saque >= 20:
reais_20 = saque // 20
... |
from random import randint
cont = 0
while True:
computador = randint(0, 10)
n = int(input('Escolha um número: '))
soma = computador + n
op = ' '
while op not in 'IP':
op = str(input('Você quer PAR ou IMPAR? [P/I] ')).strip().upper()[0]
print(f'O valor digitado pelo computador fo... |
n = input('Digite seu nome: ').strip().title()
sexo = 'H'
while sexo not in 'MF':
sexo = input('Informe o sexo: ').strip().upper()[0]
if sexo == 'M':
sexo = 'masculino'
elif sexo == 'F':
sexo = 'Feminino'
#print('Seu nome é {}, e seu sexo é {}!'.format(n, sexo))
print(f'Seu nome é {n}, e seu sexo é... |
import pandas as pd
from sklearn.feature_extraction import DictVectorizer
import matplotlib.pyplot as plt
from decision_tree import *
from random_forest import *
train = pd.read_csv('census/train_data.csv')
label = train.label
train_set = train.drop('label', 1)
test_set = pd.read_csv('census/test_data.csv')
# data p... |
"""
V1.0
Code is based on simplified AIMA book code repository, updated for python 3.
The way to use this code is to subclass Problem to create a class of problems,
then create problem instances and solve them with calls to the various search
functions."""
from utils import FIFOQueue, Stack, Dict, update
import sys
#... |
#sum of two number
num_one=int(input("Enter the first number: "))
num_two=int(input("Enter the second number: "))
sum=num_one + num_two
print(sum)
#Sorry for my bad programming
#Add two using def function
def add_two (num_one,num_two):
return num_one + num_two
num_one=int(input("Enter your first number: "))
num_tw... |
#!/usr/bin/python3
import sys
class Graph:
nodes = None
edges = None
def __init__(self):
self.nodes = dict()
def loadNodes(self, nodes):
for n in nodes:
self.nodes[n] = set()
def loadFromRelations(self, relations):
for e in relations:
if len(e) ... |
# My Program for query... TEST
#
# Input --> for Name=input("Enter your Name:")
# Input --> for Age=input("Enter you Age:")
# Input --> for Email=input("Enter your e-mail:")
# Name:
# Age:
# e-mail:
#
# Questions:
# Q1; Q2; Q3; Q4; Q5; Q6; Q7; Q8; Q9;
#
# Answers:
# choose one of the following options:
# A) B) C)
#
#... |
#Utilizando estruturas de repetição com teste lógico,
#faça um programa que peça uma senha para iniciar seu
#processamento, só deixe o usuário continuar se a senha
#estiver correta, após entrar dê boas vindas a seu usuário
#e apresente a ele o jogo da advinhação, onde o computador
#vai “pensar” em um número entre 0 e 1... |
def sorted_squared_array(array):
non_negative = len(array)
for index, _ in enumerate(array):
if array[index] >= 0:
non_negative = index
break
output = []
negative = non_negative - 1
while negative >= 0 and non_negative < len(array):
if abs(array[negative]) <... |
class Tree:
"""
A class to describe a tree node.
value: int
right: tree
left: tree
"""
def __init__(self, value, right=None, left=None):
self.value = value
self.right = right
self.left = left
def branch_sum(root):
if root:
return branch_sum_helper(root... |
class Node:
"""
name : str
children: array of Node
"""
def __init__(self, name, children=None):
self.name = name
if children is None:
self.children = []
else:
self.children = children
def breadth_first_search(self, nodes):
if len(nodes) >... |
class BST:
"""
value : value
left : BST
right : BST
"""
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
prev = None
current = self
while current:
prev = current
... |
def mark_border_water(area, row, column, height, width):
if area[row][column] == 1:
area[row][column] = 2
if row > 0:
mark_border_water(area, row - 1, column, height, width)
if row < height - 1:
mark_border_water(area, row + 1, column, height, width)
if column... |
class BST:
"""
value: int
left: BST
right: BST
"""
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def in_order_traverse(root, array):
if root is None:
return
in_order_traverse(root.left, array)
... |
class Node:
"""
value : int
prev : Node
next : Node
"""
def __init__(self, value, prev=None, nxt=None):
self.value = value
self.prev = prev
self.next = nxt
class DoublyLinkedList:
"""
head : Node
tail : Node
"""
def __init__(self):
self.hea... |
def max_subset_sum_no_adjacent(array):
if not array:
return 0
elif len(array) == 1:
return array[0]
else:
max_sums = [array[0], max(array[0], array[1])]
for index in range(2, len(array)):
temp = max_sums[1]
max_sums[1] = max(max_sums[0] + array[index],... |
def number_of_ways_to_traverse_graph(height, width):
grid = [[1 for _ in range(width)] for _ in range(height)]
for row in range(1, height):
for column in range(1, width):
grid[row][column] = grid[row - 1][column] + grid[row][column - 1]
return grid[height - 1][width - 1]
def main():
... |
import collections
def main():
chars = [e for e in "hello world"]
print(removeDuplicateCharacter(chars))
def removeDuplicateCharacter(s):
#HashMap: O(N) amortized time, O(|A|) space where |A| is size of the alphabet.
#If the alphabet is known (e.g. ASCII characters, UTF-8, etc), then it can be regarded ... |
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
#----------------------------short expression via list------------------------------------------------------------------------------------
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
def change(x):
return x.u... |
from copy import deepcopy
class Gauss:
N: int
matriz_inicial: list = []
matriz: list = []
raizes: dict = dict()
def __init__(self, matriz: list):
self.N = len(matriz)
self.matriz = matriz
self.matriz_inicial = deepcopy(self.matriz)
def __solucionar_passo(self, coluna):... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import argv
from turing_machine import TuringMachine
class Maincontroller(object):
"""
Maincontroller()
This class parses the input file, then create an
instance of a Turing machine.
Also is responsible to access a validate method of
Tur... |
def my_func(x, y):
return x**y
print(my_func(float(input("Enter x: ")), int(input("Enter y: "))))
# x = float(input('Enter x: '))
# y = float(input('Enter y: '))
# result = list(map(lambda x, y: x ** y))
#
# print(result)
|
'''
Greatest common divisors of two numbers
by trustnoedo
'''
# Function
def divisors(x):
l = []
lstrng = list(range(1, x+1))
for i in lstrng:
if x % i == 0:
l.append(i)
return l
# Introduction
print()
print("--------------------------------------------------------------------"... |
def fibonacci(n):
if n==0:
return 0
if n==1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
# print(fibonacci(7))
a = 0
print(a)
b = 1
print(b)
c = 0
while c<100:
c = a+b
print(c)
b = a
a = c
import numpy as np
print(dir(np))
|
"""
@author: Akshay Nevrekar
@created_on: 6th November,2019
@last_updated_on: 6th November,2019
"""
# import module
import csv
rows = []
with open("datafiles/akshay.csv", "rt") as f:
data = csv.reader(f)
# print(data)
for row in data:
print(row)
rows.append(row)
# field name... |
"""
@author: Akshay Nevrekar
@created_on: 4th November,2019
@last_updated_on: 4th November,2019
"""
a = 5
b = 7
# condition check
if a > b:
# block gets executed if condition is True
print("A is greater than B")
else:
# block gets executed if condition is False
print("B is greater than or ... |
"""
@author: Akshay Nevrekar
@created_on: 21st July,2019
@last_updated_on: 11th November,2019
"""
a = 7
b = 2
# addition
c = a+b
print("Addition: ", c)
# subtraction
d = a-b
print("Subtraction: ", d)
# Multiplication
e = a*b
print("Multiplication: ", e)
# Division
f = a/b
print("Division: ", f)
# Modu... |
# 汉诺塔
def move(n,a,b,c):
if n==1:
print(a,'to',c)
return
move(n-1,a,c,b)
print(a,'to',c)
move(n-1,b,a,c)
return
move(3,'A','B','C') |
from typing import List
# Logic
# create a dp 2d array of size (n+1)*(m+1) with all zero elements.
# iterate over the elements and check:
# if there's an element match, add one to the diagonal element.
# else do nothing
# ---------------------------------------
class Solution:
def findLength(self, nums1... |
"""
Given a reference to the head of a doubly-linked list and an integer, data,
create a new Node object having data value data and insert it into a sorted
linked list.
Complete the Node* SortedInsert(Node* head, int data) method in the editor below.
It has two parameters:
1. head: A reference to the head of a dou... |
from datetime import*
Balance=500000
name = input("What is your UserName? \n")
allowedUsers=['Seyi','Mike','Love']
allowedPassword =['passwordSeyi','passwordMike','passwordLove']
import random
database ={}
def init():
if(name in allowedUsers):
password = input("your password? \n")
userId = all... |
line = list(map(int, input().split()))
heights = line[:]
height = -1
maxindex = 0
n=len(line)
for index in range(n):
if line[index]>height:
height = heights[index]
maxindex = index
line[index] = 'X'
else:
j = index -1
while heights[index] > heights[j]:
j = in... |
import tkinter as tk
class Game(tk.Frame):
def __init__(self,master):
super(Game,self).__init__(master)
self.lives = 3
self.width = 610
self.height = 400
self.canvas = tk.Canvas(self,bg = '#aaaaff',
width = self.width,
... |
class a: #定義類 a
__x = '我是屬性__x' #定義私有屬性,無法被子類別繼承
y = '我是屬性y' #定義非私有屬性,能被子類別繼承
def __m1(self): #定義私有方法,無法被子類別繼承
print('我是方法 m1()')
def m2(self): #定義非私有屬性,能被子類別繼承
print('我是方法 m2()')
class b(a): #類別 b 繼承自類別 a
z = '我是屬性 z'
def m3(self):
prin... |
import random
def play_game():
country = {"Slovenia":"Ljubljana", "Croatia":"Zagreb", "Serbia":"Belgrade", "Spain":"Madrid",
"Austria":"Vienna", "Hungary":"Budapest", "Italy":"Rome", "UK":"London",
"Slovakia":"Bratislava", "Germany":"Berlin", "Portugal":"Lisboa", "Norway":"Oslo",
... |
# -*- coding: utf-8 -*-
def prime(a,b):
for i in range(a,b+1):
if is_prime(i):
print(i)
def is_prime(n):
if n <= 1 :
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i=5
while i*i <= n:
if n % i == 0 or n % (i + 2)... |
class programming_language:
"""Represent a Car object."""
def __init__(self, name='', typing='', reflection = bool, year = ''):
"""Initialise a Car instance.
fuel: float, one unit of fuel drives one kilometre
"""
self.name = name
self.typing = typing
self.reflect... |
usernames = ["jimbo", 'gaecunny']
input_name = input("Enter a username: ")
if input_name in usernames:
print("Access granted")
else:
print("Access denied") |
"""
CP1404/CP5632 - Practical
Broken program to determine score status
"""
score = float(input("Enter score: "))
if 90 > score >= 50:
print("Passable")
elif 100 >= score >= 90:
print("Excellent")
elif 0 <= score < 50:
print("Bad")
else:
print("Invalid score")
|
age = 32
name = "james"
print (len(name))
if age <10:
print ("You aint got no money")
else:
print ("YOu've got cash in your account")
if name is "collins":
print ("Hey collins")
print (len())
else:
print("this is Collins not James") |
#Python small exercise questions
#Help you getting familiar with Python syntax
#Grading:
#IMPORTANT NOTICE:
#A good practice in coding is to show your customer a working version and tell them
#what new features you want to add next.
#Thus, we require you to submit all your homework as a working version. If you
#only ... |
"""Implements elixir class and all objects connected with drinkable beverages"""
from .item import Item
class Elixir(Item):
"""Base class for all elixirs"""
def __init__(self):
super().__init__()
self.amount = 1
def __repr__(self):
return self.name + ' (' + repr(self.amount) + ')'
def drink(self, hero... |
import unittest
from unittest.mock import MagicMock
from .hero import *
from .monster import Vampire
from ..items.weapon import ShortSword, Weapon
from .character import Character
class TestFighterClass(unittest.TestCase):
"""Tests for Fighter class"""
def setUp(self):
self.h = Fighter(name = 'Fight')
self.e ... |
from re import findall
from json import loads
input = open('input.txt').read()
print sum(map(int, findall('[-0-9]+', input)))
def hook(obj):
return {} if 'red' in obj.values() else obj
#part 2 is using json.loads() object_hook to filter out objects containing red. credit to /u/meithan
print sum(m... |
"""
LeetCode 9. Palindrome Number
url: https://leetcode.com/problems/palindrome-number/
writer: Harim Kang
Language: Python3
Date: 2021.01.06
Status: Success, Runtime: 76 ms, Memory Usage: 14.2 MB
Follow up: Could you solve it without converting the integer to a string?
"""
class Solution:
def isPalindrome(self, ... |
"""
LeetCode 5. Longest Palindromic Substring
url: https://leetcode.com/problems/longest-palindromic-substring/
writer: Harim Kang
Language: Python3
Date: 2020.09.03
Status: Success, Runtime: 5424 ms, Memory Usage: 14 MB
"""
class Solution:
def longestPalindrome(self, s: str) -> str:
def is_palindrome(_s)... |
"""
LeetCode 238. Product of Array Except Self
url: https://leetcode.com/problems/product-of-array-except-self/
writer: Harim Kang
Language: Python3
Date: 2020.09.09
Status: Success, Runtime: 124 ms, Memory Usage: 20.4 MB
"""
class Solution:
def productExceptSelf(self, nums):
# max_product: Product of al... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.