text stringlengths 5 121k |
|---|
import error
class Var:
def __init__(self, data, name):
self.data = data
self.name = name
def __repr__(self):
return f"{self.name}({self.data})"
class String(Var):
def __init__(self, data):
super().__init__(data, "String")
def __repr__(self):
return f"String... |
import math
pi = math.pi
def surfacearea(r, s):
return pi * r * s + pi * r * r
def totalsurfacearea(r, h):
tsurf_ar = (2 * pi * r * h) + (2 * pi * r * r)
return tsurf_ar
radius = float(5)
height = float(12)
slat_height = float(13)
r = 5
h = 8
print( "Surface Area Of Cone : ", su... |
class Solution:
def halvesAreAlike(self, s: str) -> bool:
vowel = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
def count(s):
ans = 0
for c in s:
if c in vowel:
ans += 1
return ans
l = len(s)
return... |
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
self.left, self.right = [1], [1]
self.ans = 0
def DFS(node, level, idx):
if level>=len(self.left): self.left.append(idx)
else: self.left[level] = min(self.left[level], idx)
if level>... |
"""
# Definition for a Node.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
"""
class Solution:
def inorderSuccessor(self, node: 'Node') -> 'Node':
if node.right:
cur = node.right
... |
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head: return None
tail, count = head, 1
while tail.next:
tail = tail.next
count += 1
if k==count: return head
k = count - (k%count)
n... |
import random
import math
def IsPowerN(K,N):
x = int(round(math.log(K,N)))
if K == N**x:
return True
return False
def IsPowerNa(K,N):
while K > 1:
K /= N
if K == 1.0:
return True
return False
s = 0
s2 = 0
N = random.randrange(2,10)
print("N = ",N)
L... |
class Card(object):
"""A card from a standard card deck. Cards have the
following properties:
Attributes:
rank: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace
suit: There are four suits - hearts, diamonds, clubs, and spades. They're
represented as strings.
faceUp... |
zero = lambda f: lambda x: x
def add1(n):
return lambda f: lambda x: f(n(f)(x))
one = lambda f: lambda x: f(x)
two = lambda f: lambda x: f(f(x))
def add(a, b):
return lambda f: lambda x: a(f)(b(f)(x))
def numberize(n):
return n(lambda x: x + 1)(0)
|
"""
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
def main():
num_correct = 0
while num_correct != 3:
num1 = random.randint(10,99)
num2 = random.randint(10,99)
sum = num1 + num2
answer = int(input("what is " + str(num1) + " + " +... |
import time
import random
TEST_LENGTH_S = 10
'''
This is an alternative program for sections where you are concerned
about colorblindness getting in the way. It is basically the exact same
problem. We will get you a handout with details Monday night PDT.
recall that students don't know lists yet!
'''
def main():
... |
from simpleimage import SimpleImage
def main():
"""
This program loads an image and applies the narok filter
to it by setting "bright" pixels to grayscale values.
"""
image = SimpleImage('images/simba-sq.jpg')
for pixel in image:
average = (pixel.red + pixel.green + pixe... |
print("hello world")
'''for multi line comment'''
print('''Twinkle, twinkle, little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle, twinkle little star
How I wonder what you are''')
a=20
b="hello"
c=39.9
print(a)
print(type(a))
print(type(c))
... |
"""
sigmoid 函数
"""
import numpy as np
import matplotlib.pyplot as mp
def sigmoid(x):
return 1 / (1 + np.exp(-x))
x = np.linspace(-50, 50, 500)
y = sigmoid(x)
mp.plot(x, y)
mp.grid(linestyle=':')
mp.show()
|
"""
封装设计思想
需求:老张开车去东北
"""
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
def goto(self, str_pos, type):
print(self.__name, "去", str_pos)... |
commodity_info = {
101: {"name": "屠龙刀", "price": 10000},
102: {"name": "倚天剑", "price": 10000},
103: {"name": "九阴白骨爪", "price": 8000},
104: {"name": "九阳神功", "price": 9000},
105: {"name": "降龙十八掌", "price": 8000},
106: {"name": "乾坤大挪移", "price": 10000}
}
def choose_commodity():
display_commo... |
import collections
from collections import Iterable, Iterator
Card = collections.namedtuple('Card', ['rank', 'suit'])
class PokerCard:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for su... |
"""
创建Enemy类对象,将对象打印在控制台
克隆Enemy类对像
"""
"""
运算符重载
"""
class Vector1:
def __init__(self, x):
self.x = x
def __str__(self):
return "一唯向量的分量是 %d" % self.x
def __add__(self, other):
return Vector1(self.x + other)
def __iadd__(self, other):
... |
"""
"""
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print ("%s: %s" % (self.name, self.score))
def get_level(self):
if self.score >= 90:
return "A"
elif self.score >= 60:
... |
"""
The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next va... |
def minValueNode(node):
current = node
while (current.left is not None):
current = current.left
return current
def delete_node(root, data):
if root is None:
return root
if data < root.data:
root.left = delete_node(root.left, data)
elif (data > root.... |
def add(a,b,c):
res = a+b+c
return res
def sub(a,b,c):
res = a-b-c
return res
def main():
print("funct start")
print(add(1,2,3))
value = sub(3,0,1)
print(value)
main()
|
"""
Core diapason code.
"""
from io import BytesIO
from numpy import linspace, sin, pi, int16
from scipy.io import wavfile
def note_frequency(note, sharp=0, flat=0, octave=4, scientific=False):
"""
Returns the frequency (in hertzs) associated to a given note.
All the frequencies are based on the standar... |
password = 'e3f7d1980f611d2662d116f0891d7f3e'
print(password.lower())
if password.lower() != password:
print('loser1')
elif len(password) != 32:
print('loser2')
else:
if password != password[::-1]:
print('loser3')
try:
if int(password[:16], 16) != 16426828616880430374:
pr... |
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
sorted_num = sorted(nums)
l1, l2 = 0, len(nums)-1
while l1 <= l2 and nums[l1] == sorted_num[l1]:
l1 += 1
while l1 <= l2 and nums[l2] == sorted_num[l2]:
l2 -= 1
return l2 ... |
class Solution1:
def gameOfLife(self, board):
"""
Do not return anything, modify board in-place instead.
"""
n, m = len(board), len(board[0])
res = []
for i in range(n):
res.append([])
for j in range(m):
t... |
class Solution:
def containsDuplicate1(self, nums: List[int]) -> bool:
dictt = {}
for elem in nums:
if elem not in dictt:
dictt[elem] = 1
else:
return True
return False
def containsDuplicate2(self, nums: List[int]) -> bool:... |
class Solution:
def rotate1(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
nums[:] = nums[-k:] + nums[:-k]
def rotate2(self, nums: List[int], k: int) -> None:
"""
Do not ret... |
import sys
import codecs
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
def encrypt(sequences):
encrypted = list()
for seq in sequences:
if seq.islower():
encrypted.append(chr(219-ord(seq)))
else:
encrypted.append(seq)
return enc... |
import sys
import codecs
str = "stressed"
print(str[::-1])
str2 =list(sum(zip(str),()))
str2.reverse()
print("".join(str2))
|
class Shape():
def __init__(self, shape):
self.shape = shape
def what_am_i(self):
print("I am a " +self.shape)
class Rectangle(Shape):
def __init__(self, width, length):
self.width = width
self.length = length
self.shape = "Rectangle"
def calculat... |
def findMinAndMax(L):
if len(L)>0:
max,min=L[0],L[0]
for i in L :
if i<min :
min = i
if i>max :
max = i
print(min,max)
else:
return (None, None)
findMinAndMax([1,2,3,45,6])
|
def add(num1, num2):
return num1 + num2
def divide(num1, num2):
return num1 / num2
def multiply(num1, num2):
return num1 * num2
def minus (num1, num2):
return num1 - num2
def main():
operation = input("what do you want to do? (+-*/): ")
if(operation != "+" and operation != "-" and operation != "*" and ope... |
class Solution:
def sortList(self, head):
if head == None:
return head
if head.next == None:
return head
if head.next.next == None:
if head.val > head.next.val:
temp_val = head.val
head.val = head... |
'''Problem:
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the left... |
'''
In this example you have to validate if a user input string is alphanumeric. The given string is not nil, so you don't have to check that.
The string has the following conditions to be alphanumeric:
At least one character ("" is not valid)
Allowed characters are uppercase / lowercase latin letters and dig... |
linha1 = input().split(" ")
pi = 3.14159
A, B, C = linha1
a_ = (float(A) * float(C))/2
b_ = pi * (float(C)**2)
c_ = ((float(A) + float(B))*float(C))/2
d_ = float(B)**2
e_ = float(A) * float(B)
print('TRIANGULO: {:.3f}'.format(a_))
print('CIRCULO: {:.3f}'.format(b_))
print('TRAPEZIO: {:.3f}'.format(c_))
print('QUADRA... |
n = int(input())
err = 1
ddd = [
(61,71,11,21,32,19,27,31),
('Brasilia','Salvador','Sao Paulo','Rio de Janeiro','Juiz de Fora','Campinas','Vitoria','Belo Horizonte')
]
for i in range(len(ddd[0])):
if n == ddd[0][i]:
print(ddd[1][i])
err = 0
if(err == 1):
print('DDD nao cadastrado') |
pares = 0
for i in range(5):
n = float(input())
if n%2==0:pares += 1
print('%i valores pares'%pares) |
getal1 = input("geef het eerste getal: ")
getal2 = input("geef het tweede getal: ")
som = int(getal1) + int(getal2)
print("De som is " + str(som)) |
'''
https://leetcode.com/contest/weekly-contest-185/problems/minimum-number-of-frogs-croaking/
'''
class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
cr = 'croak'
def nextChar(c):
if c == cr[-1]: return
for i, cc in enumerate(cr):
i... |
'''
https://leetcode.com/contest/weekly-contest-169/problems/jump-game-iii/
'''
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
n = len(arr)
vis = set()
def walk(i):
if i < 0 or i >= n: return False
if arr[i] == 0: return True
... |
'''
https://leetcode.com/contest/weekly-contest-166/problems/group-the-people-given-the-group-size-they-belong-to/
'''
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
groups = []
h = {}
for n, g in enumerate(groupSizes):
if g not in h: h[g] = [... |
'''
https://leetcode.com/contest/weekly-contest-169/problems/all-elements-in-two-binary-search-trees/
'''
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
h = []
def traverse(r):
if r is None: return
h.append(r.val)
... |
'''
https://leetcode.com/contest/weekly-contest-163/problems/shift-2d-grid/
'''
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
n, m = len(grid), len(grid[0])
r = [[] for _ in range(n)]
k %= (n * m)
for i in range(n * ... |
'''
https://leetcode.com/contest/weekly-contest-168/problems/maximum-number-of-occurrences-of-a-substring/
'''
class Solution:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
max_c = 0
c = {}
for i in range(0, len(s) - minSize + 1):
current_s = s[i:... |
'''
https://leetcode.com/contest/weekly-contest-163/problems/greatest-sum-divisible-by-three/
'''
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
b = [[] for _ in range(3)]
nums.sort()
for n in nums:
b[n % 3].append(n)
def be_s... |
'''
https://leetcode.com/contest/weekly-contest-177/problems/validate-binary-tree-nodes/
'''
class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
seen = set()
edges = 0
for i in range(n):
l, r = leftChil... |
'''
https://leetcode.com/contest/weekly-contest-181/problems/check-if-there-is-a-valid-path-in-a-grid/
DFS algorithm with checks of possible previous cells for a currently visiting cell
'''
class Solution:
def hasValidPath(self, grid: List[List[int]]) -> bool:
pre = [None, (0, -1), (-1, 0), (0, -1), (0, 1)... |
'''
https://leetcode.com/contest/weekly-contest-173/problems/remove-palindromic-subsequences/
'''
class Solution:
def removePalindromeSub(self, s: str) -> int:
if len(s) == 0: return 0
if s == s[::-1]: return 1
return 2
|
'''
https://leetcode.com/contest/weekly-contest-155/problems/minimum-absolute-difference/
'''
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
min_diff = 10**7
for i in range(1, len(arr)):
min_diff = min(min_diff, arr[i] - arr[i - 1])
... |
'''
https://leetcode.com/contest/weekly-contest-175/problems/tweet-counts-per-frequency/
This is still unaccepted. No ideas whats wrong :(
'''
from collections import defaultdict
class TweetCounts:
def __init__(self):
self.per_min = {}
self.per_sec = {}
def recordTweet(self, tweetName: str, ... |
'''
https://leetcode.com/contest/weekly-contest-181/problems/longest-happy-prefix/
Algorithm:
Construct longest prefix length for every possible string s[:i]
This same prefix length array is used in KMP algorithm for pattern matching
'''
class Solution:
def longestPrefix(self, s: str) -> str:
pre... |
class A:
def test(self):
print('from A')
class B(A):
def test(self):
print('from B')
class C(A):
def test(self):
print('from C')
class D(B, C):
pass
print(D.mro())
|
import sys
for num in sys.stdin:
num = int(num.strip())
if (num % 2) == 0:
print("%s\t%s") % ("even", 1)
else:
print("%s\t%s") % ("odd", 1)
|
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
def check_items(l, i):
if i in l:
return True
else:
return False
print(check_items(items, 3))
print(check_items(items, 20))
print(check_items(items, "3")) |
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
evens = [n for n in a if n % 2 == 0]
print(evens) |
import json
from collections import Counter
with open("info.json", "r") as f:
info = json.load(f)
for each in info["birthdays"]:
birthday_month = each["month"]
print(birthday_month)
|
import json
with open("info.json", "r") as f:
info = json.load(f)
print('Welcome to the birthday dictionary. We know the birthdays of:')
for each in info["birthdays"]:
print(each["name"])
print('Whose birthday do you want to know?')
query = str(input())
print(f'You want to know the birthday of {query}.')
... |
from timeit import default_timer as timer
from math import log
def B(n):
def recur_B(n):
if n in result: return result[n]
temp_result = 1
index1 = (n + 1) // 2 - 1
index2 = n - (n + 1) // 2
temp_result += (index1 * recur_B(index1) + index2 * recur_B(index2)) / n
re... |
from datetime import datetime
'''
initiate greeting sequence to be played on jarvis startup
'''
def greet():
greet_text = ""
hour = int(datetime.now().hour)
if hour >= 0 and hour < 12:
greet_text = "Good Morning Sir. "
elif hour >= 12 and hour < 18:
greet_text = "Good Afternoon Sir. "
else:
greet_text = "... |
class Solution:
def __init__(self):
self.board = None
def validate_board(self, r, c, w):
for i in range(w):
u1 = dict()
u2 = dict()
for j in range(w):
if self.board[i][j] == '.' or self.board[i][j] not in u1:
u1[self.boar... |
"""
快慢指针,证明详见百度
"""
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
high = head
low = head
p = None
while low and high:
low = low.next
high = high.next
if not... |
while True:
numerator, denominator = map(int, input().split())
if numerator == 0 and denominator == 0:
break
else:
holenum= numerator//denominator
reminder= numerator%denominator
mixFraction= str(reminder) + " / " + str(denominator)
print(holenum, mixFraction)
|
import math
stop = False
while not stop:
r, m, c = map(float, input().split())
if r == 0 and m == 0 and c == 0:
stop = True
else:
areaOne = math.pi * math.pow(r, 2)
temp = (c / m)
areaTwo = temp * math.pow(2 * r, 2)
print(areaOne, areaTwo)
|
n = int(input())
suma= 0
fore = 0
if (n%2 == 0):
i=0
while i < n:
temp=int(input())
if i== 0:
fore = temp
else:
suma =abs(fore-temp)
fore = suma
i+=1
print(suma)
else:
print("still running")
|
g = input()
num = 0
s= "e"
for _ in range(len(g)):
if g[_] == "e":
num += 1
sv = "".join([char*(num*2) for char in s])
print("h"+sv+"y")
|
from trie import Trie
from data import *
from welcome import *
from hashmap import HashMap
from linkedlist import LinkedList
print_welcome()
food_types = Trie()
eateries = HashMap(len(types))
for food in types:
food_types.add(food)
eateries.assign(food, LinkedList())
eatery_cuisine = "cuisine"
eatery_name... |
name = input("What is your name? ")
if name == "Unded":
print("Hello", name)
else:
print("Nice to meet you", name)
|
def QuickSort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return QuickSort(left) + middle + QuickSort(right)
def fib(n):
if n <= 1:
... |
n = int(input())
students = {}
for i in range(n):
command = tuple(input().split())
name, grade = command
grade = grade.format()
if name not in students:
students[name] = []
students[name].append(float(grade))
for key, value in students.items():
value_as_str = ["{:.2f}".fo... |
expression = input()
stack = []
balanced = True
for ch in expression:
if ch in "{[(":
stack.append(ch)
else:
if len(stack) == 0:
balanced = False
break
last_opening_bracket = stack.pop()
pair = f"{last_open... |
def checkPalindrome(inputString):
backwardsStr =""
for i in range(len(inputString)-1,-1,-1):
backwardsStr+=(inputString[i]).lower()
for i in range(0, len(inputString)):
if inputString[i]!=backwardsStr[i]:
return False
return True
userWord = ... |
import re
def is_valid_email(addr):
re_email = re.compile(r'^[a-zA-Z]+[a-zA-Z\.]*@[a-zA-Z\.]+[a-zA-Z]+$')
if re.match(re_email, addr):
return True
else:
return False
def name_of_email(addr):
re_name = re.compile(r'^(<(.*?)>)|((.*?)@).*')
groups = re.match(re_name,addr).groups()
... |
class Solution:
def preorderTraversal(self, root):
if root == None:
return []
else:
return [root.val]+self.preorderTraversal(root.left)+self.preorderTraversal(root.right)
def preorderIterativelyTraveral(self,root):
result = []
node_stack =... |
class Solution(object):
def closestKValues(self, root, target, k):
"""
:type root: TreeNode
:type target: float
:type k: int
:rtype: List[int]
"""
s1 = []
s2 = []
self.traverse(False,root,s1,target)
self.traverse(True,root,s2,tar... |
import turtle
import os
player_a = str(input("Insert player A name: "))
player_b = str(input("Insert player B name: "))
window = turtle.Screen()
window.title('Pong Game by viegasdev')
window.bgcolor('#264653')
window.setup(width=800, height=600)
window.tracer(0)
score_a = 0
score_b = 0
paddl... |
"""
Created on Fri May 28 14:28:50 2021
@author: Mac_1
"""
import turtle as t
def drawRect(length):
for i in range(4):
t.forward(length)
t.left(90)
for i in range(-200,400,200):
t.up()
t.goto(i,0)
t.down()
drawRect(100)
t.done()
|
"""
Created on Fri May 28 14:50:54 2021
@author: Mac_1
"""
import turtle as t
def n_polygon(n, length):
for i in range(n):
t.forward(length)
t.left(360/n)
for i in range(20):
t.left(20)
n_polygon(6, 100)
t.done() |
a,b,c = input().split()
a = int(a)
b = int(b)
c = int(c)
sum = a+b+c
if sum ==180:
print("yes")
else:
print("no")
|
"""
@author: Mengxuan Chen
@description:
反转字符串
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
@revise log:
2021.01.11 创建程序
解题思路:双指针
"""
class Solution(object):
def reverseString(self, s):
... |
"""
@author: Mengxuan Chen
@description:
删除排序数组中的重复项
https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2gy9m/
@revise log:
2021.01.05 创建程序
"""
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i ... |
"""
@author: Mengxuan Chen
@description:
反转链表
进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
@revise log:
2021.01.16 创建程序
2021.01.17 解题思路:
# """
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
c... |
"""
@author: Mengxuan Chen
@description:
将有序数组转化为二叉搜索树
@revise log:
2021.02.09 创建程序
一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
中序遍历,总是选择中间位置右边的数字作为根节点
"""
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: ... |
object2 = open('foo.txt', 'r')
str = object2.read()
print(str)
object2.close()
obj_bar = open("bar.txt", 'w')
obj_bar.write("Python is a great language.\nYeah its great!!\n New line")
obj_bar.close()
objec_read = open('bar.txt', 'r')
str2 = objec_read.read()
print(str2)
objec_read.close() |
import numpy as np
my_list = [1,2,3]
print(my_list)
np_array = np.array(my_list)
print(np_array)
my_mat = [[1,2,3], [4,5,6], [7,8,9]]
np_mat = np.array(my_mat)
print(np_mat)
print(np.arange(0, 10))
print(np.arange(0, 11, 2))
print(np.zeros((2, 5)))
print(np.ones((3, 4)))
print(np.linspace(0, 5, 10))
... |
import sys, re
print('This is a collection of 3 script\'s to verify or find a mobile number.\n\n')
print('Script 1'.center(20, '='))
def isMobile(text):
if len(text)!=11:
print('This is not the correct length for a mobile number.\nPlease try again.')
return False
for i in r... |
import random
from random import randrange
def iniciarJuego():
j1 = random.randint(1,6)
j2 = random.randint(1,6)
print(f"\nEl jugador 1 obtuvo {j1} puntos")
print(f"\nEl jugador 2 obtuvo {j2} puntos")
if j1>j2:
print("\nEl ganador es el jugador 1")
elif j1==j2:
print("\nHubo u... |
import unittest
from src.card import Card
from src.card_game import CardGame
class TestCardGame(unittest.TestCase):
def setUp(self):
self.card1 = Card("Hearts", 10)
self.card2 = Card("Spades", 1)
self.cardGame = CardGame()
self.cards = [self.card1, self.card2]
def test_ch... |
import socket
from time import sleep
from MySocket import MySocket
class TCPSocket(MySocket):
'''
A class that represents a TCP connection with a specified host.
Wraps around an actual socket.socket, and implements send and receive methods
for easier usage.
'''
def __init__(self, ip, po... |
def stars(rows):
start = 1;
for row in range(start, rows):
str1 = " "
space = " "
for col in range(1, row + 1):
if (row == 3 and col == 2) or (row == 4 and col == 2):
space = " "
else:
space = " "
str1 +... |
"""
ZetCode Tkinter e-book
In this script , we change the default style
for the label widget class.
Author: Jan Bodnar
Last modified: January 2016
Website: www.zetcode.com
"""
from tkinter import Tk, BOTH
from tkinter.ttk import Frame , Label , Style, Entry
class Example(Frame):
def __init__(self , parent):
... |
def findClosestValueInBst(tree, target):
return findClosestValueInBstHelper(tree,target,float("inf"))
def findClosestValueInBstHelper(tree,target,closest):
if tree is None:
return closest
if abs(target-closest) > abs(target-tree.value):
closest = tree.value
... |
import numpy as np
import time
from timeit import timeit
np.random.seed(0)
def compute_reciprocals(values):
output = np.empty(len(values))
for i in range(len(values)):
output[i] = 1.0 / values[i]
return output
def array_arithmetic():
x = np.arange(4)
print("x =", x)
... |
def reverse_array(arr, start, end):
while start<end:
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start=start+1
end= end-1
def left_rotated(arr,d,n):
if d == 0:
return None
d = d%n
reverse_array(arr,0,d-1)
reverse_array(arr,d,n-1)
rever... |
class studentManage:
def __init__(self,student):
"""
menu为输入菜单选项的变量
并且每个class函数必须有一个self变量
"""
if type(student) != type({}):
print("构建存储的学生信息的存储结构有误,请使用字典结构")
self.menu=-1
self.students=student
def menuBook(self):
print ("\n")
print("***************")
print("欢迎使用学生管理系统")
print("1.增添学生信息")
... |
import os
import csv
electioncsv = os.path.join("PyPoll/Resources/election_data.csv")
totalvotes = 0
candidate_votes = {}
with open (electioncsv) as electiondata:
reader = csv.reader(electiondata)
header = next(electiondata)
print(header)
for row in reader:
candidate = row[2]
... |
class Engine:
def __init__(self, max_speed):
self.max_speed = max_speed
def move_vehicle(self):
print(f"moving at {self.max_speed} speed")
class Vehicle:
def __init__(self, name, engine):
self.name = name
self.engine = engine
def move(self):
self.engine.move_... |
class Hero:
hp = 100
damage = 10
__test = "don't touch me"
def get_test(self):
return self.__test
def __init__(self, name):
self.name = name
def __str__(self):
return f"hero {self.name}"
def __repr__(self):
return f"hero object {self.name} {self.damage} ... |
var1 = float(input("Masukkan data yang ke-1 = "))
var2 = float(input("Masukkan data yang ke-2 = "))
var3 = float(input("Masukkan data yang ke-3 = "))
var4 = float(input("Masukkan data yang ke-4 = "))
var5 = float(input("Masukkan data yang ke-5 = "))
n_var = 5
rata_rata=((var1+var2+var3+var4+var5)/n_var)
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.