text stringlengths 37 1.41M |
|---|
notas_alunos = dict()
def notas(*num, sit=False):
"""
:param num: As notas passadas para a função.
:param sit: Se quer ou não quer mostrar a situação geral das notas.
:return: Retorna o total de notas, o maior e menor valor, sua média e a situação geral das nota, caso for pedida.
"""
notas_al... |
from turtle import *
import random
import turtle
import math
turtle.pu()
class Ball(Turtle):
def __init__(self,x,y,dx,dy,radius,color):
Turtle.__init__(self)
self.shape("circle")
self.shapesize(radius/10)
self.radius = radius
self.color(color)
self.goto(x,y)
self.dx = dx
self.dy = dy
def move(self,wid... |
'''
import turtle
from turtle import Turtle
import random
turtle.colormode(255)
class Square(Turtle):
def __init__(self,size,):
Turtle.__init__(self)
self.shapesize(size)
self.shape("square")
def random_color(self):
r = random.randint(0,256)
g = random.randint(0,256)
b = random.randint(0,256)
self.colo... |
"""
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
# Calin-Andrei Bucur
# 332CB
from threading import Thread
import time
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, *... |
import math
__author__ = 'Asher'
def main():
message = 'Cenoonommstmme oo snnio. s s c'
key = 8
plaintext = decryptMessage(key, message)
print(plaintext+'|')
def decryptMessage(key, message):
numColumns = math.ceil(len(message)/key)
numRows = key
numShaded = (numColumns * numRows) - len... |
# Best O(nlongn)
# Average O(nlogn)
# Worst O(n^2)
# Good for short lists
def partition(myArr, low, high):
pivot = myArr[low]
i = low
j = high
print("pivot is -- " + str(pivot))
print("high element is --" + str(myArr[high]))
while i < j:
while True:
i += 1
if (m... |
import random
number = random.randint(0,3)
words = ["LION","JUICE","BAND","SHREW"]
hint1 = ["mane","sweet","music","long nose"]
hint2 = ["roar","made of fruit","group","looks kinda like a mole"]
secretword = words[number]
guess = ""
counter = 1
while True:
print("Guess the secret word!")
print... |
# Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words.
# You should return an array of all the anagrams or an empty array if there are none.
def anagrams(word, words):
returnedarray = []
word = sorted(word)
for givenword in wor... |
# Pete likes to bake some cakes. He has some recipes and ingredients.
# Unfortunately he is not good in maths. Can you help him to find out, how many cakes he could bake considering his recipes?
# Write a function cakes(), which takes the recipe (object) and the available ingredients (also an object) and returns the m... |
# Your friend Bob is working as a taxi driver. After working for a month he is frustrated in the city's traffic lights.
# He asks you to write a program for a new type of traffic light. It is made so it turns green for the road with the most congestion.
# Example: There are 42 cars waiting on 27th ave. There are 72 ca... |
# John has invited some friends. His list is:
# s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
# Could you make a program that makes this string uppercase gives it sorted in alphabetical order by last name.
# When the last names are the same, sort them b... |
# In this kata, your job is to create a class Dictionary which you can add words to and their entries. Example:
class Dictionary():
def __init__(self):
self.d = {}
def newentry(self, word, definition):
self.d[word] = definition
def look(self, key):
if key in self.d:
re... |
import random
def pickdice():
continueprompting = True
dicetype = 0
#Errors
while continueprompting:
dicetype = int(input("How many sides does your dice have? "))
if not (dicetype in [4,6,8,10,12,20]):
print("Invalid amount of sides, choices are 4, 6, 8, 10, 12, and 20")
... |
from math import pow
time_1_lenh=22*pow(10,-9)
time_1_congdoan=5*pow(10,-9)
def step_by_step(n):
Step=n*time_1_lenh
return Step
def pipelining(n):
pipe=5*time_1_congdoan+(n-1)*time_1_congdoan
return pipe
def tile(Step,pipe):
tile=pipe/Step
return tile
|
'''
Created on Jul 5, 2014
@author: zrehman
'''
import unittest
import json
from collections import OrderedDict
"""SymbolTable class stores a key-value pair into a table. Given a key, the
corresponding value is returned. Both keys and values are stored in two
separate lists.
"""
class SymbolTable:
def __init__(... |
#3 variant
a = float(input('Введите 1-ое число: '))
b = float(input('Введите 2-ое число: '))
c = float(input('Введите 3-е число: '))
if b==0:
print ('введите b, отличное от нуля')
else:
if a%b == c:
print ('a даёт остаток с при делении на b')
else:
print ('a не даёт ост... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 02:10:11 2018
@author: Tiago Ibacache
"""
from threading import Thread,Semaphore
import time, c
class semaforos():
def __init__(self):
self.S1 = Semaphore(1)
self.S2 = Semaphore(1)
self.S3 = Semaphore(1)
def moversem... |
"""
CURSE PLAYER FUNCTION
input: card -- an integer representing a card (can only curse if card == 12 or card == 13)
playerNum -- an integer index of the current player
PlayerList -- a list of player classes
DiscardPile -- an integer list of cards that have been discarded
output: PlayerList -- upd... |
"""
CHOOSE MOVE FUNCTION
Select a move from the options available by seeing which maximizes the predicted probability of winning
input: Xprev -- input data from the current turn
[p1.pos1,p1.pos2,p2.pos1,p2.pos2,p1.turn,p2.turn]
roll -- [die1, die2] for the current player
parameters -- a ... |
"""
SEND PLAYER HOME FUNCTION
input: card -- an integer representing the card (can only send home if card==10 or card==11)
playerNum -- the index of the current player
PlayerList -- a list of player classes
DiscardPile -- a list of the cards which have been discarded
output: PlayerList -- updated ... |
"""
MOVE MAPPER FUNCTION
input: roll -- a pair of integers from 0 to 9 (n-1)
pos -- a pair of integers (a,b) representing the player's current position
availCards -- a list of ints representing the player's current hand
curse -- a boolean keeping track of whether the player is currently cursed
... |
from decimal import *
print '[#] The Gregory-Leibniz "infinite" series for calculating Pi!'
print "[#] Though not very efficient, it will get closer and closer to pi with every iteration, accurately producing " \
"pi to five decimal places with 500,000 iterations."
pi = Decimal(0)
odd = Decimal(1)
loop = int(0)... |
import pandas as pd
#any CSV file
mlb = pd.read_csv(".csv")
height = mlb['Height'].tolist()
weight = mlb['Weight'].tolist()
# Import numpy
import numpy as np
#Create a numpy array from the weight list with the correct units.
# Multiply by 0.453592 to go from pounds to kilograms.
# Store the resulting numpy... |
numero=int(input("dime el numero del que quieres saber la tabla de multiplicar:"))
i = 0
while i <= 10:
print("{} X {} = {}".format(numero, i, numero*i))
i += 1
i = 5
while i <= 15:
print("{} X {} = {}".format(numero, i, numero * i))
i += 1
i = 0
while i <= 10:
if (numero*i) % 2 == 0:
print... |
numero_1 = int(input("dime el primer numero"))
numero_2 = int(input("dime el segundo numero"))
operacion = input("que quieres hacer Sumar, Restar , Multiplicar, Dividir?").capitalize()
if operacion =="Sumar":
print("{}".format(numero_1+numero_2))
elif operacion=="Restar":
print("{}".format(numero_1 - numero_2)... |
# #########
## Step 5
## Create a List of TRex Running Postures
## Create a variable to record the index position
## Create a variable to define how many frames each running posture should be displayed
## When the Trex is at FLOOR level, animate to show run postures
## Change the Run Posture based on frames_per_image v... |
def plural_form (number, form0, form1, form2):
if number % 10 == 1 or number == 1:
print(number, form0)
elif number % 10 >= 2 and number % 10 <= 4 or number >=2 and number <=4:
print(number, form1)
else:
print(number, form2)
|
def getdate():
"""Gives you current date and time"""
import datetime
return datetime.datetime.now()
#MAIN FUNCTION
def HMS():
""" This function is used for Health Management System for 3 People """
#LIST OF USERS
user=["MANAN","HARSH","YASH"]
#Diet data
dd={1:"manandiet.txt",2:"pokardie... |
try:
i=int(input())
except Exception as e:
print(e)
else:
print("every thing is good")
finally:
print("the entered number is") |
class A():
var1="inside class a"
def __init__(self):
self.var1="inside a's function"
class B(A):
def __init__(self):
self.var1="inside bs function"
super().__init__()
var1="inside class b"
a=A()
b=B()
print(b.var1) |
class First():
x=1
class Second():
x=2
class Third(Second,First):
pass
f=First()
s=Second()
t=Third()
print(t.x) |
import re
pattern = r"Cookie"
sequence = "Cookie"
print(re.match(pattern, sequence))
# x=re.search(r'hi',"hello hi miami")
# y=re.search(r'doba$','adoba adoba')
# print(y)
#
# print("Lowercase w:", re.search(r'Co\wk\we', 'Cookie').group())
#
# ## Matches any character except single letter, digit or underscore
# print... |
class Employee:
name3="employee"
def myprint(self):
print( f"{self.name} {self.city} {self.birth} {self.rank}\n")
def __init__(self,name,rank,birth,city):
self.name=name
self.rank=rank
self.birth=birth
self.city=city
@classmethod
def sum(cls,n):
cl... |
INF = float('inf')
def minPathCost(graph,V):
minCost = graph.copy() #[ [0 for x in range(V)] for x in range(V) ]
for k in range(V):
for i in range(V):
for j in range(V):
minCost[i][j] = min( minCost[i][j], minCost[i][k]+minCost[k][j] )
for l in range(V):
for m in range(V):
if( minCost[l][m] == I... |
# 请在下面填入定义Book类的代码
# ********** Begin *********#
class Book:
# ********** End *********#
# '书籍类'
def __init__(self, name, author, data, version):
self.name = name
self.author = author
self.data = data
self.version = version
def sell(self, bookName, price):
print("%s的销售价... |
#coding=utf-8
# 导入math模块
import math
# 输入两个整数a和b
a = int(input())
b = int(input())
# 请在此添加代码,要求判断是否存在两个整数,它们的和为a,积为b
#********** Begin *********#
for i in range(1,a):
if b==i*(a-i):
print('Yes')
break
else:
print('No')
#********** End **********#
|
class WrapClass(object):
def __init__(self, obj):
self.__obj = obj
def get(self):
return self.__obj
def __repr__(self):
return 'self.__obj'
def __str__(self):
return str(self.__obj)
# 请在下面填入重写__getattr__()实现授权的代码
# ********** Begin *********#
def __... |
class Point:
def __init__(self, x, y, z, h):
self.x = x
self.y = y
self.z = z
self.h = h
def getPoint(self):
return self.x, self.y, self.z, self.h
class Line(Point):
# 请在下面填入覆盖父类getPoint()方法的代码,并在这个方法中分别得出x - y与z - h结果的绝对值
# ********** Begin *********#
def ... |
# coding=utf-8
# 创建并初始化menu_dict字典
menu_dict = {}
while True:
try:
food = input()
price = int(input())
menu_dict[food]= price
except:
break
#请在此添加代码,实现对menu_dict的遍历操作并打印输出键与值
###### Begin ######
print('\n'.join([ str(x) for x in menu_dict.keys()]))
print('\n'.join([str(x) for x in menu_dict.values()]))
##... |
#coding=utf-8
# 输入两个正整数a,b
a = int(input())
b = int(input())
# 请在此添加代码,求两个正整数的最大公约数
#********** Begin *********#
def gcd(m,n):
if not m:return n
elif not n:return m
elif m is n :return m
if m>n: d=n
else:d=m
while m%d or n%d:d-=1
return d
#********** End **********#
# 调用函数,并输出最大公约数
prin... |
#!/usr/bin/python3
import sys
def throws():
raise RuntimeError('this is the error message')
def main():
try:
throws()
return 0
# Unterschied Python3 Pyhton2.7
# except Exception, err:
except RuntimeError as err:
sys.stderr.write('ERROR: %s\n' % str(err))
return 1
if __... |
#!/usr/bin/python
import os
import time
import datetime
# 1. the year as a four-digit number, e.g. 2007
# 2. the month (1, 2, , 12)
# 3. the day of the month (1, 2, , 31)
# 4. hour (0, 1, , 23)
# 5. minutes (0, 1, , 59)
# 6. seconds (0, 1, , 61 where 60 and 61 are used for leap seconds)
# 7. week day (0... |
from dataclasses import dataclass
from collections import defaultdict, Counter
from typing import Dict, List, Counter, Union
from pathlib import Path
# https://docs.python.org/3/library/dataclasses.html
word_list = Path(r"wordle-small.txt").read_text().split()
Green, Yellow, Miss = "GY."
Word = str
Score = ... |
#python version 3.9.5
#IP Address Defang
userInput = input("Enter IP address to be defanged: ")
defangedIP = []
for x in userInput:
if x == '.':
defangedIP.append("[.]")
else:
defangedIP.append(x)
removeList =' '.join([str(i) for i in defangedIP])
print (removeList)
|
import numpy as np
def random2D(row = 1, col = 0, logical = True):
"""
A simple generator for random 2d matrix
Attributes
__________
row :: int
number of rows, default = 1
col :: int
number of cols, default = 0
Logical :: bool
type of the output matrix, if Tru... |
import re
def open_and_edit():
f = open("verbs.txt", 'r', encoding = "utf-8")
s = f.read()
f.close()
s1 = s.lower()
a = s1.split()
for i, word in enumerate(a):
a[i] = word.strip('.,!?();:*/\|<>-_%&#№@+~—"')
return a
def find_and_print(a):
arr = []
for word in a:... |
import re
def open_and_edit():
f = open("linguistics.txt", 'r', encoding = "utf-8")
s = f.read()
f.close()
return s
def replace_and_output(s):
s1 = re.sub('язык([а-я]{,3}( |\.|,|\)))','шашлык\\1', s)
s2 = re.sub('Язык([а-я]{,3}( |\.|,|\)))','Шашлык\\1', s1)
f = open("shashlyk.tx... |
# while 1:
# i = input("请输入:")
# print(type(eval(i)))
# if i == "quit":
# break
# else:
# print('结束')
# def test(*para):
# print('有 %d 个参数' % len(para))
# return para
#
# a = [1,2,3,4]
#
# print(test(*a))
# print('-----')
# print(test(1,2,3,45,8))
# class student:
# def __init__(s... |
class Shape():
def __init__(self, height, length):
self.height = height
self.length = length
def get_area(self):
raise NotImplementedError()
class Triangle(Shape):
def get_area(self):
area = (self.height * self.length)/2
return area
class Rectangle(Shape):
def get_area(self):
area = self.height * s... |
def swap(f):
def wrapper(*args, **kwargs):
args = reversed(args)
f(*args, **kwargs)
return wrapper
def div(x, y, show=False):
res = x / y
if show:
print(res)
return res
div(2, 4, show = True)
swapped = swap(div)
swapped(2, 4, show = True)
'''
или так
@swap
def div(x, y, sh... |
# allows specifying explicit variable types
from typing import Any, Dict, Optional, Text
def find_duplicates(_list):
"""Find duplicate items in a list"""
return set([x for x in _list if _list.count(x) > 1])
def dict2list(dictionary):
if type(dictionary) == list:
return dictionary
elif type(d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module contains logic to get a link from wikipedia.
Created on Mon Jan 25 20:47:33 2021
@author: macuser
"""
import wikipedia
import requests
def check_wiki(phrase): #takes an str and returns a str
'''
Search in wiki for a keyphrase and return a corresp... |
###########
# EDIT DISTANCE
###########
import numpy as np
def edit_dist(str1, str2):
m = len(str1)
n = len(str2)
if m == 0:
return n
if n == 0:
return m
a1 = np.zeros((m + 1, n + 1)) #create empty array
# a1 = np.zeros([0 for x in range(n + 1)] for x in range(m + 1))
for... |
p1 = (input("Player 1, please input your play: "))
p2 = (input("Player 2, please input your play: "))
if p1.lower() == 'rock':
if p2.lower() == 'scissors':
print("Player 1 wins")
elif p2.lower() == 'paper':
print("Player 2 wins")
elif p2.lower() == 'rock':
print("Tie!")
else:
... |
import math
lower_bound = int(input("Enter a lower bound: "))
upper_bound = int(input("Enter an upper bound: "))
prime_numbers = [2, 3]
i = lower_bound
if(lower_bound<1):
print("Your number is invalid. Please try again.")
elif(1<=lower_bound<3):
print(f"{n}st Prime number is : {prime_numbers[n-1]}")
elif (... |
# D. R. Y. "Don't repeat yourself."
# Once your code repeats itself several times, try to find a way to condense things.
# W.E.T. "Write everything twice" is what you don't want to do
# Function goes at the top of the program.
# def is defining a function, meaning you can use it
# When you run with just the three line... |
def sumTo(n):
return (1+n)*n/2
def productTo2(n):
ans = 1
for i in range(1, n):
ans = ans * i
return ans
def func():
x = 1
for _ in range (1,15):
x = x*2
return x
|
"""O modelo representea uma interação entre shops que vendem
fun e agentes que compram fun. Agentes e shops tem uma Accont,
onde os recursos para compra e venda de fun são depositados"""
# Construção dos agentes do modelo
import random
# Cada Account tem um saldo (balance) que inicia com zero
# Cada... |
'''Questão 8. Dicionários. Dado o dicionário: d = {‘a’: 0}: faça programas que 8.1 acrescente um par
(chave, valor) {‘b’: 1}, ao dicionário; 8.2 verifique se a key ‘c’ está presente? 8.3
Concatene um dicionário a um outro dicionário: e = {z : 23}. Use o método ‘update’!'''
d = {'a': 0}
d['b'] = 1
# para testar se o p... |
# I declare that my work contains no examples of misconduct, such as plagiarism, or collusion.
# Any code taken from other sources is referenced within my code solution.
# Student ID: ……w1810194………………..…
# Date: ………2020-12-05…………..…
#decalring variables to functions as counters for each progress method... |
#!/usr/bin/python
#[HL-2010-08-27 06:07]
# Testing generator function.. doesn't seem to work so well
# http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for
import time
# Function version
def fibonA(n):
a = b = 1
result = []
for i in xrange(n):
time.sleep(1)
... |
#!/usr/bin/env python3
# coding: utf-8
n1 = 10
str1 = 'You\'re beautiful girl. '
print(n1)
print(str1)
|
#!/usr/bin/python3
# coding: utf-8
import time
localtime = time.asctime(time.localtime(time.time()))
print('本地时间为:',localtime)
|
class FileValidationError(Exception):
def __init__(self, *args):
if args:
self.message = f"An error happened while the compilation and the validation of the {args[0]} file."
else:
self.message = None
def __str__(self):
if self.message:
return self.mes... |
#!/usr/bin/env python
from enum import Enum
from textwrap import dedent
from collections import defaultdict
class Tile(Enum):
WALL = '#'
PASSAGE = '.'
KEY = '🔑'
DOOR = '🚪'
def neighbors(loc):
yield (loc[0], loc[1] - 1)
yield (loc[0], loc[1] + 1)
yield (loc[0] + 1, loc[1])
yield (lo... |
### INPUT OUTPUT FILE
### MEMBUAT FILE DENGAN MENGGUNAKAN PYTHON
"""
ATURAN/MODE DALAM MANIPULASI FILE DENGAN PYTHON
1) w = WRITE MODE/CREATE FILE : akan menulis dengan menimpa isi dari file lama/membuat file baru jika file belum ada
2) r = READ ONLY MODE : hanya membaca isi dari file
... |
text1 = "Data String!"
print(text1)
text2 = "ini hari jum'at"
print(text2)
### untuk tanda petik 1 maupun 2 dalam string bisa diberikan tanda back-slash (\)
text3 = "Kancil berkata \"Kemana broh?\""
print(text3)
### untuk menciptakan baris baru maka dapat digunakan \n
text4 = "Hari ini ngantuk aja \nenakn... |
import time
import os
import sys
import random
def f_dynamic_path_to_initial_list(file_name):
"""This function allow us to open file with
the list of cities without regard to location folder """
dir_path = os.path.dirname(__file__)
list_file = dir_path+'/'+file_name
return list_file
def f_get_wor... |
#!/usr/local/bin/python3
# NAME: Victor Mora
# FILE: week8_exercises.py
# DESC: Week 8 Exercises
# DATE: October 8, 2016
import math
# Write a function named reverser() that reverses lists
# and strings. When the function is passed a string,
# it returns a string. When the function is passed a list,
# it returns a li... |
import math
# make a SD calculator
# take in inputs as numbers divided by commas
# make a function which retruns the number of inputs (len(smth))
# make another function that add all values and returns value
# make another function that calculates mean and returns its value
# run a while loop which ends when user in... |
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
import copy
class Point:
x = 0
y = 0
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({0}, {1})'.format(self.x, self.y)
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def asTuple(self):
return... |
# **************************** Challenge: Sensitive Information ****************************
'''
Author: Trinity Terry
pyrun: python sensitive_info.py
'''
# Create a class to represent a patient of a doctor's office. The Patient class will accept the following information during initialization
# Social security num... |
''' Search algorithms. '''
import click
from collections import deque
from copy import copy
from core.match import PatternMatcher
from core.structures import AnnotatedSentence,Pattern
class GraphSearch():
''' Base class for Graph Searching Algorithms.
Probably not as important in Python since duck-typing... '... |
# 42. Write a Python program to convert a list to a tuple.
list_=[1,2,4,9,5]
print(list_)
tuple_=tuple(list_)
print("the reaquired tuple is:",tuple_)
|
# 7. Write a Python function that accepts a string and calculate the number of
# upper case letters and lower case letters.
def up_low(string_):
upper_=0
lower_=0
for i in string_:
if i.isupper():
upper_+=1
elif i.islower():
lower_+=1
else:
pass
... |
# 12. Write a Python program to create a function that takes one argument, and
# that argument will be multiplied with an unknown given number
def fund1(n):
return lambda x:x*n
result=fund1(2)
print("the multiplication is",result(10))
|
# 17. Write a Python program to multiplies all the items in a list.
def mul_list(myList_):
result = 1
for x in myList_:
result = result * x
return result
list_1=[1,2,3]
print(mul_list(list_1)) |
#! /usr/bin/python37
"""
Author: Wytze Gelderloos
Date: 30-7-2019
Overlap Graphs
This function takes a list of DNA sequences and outputs an adjacency list
All overlap between the ends of DNA sequences can only occur once.
"""
file = open("rosalind_grph.txt", "r")
string = file.read()
string_list= string.split(">")
s... |
##########################################################################
# Love is the Ruin of Us All
#
# The social network of infatuation can be represented by a dictionary
# which maps a person's name to a set of people who are infatuated by
# that person (one person can have a crush on many other people). For
# ... |
import random
##########################################################################
# Write a function number_of_holes(n) that takes an integer n and returns
# the total number of holes of its digits (when the number is written in
# base 10). For instance, the digits 0, 4 have 1 hole each and the digit
# 8 has 2 ... |
##########################################################################
# Write a function in_union(x, y, circles) which returns True if the
# point $(x, y)$ lies in at least one of the circles from the list
# circles. Otherwise, the function must return False.
#
# The list circles is comprised of triples of the for... |
# Project Sudoku
def load_sudoku(file_name):
m = []
with open(file_name) as f:
for i in range(9):
line = list(f.readline().strip())
for j in range(len(line)):
if line[j] == '.':
line[j] = 0
else:
... |
##########################################################################
# Encryption
#
# A substitution cipher is a simple method of encryption by which each letter
# of a given alphabet is replaced by another letter. Such a cipher is
# represented by a dictionary that maps letter to their corresponding
# encrypted... |
##########################################################################
# FizzBuzz
#
# FizzBuzz is a popular game among children. Children pronounce numbers
# 1, 2, 3, ... If the number is divisible by 3 then they should say ‘Fizz!’
# instead of the number. If it is divisible by 5 then they should say
# ‘Buzz!’. If... |
"""
File: extension.py
--------------------------
This file collects more data from
https://www.ssa.gov/oact/babynames/decades/names2010s.html
https://www.ssa.gov/oact/babynames/decades/names2000s.html
https://www.ssa.gov/oact/babynames/decades/names1990s.html
Please print the number of top200 male and female on Consol... |
# # 1. Дан список a = [1, 2, 2, 4, 11, 2, 3, 1]. Напишите код, который выведет
# # список a без дубликатов.
# print("Задание №1 :")
# a = [1, 2, 2, 4, 11, 11, 3, 4, 4, 2, 5, 5, 3, 1]
# print('Исходный список: ', a)
# a = list(set(a))
# print(f'Новый список без дубликатов: {a}')
#
#
# # 2. Дан список a = [‘John’, ‘Anna’... |
import duckduckgo
# diagnostic logging
debug = False
def DuckWebSearch(search, youtube=False):
"""Performs a DuckDuckGo Web search and returns the results.
youtube : bool
True if doing a Youtube lookup
Returns:
str : the result of the web search
"""
if debug: print 'DuckWebSearch... |
"""A helper function for parsing and executing regex skills."""
import logging
import re
import copy
_LOGGER = logging.getLogger(__name__)
async def calculate_score(regex, score_factor):
"""Calculate the score of a regex."""
# The score asymptotically approaches the max score
# based on the length of th... |
import string
import nltk
from nltk.corpus import stopwords
def sort_it_1(fart):
lst=list(fart.keys())
lst.sort()
print('the keys:\n',lst,'\n')
for key in lst:
print(key,fart[key])
def sort_by_value(fart):
lst=list()
for key,val in list(fart.items()):
lst.append((val,key))
... |
print("Hi I'm test, who are you?", end=' ')
name = input()
print("How tall are you?", end=' '"Inches.")
x = int(input())
height = x / 12
print(f"Hello {name}, you are {height} feet tall. ")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter.messagebox as messagebox
class MyAPP(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.creatWidget()
def creat_widget(self):
self.nameInput = Entry(self)
... |
def recite(start_verse, end_verse):
song = """
a Partridge in a Pear Tree.
two Turtle Doves,
three French Hens,
four Calling Birds,
five Gold Rings,
six Geese-a-Laying,
seven Swans-a-Swimming,
eight Maids-a-Milking,
nine Ladies Dancing,
ten Lords-a-Leaping,
eleven Pipers Piping,
twelve Drummers Drumming,
""".split(... |
def square(number):
if number>0 and number<65:
return 2**(number-1)
else:
raise ValueError("Number must be between 1 and 64.")
def total():
total=0
i = 1
while i<65:
total+=square(i)
i+=1
print(total)
return total |
#!/usr/bin/env python3
import sys
print("Digite valores nao-nulos e positivos.")
try:
a = float(input("Entre com a medida do lado 1 do triangulo: "))
b = float(input("Entre com a medida do lado 2 do triangulo: "))
c = float(input("Entre com a medida do lado 3 do triangulo: "))
except ValueError:
print("Digit... |
def students_per_category_line_list_constructor(students_per_category_matrix):
"""
:param students_per_category_matrix: integer matrix of size - students X rounds (3 rounds assumed)
:return: return_list: list of strings used to construct a 2D array document containing the input matrix.
details:
#... |
import pickle
from math import sqrt
import numpy as np
from scipy.stats import chi2
import os
from .team_comparator import TeamComparator
from ..game_attrs import GameValues, GameWeights, Team
class PageRankComparator(TeamComparator):
"""
Ranks all Division I NCAA Basketball teams in a given year... |
from random import randrange
def input_group(n, m):
groups = []
for x in range(m):
groups.append([])
for group in groups:
for x in range(n):
group.append(randrange(100, 1000))
return groups
def output(groups_func):
counter = 1
for group in groups_func:
print("Group {} contains:".format(counter))
c... |
import sys
import os
class FizzBuzz(object):
def __init__(self):
self.line_count = 0
self.filename = ''
self.check_file()
def check_file(self):
self.filename = str(sys.argv[1])
if os.path.exists(self.filename):
self.import_list(self.filename)
else... |
# -*- coding: utf-8 -*-
import random
def ls(a, s):
found = False
i = 0
while i < len(a) and not found:
if a[i] == s:
found = True
i += 1
return found
if __name__ == "__main__":
array = []
for i in range(random.randint(0, 8)):
array.append(random.randint(0,... |
import turtle
import os
import time
HEIGHT = 800
WIDTH = 800
a_score = 0
b_score = 0
window = turtle.Screen()
window.title("Pong Game")
window.bgcolor("black")
window.setup(width=WIDTH, height=HEIGHT)
window.tracer(n=0)
def Draw_shape(pos, wid=5, _len=1, ball=False):
paddle = turtle.Turtle()
paddle.speed(0)
pad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.