text stringlengths 5 121k |
|---|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
def isEmpty(self):
"""Returns True if Queue is empty, False otherwise"""
if self.head:
return False
return True
def enq... |
rome_file = open('rome.txt', 'a')
numbers = [1,2,3]
for i in range(len(numbers)):
num = numbers[i]
rome_file.write("{}\n".format(num))
rome_file.close()
adam_file = open('adam.txt', 'w')
adam_file.write('Adam')
adam_file.close()
new_file = open('new_file.txt')
file_items = new_fi... |
"""
Chris Campbell
3/27/19
Python 1 - Dat 119 - Spring 2019
Week 8
"We’re going to create an application to track a user’s todo list!
Our application will maintain at least two lists:
1) items that need to be done and
2) items that have already been completed."
"""
todo_list = ["run", "eat", "breathe"]
completed_... |
def kangaroo(x1, v1, x2, v2):
start_diff = x1 - x2
velocity_diff = v2 - v1
if (v2 > v1 or velocity_diff == 0):
return 'NO'
if((start_diff % velocity_diff) == 0):
return 'YES'
else:
return 'NO'
print(kangaroo(0, 2, 5, 3))
print(kangaroo(0, 3, 4, 2))
print(kangaroo(43, 2... |
command = input ("Put in the number")
com_int = int(command)
import time
num = 1
while(num <= com_int ):
print(num)
num = num +1
|
import time
num = 1
while(num <= 10 ):
print(num)
num = num +1
print("Anna Is AMAZING") |
import time
Running = True
def Intro():
print("Welcome to LessonUp Bot!!!")
time.sleep(1.5)
print("This bot is able to perform")
time.sleep(1.5)
print("A lot of actions realy fast")
time.sleep(1.5)
print("It is able to answer randomly.")
time.sleep(1.5)
print("And give custom a... |
"""
This class parses the TUNE block and returns a checked dictionary containing all TUNE user
parameters
"""
import numpy as np
import os
class TuneChecker():
"""
This class checks the input for any errors/typos and then overwrites the default inputs by user ones
Inputs:
master_p... |
def Punctuation(string):
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
for x in string.lower():
if x in punctuations:
string = string.replace(x, "")
return string |
n = int(input())
arr=[]
for i in range(n):
x = list( map(int, input().split()))
arr.append(x)
print (arr)
larger= max(num for num in arr if num!=max(arr))
print (larger)
|
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) < 1:
return True
alphanumeric = "".join(c.lower() for c in s if c.isalnum())
return self.isPalindromeHelper(0,len(alphanumeric)-1,alphanumeric)
... |
import random as rd
import matplotlib.pyplot as plt
def main():
result20 = experiment(20)
result100 = experiment(100)
result200 = experiment(200)
result1000 = experiment(1000)
result2000 = experiment(2000)
result10000 = experiment(10000)
plt.rcParams['figure.figsize'] = (24, 18)... |
"""
File Name: 40 数组中只出现一次的数字
Description :
Author : simon
date: 19-3-3
"""
class Solution:
def FindNumsAppearOnce(self, array):
if array == None or len(array) <= 0:
return []
resultExclusiveOr = 0
for num in array:
resultExclus... |
"""
File Name: 41 和为s的两个数字
Description :
Author : simon
date: 19-3-4
"""
class Solution:
def FindNumbersWithSum(self, array, tsum):
if not array:
return []
left, right = 0, len(array)-1
while left < right:
sum_ = array[left]... |
"""
File Name: 19 二叉树的镜像
Description :
Author : YYJ
date: 2019-02-16
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Mirror(self, root):
if root == None:
re... |
"""
File Name: 200. Number of Islands
Description :
Author : simon
date: 19-3-31
"""
"""
DFS
这道题其实和之前的剑指offer最后补充的回溯问题很相似 机器人的运动范围
每次找到一个运动范围之后 将这个范围全部清成0
"""
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
... |
"""
File Name: 283. Move Zeroes
Description :
Author : simon
date: 19-3-12
"""
"""
直接考虑每个非零数字最终需要移动的次数
使用一个List存放每一个元素需要移动的距离
"""
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in... |
"""
File Name: 17 合并两个排序的链表
Description :
Author : YYJ
date: 2019-02-16
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def Merge(self, pHead1, pHead2):
if pHead1 == None:
return pHead2
... |
"""
File Name: 647. Palindromic Substrings
Description :
Author : simon
date: 19-3-12
"""
"""
考虑每一个可能的对称轴 共有2N-1个可能的点(包含两个index的中点)
"""
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
... |
"""
File Name: 41 和为S的连续正数序列
Description :
Author : simon
date: 19-3-4
"""
class Solution:
def FindContinuousSequence(self, tsum):
if tsum <= 0:
return
small, big = 1, 2
curSum = 3
res = []
while small <= (tsum-1)/2:
... |
"""
File Name: 01 二维数组查找
Description :
Author : YYJ
date: 2019-02-12
"""
"""
二刷记录
"""
class Solution2:
def Find(self, target, array):
rows = len(array)
cols = len(array[0]) if array else 0
i, j = rows - 1, 0
while i >= 0 and j < cols... |
"""
File Name: 33 把数组排成最小的数
Description :
Author : simon
date: 19-2-24
"""
from functools import cmp_to_key
class Solution:
def PrintMinNumber(self, numbers):
if not numbers:
return
numstr = list(map(str, numbers))
numstr.sort(k... |
"""
File Name: 572. Subtree of Another Tree
Description :
Author : simon
date: 19-3-24
"""
"""
Naive approach, O(|s| * |t|)
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def i... |
"""
File Name: 把字符串转换成整数
Description :
Author : simon
date: 19-3-19
"""
class Solution:
def StrToInt(self, s):
if not s:
return 0
s = list(s)
for i in s:
if i not in ['+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '... |
import re
def getNumbers(str,sum):
array = re.findall(r'[0-9]+', str)
for i in array:
sum+=int(i)
return sum
sum = 0
file = "regex_sum_702801.txt"
fh = open(file)
for line in fh:
result = getNumbers(line,sum)
sum = result
print(sum) |
class Node(object):
"""单链表的节点"""
def __init__(self,elem):
self.elem = elem
self.next = None
class SingleLinkList(object):
"""单链表的实现"""
def __init__(self):
self.__head =None
def is_empty(self):
"""判断是否为空"""
return self.__head == None
def... |
from math import *
from tkinter import *
screen_width = 700
screen_height = 600
is_show_X_axis = True
is_show_Y_axis = True
a = -10
b = 10
func = lambda x: sin(x)+cos(x/2)
x0 = 0
ymin = ymax = y0 = func(a)
axis_y_x = axis_x_y = 0
if a > 0 and b > 0 or a < 0 and b < 0:
is_show_Y_axis = False
print('Not ... |
RULE_DICT = {}
def read_grammar(grammar_file):
with open(grammar_file) as cfg:
lines = cfg.readlines()
return [x.replace("->", "").split() for x in lines]
def add_rule(rule):
global RULE_DICT
if rule[0] not in RULE_DICT:
RULE_DICT[rule[0]] = []
RULE_DICT[rule[0]].append(rule[1:])
... |
def greet(name):
"""
This function greets to
the person passed in as
parameter
"""
print("Hello, " + name + ". Good morning!")
while(True):
name = input("Input your name : ")
if (name != ""):
greet(name)
else:
break
|
CODE_TO_COlOUR = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7",
"AntiqueWhite1": "#ffefdb", "AntiqueWhite2": "#eedfcc",
"DodgerBlue3": "#1874cd", "gray": "#bebebe",
"aquamarine1": "#7fffd4", "OldLace": "#fdf5e6",
"aquamarine4": "#458b74", "azure1": "#... |
import sqlobject
from sqlobject.mysql import builder
conn = 'mysql://dbuser:dbpassword@localhost/sqlobject_demo?debug=1'
"""
Database Connections Examples:
MySQL
conn = MySQLConnection(user='test', passwd='pwd', db='testdb')
[this method is now deprecated. Use the URI method below]
conn = ... |
print(round(3.024))
print(round(-3.024))
print(min(1, 2, 3))
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
|
animalList = ['Hamster', 'Tiger', 'Gnu', 'Lion']
for i in animalList:
print(i)
print('')
for i in range(len(animalList)):
print(animalList[i])
print('')
for i in animalList:
print(i)
if i == 'Tiger':
break
print('')
i = 0
while i < len(animalList):
print(animalList[i])
i += 1... |
from numpy import random
from numpy.ma import exp, array, dot
class NeuralNetwork:
def __init__(self):
random.seed(1)
self.synaptic_weights = 2 * random.random((3, 5)) - 1
def __sigmoid(self, x):
return 1 / (1 + exp(-x))
... |
print("math")
number_1 = eval(input("number1: "))
operation = input("operation - +,-,*,/: ")
number_2 = eval(input("number2: "))
if operation == "+":
result = number_1 + number_2
elif operation == "-":
result = number_1 - number_2
elif operation == "*":
result = number_1 * number_2
elif operation == "/... |
import json
import BookItemCSV
import LoanItem
import PersonCSV
CURRENTUSER = 0
class Book():
"""This is a book class"""
def __init__(self, author, country, imageLink, language, link, pages,
title, year):
self.author = author
self.country = country
self.imageLink = imageLink
... |
def single_letter_count(word, letter):
"""How many times does letter appear in word (case-insensitively)?
>>> single_letter_count('Hello World', 'h')
1
>>> single_letter_count('Hello World', 'z')
0
>>> single_letter_count("Hello World", 'l')
3
... |
d = int(input("Teclea la distancia en km. enteros: "))
t = int(input("Teclea el tiempo en hrs. enteros: "))
v = d*t
print("Velocidad promedio:",v, "km/h") |
from tkinter import *
import time,random
tk=Tk()
tk.title("Bounce ball game")
tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
c=Canvas(tk,width=500,height=450,bd=0,highlightthickness=0)
c.pack()
tk.update()
class ball:
def __init__(self,ca,co):
self.ca=ca
self.id=ca.create_oval(10,10,30,3... |
import turtle
t = turtle.Pen()
def draw_star(size, points):
angle = 360 / points
for x in range(0, points):
t.forward(size)
t.left(180 - angle)
t.forward(size)
t.right(180-(angle * 2))
|
def money(fiveNumber,twoNumber,oneNumber):
total=5*fiveNumber+2*twoNumber+oneNumber
return total
fiveNumber=int(input("Enter a number of five:"))
twoNumber=int(input("Enter a number of two:"))
oneNumber=int(input("Enter a number of one:"))
print("total money is:",money(fiveNumber,twoNumber,oneNumber)) |
import pygame
pygame.init()
screen=pygame.display.set_mode([700,500])
screen.fill([255,255,255])
my_ball=pygame.image.load("beach_ball.png")
screen.blit(my_ball,[60,60])
pygame.display.flip()
x=60
y=60
for i in range(1,100):
pygame.time.delay(1000)
pygame.draw.rect(screen,[255,255,255],[x,y,90,90],0)
x+=20... |
"""
Created on Fri Oct 2 18:56:32 2020
@author: duanyiting
"""
class student:
def __init__(self):
self.name=""
self.score=0
self.next=None
head=student()
head.next=None
ptr=head
select=0
while select !=2:
print("输入1添加数据,输入2离开:")
select=int(input())
if select==1:
new_da... |
"""
Created on Wed Apr 15 20:12:07 2020
@author: duanyiting
"""
class account:
def see_account(self):
print(self.account_name,",",self.account_money)
def change_account(self):
name=input()
money=int(input())
self.account_name=name
self.account_mon... |
"""
Created on Sat Jul 4 19:37:40 2020
@author: duanyiting
"""
class employee:
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def __str__(self):
return "name:"+self.name+"\t age:"+str(self.age)+"\t sex:"+self.sex
class employee1(employee):
... |
"""
Created on Fri Jul 3 20:age3:33 2020
@author: duanyiting
"""
class Person:
def __init__(self,name,addr,sex,age):
self.name=name
self.addr=addr
self.sex=sex
self.age=age
def output1(self,name,addr,sex,age):
print("name:",name,"addr:",addr,"sex:",sex,"age:",age)
... |
if __name__ == '__main__':
n = 5
for i in range(n):
if i >= 3:
print(i)
|
"""code_info
@Time : 2021 2021/4/2 13:48
@Author : jiangliming
@File : test.py
"""
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://localhost:8000')
assert 'Django' in browser.title
|
import unittest
from binary_tree.binary_tree import BinaryTree
class TestBinaryTree(unittest.TestCase):
def test_breadth_first_traversal(self):
bt = BinaryTree()
bt.insert(9)
bt.insert(4)
bt.insert(6)
bt.insert(20)
bt.insert(170)
bt.insert(15)
bt.insert(1)
ordered = [9, 4, 20,... |
def roll_the_dice(dice: str):
"""
bonus version.
"""
from random import randint
amount, size = dice.split("d")
results = []
print
for i in range(1, int(amount) + 1):
results.append(randint(1, int(size)))
result = str(sum(results)) + ":"
for each in results:... |
def main(base_word, added_letters):
__author__ = "Jonathan Greenberg"
import pandas as pd
import collections
import pprint
import pickle
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z']... |
from Translator import Translator
'''
Author:Maxim Toyberman
Date:18.11.2015
'''
class Rotor(Translator):
def __init__(self, ringOffset, ringSetting, permutation, notch):
super(self.__class__, self).__init__(permutation)
self.ringOffset = ringOffset
self.ringSetting = ringSetting
s... |
from Climate import Climate
from Location import Location
class LandUnit:
"""
The basic unit that produces grain and houses serfs
"""
SERF_MAX = 10
PRODUCTION_VALUE = 50
SERF_UPKEEP_COST = 5
def __init__(self, x, y, fief):
"""
Makes a new land unit
:param x: the x ... |
"""
Sets
numerical sets and operations on them
Created on Tue May 19 20:08:17 2020
@author: Tim
"""
test_set = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
def set_mod_2_3(size):
temp = {}
index = 0
for i in range(1, size + 1):
if (i % 2 == 0) or (i % 3 == 0):
temp[index] = i
inde... |
"""
Hanoi Towers
how many turns to solve a Hanoi towers puzzle with n discs
Created on Wed Apr 8 16:54:52 2020
@author: Tim
"""
def turns_to_solve(n):
if n == 1:
return 1
elif n == 2:
return 3
else:
return (turns_to_solve(n-1) * 2) + 1
|
"""
Counting
examples of counting and recursive counting used in cominatorics
We will be implementing a graph consisting of nodes
and then use recursive counting to find the number of
possible paths from the start node to any given node
in the graph.
The number of possible paths to any given node
is the sum of th... |
def merge(arr,start,middle,end):
i=0
j=0
k=start
nl=int(middle-start+1)
nr=int(end-middle)
l=[0]*nl
r=[0]*nr
for i in range(0,nl):
l[i]=arr[i+start]
for j in range(0,nr):
r[j]=arr[j+middle+1]
while i<nl and j<nr:
if l[i]<=r[j]:
... |
"""
Created on Wed Aug 8 21:51:20 2018
@author: pawan_300
"""
"""
Created on Mon Jul 30 12:38:05 2018
@author: pawan_300
"""
l=[]
def insertionmax(l,temp):
for i in range(1,temp):
lamda=l[i]
j=i-1
while((j>=0)&(lamda>l[j])):
l[j+1]=l[j]
j=j-1
... |
import json
def create():
def writejson(data,filename="datastore1.json"):
with open (filename,"w") as f:
json.dump(data,f,indent=3)
with open("datastore1.json") as jfile:
data = json.load(jfile)
temp=data["employee_details"]
per = {}
vem=input("enter employ... |
def check_simulation(filen, nsteps):
"""Check the energy file to determine if the simualtion is complete
Parameters
----------
filen : string
energy file name to check
nsteps : int
number of steps in simulation
Returns
-------
complete : bool
True if the simulat... |
numero = float(input("Ingresa un numero:."))
raiz = numero **(1/2)
print("La raiz es de:. {}".format(raiz))
|
fname1 = input("Enter the first filename: ")
fname2 = input("Enter the second filename: ")
file1 = open(fname1)
file2 = open(fname2)
check1 = file1.readline()
check2 = file2.readline()
line_check = 1
while check1 != '' or check2 != '':
check1 = check1.rstrip()
check2 = check2.rst... |
import random
MOVIES = ["The Green Book", "Django", "Hors de prix"]
def get_recommendation(user_input: dict):
m1 = user_input["movie1"]
r1 = user_input["rating1"]
m2 = user_input["movie2"]
r2 = user_input["rating2"]
m3 = user_input["movie3"]
r3 = user_input["rating3"]
"""The rest... |
"""
Stacked Array
push, pop, LIFO
-> Those three features are characters that Stack data has.
- Assuming implementing an array same as the input array.
- From the ascending array.
If the number of pushed numbers are more than one,
but requires ascending order -> It cannot be implemented.
"""
list_of_pushed_numb... |
"""
The stack stores integers by input.
The stack has the following commands:
push X: Push the integer 'X' into the stack
pop: Pop the top element of the stack and print. If the stack is empty, print -1
size: Print the size of the stack
empty: Print 1 if the stack is empty, otherwise 0
top: Prin... |
from collections import namedtuple
IncomeTaxQuickLookupItem = nametuple(
'IncomeTaxQuickLookupItem'
['start_point','tax_rate','quick_subtractor']
)
INCOME_TAX_START_POINT = 3500
INCOME_TAX_QUICK_LOOKUP_TABLE = [
IncomeTaxQuickLookupItem(80000,0.45,13505),
IncomeTaxQuickLookupItem(55000,0.35,5505),
IncomeTaxQui... |
import math
r = 2
PI = 3.1415926535898
s = r*r*PI
print('{:.10f}'.format(s))
|
class Animal(object):
owner = 'jack'
def __init__(self,name):
self._name=name
@classmethod
def get_owner(cls):
return cls.owner
def get_name(self):
return self._name.lower().capitalize()
def set_name(self,value):
self._name=value
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):... |
class Graph(object):
nodes = []
edges = []
nodemap = {}
edgemap = {}
def add_edge(self,v,w,k):
if v in self.nodes:
self.nodemap[v].append(w)
else:
self.nodemap[v] = [w]
if w in self.nodes:
self.nodemap[w].append(v)
else:
... |
a, sign, b = input().split()
a = float(a)
b = float(b)
if b == 0 and sign == "/":
print("Ошибка. Деление на ноль невозможно. Введите новые значения.")
else:
if sign =="+" :
print(a + b)
elif sign =="-" :
print(a - b)
elif sign =="*" :
print(a * b)
elif sign =="/" :
... |
for i in range(1,10):
for j in range(1,i+1):
print('%d*%d=%d'%(i,j,i*j),end='\t')
print('')
|
print("Convertion of Kilometers KM to Miles")
km = float(input("Type the number of Kilometers : "))
miles = km/1.609344
print(km, "Kilometer = ", round(miles,4), "Mile : ")
|
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original X position: " + str(alien_0['x_position']))
alien_0['speed'] = 3
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien... |
class User():
def __init__(self, first_name, last_name, age, user_name, phone_number):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.user_name = user_name
self.phone_number = phone_number
self.login_attempts = 0
def describe_user(self):
print("Here is a list of the user ... |
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
rw = RandomWalk(50000)
rw.fill_walk()
plt.figure(figsize=(10,6))
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1)
plt.scatter(0,0, c=... |
"""
Spyder Editor
This is a temporary script file.
l'indentation est très importante en python'
"""
def myFunct(int_in) :
return int_in/5
print("HELLO")
if __name__ == '__main__':
print(myFunct(21))
else:
print("primer imported, not invoked")
"""
class myClass:
def __init__(self):
... |
from utils.color import scale
class Modifier:
"""
Modifier class used for variable attributes in the Patterns
"""
def __init__(self, name, value, minimum=None, maximum=None, options=None, on_change=None):
"""
:param name: str, the name of the modifier, the one shown in the interfaces... |
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
print("gcd(60,100):", gcd(60,100))
|
class books:
totalbooks=0
def __init__(self, name, id):
self.name=name
self.id=id
books.totalbooks+=1
def totalnumberofbooks(self):
print("total books : ",books.totalbooks)
def bookinformation(self):
print("book name : ",self.name,"book ... |
name="Python programming"
print("Loop 1")
for ch in name:
print(ch),
print("")
print("loop 2")
len=len(name)
for i in range(len):
print (name[i]),
print("")
print("loop 3")
for ch in name:
print(ch),
else :
print("")
print("Third loop completed")
|
num=12
if(num==12):
print("num : 12")
elif(num==13):
print("num : 13")
elif(num==14):
print("num : 14")
else:
print("num is :",num)
|
list=[1,2,3,4,5,6,7,8];
print("list[0] :",list[0])
print("list[1] :",list[1])
print("list[2:5] :",list[2:5])
list[3] = 44
print("list(after update):",list)
del list[3]
print("list(after delete) :",list)
print("length of list : ",len(list))
list2= [99,100]
list = list + list2
print("list (after appending ano... |
import random
import pygame
class Triangle(pygame.sprite.Sprite):
'''
Created on May 4, 2015
The constructor has 6 required parameters: surface, color,
starting x and y coordinates, speed and the size
This class draws a triangle with the giv... |
... |
import turtle
t = turtle.Pen()
def octagon(size, points, filled):
if filled == True:
t.begin_fill()
for x in range(0, points):
t.forward(size)
t.right(360 / points)
if filled == True:
t.end_fill()
t.color(0, 0.85, 1)
octagon(80, 8, True)
t.color(0, 0, 0)
octagon(80, ... |
'''
用from 模块名 import *,就不用模块名使用模块的内容了
Tk类创建一个基本的窗口,可在上面增加东西如按钮、输入框或画布
这是tkinter模块最主要的类
Button创建了一个按钮,把tk作为第一个参数
还要pack让按钮显示
+++++++++++++++++++++++++++++++++++++++++++++
画图:canvas画布
#ffd800,金色,16进制表示法
print('%x' % 15),把15转成十六进制f
print('%02x' % 15),把15转成十六进制,有两位0f
'''
from tkinter import *
import time
t... |
import random
ELE... |
numbers = [ 5, 4, 10, 30, 22 ]
print(max(numbers))
strings = 's,t,r,i,n,g,S,T,R,I,N,G'
print(max(strings))
print(max(10, 300, 450, 50, 90))
numbers = [ 5, 4, 10, 30, 22 ]
print(min(numbers))
guess_this_number = 81
player_guesses = [ 12, 15, 70, 45 ]
if max(player_guesses) > guess_this_number:
print('Boom! You a... |
'''
八边形
360/8=45
'''
import turtle
t = turtle.Pen()
def octagon(size, points):
for x in range(0, points):
t.forward(size)
t.right(360 / points)
octagon(100, 10)
|
print("Ingrese palabra: ")
word1 = input()
word2 = word1[::-1]
if word1.lower() == word2.lower():
print("La palabra es un palindromo.")
else:
print("La palabra no es un palindromo.") |
word = input("Ingrese una palabra:")
dicc = {}
list = []
def num_primo(num):
if num <= 1:
return False
elif num == 2:
return True
else:
for i in range(2, num):
if num % i == 0:
return False
return True
for i in word:
if i in dicc:
d... |
import toolbox
class Player(object):
def __init__(self):
pass
def guess(self):
letter = toolbox.get_string('What is your letter guess?')
while len(letter) != 1:
print('Your guess has to be one character.')
letter = toolbox.get_string('What is your le... |
import itertools
def replace(string):
if string == '':
return ['']
if string[0] != '?':
return [string[0] + rest for rest in replace(string[1:])]
return [x + rest for rest in replace(string[1:]) for x in ['0', '1']]
print(replace('?01?'))
def replace_joey(x):
if x == '':
return ... |
def merge(a1, a2, a):
i = j = 0
while i + j < len(a):
if j == len(a2) or (i < len(a1) and a1[i] < a2[j]):
a[i+j] = a1[i]
i += 1
else:
a[i+j] = a2[j]
j += 1
|
"""
Random data generation
"""
from shapes import *
from triangulation import *
from random import random
def random_convex_polygon(xmin, xmax, ymin, ymax, n, shift=0):
points = [Point((xmax - xmin) * random() + xmin, (ymax - ymin) * random() + ymin) for _ in range(n)]
shifted = Point.random(shift)
re... |
import math
from typing import List
__author__ = 'Xomak'
class Pages:
"""
Pages class is intended to store data, relevant to pagination
"""
def __init__(self, endpoint, rows_per_page, current_page, total_number, request_args):
"""
Creates Pages object.
:param endpoint: Flask ... |
class Node:
def __init__(self,data):
self.data=data
self.ref=None
class Sll:
def __init__(self):
self.head=None
self.tail=None
def insert_data(self,data,location):
new_node=Node(data)
if... |
import tkinter as tk
from tkinter import ttk
root=tk.Tk()
labels=["user name :-","user email :-","age:-","gender:-",'state:-',"city:-"]
for i in range(len(labels)):
cur_label="label" +str(i)
cur_label=tk.Label(root,text=labels[i])
cur_label.grid(row=i,column=0,stic... |
class Node:
def __init__(self,data):
self.data=data
self.ref=None
class circular:
def __init__(self):
self.head=None
self.tail=None
def circular_ll(self,data):
new_node=Node(data)
new_node... |
class Solution:
node_counter = 0
def find_next_different_node(self, head):
self.node_counter += 1
if head.next is None:
return None
if head.val == head.next.val:
return self.find_next_different_node(head)
return head
def deleteDuplicates(se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.