text stringlengths 37 1.41M |
|---|
from Player import *
from Enemy import *
from Level import *
import random
import pygame
#Sets up a game between the AI and non-AI
class Game():
def __init__(self, screen, player=None):
""" Creates a game that contains two players and a level """
self.screen = screen
if player !=... |
from argparse import ArgumentParser
from itertools import product
import numpy as np
import points as pts
def build_parser():
parser = ArgumentParser()
parser.add_argument('--data-path', type=str, required=True)
parser.add_argument('--max-distance', type=int, default=10000)
return parser
def mai... |
from argparse import ArgumentParser
def build_parser():
parser = ArgumentParser()
parser.add_argument('--data-path', type=str, required=True)
return parser
def main():
args = build_parser().parse_args()
with open(args.data_path) as file:
data = file.read().splitlines()
frequency = s... |
"""The Passenger class tracks who has entered the plane, at which row they are
currently, and to which row they need to get before sitting down.
Usage:
from airplane import Seat
from passenger import PassengerQueue
seat = Seat(row=10, seat=0, window_middle_aisle='window')
passenger = Passenger(seat=se... |
import numpy
import itertools
def queens_check(list):
result = 0 # đếm số lời giải
# kiểm tra lời giải
for k in list:
fitness = 0 # đếm số vị trí không phù hợp
for i in range(len(k) - 1):
for j in range(i + 1, len(k)):
if (k[j] == k[i]) or (k[j] == k[i] + (j - ... |
# matplotlib_intro.py
"""Python Essentials: Intro to Matplotlib.
<Name> Elaine Swanson
<Class> MTH 420
<Date> 1/29/2021"""
import numpy as np
from matplotlib import pyplot as plt
# Problem 1
def var_of_means(n):
"""Construct a random matrix A with values drawn from the standard normal
distribution. Calculate ... |
# This defines the base object that all classes inherit from
class RDObject(object):
def __init__(self, elevation_bottom = 0):
self.elevation_bottom = elevation_bottom
@property
def start_stage(self):
return self.elevation_bottom
@property
def start_stage_elevation(self):
return self.start_stage
class... |
# Module 1 Required Coding Activity
# Introduction to Python (Unit 2) Fundamentals
# This Activity is intended to be completed in the jupyter notebook, Required_Code_MOD1_IntroPy.ipynb, and then pasted into the assessment page that follows.
# The link to the .ipynb Jupyter Notebook files are in the last lesson of sec... |
# -*- coding:utf-8 -*-
# python2.7.9
"""
ʵһһַеĿո滻ɡ%20磬ַΪWe Are Happy.滻ַ֮ΪWe%20Are%20Happy
"""
class Solution:
# s Դַ
def replaceSpace(self, s):
# write code here
words = s.split(' ')
g = lambda x:'%20' if x == ' 'else x
return '%20'.join([g(i) for i in words])
if __name__ == '__main__':
s = Soluti... |
from datetime import datetime
# Función para devolver columna de fecha y hora
def fecha_hora(df):
'''
Separa la indormacion de fecha y hora que en todos los df estan juntas como string
Argumentos
----------
df: el dataframe de cada año de recorridos de bicis
'''
# Se splitea ... |
#creating 5*5 matrix with initial value 0
def create_matrix(row,column,initial_value):
#matrix=[[initial_value]*column]*row
matrix=[[initial_value for i in range(5)] for j in range(5)]
return matrix
#returns the index of given element
def find_index(matrix,letter):
for i in range(5):
for j in r... |
import argparse
import re
from typing import List
parser = argparse.ArgumentParser(description='Run an Advent of Code program')
parser.add_argument(
'input_file', type=str, help='the file containing input data'
)
args = parser.parse_args()
input_data: List = []
with open(args.input_file) as f:
for line in f.r... |
import argparse
from typing import List, Set
parser = argparse.ArgumentParser(description='Run an Advent of Code program')
parser.add_argument(
'input_file', type=str, help='the file containing input data'
)
args = parser.parse_args()
input_data: List = []
with open(args.input_file) as f:
input_data = [line f... |
#FUNÇÕES (FUNCTION)
#EXEMPLO SEM O USO DE FUNÇÃO :(
rappers_choice = ["L7NNON", "KB", "Trip Lee", "Travis Scott", ["Lecrae", "Projota", "Tupac"], "Don Omar"]
rappers_country = {"BR":["Hungria", "Kamau", "Projota", "Mano Brown", "Luo", "L7NNON"],
"US":["Tupac", "Drake", "Eminem", "KB", "Kanye West", "Lecrae", "Tra... |
# Scrabble: Freeform project using dictionaries
# credit: Codecademy (Python 3)
# The focus of this project is to process data from a game of scrabble, using dictionaries to organize players, words, and points.
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "... |
from random import randint
choices=["rock", "paper", "scissors"]
player_lives = 5
computer_lives = 5
computer=choices[randint(0,2)]
player = False
def winorlose(status):
print("called win or lose function", status, "\n")
print("You", status, "! Would you like to play again?")
choice = input("Y / N? ")
if ... |
# https://leetcode.com/problems/sliding-window-median/description/
import bisect
class Solution(object):
def medianSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[float]
"""
window = sorted(nums[:k])
res = [(window[k / 2] +... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
... |
"""
01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0
for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given matr... |
# The n-queens puzzle is the problem of placing n queens
# on an n×n chessboard such that no two queens attack each other.
# Given an integer n, return all distinct solutions to the n-queens puzzle.
# Each solution contains a distinct board configuration of the n-queens' placement,
# where 'Q' and '.' both indicate... |
"""
Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
class Solution(object):
def maxProduct(self, nums):
"""
... |
import csv
import math
file = open('election_data.csv', mode='r')
#convert to dictionary with csv reader library
#csvdat = csv.DictReader(dat)
csvdat = csv.reader(file)
rowcount = 0
total = 0.0
votes = {}
#no clue why this takes a user programmed loop
for row in csvdat:
if row[0] == "Voter ID":
continue
... |
class Movie():
def info(self):
print("moive name:",self.name)
print("hero is:",self.hero)
print("director is",self.director)
print("rating is:",self.rating)
m=Movie()
m.name="ls"
m.hero="nc"
m.director="sk"
m.rating=100
m.info() |
#setters and getters
class Student:
def setName(self,name):
self.name=name
def setMarks(self,marks):
self.marks=marks
def getName(self):
return self.name
def getMarks(self):
return self.marks
n = int(input("enter number of students: "))
for i in range(n):
s=Student()
... |
import mariadb
con=mariadb.connect(
user="root",
password="password",
host="127.0.0.1",
port=3306,
autocommit=True,
database='schools'
)
cursor=con.cursor()
"""cursor.execute("SELECT * FROM COMPUTERS WHERE FACULTY_NAME='ANIL'")"""
'''cursor.execute("select * from computers where depart_id =1 ")
... |
## unziping
from zipfile import *
f=ZipFile("file1.zip","r",ZIP_STORED)
# if you the file name
f1=open("names.txt","r")
data=f1.read()
print(data)
# if you don't know the file names
names=f.namelist()
for i in names:
print("file name: ",i)
print("content of file is ")
f1=open(i,"r")
data=f1.read()
... |
class Book:
def __init__(self,pages):
self.pages=pages
def __add__(self,other):
print("magic add method is calling")
total= self.pages+other.pages
return Book(total)
def __str__(self):
print("Str method is calling ")
return str(self.pages)
b=Book(200)
b1=Book(... |
# static variable is same to all the obbjects
class Team():
# 1:
game="cricket"
def __init__(self,name,team,country):
self.name=name
self.team=team
self.country=country
Test.
def about(self):
print("player_name:",self.name)
print("team",self.team)
... |
import os
fname=input("enter the file name: ")
a=os.path.isfile(fname)
if a==True:
f=open(fname,"r+")
list=f.readlines()
lcount=0
wcount=0
ccount=0
for i in list:
lcount=lcount+len(list)
ccount=ccount+len(i)
words=i.split()
wcount=wcount+len(words)
... |
#f=open("file.md","r")
try:
fname=input("enter the name of the file you want to open: ")
mode=input("enter the mode in which you want to open the file")
f=open(fname,mode)
n=int(input("enter the number of line you want to print: "))
except ValueError as msg:
print("enter the integers only ",msg)
exc... |
a=10
b=2
print(a+b," addition")
print(a-b,"substraction")
print(a/b,"division")
print(a%b,"modulo division")
print(a**b,"power or exponential")
print(a//b,"floor division")
|
## composition or HAS-A-RELATION
class Engine:
a=10
def __init__(self):
b=100
print("Engine function")
def test(self):
print("successfully tried")
class car:
def __init__(self):
self.engine=Engine()
self.m2()
def m2(self):
print(Engine.a)
... |
def checking(a):
if a%2==0:
print(a,"is a even number")
else:
print(a,"is a odd number")
checking(8647)
checking(7) |
#with multithreading
from threading import *
import time
def double(numbers):
for i in numbers:
print("double: ",2*i)
def square(numbers):
for i in numbers:
print("square: ",i**i)
numbers=[1,2,3,4,5,6]
begintime=time.time()
t1=Thread(target=double,args=(numbers,))
t2=Thread(target=double,args=(n... |
class X:
a=10
def __init__(self):
self.b=100
def m1(self):
print("this is m1 from class X")
class Y:
c=20
def __init__(self):
self.d=200
def m2(self):
x=X()
print(x.a)
print(x.b)
x.m1()
print(self.c)
print(self.d)
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 18 20:19:20 2016
@author: Rahul Patni
"""
import random
class Node():
def __init__(self, x, y):
self.next = None
self.x = x
self.y = y
self.hit = 0
self.visited = 0
self.next = None
def checkOver(self):
if self.x >= 8 or self.y < 0 or self.x < 0 or self... |
def fibonacci(n):
'''input: from distinct_list import distinct_list
out: fibonaccis sequence'''
try:
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
except exception as e:
raise ValueError()
|
class Math:
@staticmethod
def min(first, last):
if first > last:
return last
return first
@staticmethod
def max(first, last):
if first > last:
return first
return last
class Employee:
annual_raise = 1000
def __init__(self, imie, nazwi... |
class Animal:
legs = None
head = None
eyes = 2
_max_speed = 12
def __init__(self, legs: list = None):
print('init invoked')
self.legs = []
if legs:
self.legs = legs
self.speed = 0
self.eyes = 3
def run(self):
self.speed = 10
de... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#########################################################################
# File Name: testiterator.py
# Author: Wang Biwen
# mail: wangbiwen88@126.com
# Created Time: 2016.03.14
#########################################################################
class TestIterator(ob... |
# Program : Movie Search App
# Author : David Velez
# Date : 07/18/18
# Description: Movie Searching App running against movie_service.talkpython.fm
# that returns a list of movies based upon user search input
# Learned from Michael Kennedy's Python Jump Start Training Videos
# I... |
input_string = "abcd"
purmutations_set = set()
def list_to_str(string):
permutation = ''
for s in string:
permutation = permutation + s
return permutation
def permute(j, input_string, length):
for i in range(j, length):
string = list(input_string)
string[j], string[i] = input_... |
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
1964 : "ferrari",
}
'''
for item in thisdict:
print(item, end='\t')
print(thisdict[item])
'''
item = 1964
if 1964 in thisdict:
print(thisdict[item])
my_dict = {k:k**k for k in range(10)}
for item in my_dict:
print(item, end='\t... |
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def email(self):
return self.first + '.' + self.last + '@email.com'
@property
def fullname(self):
return f'{self.first} {self.last}'
@fullname.setter
def ful... |
def square(x):
return x * x
def my_map(func, arg_list):
results = []
for arg in arg_list:
results.append(func(arg))
return results
squares = my_map(square, [1,2,3,4,5])
for square in squares:
print(square) |
from typing import List
from itertools import permutations
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
temp = nums.copy()
temp.sort()
perm = permutations(temp, len(nums))
per... |
str_to_float = ['2.1', '2.3', '7,5', '$12.12', '8.9', '5%', '33.1', '33#1']
floats = []
for s in str_to_float:
try:
floats.append(float(s))
except:
floats.append(None)
print('exception')
print (floats)
def adder(x, y):
try:
z = x+y
except TypeError as target:
r... |
# 1_5
print("chaotic function")
x = eval(input("Number between 0 and 1: "))
n = eval(input("how often? "))
for i in range(n):
x = 3.9 * x * (1-x)
print(x)
|
def merge_sort0(a: list, b: list):
""""Сортировка слиянием 2-х массивов(списков)"""
c = [0]*(len(a)+len(b))
i = k = n = 0 # инициализируем 3 счетчика
while i < len(a) and k < len(b):
if a[i] <= b[k]:
c[n] = a[i]
i += 1
n += 1
else:
c[n] =... |
#возвращает рекурсивно число фиббоначи
def fib(n: int):
assert n >= 0
if n <= 1:
return n
else:
return (fib(n-1) + fib(n-2))
return fib[n]
# вычисляется число фиббоначи динамический
def fib2(n: int):
assert n >= 0
fib = [None]*(n+1)
fib[:2] = [0,1]
for k in range(2, n+1)... |
def find_factors(number):
"Нахождение простых множителей"
factors=[]
i=2
while i < number:
#Проверяем делимость на i.
while number%i==0:
#i является множителем. Добавляем его в список.
factors.append(i)
#Делим число на i.
number = number / ... |
'''
Add two numbers represented by linked lists | Set 2
Given two numbers represented by two linked lists, write a function that returns sum list.
The sum list is linked list representation of addition of two input numbers. It is not allowed
to modify the lists. Also, not allowed to use explicit extra space (Hint: Use... |
'''
Partition a set into two subsets such that the difference of subset sums is minimum
Given a set of integers, the task is to divide it into two sets S1 and S2 such that
the absolute difference between their sums is minimum.
If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2
must ... |
'''
Maximum Path Sum in a Binary Tree
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.
Example:
Input: Root of below tree
1
/ \
2 3
Output: 6
'''
import sys
class Node(object):
def __init__(self, num):
self.val = num
self.left = None
... |
'''
Compare two strings represented as linked lists
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s->b
Output: -1
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s
Output: 1
Input: list1 = g->e->e->k->s
list2 = g->e->e->k->s
Output: 0
'''
from ListNode import ListNode
def compareString(... |
'''
Given a string, print all possible palindromic partitions
example:
input:
nitin
output:
n i t i i n
n iti n
nitin
input:
geeks
output:
g e e k s
g ee k s
'''
def isPalidrom(string):
return "".join(string[::-1]) == string
def allPossiblePalUtil(string, st... |
'''
Length of the largest subarray with contiguous elements | Set 1
Input: arr[] = {10, 12, 11};
Output: Length of the longest contiguous subarray is 3
Input: arr[] = {14, 12, 11, 20};
Output: Length of the longest contiguous subarray is 2
Input: arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45};
Output: Length of ... |
'''
Dynamic Programming | Set 18 (Partition problem)
Partition problem is to determine whether a given set can be partitioned into
two subsets such that the sum of elements in both subsets is same.
'''
def partitionToSameSum(arr):
total = sum(arr)
if total%2 == 1:
return False
target = total/2
t = [ [Fals... |
from flask import Flask, request
"""Extensão Flask"""
def init_app(app: Flask):
@app.route('/')
def index():
print(request.args)
return "Hello Codeshow"
@app.route('/contato')
def contato():
return "<form><input type='text'></input></form>"
def page_other(app: Flask):
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Simple Sudoku CLI Application.
Example usage:
sudoku COMMAND INPUT_GRID
sudoku show INPUT_GRID
sudoku solve INPUT_GRID
sudoku validate INPUT_GRID
Format of INPUT_GRID: nine nine-digit numbers separated by commas
530070000,600195000,098000060,800060003,400803001,70002000... |
name=input("请输入姓名:")
print("{}同学,学好python,前途无量".format(name))
print("{}大侠,学好pathon,大展拳脚".format(name[0]))
print("{}哥哥,学好pathon,人见人爱".format(name[-2]))
|
strcount=0
intcount=0
spacecount=0
othercount=0
try:
x=input('请输入一行字符:')
y=eval(x)
except (Namerror,SyntaxError):
for i in x:
if ord(i) in range(68,91) or ord(i) in rang(97,123):
strcount+=1
elif ord(i) in range(48,58):
intcount+=1
elif i =="":
spa... |
def moon_weight(start_weight, increase_weight,year):
weight_every_year = []
for year in range(year):
weight = start_weight*0.165+ increase_weight*year*0.165
weight_every_year.append(weight)
print(weight_every_year)
input1 = float(input('Please enter your current Earth weight>',))
in... |
radius=25
area=radius*radius*3.1415926
print(area)
print({".2f"}.format(area))
|
import sys
inputs = sys.argv
inputs.pop(0)
for entry in inputs:
integer = int(entry)
print_string = ""
if integer % 3 == 0:
print_string = print_string + "fizz"
if integer % 5 == 0:
print_string = print_string + "buzz"
if print_string == "":
print(integer)
else:
print(print_string) |
#!/usr/bin/env python
# coding: utf-8
# In[24]:
Dictionary = {"hello": [1, 2, 3], "hi": "1,2,3"}
print(Dictionary["hello"])
print(Dictionary.get('age')) # get.[] it is used to avoid error when we search a key which is not present in a dictionary.
print("hello" in Dictionary.keys())
print('1,2,3' in Dictionary.val... |
#!/usr/bin/env python
try:
import requests
except ImportError:
print("\nA package called requests is required to run this script.")
print("Install it by : sudo apt-get install python-requests\n")
quit()
try:
from bs4 import BeautifulSoup
except ImportError:
print("\nA package called Beautiful Soup i... |
"""Program to count the number of words in a file using pyspark."""
from pyspark.sql import SparkSession
import constants as constants
from operator import add
from typing import List
class SparkEnv:
def __init__(self):
self.spark_session = SparkSession\
.builder\
.appName("PysparkWordCounter")\
.getOr... |
import random
user_input = input('Enter a single digit number:\t')
guess = random.randrange(0, 9)
if int(user_input) == int(guess):
print('Congratulations, You have won the lottery!!')
else:
print('Sorry, please try again!')
|
# 2. Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560,
# в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
n = (input('Введите число: '))
even_num = 0
uneven_num = 0
for i in range(len(n)):
num_int = int(n[i])
if num_int % 2 != 0:
uneven_num += 1... |
# 2. Написать два алгоритма нахождения i-го по счёту простого числа.
# Функция нахождения простого числа должна принимать на вход
# натуральное и возвращать соответствующее простое число.
# Проанализировать скорость и сложность алгоритмов.
import cProfile
# Первый — с помощью алгоритма «Решето Эратосфена».
def first... |
numbers= [1, 6, 8, 1, 2, 1, 5, 6]
n= int(input("Enter number: "))
count=0
i=0
while i < len(numbers):
c=numbers[i]
i+=1
if n==c:
count += 1
print(n, "appears", count, "times in my list")
|
n=int(input("Nhap so cot"))
m=int(input("Nhap so dong"))
for i in range (m):
print("\n")
for i in range (1,n+1,2):
print("* o ", end='')
|
prices={
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock={
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
fruits = list(prices.keys())
for i in fruits:
print(i)
i ==prices.get(i,0)
i ==stock.get(i,0)
print("price: ",prices.get(i,0))
print("stock: ",stock.get(i,0))
print()
total ... |
print("Welcome to our shop, what do you want?")
print("Our items:")
items = ["T-Shirt", "Sweater"]
print(*items, sep=', ')
new_item=input("Enter new item:")
items.append(new_item)
print(*items, sep=', ')
n= int(input("Update position:"))
items.pop(n-1)
m=input("New item?")
items.insert(n-1,m)
print(*items, sep=', ')
... |
n=int(input("Nhap so:"))
result = 1
for i in range (1,n+1):
result = result * i
print (result)
|
print ("Hello Chung")
n=input("What's your name?")
print("Hi",n)
|
def print_max(a,b):
if a > b:
print(a," is maximum")
elif a == b:
print(a, " is equal to " , b)
else:
print(b, "is maximum")
if __name__ == '__main__':
pass
#print_max(3, 4) # directly pass literal values
x = 5
y = 7 # pass variables as arguments
print_max(x, y)... |
def compress( _str ):
comp_str = []
count = 1
comp_str.append(_str[0])
for i in xrange(1, len(_str)):
if _str[i] == _str[i-1]:
count += 1
else:
if count != 1:
comp_str.append(str(count))
comp_str.append(_str[i])
count = 1
else:
comp_str.append(_str[i])
if count != 1:
comp_str.ap... |
from wip_list import build_list as build
from lexicon import word_list as lex
#print(lex)
def find_example_word(wip):
example = ""
wip_len = len(wip)
if wip in lex:
example = wip
else:
for word in lex:
print("++++\nWORD: ", word, "\n++++\n")
#assume the word ... |
def main():
import sys
#write this command to run:
#python practice.py < [file].txt > [file].html
#the txt file is known, you are creating the html file
writeToFile (sys.stdin, sys.stdout)
def writeToFile(query, w):
import MySQLdb
temp = query.readline()
query = query.read()
conn = MySQLdb.connect('loc... |
def is_palindrome(fname):
with open(fname) as f:
lines = f.readlines()
for line in lines:
input_string = (" ".join(line.split()))
reverse_string = input_string[::-1]
if reverse_string == input_string:
print (input_string)
fname = "/home/pavkata/test/test.txt"
is_pa... |
'''
def sum(a, b, c, d):
result=(a+b+c+d)
print ("The result on sum is "+ str(result))
def multiply(a, b, c, d):
result=(a*b*c*d)
print ("The result of multiply is "+ str(result))
a = input("Please enter a number: ")
b= input("Please enter a number: ")
c= input("Please enter a number: ")
d= input("Ple... |
import re
def make_ing_form(verb):
vowels = ["a", "e", "i", "o", "u"]
consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z" ]
suffix1 = ("e")
suffix2 = ("ie")
if verb in ["be", "see", "flee", "knee"]:
return "".join((verb, "i... |
from tkinter import *
root = Tk()
top_frame = Frame(root)
top_frame.pack()
bottom_frame = Frame(root)
bottom_frame.pack(side=BOTTOM)# параметр side позволяет задать положение
button1 = Button(top_frame, text='кнопка1', fg='red', bg='orange')
button2 = Button(top_frame, text='кнопка2', fg='blue', bg='orange')
button... |
from tkinter import *
root = Tk()
one = Label(root, text='one', bg='red', fg='yellow')
one.pack()
two = Label(root, text='two', bg='blue', fg='orange')
two.pack(fill=X)# будет растягиваться в соответствии с размером окна по оси Х
three = Label(root, text='three', bg='black', fg='white')
three.pack(side=LEFT, fill=Y)#... |
from card import *
class Hand(object):
def __init__(self, contents = None):
self._contents = contents if contents else []
# if contents is nont None:
# self._contents = contents
# else:
# self._contents = []
def __repr__(self):
return "Hand({})".format(self._contents)
def __str__(self):
return s... |
colors = set(['White', 'Black', 'Blue', 'Red', 'Yellow'])
N = int(raw_input())
for _ in range(N):
color = raw_input()
if color in colors:
colors.remove(color)
print colors.pop()
|
import random
print("rock paper or scissor game")
player1 = input("Enter your option: ")
choice = ["rock", "paper", "scissor" ]
player2 = random.choice(choice)
def game(p1, p2):
if p1 == p2:
print("Its a tie")
elif p1 =="rock":
if p2 == "scissor":
print("Rock Wins")
else... |
#list with numbers with new list with numbers less than a number
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b =[]
for each in a:
if each<5:
b.append(each) |
class productos:
def __init__(self,nombre,elaboracion):
self.nombre=nombre
self.elaboracion=elaboracion
class nodo:
def __init__(self,producto =None,siguiente=None):
self.producto=producto
self.siguiente=siguiente
class lista_productos:
def __init__(self):
self.primero = None
def in... |
import time
import math
start = time.time()
#time: 1.92652 seconds
def prime_array():
#array of prime numbers
array = [2,3]
step = 0
i = 5
comp = 0
count = 1
count2 = 2
while len(array) < 10001:
# this loop get the next 6n+/-1 number and checks whether it be divided by each prim... |
# Reading and Writing files and directories
# Read the Docs: https://docs.python.org/3/library/os.path.html
# os.path.join() allows us to build paths that will work on any OS
import os
os.path.join('usr', 'bin', 'spam')
# returns: 'usr\\bin\\spam'
# on linux or OS X it would have returned usr/bin/spam
# the followi... |
#firstchallenge
#List down all the error types
#1.)NameError
#2.)ModuleNotFoundError
#3.)IndexError
#4.)ZeroDivisionError
#5.)ValueError
try:
raise NameError('Aeroplane')
except NameError:
print("The exception demolished")
#ModuleNotFoundError
try:
import numpy
print("Module found")
except:
print... |
# 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
#
# 示例:
#
# Trie trie = new Trie();
#
# trie.insert("apple");
# trie.search("apple"); // 返回 true
# trie.search("app"); // 返回 false
# trie.startsWith("app"); // 返回 true
# trie.insert("app");
# trie.search("app"); // 返回 true
# 说明:
#
# 你可以假设所有的输入都是由小写字母 a-... |
from typing import List
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
max_length = [1 for _ in nums]
for i in range(1, len(nums)):
max_num = 0
for j in range(i):
if max_length[j] > max_num and nums[j] < nums[i]:
max_num = ... |
def quicksort(nums):
res = []
for i in nums:
has_found = False
for j in range(len(res)):
if res[j] >= i:
has_found = True
res.insert(j, i)
break
if not has_found:
res.append(i)
return res
if __name__ == '__m... |
name = input("What is your name?")
starter = input("What is your favourite starter?")
main_course = input("What is your favourite main course?")
dessert = input("What is your favourite dessert?")
drink = input("What is your favourite drink?")
print ("Hello " + name + "! Your favorite meal is " + starter +","+ mai... |
##suma de filas y de columnas
import numpy as np
def numero_filas_columnas (filas, columnas):
return np.random.randint(0, 11, (filas, columnas))
matriz = numero_filas_columnas(5, 5)
print(matriz)
v1 = np.array([])
w1 = np.array([])
vt = np.array([])
for v in range(0, 5):
suma_filas = 0
cuadrado = 0
suma... |
for i in range(20, 0, -1):
print(" informes del año: ", i)
#factorial de un numero
factorial = int(input(" poner el valor a factorial: "))
for i in range(1, factorial, 1):
factorial *= i
print(" factorial es igual: ", factorial)
#cuadrado de un número
n = int(input(" leer valor: "))
respuesta = 0
for i in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.