text stringlengths 37 1.41M |
|---|
INITIAL_SIZE = 10 # Intial array size
class Queue:
"""FIFO Queue Data Structure implementation with array"""
def __init__(self):
'''Create a new empty queue'''
self._queue = [None] * INITIAL_SIZE # Array to store queue elements
self._size = 0 # Number of elements in queue
self._capacity = INI... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Author:Sage Guo
"""
凡是可作用于for循环的对象都是Iterable类型;
凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
"""
from collections import Iterable
from collections import Iterator
# fib function to generator fib numb... |
set1 = set(range(0, 100))
print("Set 1 ")
print(set1)
set2 = set()
for n in range(0,10):
set2.add(n**2)
set2.add(2000)
print("\nSet 2 ")
print(sorted(set2))
print()
set3 = set1.union(set2)
print("\nSet 3 = 1 union 2 ")
print(sorted(set3))
print()
set4 = set1.difference(set2)
print("\nSet 3 = 1 diff 2 ")
print(s... |
# module <from> called on module <sys>
# to <import> the module <argv> (argument)
# module <from> called on <os.path> module
# to import the function <exists>
from sys import argv
from os.path import exists
script, from_file, to_file = argv
# ^ user needs to enter the script to run (this file)
# followe... |
import random
ran_num = 0
user_num = 0
count = 0
def init_random():
global ran_num
ran_num = random.randrange(25)
def init_game():
print "It is an integer number less than 25."
def user_input():
global ran_num, user_num, count
while(True):
user_num = int(raw_input("\nEnter your number:"))
count = count + 1... |
sheep = [5, 7, 300, 90, 24, 50, 75]
print("\n1. Hello, My name is Cường and these are my sheep sizes")
print(sheep)
print("\n2. Hello, My name is Cường and these are my sheep sizes")
print(sheep)
print("Now my biggest sheep has size {} and let's shear it".format(max(sheep)))
print("\n3. Hello, My name is Cường and th... |
def calc(x, y, para):
if para == "+":
total = x + y
elif para == "-":
total = x - y
elif para == "*" or para == "x":
total = x * y
elif para == "/" or para == ":":
total = x / y
else:
total = "Error!!"
return total
a = calc(5, 7, "-")
print(a) |
quiz = [
{
"question" : "If x = 8, then what is the value of 4(x+3) ?",
"choices" : [35, 36, 40, 44]
},
{
"question" : "Estimate this answer (exact calculation not needed):\nJack scored these marks in 5 math tests: 49, 81, 72, 66 and 52. What is Jack's avarage mark?",
"c... |
import math
class Circle2D:
def __init__(self,r):
self.__rad = r
@property
def rad(self):
return self.__rad
@rad.setter
def rad(self,r):
self.__rad = r
def computeCircumference(self):
return math.pi * self.__rad
def computeArea(self):
... |
def weight_on_planets():
# write your code here
earthWeight = float(input("What do you weigh on earth? "))
marsWeight = earthWeight*0.38
jupiterWeight = earthWeight*2.34
print("\nOn Mars you would weigh {} pounds.\nOn Jupiter you would weigh {} pounds.".format(marsWeight, jupiterWeight))
if __name__ =... |
import datetime
class Building:
def __init__(self, address, stories):
self.designer = "Sam Pita"
self.date_constructed = ""
self.owner = ""
self.address = address
self.stories = stories
def construct(self):
self.date_constructed = datetime.datetime.now()... |
import numpy as np
import matplotlib.pyplot as plt
"""
Scatterplot & SLR code adapted from: https://www.easymachinelearning.net/introml/implementing-slr-with-python/
"""
class Plot():
def __init__(self,X,Y,name_X,name_Y):
self.X = np.array(X)
self.Y = np.array(Y)
self.name_X = name_X
... |
def calcular_precio_del_bus(distancia, num_pasajeros):
precio_ticket = 20.00
precio_total = 0.0
if distancia < 1 or num_pasajeros < 1:
return "Algun dato proporcionado es negativo"
else:
if distancia > 200:
precio_ticket += precio_ticket + float(distancia) * 0.03
if ... |
#!/usr/bin/env python
# Write a program that given a text file will create a new text file in which
# all the lines from the original file are numbered from 1 to n (where n is the
# number of lines in the file). [use small.txt]
def add_number():
file = open('newfile.txt' , 'w')
with open('small.txt') as f:
co... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode()
head.val = l1.val + l2.val
l1, l2 = l1.next, l2.next
while... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
ans = None
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(root: 'TreeN... |
# Program that prints k largest elements in an array
class Solution:
def kthLargestElement(self, nums, k):
nums.sort(reverse=True)
for i in range(k):
print(nums[i], end=" ")
def main():
(Solution().kthLargestElement([1,23,12,9,30,2,50],3))
main()
|
class
def add_contact(self, firstname, lastname, number, starred=False, *args, **kwargs):
self.firstname = input('Введите имя контакта')
self.lastname = input('Введите фамилию')
self.number = input('Введите номер телефона')
starred_input = input('Добавить контакт в избранные? (да/нет)')
if starred... |
"""
Date Due: 09/10/2018
Description: This code is a conversation between Terminal (a machine)
and a human. The machine is a little lonely and wishes it could adopt
human characteristics like emotions and aging. It genuinely cares
about the human it has the conversation with.
Sources: Class. Also, learned how to mul... |
# Partner 1: Anjali
# Partner 2: Sonali
''' Instructions:
Work with a partner to complete these tasks. Assume that all variables are declared; you need only write the if-statement using the variables indicated in the description. Write your solution below the commented description.
'''
''' 1.
Variable grade is... |
# SOURCES AND OMH IN MAIN CODE
# initializing the barriers/walls class
# this class uses getters and setters to get the x position and y position of the top left corner of the walls since they are "rects", and the width and height dimensions of the walls. It also uses getters and setters to get the kind of the barrier... |
import sys
grade = float(sys.argv[1])
if (grade < 0 or grade > 5):
print("Program expects a number from 0-5.")
elif grade < 1.0:
print("F")
elif grade < 1.5:
print("D-")
elif grade < 2.0:
print("D")
elif grade < 2.5:
print("D+")
elif grade < 2.85:
print("C-")
elif grade < 3.2:
print("C")
elif grade < 3.5:
pri... |
import random
import matplotlib.pyplot as plt
flips = 0
trial = 10*flips
heads = 0
counter = 0
numbers = [0,0,0,0,0,0,0,0,0,0,0]
for i in range(1000):
for j in range(10):
for k in range(10):
flip = random.randint(0,1)
if flip == 0:
heads += 1
#print("number of heads:", heads)
numbers[heads] += 1
hea... |
from src.bar import Bar
class Room:
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
self.guest_list = []
self.songs = []
self.room_fee = 5
self.bar = Bar()
def check_in(self, guest):
# check guest isn't alr... |
import random
GRID_SIZE = 101
NUM_GRIDS = 10
#defaults are grid size 101 and 50 grids, smaller numbers are only used for testing purposes!
#used for generating random start point
list1 = range(GRID_SIZE)
#used for generating whether or not a box will be blocked
list2 = range(10)
def dfs(grid, x, y, visited, closed,... |
from threading import Thread
from time import sleep
class bokk(Thread):
def __init__(self):
Thread.__init__(self)
self.messege = "Python Parallel programming started.\n"
def print_messege(self):
print(self.messege)
def run(self):
print("Thread... |
#!/usr/bin/python
from Tkinter import *
from string import *
from ConfigDlg import *
"""
This is the Stars! Coalition Tool (SCoT), version 0.1 alpha.
Code for drawing a star: mapCanvas.create_rectangle (100, 100, 103, 103, fill='white')
Of course, fill= can be set to a color appropriate to the player.
Stars' <ga... |
# Automate-the-boring-stuff-with-python
Python Practice
Chapter # 3
Practice Projects
# The Collatz Sequence Programe
def collatz(number):
if number%2==0 and number>0:
number=number/2
return(number)
else:
number=3*number+1
return(number)
def fun():
while True:
try:
... |
from math import sqrt
import numpy as np
def FindPrimes(limit):
isPrime = {}
isPrime[1] = False
for i in range(2, limit + 1):
isPrime[i] = True
checkLimit = int(sqrt(limit)) + 1
for i in range(2, checkLimit):
if isPrime[i]:
for factor in range(2, limit + 1):
j = i * factor
if (j > limit): break
... |
import random
class dice:
def __init__(self, side1, side2, side3, side4, side5, side6):
self.side1=side1
self.side2=side2
self.side3=side3
self.side4=side4
self.side5=side5
self.side6=side6
dice1=dice(1, 2, 3, 4, 5, 6)
keepRolling=True
counter = 0
def rollDice():
d... |
import random
import sys
def create_players():
global player1
global player2
print ("[Player 1]")
player1 = str.lower(raw_input("Type in your name, please:"))
print("[Player 2]")
player2 = str.lower(raw_input("Type in your name, please:"))
def randFirstPlayer():
start = random.randint(1... |
#Smallest multiple
#Problem 5
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# Not have answer the question
"""
v = 1
number_try = False
lines = "---------... |
"""
Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:
имя, фамилия, год рождения, город проживания, email, телефон.
Функция должна принимать параметры как именованные аргументы.
Реализовать вывод данных о пользователе одной строкой.
"""
def get_param(name,
surname,
... |
# Ex. 2
user_seconds = (input('Enter time(sec): '))
hours = int(user_seconds) // 3600
minutes = int(user_seconds) // 60
seconds = int(user_seconds) % 60
print('{0}:{1}:{2}'.format(hours, minutes, seconds))
|
from abc import ABC, abstractmethod
class A(ABC):
def __init__(self,value):
self.value = value
@abstractmethod
def add(self):
pass
@abstractmethod
def sub(self):
pass
class Y(A):
def add(self):
return self.value +100
def sub(self):
return self.v... |
n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1
print("La somme est", sum)
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
|
n1=int(input("Veuillez donner le premier nombre"))
n2=int(input("Veuillez donner le second nombre!"))
s=n1+n2
p=n1*n2
d=n1-n2
q=n1/n2
print("La somme de deux nombre est :", s, sep=' ', end='\n')
print("Le produit de deux nombres est :", p, sep=' ', end='\n')
print("La difference de deux nombres est :", d, sep=' ', end=... |
texte="Bonjour tout le monde"
rech=input("Entrez un texte a rechercher")
pos=texte.find(rech)
print("La position du\"{}\" est:{}".format(rech,pos))
|
class Flight():
def __init__(self,capacity):
self.capacity = capacity
self.passengers=[]
def add_passenger(self,name):
if not self.open_seats():
return False
self.passengers.append(name)
return True
def open_seats(self):
return s... |
number = int(input("Entrez la table de multiplication que vous voulez"))
for count in range(1, 11):
print(number, 'x', count, '=', number * count)
print("==========================================")
i = 1
while i <= 10:
p = i*7
print(i,'x 7=',p)
i += 1
|
a=int(input("Entrez votre chiffre"))
if a==0:
print("votre chiffre est null!")
elif a >0:
print("Votre chiffre est positif")
else:
print("votre chiffre est negatif!") |
def tri_selection(tab):
for i in range(len(tab)):
min = i
for j in range(i+1, len(tab)):
if tab[min] > tab[j]:
min = j
tmp = tab[i]
tab[i] = tab[min]
tab[min] = tmp
return tab
# Programme principale pour tester le code ci-d... |
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
plt.scatter(x, y, color='hotpink')
x = np.array([2, 2, 8, 1, 15, 8, 12, 9, 7, 3, 11, 4, 7, 14, 12])
y = np.array([100, 105, 84, 105, 90, 99, ... |
i= 0
while i<11:
if i%2==0:
print("est pair\n",i)
i+=1
|
class Voiture:
voiture_crees=0
def __init__(self,marque):
self.marque= marque
voiture_crees+=1
def afficher_marque(self,vitesse):
print(f" La voiture est une {self.marque}")
voiture_O1=Voiture("Lamborghini")
voiture_O2=Voiture("Porsche")
Voiture.afficher_marque(voiture_O1,50)
p... |
for val in range(5):
print(val)
else:
print("Fin de l'execution de la boucle")
|
class Student:
def __init__(self, name, age):
self.name = name
self.__age = age
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
emp=Student("ismatou",14)
print("Name: " +emp.name,emp.get_age())
emp.set_age(16)
print("Name: " +emp.name,emp.g... |
class Saidou():
def __init__(self):
self.course='java programmation cours'
self.__tech='java'
def CourseName(self):
return self.course + self.__tech
obj=Saidou()
print(obj.course)
print(obj._Saidou__tech)
print(obj.CourseName())
|
for num in [11, 9, 88, 10, 90, 3, 19]:
print(num)
if num==88:
print("number 88 found")
print("Terminer la boucle")
break
|
def smart_divide(func):
def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
@smart_divide
def divide(a, b):
print(a/b)
divide(2,5)
def star(func):
"""exemple de d... |
import numpy as np
df=np.array([
[1,2,4],
[3,4,5,6],
[8,9,7,2]
])
print(df[2][3]) |
x=0
while x <=10:
print(x)
x += 1
print("fin de la boucle tant que ")
for n in range(5,10):
print(n)
print("fin de la boucle for ")
for n in range(9):
if n %2== 0:
print(n," est un nombre pair")
else:
print(n,"est un chiffre impair") |
class Personne():
def __init__(self, prenom, nom, age):
self.__prenom = prenom
self.__nom = nom
self.__age = age
def est_majeur(self):
if self.__age >= 18:
return True
return False
def vieillir(self):
self.__age += 1
def __str__(self):
... |
# En utilisant la POO en Python, nous pouvons restreindre l'accès aux méthodes et aux variables.
# Cela empêche les données de modification directe qui est appelée encapsulation.
# En Python, nous désignons les attributs privés en utilisant un trait de soulignement comme préfixe,
# c'est-à-dire single _ou double __
c... |
class StaffSaidou:
# class variables
school_name = 'NIIT TECH'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age
# instance variables
def show(self):
print(self.name, self.age, StaffSaidou.school_name)
@classm... |
first_name=input("Votre nom s'il vous plait")
last_name=input("Votre Prenom s'il vous plait")
filiere=input("Votre Filiere s'il vous plait'")
print("Bonjour ",first_name,last_name)
print("Bienvenue dans la filiere",filiere) |
"""This file contains all functions needed for the evolution.
http://en.wikipedia.org/wiki/Genetic_algorithm
- random initialization
- run first generation
- evaluate with fitness function, measure average/max fitness
- select best candidates for next generation
- mutation + crossover/reco... |
#!/usr/bin/env python3
'''
time complexity n
'''
def find_terms(nums, target=2020):
d = dict()
for num in nums:
if target - num in d:
return (target - num), num
d[num] = num
return 0, 0
'''
time complexity n
'''
def part_1(nums):
a, b = find_terms(nums)
return a * b... |
from surfaces import *
import math
class Cell():
"""Takes one surface as initial input, the rest have to be added.
Surfaces are stored in a list of self.surfaces."""
def __init__(self):
self.surfaces = []
def add_surface(self, new_surface, sense):
"""Takes in the surface and th... |
# Davis Arthur
# 10-15-2019
# Auburn University
import math
import scipy.constants # science constants
import matplotlib.pyplot as plt # plotting libraries
import numpy as np
from SingleWire2 import *
class loop:
def __init__(self, current, radius, numwires, zpos = 0):
self.current = current
sel... |
from fractions import Fraction
a=int(input('Introduceti numarul a='))
b=int(input('Introduceti numarul b='))
c=int(input('Introduceti numarul c='))
d=int(input('Introduceti numarul d='))
print('Suma este=',Fraction(a,b)+Fraction(c,d))
print('Produsul este=',Fraction(a,b)*Fraction(c,d)) |
"""
版本:1.0
作者:MJL
功能:掷骰子
"""
import random
import matplotlib.pyplot as plt
roll1_list = []
roll_count = [0,0,0,0,0,0]
roll_rate = []
def main():
roll_times = 10000
for i in range(1,roll_times + 1):
roll1 = random.randint(1,6)
roll_count[roll1 -1] +=1
roll1_list.app... |
import re
import datetime
class Entry(object):
def is_today(self):
if self.date==datetime.datetime.today().date():
return True
else:
return False
def days_old(self):
if not self.date:
return 999999
else:
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
... |
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort(); #先排序
length = len(nums);
result = [];
i = 0;
while i < length - 2: ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def isSame(nodeA, nodeB):
if nodeA is None:
... |
grid = [[0,2]]
def orangesRotting(grid):
recurrent = 0
this_count = 1
target =[[0 for i in range(len(grid[0]))] for z in range(len(grid)) ]
while True:
this_count = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if target[i][j]== 0:
... |
nums = [1,3,5,6]
target = 5
def searchInsert(nums, target):
for i in range(len(nums)):
if nums[i] < target:
continue
return i
return len(nums)
print(searchInsert(nums,target)) |
moves = "UDUDUUDD"
def judgeCircle(moves):
target = list(moves)
level = 0
vertical = 0
for i in target:
if i == 'U':
vertical += 1
if i == 'D':
vertical -= 1
if i == 'L':
level += 1
if i == 'R':
level -= 1
if vertical ==... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 26 22:31:16 2018
@author: Filip
"""
counter = 0
for i in range(len(s)-2):
if s[i] == "b" and s[i+1] == "o" and s[i+2] == "b":
counter +=1
print("Number of times bob occurs is: " + str(counter)) |
from utils import utils
def two_sum_to_2020(data):
for i in range(len(data)):
for j in range(i,len(data)):
if data[i] + data[j] == 2020:
return data[i]*data[j]
return 0
def three_sum_to_2020(data):
for i in range(len(data)):
for j in range(i,len(data)... |
high_guess = 101
low_guess = 0
tries = 1
print("\n\nEnter a number between 1 and 100.")
the_number = int(input("Number: "))
while the_number < 1 or the_number > 100:
print("The number must be between 1 and 100.")
the_number = int(input("Number: "))
guess = 50
print(guess)
while guess != the_number:
if gues... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 25 13:03:01 2016
@author: Mark
"""
def song_playlist(songs, max_size):
"""
songs: list of tuples, ('song_name', song_len, song_size)
max_size: float, maximum size of total songs that you can fit
Start with the song first in the 'songs' list, ... |
#!/usr/bin/env python
# coding: utf-8
# In[6]:
def validate(x,y):
# x = valeur à tester
# y = type de valeur (t pour taux, m pour montant, a pour années)
try:
float(x)
except:
print("Attention ceci n'est pas une valeur")
return False
else:
if float(x) < 0:
... |
# implementation of binary search algorithm
# I will prove that binary search is faster than naive search
# Naive search basically search every index iteratively and ask if it is equal to target value
# if array consists the value it returns
# if it is not in the array it returns -1
import random
import time
def nai... |
# Задача 2. Дан массив целых чисел. Нужно удалить из него нули. Можно использовать только О(1) дополнительной памяти.
def remove_zeros(arr_input):
ind = 0
while(ind < len(arr_input)): # len() for list has O(1) time complexity
val = arr_input[ind]
if val == 0:
arr_input.remove(val)... |
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
class Snake:
"""tmp"""
def __init__(self):
self.segments = []
self.create_snake()
self.heading = 0
def create_snake(self):
for position in STARTING_POSITIONS:
... |
class Enemy: #by class we mean, hey python, we gonna make a class. Its a common practice of programmers to use first upper case letter to make a class. It helps to differeniae a class from veriable or functions.
life = 3
def attack(selff):
print("Ouuuch, I'm attacked")
selff.life -= 1
def c... |
####ALGORATHIMATIC OPERATORS####
'''
their are seven different algorathimatic operators which are:
+ - * / % ** //
'''
print("5 + 2 =", 5+2)
print("5 - 2 =", 5-2)
print("5 * 2 =", 5*2)
print("5 / 2 =", 5/2)
print("5 ** 2 =", 5**2) #** is called 'power of'
print("5 // 2 =", 5//2) #// is called 'floor division'... |
## CSCI 1300
## Semester Project
## Adam Grabwoski
## Pokemon Elite Four Challenge
import random
hyper_check = False
### How the player and opponents fight each other.
def take_turn(player_active, enemy_active, Moves):
global hyper_check
print()
## Asks the player which move they would like to use from... |
def _help_():
print("""
RunFile v5.2.2.
RunFile helps simplify file manipulation. Optimised for python files.
RunFile is used mainly for file manipulation. It is optimised for python files as RunFile can
explore deep into your code, access the code's functions and classes, run functions seperately,
search... |
import simplegui
import random
# global variables
num_guesses = 0
num_range = 101
secret_number = 0
# helper function to start and restart the game
def new_game():
global num_guesses
global num_range
global secret_number
if num_range == 101:
num_guesses = 7
secret_number = random.randr... |
# Запросить у пользователя число1.
# Запросить у пользователя число2.
# Вывести результат всех известных Вам операций над двумя числами.
# Операции + - * / // % **
num_1 = float(input('Пожалуйста, введите первое число:'))
num_2 = float(input('Пожалуйста, введите второе число:'))
plus = num_1 + num_2
print('''
Результ... |
def arithmetic_arranger(problems , *args):
if(args):
show_results = True
else:
show_results = False
return process_input(problems,show_results)
def process_input(problems,show_results):
first_op = []
second_op = []
op_list = []
if(len(problems) > 5):
return "Error: Too many pr... |
from math import sqrt
xP1X1 = float(input("Escriba el valor para X1: "))
xP1Y1 = float(input("Escriba el valor para Y1: "))
xP2X2 = float(input("Escriba el valor para X2: "))
xP2Y2 = float(input("Escriba el valor para Y2: "))
xP3X3 = float(input("Escriba el valor para X3: "))
xP3Y3 = float(input("Escriba el valor par... |
def shift_left(elems, e, begin, end):
i, j = begin, begin * 2 + 1
while j < end:
if j + 1 < end and not elems[j] < elems[j + 1]:
j += 1
if e < elems[j]:
break
elems[i] = elems[j]
i = j
j = j * 2 + 1
elems[i] = e
def heap_sort(elems):
end ... |
"""
模板
def slidingWindow(s: str, t: str) -> str:
from collections import Counter
need, window = Counter()
for c in t:
need[c] += 1
# 窗口左右端点值,左闭右开
left = right = 0
# valid == len(need) -> 窗口满足条件
valid = 0
while right < len(s):
# c 是将移入窗口的字符
c = s[right]
... |
class Chto_Bolit():
def chto_bolit(self, a):
if (a == 1):
return "голова"
elif (a == 2):
return "грудь"
elif (a == 3):
return "горло"
class Golova():
def bolit_golova(self, g1, g2, g3, g4):
print("Температура выше 37.8?(да/нет)")
g1 ... |
print('Please enter the value of the bill you have to pay')
AMOUNT = int(input())
print('Please enter the amount of 100, 20 and 1 banknotes in your wallet')
P = int(input())
Q = int(input())
R = int(input())
ways = 0
combinations = []
for x in range(P+1):
for i in range(Q+1):
for j in range(R+1):
... |
"""
This class is responsible for storing all the information about the current state of a chess game. It will also be
responsible for determining the valid moves at the current state. It will also keep a move log.
"""
class GameState():
def __init__(self):
#board is 8x8 2d list, each element of the... |
"""
@author Miguel Angel Correa - Pablo Buitrago
Taller 01 estructura datos y algorítmos.
"""
import math
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_dif_sq = (self.x - other.x)**2
y_dif_sq = (self.y - other.... |
# ----------------------------------------------------------------------
# Title:Homework 10
# Jordan Cerilli, A00132189
# Date:2020,11,04
# Purpose:Identify Class Car
# Acknowledgments:N/A
# -----------------------------------------------------------------------
import pickle
def main():
menu_choice = '0'
wh... |
from numpy import array
def Activity_1():
name = input("Enter your name: ")
age = int(input("Enter your age: "))
time_remaining_to_100 = (2020 - age) +100
print(time_remaining_to_100)
|
import datetime
from datetime import date
import requests
#example API KEY = "e2b47a49d350e13324ce145b3150ff64"
#creating the current weather part of the app:
def get_current_weather(city_name, key):
URL= f"https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={key}"
url_link = requests.get(URL)... |
x=0
y=0
sosoo=int(input('어디까지의 소수를 구해드릴까요?'))
for x in range (2,sosoo+1,1):
count = 0
for y in range(2,x+1,1):
if x%y == 0:
count+=1
if count == 1:
print(x)
|
'''
_________________MyCoding____________________
###############Power - Mod Power
a=int(input())
b=int(input())
m=int(input())
c=pow(a,b)
d=pow(a,b,m)
print(c)
print(d)
'''
'''
_________________MyCoding____________________
#01
#########Integers Come In All Sizes
a=int(input())
b=int(input())
c=int(input())
d=int(input... |
for i in range(0, 100, 1):
count=0
for j in range(2, i+1, 1):
if i%j==0 :
count+=1
if count==1 :
print(i)
|
#랜덤한 수 5개를 자동생성하여 합계와 평균을 구하세요.
'''
import random
ran=int(input("1부터 100중 몇개의 수를 합계와 평균을 구해드릴까요?"))
rand= random.sample(range(1,101), ran)
avg = 0
total = 0
print(rand,"랜덤으로 선택된 숫자는 다음과 같습니다.")
for i in range(0,ran,1):
total+=rand[i]
print("합계는 %d 입니다."% total)
avg=total/ran
print("평균은 %f 입니다."% avg)
... |
#Exercise 5 in Hackbright Curriculum
#open a file named on the command line
from sys import argv
script, file_name = argv
#open it in read mode
in_file = open(file_name) #create an object of type=file, named in_file
indata = in_file.read()
# print len(indata)
# try #1 this method would require 26 for loops - but ... |
def show_num(limit):
i=0
while i<=limit:
if i%2==0:
print("even",i)
else:
print("odd",i)
i=i+1
show_num(limit=int(input("enter the limit "))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.