text stringlengths 37 1.41M |
|---|
###################################################
'''
# 使用变量保存数据并进行加减乘除运算
a = 321
b = 123
print(a+b)
print(a-b)
print(a*b)
print(a/b)
'''
###################################################
###################################################
'''
# 使用type()检查变量的类型
a = 100
b= 12.345
c= 1+5j
d='helo world'
e=True
pr... |
import numpy as np
import math as mt
import matplotlib.pyplot as plt
x = (0, 1, 3, 6, 10)
y = (5, 6, 6, 10, 30)
z = (1,2,2,3,3)
a = (50, 40, 30, 20, 10)
plt.plot(x, y,z, a)
plt.ylabel('some numbers')
plt.xlabel('x axis')
plt.title('a graph for mam')
plt.show()
|
# Global Variables
flavorPrice = 1.25
def askCustomer():
#global flavorPrice
flavorPrice = 2.50
name = input("What is your name? ")
age = int(input("How old are you? "))
flavors = []
numFlavors = int(input("How many flavors do you want? "))
for n in range(numFlavors):
f = input(f"Flavor {n+1} name: ")
flavo... |
"""
This is the file containg our car data.
This data should be converted into the three different classes,
based on their make.
For simplicity's sake you have access to a function,
that will return a list of class dictionaries based on their make.
You are welcome to not use the given function but rather use the lis... |
import threading
DEBUG = 0
MAX_THREAD = 8
array = []
key = -1
found = False
position = -1
part = 0
def linear_search():
global array,key,found,position,part
if found:
return
thread_part = part
part+=1
low = thread_part*(len(array)//MAX_THREAD)
high = min(len(array),(thread_part+1)*(len(a... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 21 15:46:08 2018
@author: lqy45
"""
def creating_fibonacci_sequence(longth=1000):
Fib1=0
Fib2=1
Fib_list=[0,1]
k=2
while 1:
Fib=Fib2
Fib2=Fib2+Fib1
Fib1=Fib
Fib_list.append(Fib2)
k+=1
i... |
"""
Meetings are stored as tuples (start, end).
Write a function condense_meeting_times() that takes a list of meeting time
ranges and returns a list of condensed ranges.
For example, given:
[(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
your function would return:
[(0, 1), (3, 8), (9, 12)]
Do not assume the... |
"""
While Queen Elizabeth has a limited number of types of cake, she has an
unlimited supply of each type.
Each type of cake has a weight and a value, stored in a tuple with two indices:
An integer representing the weight of the cake in kilograms
An integer representing the monetary value of the cake in British poun... |
"""Implement a queue with two stacks. Have enqueue and dequeue"""
class Q:
def __init__(self):
stack1 = []
stack2 = []
def nq(self, item):
stack1.append(item)
def dq(self):
# remove all but first item from stack 1
while len(stack1) > 1:
stack2.append(st... |
# 21: Find Missing Drone
# Runtime: O(n)
# Space: O(n)
# Edge cases:
def find_drone(arr):
"""Returns the ID that isn't repeated in arr
>>> find_drone([1, 2, 4, 4, 3, 6, 6, 3, 1, 2, 7, 9, 7])
9
"""
checked_out = set()
for item in arr:
if item in checked_out:
check... |
# 0, 1, 2, 3, 4, 5, 6, 7, 8, ...
# 0, 1, 1, 2, 3, 5, 8, 13, 21,...
def fib(n):
"""Returns n'th fibonacci number
>>> fib(7)
13
"""
if n in [0, 1]:
return n
# initialize previous two numbers
prev2 = 0
prev1 = 1
# loop will be for 2nd fib num forward
step = 2... |
"""
I like parentheticals (a lot).
"Sometimes (when I nest them (my parentheticals) too much (like this
(and this))) they get confusing."
Write a function that, given a sentence like the one above, along with the
position of an opening parenthesis, finds the corresponding closing parenthesis.
Example: if the exampl... |
from tkinter import *
from tkinter import messagebox
import random
root=Tk()
root.config(bg="#E7C333")
root.minsize(width=300,height=500)
root.maxsize(width=300,height=500)
root.title("My To Do List")
root.geometry("300x500")
tasks=[]
#tasks=["Call mom", "Buy a guitar", "Eat Sushi"]
def update_listbox():
cl... |
import socket
import urllib.parse
def make_absolutepath(new_path, old_path):
"""Make an absolute pathname and handle relative paths.
Examples:
make_absolutepath('seite2.html','/index.html') = '/seite2.html'
make_absolutepath('seite2.html','/somedir/index.html') = '/somedir/seite2.html'
... |
print("Inserire i voti e il nome del primo candidato")
voti_primo_candidato = int(input("Inserire i voti del primo candidato"))
nome1 = input("Inserire il nome del candidato")
voti_secondo_candidato = int(input("Inserire i voti del primo candidato"))
nome2 = input("Inserire il nome del candidato")
lista_nomi = [no... |
while True:
numero=int(input("Inserisci il numero che vuoi controllare se è pari o dispari: "))
if numero%2==0:
print("Il numero è pari")
else:
print("Il numero è dispari")
esc=input("Per uscire premi q per continuare premi qualsiasi altra lettera ")
if esc=="q":
prin... |
nomi_numeri={}
while True:
nome_contatto=input("Inserire il nome della persona della quale si vuole cercare il numero; \nPer fermare il programma premi q ")
nome_contatto=nome_contatto.capitalize()
if nome_contatto=="Q":
break
if nome_contatto in nomi_numeri:
print("Il numero di"... |
#0~100의 성분을 갖는 행렬에서 20보다 크고 55보다 작은 값은 2 나머지 값은 0으로 출력되는 arrray를 만드시오
import numpy as np
A = np.arange(0,100)
B = np.logical_and((A>20),(A<55))
print(2*B)
B = 2*(A>20)*(A<55)
print(B)
#B를 가지고 A값이 3의 배수일때만 B에다가 A를 곱하시오
condition = (A%3 == 0) #A에서 3의 배수일때만 True값 준다.
print(condition)
B[condition] *= A[conditio... |
#!/usr/bin/env python3
# 03 – QUESTÃO
# Digamos que você tenha um array para o qual o elemento i é o preço de uma determinada ação
# no dia i.
# Se você tivesse permissão para concluir no máximo uma transação (ou seja, comprar uma e
# vender uma ação), crie um algoritmo para encontrar o lucro máximo.
# Note que você n... |
import numpy as np
def skew(v):
return np.float32([[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v[1], v[0], 0]])
class HTransf(object):
"""
Class for representing and manipulating homogeneous transformation matrices in SE(3)
construc... |
# Finding Numbers in a Haystack
# In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers.
# Data Files
# We provide two files for this assignment. One is a sample file where we give you the sum for your testing ... |
import re
import os
text = """
this is my text wow.
But this wow, has some problems.
Python 101
A problem of problems
"""
expresion_regular = '\\W+'
#print(text.split())
#palabras = re.split(expresion_regular, text)
palabras = re.findall(r'[a-z|A-Z]+', text)
print(palabras)
numeros = re.findall(r'\d+', text)
pri... |
#dic = {1:'lunes', 2:'martes', 3:'miercoles'}
#print(dic[2])
#dic[4] = 'jueves'
class contadorDePalabras():
def contar(self, text):
dic = {}
dic = text.lower().split()
# if item in dic:
# dic[item] += 1
# elif item not in dic:
# dic[item] = 1
... |
#body mass index
def BMI():
a=int(input("Enter Your Age: "))
w=float (input("enter weight of person"))
h=float(input("enter height of person"))
BMI=float(format((w*703)/(h**2), ".2f"))
if(BMI>=18.5) and (BMI<=25):
print("balanced" , BMI)
elif(BMI<18.5):
print("underweight" ... |
print("human:")
n = input()
number = [1]
i = 0
for n in range(1,n):
i += 1
number.append(i)
print(number)
|
"""Data that defines a shape in 3D space."""
# Copyright © 2014 Mikko Ronkainen <firstname@mikkoronkainen.com>
# License: MIT, see the LICENSE file.
from math import *
import numpy as np
from pymazing import color, matrix
class Mesh:
def __init__(self):
self.vertices = []
self.col... |
"""
What the program will do:
1. Track the amount of time elapsed between presses of the ENTER key, with each key press startimg a mew "lap" on the timer.
2. Print the lap number, total time, and lap time.
This menas your code will need to do the following:
1. Find the current time by calling time.time() and store it... |
spam = ['apples', 'bananas', 'tofu', 'cats']
def listToString (words):
words[-1] = 'and ' +words[-1]
string=''
for word in words:
if word == words[-1]:
string += words[-1]
break
elif word == words[-2]:
string+=word + ' '
else:
string +... |
#~ The letters "A", "B", "C", "D" and "E" are the early letters in the
#~ alphabet (and fairly common), and the letters "V", "W", "X", "Y", "Z"
#~ are the late letters in the alphabet. To generate a summary of a line,
#~ remove any other characters asides from the above 10 letters
#~ (case-insensitive), then conver... |
#~ You're working in a big bank with a lot of money transactions everyday.
#~ Your boss gave you a task to increase the stability of your system.
#~ After some thinking you came up with the following way for determining
#~ the stability of the set of transactions: if you have n transactions,
#~ ith of which was mad... |
# https://leetcode.com/discuss/interview-question/762546/
# Amazon Fresh is running a promotion in which customers receive prizes for purchasing
# a secret combination of fruits. The combination will change each day, and the team
# running the promotion wants to use a code list to make it easy to change the combinat... |
# https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/564/week-1-november-1st-november-7th/3517/
# https://leetcode.com/problems/insertion-sort-list/
#
# Sort a linked list using insertion sort.
#
# A graphical example of insertion sort. The partial sorted list (black)
# initially contains only t... |
# https://leetcode.com/discuss/interview-question/373006
# Given a map Map < String, List < String >> userSongs with user names as keys
# and a list of all the songs that the user has listened to as values.
#
# Also given a map Map < String, List < String >> songGenres, with song genre
# as keys and a list of all the... |
# https://leetcode.com/problems/search-a-2d-matrix-ii/
# Search a 2D Matrix II
# Write an efficient algorithm that searches for a value in an m x n matrix.
# This matrix has the following properties:
#
# Integers in each row are sorted in ascending from left to right.
# Integers in each column are sorted in ascending ... |
# https://leetcode.com/explore/interview/card/amazon/76/array-and-strings/2962/
# Implement atoi which converts a string to an integer.
# The function first discards as many whitespace characters as necessary until
# the first non-whitespace character is found. Then, starting from this character
# takes an optional... |
# 1119. Remove Vowels from a String
# https://leetcode.com/problems/remove-vowels-from-a-string/
# Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
#
# Example 1:
# Input: "leetcodeisacommunityforcoders"
# Output: "ltcdscmmntyfrcdrs"
# Example 2:
# Input: "aeiou... |
# https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/564/week-1-november-1st-november-7th/3518/
# https://leetcode.com/problems/consecutive-characters/
#
# Given a string s, the power of the string is the maximum length of a non-empty
# substring that contains only one unique character.
#
# Retu... |
# https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/564/week-1-november-1st-november-7th/3521/
# https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/
#
# Given an array of integers nums and an integer threshold, we will choose
# a positive integer divisor and divide all th... |
# https://leetcode.com/discuss/interview-question/782606/
# In order to improve customer experience, Amazon has developed a system to
# provide recommendations to the customers regarding the items they can
# purchase. Based on historical customer purchase information, an item
# association can be deinfed as - if an ... |
# https://leetcode.com/discuss/interview-question/411357/
# Given a 2D grid, each cell is either a zombie 1 or a human 0. Zombies can
# turn adjacent(up/down/left/right) human beings into zombies every hour.
# Find out how many hours does it take to infect all humans?
# Example:
# Input:
# [[0, 1, 1, 0, 1],
# ... |
#!/usr/local/bin/python3.8
# https://leetcode.com/problems/unique-paths-iii/
# https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/556/week-3-september-15th-september-21st/3466/
#
# Unique Paths III
# On a 2-dimensional grid, there are 4 types of squares:
#
# 1 represents the starting square. T... |
# -*- coding: utf-8 -*-
import math
#获取基准点的下标
def get_leftbottompoint(p):
k = 0
for i in range(1, len(p)):
if p[i]['y'] < p[k]['y'] or (p[i]['y'] == p[k]['y'] and p[i]['x'] < p[k]['x']):
k = i
return k
#叉乘计算方法
def multiply(p1, p2, p0):
return (p1['x'] - p0['x']) * (p2['y'] - p0['y... |
import time
from datetime import timedelta
def start_timer():
return time.time()
def end_timer(start_time):
end_time = time.time()
print("Time usage: " + str(timedelta(seconds=int(round(end_time - start_time))))) |
def valid_passwords_count(x):
#[min, max, letter, password]
count = 0
for i in x:
minLet, maxLet, letter, password = i[:]
dex = password.find(letter)
occurances = 0
while dex != -1:
occurances += 1
password = password[dex+1:]
dex = passwor... |
def crab_cup_game_move(cups, current_cup_index):
cur_cup = cups[current_cup_index]
grabbed = cups[current_cup_index+1:current_cup_index+4]
cups = cups[:current_cup_index+1] + cups[current_cup_index+4:]
max_label = max(cups)
min_label = min(cups)
dest_label = cur_cup-1
try:
dest_ind... |
import random
data_list = random.sample(range(100),20)
def merge(left_list, right_list):
return_list = list()
left_index = 0
right_index = 0
# left, right 둘다 있을 때
while len(left_list) > left_index and len(right_list) > right_index:
if left_list[left_index] < right_list[right_index]:
... |
class Queue :
def __init__(self):
self.list = list()
def enqueue(self, data):
self.list.append(data)
def dequeue(self):
first = self.list[0]
del self.list[0]
return first
## main
queue = Queue()
[queue.enqueue(i) for i in range(1,11)]
print(queue.list)
for i i... |
import unittest
import logging
LOG = logging.getLogger(__name__)
class Trie:
"""
https://leetcode.com/problems/implement-trie-prefix-tree/
Trie is a tree-based data structure, which is used for efficient retrieval of a key in a
large data-set of strings.
Unlike a binary search tree, where node ... |
#!/usr/bin/env python
# open file, read file as string x
# put string into list of words x
# create dictionary with keys as tuples from the list of words x
# account for case of words that are not followed by other words (go back and create a new sentence)
# run make_chains 10 times to come up with a sentence
# displa... |
#i.e dictionaries dont allow duplication
my_dict = {
'name': "maryanne",
'age':26 ,
'group': "girls",
'friends':['isha','carlene', 'Cynthia']
}
print("hello ", my_dict['name'], "Your age is: ", my_dict['age'])
print(my_dict['friends'])
print(type(my_dict))
x= my_dict['friends']
print("Your fr... |
from math import * #imports all math functions eg squareroot etc here
name = input("enter your name ")
name = name.strip() #removes spaces before and after the text. rstrip() from right, lstrip() from left you can specify text to remove in the brackets
print("Your name is ", name)
print("Hello there", name)
age = ... |
"""
Using origin and destination coordinates (manually identified as
beginning and ending nodes of an OSM segment), travel distance along the
segment is calculated across the OSM (MapQuest) and Google Maps dataset
"""
__author__ = "Derek Marsh"
__email__ = "dmarsh19@uncc.edu"
import os
import datetime
import time
imp... |
"""Finding the s,mallest of a set of numbers"""
def findsmallest(arr:list) -> int :
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
new_arr =... |
from typing import TextIO
def skip_header(reader:TextIO)-> str:
"""Skip the header in reader and return the first real piece of data.
>>> infile = StringIO('Example\\n# Comment\\n# Comment\\nData line\\n')
>>> skip_header(infile)
'Data line\\n'
"""
# Skip over the description
line = reader.read... |
import temperature
def get_baking_temperature(temp:float)-> str:
'''Shows what the temperature would be in celsius if the baking instruction is in fahrenheit
>>> get_baking_temperature(500)
'Preheat oven to 500 degrees F (260 degrees C )'
'''
cel = str(temperature.convert_to_celsius(temp))
te... |
import cupy
# TODO(okuta): Implement delete
# TODO(okuta): Implement insert
# TODO(okuta): Implement append
# TODO(okuta): Implement resize
# TODO(okuta): Implement trim_zeros
def unique(ar, return_index=False, return_inverse=False,
return_counts=False, axis=None):
"""Find the unique elements... |
# Allen, Sungmin, Yejun, Taiga
import turtle as trtl
t = trtl.Turtle()
t.speed(0)
# The Slope and Y-intecept
print("This program Creates a linear line (only positive) Y = mx + b")
m = int(input("Enter a number for m : "))
b = int(input("Enter a number for b: "))
# coordanite plane
# y hashma... |
# File which has all the collision-detection functions
# Self-collision detection, given a certain configuration
import numpy as np
import math
from scipy.linalg import expm, logm
import helper_library as helpme
# Defined radius for all collision detection. Units are meters
RADIUS = 0.015
# Calculate ... |
import string
import keyword
letterdigits=string.letters+string.digits
initials=string.letters+'_'
keywords=keyword.kwlist
for item in keywords:
print item,
print
identifier=raw_input('please input the identifier:\n')
if identifier in keywords:
print "Illegal identifier : Python keyword"
exit()
if identifie... |
class Encrypt:
ALPHABET = 'abcdefghijklmnopqrstuwxyz'
SECRET_VALUE_MIN = 2
SECRET_VALUE_MAX = 25
def __init__(self, key:int):
"""
Class designed to encode the text with asymmetric encryption. To properly encrypt the message,
algorithm uses the provided key and a secret value no... |
class Perceptron:
w1=0.0
w2=0.0
bias=0.0
def __init__(self, w1, w2, bias):
self.w1 = w1
self.w2 = w2
self.bias = bias
def set_weights(self, w1, w2):
self.w2=w2
self.w1=w1
def set_bias(self, bias):
self.bias = bias
def process_input(self, i1... |
n1 = int(input("Enter start number: "))
n2 = int(input("Enter end number: "))
for n in range(n1, n2):
count = 0
hm = 0
for i in range(2, int(n/2) + 1):
if not (n % i):
hm += 1 / i
count += 1
hm += 1/ n + 1
count += 2
hm = count / hm
hi = int(hm)
if hi == ... |
import random
ip = random.randrange(1,100)
n = int(input("Enter number of attempts: "))
for j in range(n):
x = int(input("Guess a number between 1 and 100: "))
if x == ip :
print("Correct!!")
if x < ip :
print("Number is greater than", x)
if x > ip :
print("Number is less than",... |
def compare_strings(string_1, string_2):
string_1 = str(string_1)
string_2 = str(string_2)
if string_1 == string_2:
return ("1")
elif len(string_1)> len(string_2):
return ("2")
elif string_1 != string_2 and string_2 == 'learn':
return ("3")
string_1 = str(input("Введите перв... |
print("practice stacks and queues")
#stack: first in last out
#queue: first in first out
# Q26
def q26(str):
stack = []
fail = False
for i in str:
if i == "(":
stack.append(i)
else:
if len(stack) == 0:
fail = True
break
els... |
__author__ = 'clyde'
import state_codes
import csv
from validator import prohibited_states
class Validator(object):
"""Validator class created with an orders file object.
When an instance is called it iteratively validates each order and returns a
list of validated orders"""
def __init__(self, ... |
#!/usr/bin/env python
#coding:utf-8
#pack and uppack list in python
a,b=[1,2,3],[4,5,6]
#pack
c=zip(a,b)#[(1, 4), (2, 5), (3, 6)]
#unpack
d=zip(*c)#[(1,2,3),(4,5,6)]
#create iterator
#create the iterator with max value no more than 1000
class x(object):
def __init__(self):
self.a=0
self.b=3
def next(self... |
#!/usr/bin/env python
#coding:utf-8
def nbr_of_laps(x, y):
"""两个数的乘积等于最大公因数与最小公倍数的乘积"""
mn,man=min(x,y),max(x,y)
n1=man
n2=mn
mul=mn*man
while(n2!=0):
gcd=n1%n2
n1=n2#to get the greatest common divisor
n2=gcd
nmn=mul/n1#get the least common multiple
return [nmn/x... |
# Bubble Sort
# Is Stable
# Worst complexity: n^2
# Average complexity: n^2
# Best complexity: n
# Space complexity: 1
def bubbleSort(arrayIn):
swapFlag = False
firstPass = True
while swapFlag is True or firstPass:
#reset the flag
swapFlag = False
#loop through entire list
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# bubble_sort.py
#
# Copyright 2017 HP <HP@HP-PC>
#
# Сортировка "пузырьком" целых чисел
#
num_list=input('Input unsort sequence: ').split()
num_list = [int(item) for item in num_list]
len_list=len(num_list)
while (len_list>1):
for i in range(0, len_list-1):
i... |
import math
orientation = 'N'
origin = [0,0]
origin2 = [0,0]
history = []
flag = False
def calc_distance(point):
return int(math.fabs(point[0])+math.fabs(point[1]))
def turn_right():
global orientation
if orientation == 'N':
orientation = 'E'
elif orientation == 'E':
orientation = 'S'
... |
"""This is to help me learn"""
#introduction to question game
print('welcome to my program')
#collect persons info func
def collect():
print('hi, what is your name?')
global name
name = input()
print('how old are you?')
global age
age = int(input())
print('what month were you born?')
g... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
'''
script util para gerar as palavras para
que sejam diretamente insteridas no xml
'''
#dict dificuldade : lista de palavras
dificuldade = {}
#dict palavra : descricao
par = {}
#estrutura do campo a ser adicionado ao xml
form = "<extra\n\
android:name=\"{}\... |
import random
theAnswer = random.randint(1, 100)
for i in range(0,10):
userInput = input('1-100之內,猜個數字吧')
theNumberUserGuesses = int(userInput)
if theNumberUserGuesses == theAnswer:
print('Bingo!')
break
elif theNumberUserGuesses <= theAnswer:
print('太小了,再猜一次看看')
else:
... |
import random
import time
from Utils import screen_cleaner
def generate_sequence(difficulty):
random_list = [0] * difficulty
for i in range(len(random_list)):
number = random.randint(1, 101)
random_list[i] = number
print(random_list)
time.sleep(0.7)
screen_cleaner()
return random... |
# Abstract Base Class example
"""Example 1"""
from abc import ABC, abstractmethod
class Polygon(ABC):
# abstract method
@abstractmethod
def no_of_sides(self):
pass
class Square(Polygon):
# overriding abstract method
def no_of_sides(self):
print("I have 4 sides")
class Hexagon(... |
#!/usr/bin/env python
# This is an ascii art implementation of iphone-like "apps" for the terminal
# currently launching aliases, shellscripts and python programs in bash.
# To do: ability to add or remove "apps" or create your own.
# Note: Current version 1.0 is an alpha rather than fully realized program.
from os... |
class Table:
"""
This class represents a sudoku table
colors is a list of colors, colors with smaller index has more priority
content is the real table
size is the size of content (row or columns)
domains is valid answers for each cell, each answer is a cell stored in corresponding index
do... |
def pangram():
n = int(input())
s = input()
string = s.upper()
for i in range(0,n):
count = string.count(string[i],i,n)
if count>1:
return False
return True
if pangram():
print("YES")
else:
print("NO")
|
n,k = input().split()
n = int(n)
k = int(k)
list1 = []
for i in range(1,n+1,2):
list1.append(i)
for i in range(2,n+1,2):
list1.append(i)
print(list1[k-1])
|
n = int(input())
for i in range(n):
string = input()
length = len(string)
if (length <= 10):
print(string)
else:
print(string[0] + str(length-2) + string[-1])
|
string = input()
q = '0000000'
p = '1111111'
if q in string or p in string:
print("YES")
else:
print("NO")
|
class Author(object):
'''Class object representing Authors. Author identified by `id`, but can be
instantiated using only `lastname`.
'''
def __init__(self, lastname, firstname=None):
self.lastname = lastname
self.firstname = firstname
self.works = []
self.id = None
... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
'''
Assignment 2: Recomputing the minimum spanning tree
Team Number:
Student Names:
'''
import unittest
import networkx as nx
"""IMPORTANT:
We're using networkx only to provide a reliable graph
object. Your solution may NOT rely on the networkx implementation of
any gr... |
#!/usr/bin/env python3
"""
Tento modul poskytuje třídu Point
"""
import math, turtle as t
from random import *
class Point:
def __init__(self, x=0, y=0, color='black', size=5):
""" 2D kartézská souřadnice """
self.x = x
self.y = y
self.color = color
self.size = size
... |
#!/usr/bin/env python3
infile = open("./skola_data.csv", "r")
alines = infile.readlines()
infile.close()
seznam = []
for line in alines:
prijmeni,jmeno,trida,other = line.split(',',3)
seznam.append([jmeno,prijmeni,trida,other])
seznam = sorted(seznam,key=lambda x: x[1])
for jmeno,prijmeni,trida,_ in seznam:... |
#!/usr/bin/env python3
from sequences import fibonacci
#n = ("what fibonacci number would you like to find: ")
#n = int(n)
#a = fibonacci(n)
#x = a.pop(-1)
#print(x)
def main(argv):
a = fibonacci(int(argv[1]))
print(a[-1])
if __name__ == "__main__":
import sys
main(sys.argv)
|
import sys as s
s.setrecursionlimit(3000)
def depth(n):
if n == 0 or n == 1:
return 1
return n * depth(n-1)
print(depth(1000)) |
#!/usr/bin/python3
"""Function that open/write and append a file"""
def append_write(filename="", text=""):
""" Open/write append text in filename"""
char_written = 0
with open(filename, 'a', encoding='utf-8') as f:
char_written = f.write(text)
return char_written
|
#!/usr/bin/python3
"""function that inherits from"""
def inherits_from(obj, a_class):
"""check if the object is an instance of
a class that inherited (directly or indirectly)
from the specified class """
if issubclass(type(obj), a_class) and type(obj) != a_class:
return True
else:
... |
#!/usr/bin/python3
def multiple_returns(sentence):
if not sentence:
tupl = (0, None)
return tupl
lenth = len(sentence)
tupl = (lenth, sentence[0])
return tupl
|
#!/usr/bin/python3
"""
Square class - setter and initialize the class
"""
class Square:
""" Square class """
def __init__(self, value=0):
""" Initialize attributs
Args: value (int): size of the square
"""
self._size = value
@property
def size(self):
"""Getter ... |
#!/usr/bin/python3
"""
matrix_mul - multiplication matrix
"""
def matrix_mul(m_a, m_b):
""" function that multiply two matrix into one
Args:
m_a: (list of lists): list of lists of integer
m_b: (list of lists): list of lists of integer
"""
if not isinstance(m_a, list):
raise ... |
choice1 = input("Choice 1:")
choice2 = input("Choice 2:")
hateRate1 = float(input(choice1 + "? "))
hateRate2 = float(input(choice2 + "? "))
if hateRate1 <= hateRate2:
result = "Choose the first choice!"
else:
result = "Choose the second choice!"
print(result)
|
A = input("Input A:")
B = input("Input B:")
C = input("Input C:")
if( A<B and B<C):
print("Sandwiched!")
else:
print("Not sandwiched.")
|
#!/usr/bin/env python3.6
from sys import argv
import re
import argparse
parser = argparse.ArgumentParser(description="Поиск в тексте по регулярному вырожению")
parser.add_argument('file_name', action="store", help="Название файла с текстом")
parser.add_argument('regex', action="store", help="Регулярное вырожение")
a... |
class UnionFind():
def __init__(self,n):
self.n = n
self.parents = [-1]*n
def find(self,x):
if self.parents[x]<0:
return x
else:
self.parents[x]=self.find(self.parents[x])
return self.parents[x]
def union(self,x,y):
x = self.f... |
#首先先定义一个类
class people:
#下面是定义基本属性(在外部可以直接进行访问)
name=''
age=0
#下面是定义私有属性(在外部不能直接进行访问)
__weight=0
#定义构造方法
def __init__(self,n,a,w):
self.name=n
self.age=a
self.__weight=w
def speak(self):
print("%s说:我%d岁,体重%d公斤"%(self.name,self.age,self.__weight))
... |
from Airplane import *
from LinkedList import *
class HashTable:
def __init__(self):
#self.avionesIsFull = False
self.maxSize = 3
self.linked_list_0 = LinkedList()
self.linked_list_1 = LinkedList()
self.linked_list_2 = LinkedList()
self.arr = [self.linked_list_0, sel... |
from scraper import scrape_box_scores, get_links
year = input('Please enter the year in this format: xxxx\n')
month = input('Please enter the month in this format: x\n')
day = input('Please enter the day in this format: x\n')
# Or if you want to run this as a daily script to get previous night's boxscores:
# yesterda... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.