blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
cc491ee2c2af3a105cf0d8ca0154f1977a383577 | vorobyovk/Python-learning | /Section 2, lesson 17.py | 1,484 | 4.03125 | 4 | class Hero():
"""Class to create of hero"""
def __init__(self, name, level, race):
"""initiate our hero"""
self.name = name
self.level = level
self.race = race
self.health = 100
def show_hero(self):
description = (self.name + " Hero level is: " + str(self.le... |
8cc43c88da339d72661e9aced61090f37881a47c | rupalisinha23/PythonProjects | /daily_horoscope_project/horoscope.py | 1,499 | 3.578125 | 4 | """
This program gets the daily horoscope and mails to the user.
Author: Rupali Sinha
"""
from bs4 import BeautifulSoup
import requests
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def retrieve_horoscope(url):
"""
This function gets the html content of th... |
8cae4d19dcb67105103e61a2f4159f319e7eb24f | dlnnlsn/generating_sets | /generators.py | 653 | 3.578125 | 4 | from disjoint_set import DisjointSet
from random import shuffle
def find_generating_set(group_elements = [], group_operation = lambda x, y: x * y, identity_element = None):
components = DisjointSet(group_elements)
shuffle(group_elements)
candidates = iter(group_elements)
generating_set = []
while components.compo... |
bbe9a65b024cfcdfeaada9df81b494e118ad5a4e | yusuke-konishi/PyConTutorialSampleCode | /step3/samplebot/plugins/libs/tictactoe.py | 5,284 | 3.84375 | 4 | # -*- coding: utf-8 -*-
NUMBER_ALPHA = [
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'keycap_ten',
]
class Player:
"""三目並べのプレイヤー
Attributes:
mark: このプレイヤーが置くマーク
"""
def __init__(self, mark):
self.mark = ... |
12115f7ea537cb55abfbaf155f5744680616a031 | yusuke-konishi/PyConTutorialSampleCode | /step1/file_read_and_write/file_reader.py | 764 | 3.703125 | 4 | # -*- coding: utf-8 -*-
def file_reader():
# sushineta.txtを読み込み専用で開く
f = open('sushineta.txt', mode='r', encoding='utf-8')
# read関数でファイル全体を文字列として読み込む
data = f.read()
# ファイルを閉じる(リソースの解放)
f.close()
print(data)
def file_reader_2():
f = open('sushineta.txt', mode='r', encoding='utf-8')
... |
a2db67595e3eea6d05330f328360d7669b1feba7 | obabawale/my_python_codes | /using extract_email.py | 258 | 3.875 | 4 |
from email_split import email_split
def extract_email(email):
""" extract the email addresses from a user-friendly email address"""
addresses = email_split(email)
return addresses[0] if addresses else ''
print extract_email('obabawale@mgbcomputers.com') |
9fef6a44f9cedc3366c2daa5493efb3101abf903 | obabawale/my_python_codes | /guessgame.py | 300 | 3.921875 | 4 | import random
comGuess = random.randint(0,100)
while True:
userGuess = int(input("Enter a guess between 0 and 100: "))
if userGuess > comGuess:
print ("Guess lower")
elif userGuess < comGuess:
print ("Guess higher")
else:
print ("Congratulations you've guessed right")
break |
b98370b24718f618c42d349c7a40aa8bc3e0e4ab | obabawale/my_python_codes | /reverseString.py | 166 | 4.125 | 4 | def reverse(text):
outputStr = ''
a = input("Enter String: ")
for i in range(len(a), 0, -1):
outputStr += a[i-1]
return outputStr
|
170415601775f49fdb8a8cd4f9884849b09eeab7 | Beardocracy/holbertonschool-web_back_end | /0x02-python_async_comprehension/0-async_generator.py | 381 | 3.78125 | 4 | #!/usr/bin/env python3
'''
This module contains the function async_generator
'''
import asyncio
import random
from typing import Generator
async def async_generator() -> Generator[float, None, None]:
'''
This coroutine loops 10 times, and yields a number between 0 and 10
'''
for i in range(10):
... |
7ba76ecef9722466927df39656e03f61a9ac9694 | Beardocracy/holbertonschool-web_back_end | /0x00-python_variable_annotations/3-to_str.py | 255 | 3.671875 | 4 | #!/usr/bin/env python3
'''
This module contains a type-annotated function takes a float n
as argument and returns the string representation of the float
'''
def to_str(n: float) -> str:
'''
Converts a float to a string
'''
return str(n)
|
040e2496ec59b9142f1f2d5fb8260159d26b3a47 | bruichriach/poker | /Poker/Poker/old_poker.py | 2,745 | 3.828125 | 4 | def input_command(message,hand_size):
global main_loop
global hand_loop
input = raw_input(message)
if input == "xx":
main_loop = False
hand_loop = False
return input
elif input == "x":
hand_loop = False
return input
else:
if (2*(len(input)/2)==len(... |
d104c332022e3ddbe049f58fc4bfb2de26fe0609 | KiD21606/LeetCode | /Problems/count-different-palindromic-subsequences.py | 4,276 | 3.65625 | 4 | # The previous three solutions try to find all the different palindromic subsequences solutions, so the runtime and memory are depend on how much the amount is.
# The last solution finds the number of different palindromic subsequences without recoding them.
# recursion
# runtime: ?
# memory: ?
# Time Limi... |
9b9f335a28b9b0eafff1810e84dcabd63b14ecc0 | aidanmatthew/Group1Projects | /Python/Peter Barredo/PythonExercise/function1.py | 133 | 3.984375 | 4 | def printMax(x,y):
'''Prints
'''
x = int(x)
y = int(y)
if x > y :
print(x, ' is maximum')
else:
print(y, ' is maximum')
|
8a8bb62e864bb8f0a03db4d205b6111d932f0aa2 | aidanmatthew/Group1Projects | /Python/Peter Barredo/PythonExercise/exerciseSet.py | 149 | 3.53125 | 4 | x = set("jihite")
print (x)
z= {'cisco', 'baidu', 'taobao'}
z= {'cisco', 'baidu', 'taobao','cisco'}
z.add('gameevil')
y = set(['d','e'])
print(y)
|
4e1c263de0a8c2468878337bd40970157da23fd6 | aidanmatthew/Group1Projects | /Python/Peter Barredo/PythonExercise/function2.py | 175 | 4 | 4 | def printMax(x,y):
'''Prints
'''
x = int(x)
y = int(y)
if x > y :
print(x, ' is maximum')
else:
print(y, ' is maximum')
if __name__ == '__main__':
printMax(4,5) |
22add8caecf5e6e9d16e723243ab678c5c9593c6 | jumarko/BioinformaticsForBeginners | /python-codecademy-course/03_conditionals_and_control_flow.py | 4,624 | 4.1875 | 4 | ### Unit 3. Conditionals and Control Flow lesson - 15 excercices
### https://www.codecademy.com/courses/python-beginner-BxUFN/0/1?curriculum_id=4f89dab3d788890003000096
## 1. Go with the flow - motivation
def clinic():
print "You've just entered the clinic!"
print "Do you take the door on the left or the right... |
99cd551d48ef24598869c1d76cc971a49478b7f5 | joeyuan19/TowerDefense | /simple.py | 1,680 | 3.515625 | 4 | DIM = (8,8)
class Tower(object):
def __init__(self,x,y,char,radius):
self.pos = (x,y)
self.char = char
self.bullets = []
self.radius = radius
def in_range(self,monster,road):
mx,my = road.get_xy(monster.pos)
tx,ty = self.pos
if dist_2D(tx,ty,mx,my) <= r:... |
d0aac7313ecf28787a30b512c6b89ec14bab8551 | hseifu/Algorithms | /Hollerith.py | 2,197 | 3.90625 | 4 | #! /usr/bin/env python3
import random
#A = list to be sorted, d = maximum number of digits with index of 0, count initialized to zero and incremented through every iteration
def hollerith_radix(A, d, count = 0, base = 10):
if len(A) == 1 or count > d:
return A
else:
final = []
buckets ... |
3eaa4b0dadadfb5052d04d471bb95a5a3b1e952a | hseifu/Algorithms | /Heap-Sort.py | 2,152 | 3.65625 | 4 | #! /usr/bin/env python3
import random
import pylab
import timeit
import numpy as np
import matplotlib.pyplot as plt
import sys
def max_heapify(A,i):
left = 2*(i+1)-1#get the two children
right = 2*(i+1)
if left < len(A) and A[left] > A[i]:#if the left is greater set as the largest
largest = left
... |
8658c7a07d93b0dcb7e95b3488d1fe6c409bde05 | thimmojn/pwb-piranhas-2019 | /agent.py | 978 | 3.625 | 4 | import random
from move import Move
"""
Agent for Piranhas.
"""
class PiranhasAgent:
def __init__(self):
self.me = None
self.memento = None
def setPlayer(self, player):
self.me = player
def updateMemento(self, memento):
self.memento = memento
def requestMove(self):
... |
0789eb5eb829f77764fbd45fcd7418b31942acbe | thoma55s/DnDTownMaker | /townMaker.py | 1,510 | 3.625 | 4 | import random
import sys
if "dawn" in sys.argv:
print("dawn")
animals = "animals.txt"
races = "dawnRaces.txt"
townPrefix = "dawnTownPrefix.txt"
townSuffix = "dawnTownSuffix.txt"
leader = "leaders.txt"
monsterIssues = "dawnMonsterIssues.txt"
dieties = "dawnDieties.txt"
else:
animals = "monsters.txt"
races = "... |
1a8c576dcb36cf882731dca6d150950bf9954b11 | kayanpang/champlain181030 | /week13_1/unittest_Class.py | 610 | 3.59375 | 4 | import unittest
from .addingMachineClass import *
class test_adding_macine(unittest.TestCase):
def setup(self):
self.number1 = 2
self.number2 = 3
self.adding_machine_instance = AddingMachine(self.number1, self.number2)
def class_Instantiated(self):
self.assertIsNotNone(self.ad... |
33c10e011dc7dcffc9b2be916c96715ea065edc2 | kayanpang/champlain181030 | /week6-1_class/debugging-2.py | 205 | 3.640625 | 4 | def calculate_tax(amount):
amount_with_tax = amount * 1.1556
value = 101
print("the value is " + str(value))
value_with_tax = calculate_tax(value)
print("the value with tax is " + str(value_with_tax)) |
2b26873e89f44f8959a014a6376c46a21ab5c03a | kayanpang/champlain181030 | /week6-1_class/review-function_ex8-6.py | 277 | 3.734375 | 4 | # python 8.6 to return
def city_country(city, country):
return city + ", " + country
print(city_country("Montreal", "Canada"))
# suugestion beginner
def city_country(city, country):
# return str(city) + ", " + str(country)
return "{0}, {1}".format(city, country)
|
dbc9eafd0700634cd98513eb886ced8dde48c635 | kayanpang/champlain181030 | /week3_181113/string.py | 239 | 3.9375 | 4 | myString = input(">")
print(myString.upper())
print(myString.title())
print(myString.lower())
print("The length of the entered string is " + str(len(myString)))
print(myString.replace("!" , "."))
print(myString.upper().replace("!" , ".")) |
a87fa54c7333f4b517a7c4daf7883b6d463a6234 | kayanpang/champlain181030 | /week5-2_functions_181129/function.py | 684 | 4.34375 | 4 | # example: repetition
print("this is line 1")
print("---------------")
print("this is line 2")
print("---------------")
print("this is line 3")
print("---------------")
# so create a function to do this repetition
def print_underscores():
print("---------------")
# function needs to be defined before used
print("th... |
d7a6b2495bfe735c03bc4ab200f2cbf0e1fb7aec | kayanpang/champlain181030 | /week16_revision/getter_setter.py | 485 | 3.734375 | 4 | class Item():
def __init__(self, description: str, price: float):
self.__description = description
self.__price = price
def get_description(self):
# no value in () is needed (self, description) this is to get a value so no need to assign a value to it
return self.__description
... |
df59290f0f8f9860ead3eb5d9cc78dc23fbcd1d3 | kayanpang/champlain181030 | /week6-1_class/debugging.py | 158 | 3.9375 | 4 | # debugging1
value = input("please enter a value to print out :")
value_plus_tax = int(value) * 1.1556
print("The value with tax is " + str(value_plus_tax)) |
e4754d3dce75fe063cd24ecfc5dc2d543cdf0932 | kayanpang/champlain181030 | /190225_revision/different-kinds-of-array.py | 1,524 | 4.5625 | 5 | # list is ordered and changeable. Allows duplicate members. it uses [] square brackets
# – Use lists if you have a collection of data that does not need random access.
# Try to choose lists when you need a simple, iterable collection that is modified frequently.
mylist = [1, 2, 'Brendan']
print(mylist[1])
# tuple is o... |
a7639b19800f9130430dbb61a7957143a8803068 | kayanpang/champlain181030 | /190225_revision/slide2_list.py | 278 | 3.890625 | 4 | # to access a member of the list, use the indexer
alist = [1, 2, "Brendan"]
print(alist[1])
print(alist)
alist.append('another value')
print(alist)
alist.remove('another value')
print(alist)
alist2 = alist +[4,5,6]
print(alist2)
mylist = [1, 3, 5, 6, 8, 10]
print(mylist[0:6]) |
c8b21caf9356d06471480f3488522d6ca31b01ed | kayanpang/champlain181030 | /week7-2_private-contribution/encapsulation.py | 859 | 4.375 | 4 | # worker - employee - contractor initializer in child Classes (slide15)
# read everything about class he whole chapter
class Worker:
"""this class represents a worker"""
def __init__(self, worker_name=""):
self.name = worker_name
def set_name(self, new_name):
self.__name - new_name
def ... |
8e85a80bc0796b297bf516198e80e74c4b8e3457 | kayanpang/champlain181030 | /week12-2_practice/practice-teacher.py | 4,977 | 3.953125 | 4 | import datetime
class Worker:
""" This is the base class of an Employee and a Contractor """
auto_id = 0
def __init__(self, first_name: str, last_name: str, hire_date: datetime):
self.__id = Worker.auto_id + 1
Worker.auto_id = self.__id
self.__first_name = first_name
sel... |
a8b951e454d19af1606d7ca8951b971330b8928e | kayanpang/champlain181030 | /week6-1_class/review-function.py | 268 | 3.8125 | 4 | # python ex. 8.5 city in a country
def describe_city(city, country = "Unknown country"):
print(city.title() + " is in " + country.title())
print("{0} is in {1}".format(city.title, country.title))
describe_city("Montreal", "Canada")
describe_city("Montreal")
|
3a9007e14583d62d02d9a88505e655b98569d954 | kayanpang/champlain181030 | /week5-1_list-range/province-dictionary3.py | 317 | 3.84375 | 4 | # another method: except
provinces_list = {'QC': 'Quebec', 'ON': 'Ontario', 'BC': 'British Columbia'}
Prov = input("Enter the province code > ")
try:
result = provinces_list[Prov.upper()]
print("The province name is {0}".format(result))
except KeyError:
print("Sorry the province code is not recognized!") |
3aa9a49232be6b9e2a1f25204aaec23d481d920f | kayanpang/champlain181030 | /review_quiz-class-file-csv/file review.py | 574 | 3.703125 | 4 | # file open close with try/finally clause
try:
f = open("text.txt", encoding = 'utf-8')
print(f.read())
finally:
f.close()
# file open close "with" statement, anything under with (the indentation)
with open("text.txt", encoding = 'utf-8') as text:
content = text.read()
print(content)
# read a bit ... |
953f2387d90085655d8759efe4d03d4584f8d9bc | kayanpang/champlain181030 | /week3_181113/break.py | 109 | 3.984375 | 4 | # equal sign in python is ==, = assigns value
for a in range(10):
if a == 3:
break
print(a)
|
b45b5641fedf093ae8fe6683ec80662f6cfb5553 | sprenkamp/HackerRankTestPython | /robot_circular.py | 882 | 3.515625 | 4 | N = 0
E = 1
S = 2
W = 3
def isCircular(path):
x = 0
y = 0
dir = N
for i in range(len(path)):
move = path[i]
if move == 'R':
dir = (dir + 1)%4
elif move == 'L':
dir = (4 + dir - 1)%4
else:
if dir == N:
... |
6c1589c22a23181bc864c9b256a5db9c82f2f57c | serdarcw/my_workings | /Python/Konu anlatımları Python_dosya /listeler_1.py | 3,667 | 3.734375 | 4 |
#country = [['Gana', 'South Africa', 'Ethiopia'], ['Germany' ,'France', 'Nederlands', 'Greece'], 'Turkey', 'New Zealand']
#
#print(country)
#
#print(type(country))
#string_1 = 'I will be a good DevOps Engineer'
#
#new_list_1 = list(string_1) # we created multi element list
#print(new_list_1)
#print(len(ne... |
43a4de07a5afdf44155fb6ae4658825b814b593c | serdarcw/my_workings | /Python/Assignments/Miles to km.py | 118 | 4.09375 | 4 |
km = input("Please enter your distance in km : ")
mile = float(km)/1.609
print("Distance is %.2f miles" % (mile))
|
d07d65d8e417c203cc2219967cbb9f9cf5718341 | serdarcw/my_workings | /Python/Assignments/sell_cost.py | 408 | 3.75 | 4 | cost_value =input("Please enter cost value (in dollar) : ")
sell_value =input("Please enter sell value (in dollar) : ")
inventory = input("Please enter inventory : ")
sales = {
"cost_value": float(cost_value),
"sell_value": float(sell_value),
"inventory": int(inventory)
}
profit = (sales['sell_v... |
a5a9ffeae62e7c1d15354afdcfba621eba4d8e4a | serdarcw/my_workings | /Python/Konu anlatımları Python_dosya /dictionaries.py | 5,479 | 3.515625 | 4 |
#empty_dict_1 = {}
#
#empty_dict_2 = dict()
#empty_dict_1 = {}
#
#print(type(empty_dict_1))
#my_dict = {'key1': 'value1',
# 'key2': 'value2',
# 'key3': 'value3'
# }
#
#print(my_dict['key1'])
#state_capitals = {'Arkansas': 'Little Rock',
# 'Colorado': '... |
679a69239a66a4c560b81955746294e168e154b6 | rocazac1/python-rest-101 | /src/test_models.py | 496 | 3.515625 | 4 | import unittest
from models import Person
class TestPerson(unittest.TestCase):
def test_str(self):
actual = Person("Robert", 27).__str__()
self.assertEqual('name = Robert, age = 27', actual)
def test_isAdult(self):
actual = Person("Robert", 27).isAdult()
self.assertEqual(True, a... |
8656aedb40369d32db73cb1d947ee7fae4afbfde | markerickson314/python-challenge | /PyPoll/main.py | 2,495 | 3.65625 | 4 | # import dependencies
import os
import csv
# specify path
csvpath = os.path.join("Resources", "election_data.csv")
# open csv and skip header row
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
header = next(csvreader)
# define variables
total_votes = 0
cand_list = [... |
ef2e91268fa267613efc9327b761084c0f1c27b9 | ChrisLeeSlacker/Calculator | /Adv. Calc.py | 5,954 | 4.0625 | 4 | def ask_input(text_prompt):
# Divine local variable
converted_num = math.nan
# Wait for valid numerical input
while True:
num = input(text_prompt)
try:
# Try to typecast the input to a float
float(num)
except ValueError:
# Catch the... |
4f152787f7b672af712b9b5e96d29836986b456b | BraweGit/Malware-scanner | /db_manager_.py | 3,608 | 3.640625 | 4 | import json
from pathlib import Path
class DBManager:
""" Provides basic functionality for communication with local JSON database.
Creating database. Inserting new records. Updating existing records.
Or selecting record by its MD5 hash.
"""
def __init__(self):
self.Name = "mydb.json"
... |
6598c3747d598b1c2d72efbee4bbe35a73231e28 | MWessels62/heat_map | /data.py | 6,045 | 3.625 | 4 | import urllib.request, urllib.parse, urllib.error
import requests
import pandas as pd
import dask.dataframe as dd
from bs4 import BeautifulSoup
#create data module, i might make this into a class though, and make use of inheritance to call functions within this
#this function takes in a country name and then w... |
6c01d290efd21c4d689c0c102398550d308dda30 | adesanyaaa/ThinkPython | /fermat.py | 941 | 4.46875 | 4 | """
Fermat's Last Theorem says that there are no positive integers a, b, and c such that
a^n=b^n=c^n
Write a function named check_fermat that takes four parameters-a, b, c
and n-and that checks to see if Fermat's
theorem holds. If n is greater than 2 and it turns out to be true
the program should print, "Holy smokes, F... |
32c8fe672f6a6127973b4b28a62ab056321249bf | adesanyaaa/ThinkPython | /lists10.py | 862 | 4.15625 | 4 | """
To check whether a word is in the word list, you could use the in operator, but it
would be slow because it searches through the words in order.
Because the words are in alphabetical order, we can speed things up with a bisection search (also
known as binary search), which is similar to what you do when you look a ... |
3f7e4990a911eabae25c224a4d9454f1196d4e4e | adesanyaaa/ThinkPython | /VolumeOfSphere.py | 300 | 4.375 | 4 | """ The volume of a sphere with radius r is (4/3)*pi*r^3
What is the volume of a sphere with the radius 5
Hint: 392.7 is wrong
"""
# For this we will be using the math.pi function in python
# first we need to import the math class
import math
r = 5
volume = (4 / 3) * math.pi * r ** 3
print(volume)
|
b53589d847129162c6f120c3f29ea41e54561246 | adesanyaaa/ThinkPython | /Test/countClean.py | 511 | 4.03125 | 4 | """
3. countclean:
Read words from test.txt and 'noise words' from
noise.txt. Print words from test.txt if it is not a noise word.
"""
noiseText = []
with open('noise.txt') as noise:
for lines in noise:
noiseText = noiseText + lines.split()
def main():
g = ""
with open('test.txt') as text:
... |
712e3c920965f9a21bedcdd7df712a7f79cd9dbd | adesanyaaa/ThinkPython | /dictionary2.py | 502 | 4.34375 | 4 | """
Dictionaries have a method called keys that returns the keys of the dictionary, in
no particular order, as a list.
Modify print_hist to print the keys and their values in alphabetical order.
"""
hist = {1: 2, 3: 4, 5: 6, 7: 8}
mydict = {'carl': 40,
'alan': 2,
'bob': 1,
'danny': 3}
d... |
88140b85b4cbc6075b2f18b09f12beb48eacc55a | adesanyaaa/ThinkPython | /store_anagrams.py | 1,116 | 4.1875 | 4 | """
Write a module that imports anagram_sets and provides two new functions: store_anagrams
should store the anagram dictionary in a "shelf;" read_anagrams should look up a word and return
a list of its anagrams.
"""
import shelve
import sys
from anagram_set import *
def store_anagrams(filename, ad):
"""Stores ... |
a6ae696b7ffe00652f7ef0d1c5ab8c4a7de0b474 | adesanyaaa/ThinkPython | /lists3.py | 570 | 4.21875 | 4 | """
Write a function that takes a list of numbers and returns the cumulative sum
that is, a new list where the ith element is the sum of the
first i + 1 elements from the original list. For
example, the cumulative sum of [1, 2, 3] is [1, 3, 6]
"""
def nested_sum():
a = int(input("Enter the number of Elements you ... |
481095e995d267d95df513b8deace98d3492090a | adesanyaaa/ThinkPython | /VariableAndValues.py | 849 | 4.6875 | 5 | """ Assume that we execute the following statements
width= 17
height=12.0
delimiter='.'
for each of the expressions below write down the expression and the type
1. width/2
2. width/2.0
3. height/3
4. 1+2*5
5. delimiter*5
"""
width = 17
height = 12.0
delimiter = '.'
# 1. Width /2 should give an integer value of 8.5-f... |
eabb94070c3ae9431d58e9ed3d3928ac2a39bffe | andrealmeidaa/ProgAmbRedes20201 | /Python/exemplos-basicos/ex02.py | 584 | 3.75 | 4 | import abc
class FiguraGeometrica(metaclass=abc.ABCMeta):
@abc.abstractclassmethod
def area(self):
pass
class Quadrado(FiguraGeometrica):
def __init__(self,lado):
self.lado=lado
def area(self):
return self.lado**2
class Retangulo(FiguraGeometrica):
def __init__(self,base,altu... |
a9a26e340dfc5a250e6631b692a3f90829c4a586 | vladgithub211/pythonlesson4 | /pythonlesson4/задача1.py | 291 | 3.5625 | 4 | a= int(input("Введите число месяцев="))
b= int(input("Введите сумму="))
proc= int(input("Введите процент"))
if a >=12:
n=b+b*(proc/100)
print("Твоя сумма", n)
else:
print("Деньги возвращены", b)
|
015d3567b69cba6808ab836c198da69219a5f652 | nuria/study | /advent/2022/advent3.py | 796 | 3.84375 | 4 | #!/usr/bin
import sys
import string
def main():
_file = sys.argv[1]
f = open (_file)
repeated = []
for l in f:
sack = l.strip()
c1 = set(sack[0:len(sack)/2])
c2 = set(sack[len(sack)/2:len(sack)])
item = c1.intersection(c2).pop()
# now find the characte... |
97914bc6f8c62c76aa02de1bd5c5f2a82e02e6db | nuria/study | /EPI/11_real_square_root.py | 748 | 4.1875 | 4 | #!usr/local/bin
import sys
import math
def inner_square_root(_max, _min, n):
tolerance = 0.05
middle = (_max - _min) *0.5
middle = _min + middle
print "max: {0}, min:{1}, middle:{2}".format(_max, _min, middle)
if abs(middle* middle -n) < tolerance:
return middle
elif middle * middle ... |
e5a1272ef945e40e1015499c400ff56f82188848 | nuria/study | /EPI/word_count.py | 1,340 | 3.609375 | 4 | #usr/local/bin/python
# coding: utf-8
"""
input: document = "Practice makes perfect. you'll only
get Perfect by practice. just practice!"
output: [ ["practice", "3"], ["perfect", "2"],
["makes", "1"], ["youll", "1"], ["only", "1"],
["get", "1"], ["by", "1"], ["just", "1"] ]
Re... |
f88b9f5332c2996a0c3a8f79bfc805b889b3b548 | nuria/study | /EPI/length_longest_subarray.py | 1,605 | 3.6875 | 4 | #!/usr/local/bin
# Find the length of the longest continuous strictly increasing subarray in an integer array
# with one change allowed
# not trivial
"""
Step 1: We first compute the longest increasing subarray ending at an index for every index in the given array. We store these values in l[].
Step 2: Then calculate ... |
a892fde3ae40e06cc8870db13958cdc5e098a6dc | nuria/study | /EPI/prefix_to_postfix.py | 1,078 | 4.0625 | 4 | #!usr/local/bin/python
import collections
"""
See https://www.geeksforgeeks.org/prefix-postfix-conversion/
prefix = *, +, A,B,-,C,D, -> operand op1 op2
postfix = A, B, +,C, D, -, *-> op1, op2 operand
"""
stack = collections.deque()
operator_set = ('+', '-', '*', '/')
def prefix_to_postfix(prefix):
# read t... |
b53a65441f96c18f0a1f7b46b31d9a875195e60f | nuria/study | /EPI/11_1_first_occurrence.py | 937 | 3.640625 | 4 | #/usr/bin
#search a sorted array for the 1st ocurrence of k
# and return its index
import sys
def main():
A = eval(sys.argv[1])
# target
t = eval(sys.argv[2])
# binary search but carrying the index?
top = len(A)
bottom = 0
while bottom < top:
m = bottom + (... |
a8605ec20d9b684325b7bfab7e24ef17ccfde092 | nuria/study | /EPI/17_gasup.py | 1,218 | 3.78125 | 4 | #!usr/local/bin/python
class Node:
def __init__(self, distance_next_city, distance_you_can_cover, _next = None):
self.distance_next_city = distance_next_city
self.distance_you_can_cover = distance_you_can_cover
self.next = _next
def find_ample(gas, distance_next_city):
print "distan... |
12cf675d18c06ce933d57aec995115415e2a2439 | nuria/study | /EPI/tmp_permutations.py | 786 | 4.03125 | 4 | # /usr/local/bin
# find all permutations of s within b
def find_perms(s, b):
import collections
# o(len(s)) time o(len(s)) space
c = collections.Counter(s)
# in order to be a permutation a string needs to have
# the configuration of 'c'
# in terms of keys and ocurrences
# we can walk t... |
c0e9fd0458365f8f2bbeba45214111c02f86eea4 | nuria/study | /advent/2022/advent7.py | 3,165 | 3.5625 | 4 | #!/usr/bin
import sys
import re as re
class node():
def __init__(self,name):
self.name = name
self.size = 0
self.children = []
self.parent = None
self.files = []
def set_size(self,size):
self.size = size
def add_file(self,file_size, file_name):
s... |
0e4d9a74c141fe8458e3f766e92b887955531772 | nuria/study | /algorithms2/week1/scheduling.py | 1,468 | 3.78125 | 4 |
# file with 1000 entries
# weight, length
# write algorithm that schedules jobs in decreasing order of (wi-li)
# to break ties, job with higher weight goes first
# report the sum of weighted completition times
import csv as csv
import heapq as hp
class Task(object):
def __init__(self, weight, length):
self.we... |
959499876a3866ac259557e5e2875cfbc2ddca31 | nuria/study | /algorithms2/week5/printSolutions.py | 2,388 | 3.59375 | 4 | # traveling salesman problem
# The first line indicates the number of cities. Each city is a point in the
# plane, and each subsequent line indicates the x- and y-coordinates of a
# single city.
# The distance between two cities is defined as the Euclidean distance
#import numpypy
import csv as csv
import math as ... |
8f2a5fc8965a001a7d051ed0e9cb28d901347a0f | nuria/study | /EPI/16_score.py | 1,295 | 3.875 | 4 | #!/usr/local/bin
# play , 2 points (safety)
# 3 points (field goal)
# 7 points (touchdown)
# four combinations of plays yield a score of 12
# [2,2,2,2,2,2]
# [2,2,2, 3,3]
# [2,3,7]
# [4,4,4]
# write aprogram that takes a final score for individual plays and returns the number
# of combinations of plays that result ... |
fd5abb56732e9ddf37f093fe007c6c848d414b44 | nuria/study | /misc/five-problems/problem3.py | 714 | 4.25 | 4 | #!/usr/local/bin/python
'''
Write a function that computes the list of the first 100 Fibonacci numbers. By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. As an example, here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13... |
e56f9d9ee01f2f4991b90e034038a65113eab84d | nuria/study | /EPI/8_5_max_api_queue.py | 1,654 | 3.9375 | 4 | #!/usr/local/bin
# implement a fifo queue with enque deque and max operations
# we can use a heap rather than a sorted list as an additional structure
#
import unittest
from collections import deque
class QMax():
def __init__(self):
# what is the data structure we are going to use?
# two fifo qu... |
056152c2b4e6a34599cc0fe5645511a3bc4b2fc4 | nuria/study | /advent/advent4.py | 787 | 3.609375 | 4 | #!/usr/local/bin
"""
It is a six-digit number.
The value is within the range given in your puzzle input.
Two adjacent digits are the same (like 22 in 122345).
Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679).
input = 145852-616942
"""
from collection... |
9713555fe7b5ce02facc03a99795174143d43585 | nuria/study | /EPI/text_justification.py | 3,105 | 3.796875 | 4 | #!/usr/local/bin
"""
Can you justify input text represented by an array of words so it looks pretty when printed and the whitespaces are balanced?
"""
import unittest
EMPTY =' '
k = 11
def right_justify_line(words):
# k is line length
global k # cause last char is reserved for line break
total_chars ... |
d929b25cb329d8a2c6589856e48e660c372b7aae | nuria/study | /crypto/xor.py | 1,748 | 4.46875 | 4 | #!/usr/local/bin/python
import sys
import bitstring
import virtualenv
# snipet given in coursera crypto course
# note xor of 11 and 001 will be 11, chops the last '1' at the longer string
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)... |
6be78b2e262e484d88238515381eb9ad2a62eab9 | nuria/study | /algorithms2/week4/plot.py | 1,036 | 3.75 | 4 |
# plot graph with networkx
# http://networkx.lanl.gov/tutorial/tutorial.html#graph-generators-and-graph-operations
import csv as csv;
import networkx as nx;
import matplotlib.pyplot as plt
#---------------------------- main program ---------------------
#f = open('./g3.txt','rb');
f = open('./testCase7.txt','rb');... |
16ff7aff5295ebfa65ab90ed749718e5d07d5f9d | nuria/study | /EPI/15_gcd.py | 307 | 4.03125 | 4 | #!usr/local/bin/python
def GCD(x,y):
# the idea is that if y> x
# the GCD of x and y is the GCD of x and y -x
if y == x:
return y
if y > x:
return GCD(x, y-x)
else:
return GCD(x-y, y)
if __name__=="__main__":
print GCD(100,10)
print GCD(17,31)
|
eb0dcf64a48aa365eb7d4f4df15c8a2378d4ac83 | nuria/study | /algorithms2/week2/clustering2.py | 4,885 | 4.125 | 4 |
#In this question your task is again to i
#run the clustering algorithm from lecture,
#but on a MUCH bigger graph.
#So big, in fact, that the distances (i.e., edge costs) are only defined implicitly, rather than being provided as an explicit list.
#The data set is here. The format is:
#[# of nodes] [# of bits for ea... |
f06d919d4e10a8043dfbd9ccf55802e5ee1bf396 | nuria/study | /EPI/trie.py | 3,421 | 4.25 | 4 | #usr/local/bin/pythonn
import string
import unittest
class Node:
def __init__(self, val=''):
self.val = val
# storage o(n) per node
# this will really be a dictionary later
self.children = {}
def is_leaf(self):
# a node with no children is a leaf
return len(self... |
352b8196d758694512da5c5105977cf6d4e76ce4 | nuria/study | /EPI/tmp_linked_list_flatten.py | 1,957 | 4.1875 | 4 | #!usr/local/bin
# define each node with two pointers
class llNode:
def __init__(self, value, _next = None, head = None):
self.value = value
# next node
self.next = _next
self.head = head
def __str__(self):
if self.value is None:
return 'None ->'
ret... |
7b9f6ba5aacf7efca41a7c6a5f44f5f73f8dc593 | nuria/study | /EPI/6_reverse_words.py | 986 | 3.96875 | 4 | #!/usr/bin
# reverse words in a sentence -> Hello world -> World Hello
import sys
import unittest
def main():
# array of words
def reverse(w):
pass
"""
Hello World
treating string like a list of chars
this once string is converted to a list i... |
cc3c31b09a402b7637ed05d98a01476620f26280 | nuria/study | /misc/five-problems/problem6.py | 1,726 | 4.25 | 4 | #!/usr/local/bin/python
import sys
def main():
'''
Given a sorted array and a target value, return the index
if the target is found. If not, return the index where
it would be if it were inserted in order. There won't be duplicate values in the array.
For example:
[1, 3, 5, 6] with target v... |
e943e0a5d431305080faa7ecdbfada2b56beeaf0 | nuria/study | /EPI/17_area.py | 1,255 | 3.890625 | 4 | #!usr/local/bin
rectangles = []
def area(A):
print A
# super duper tonto
global rectangles
# find max
tallest = max(A)
# how many tallest together there are?
# since we cannot sort we just have to walk the array
# o(n)
count = 0
max_count = 0
for i in range(0, len(A)):... |
220ab21698c31c080ff3a995aa03b78266051e24 | nuria/study | /EPI/16_traverse.py | 510 | 3.796875 | 4 | #!usr/local/bin
def traverse(n, m):
A = [[0]*(m) for _ in range(n) ]
# A[i][j]
# i = rows j columns
# n=rows and m=columns
for i in range(0, n):
for j in range(0, m):
if i == 0 :
A[i][j] = 1
if j == 0:
A[i][j] = 1
el... |
3964bbea06be54b37e419f43b02c0eefafaf7080 | nirajkumar27297/DataEngineering | /Python/Logical Programs/TicTacToe.py | 3,119 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 14:01:37 2020
@author: Niraj Kumar
Write a Program to play a Cross Game or Tic-Tac-Toe Game. Player 1
is the Computer and the Player 2 is the user. Player 1 take Random Cell that is
the Column and Row.
"""
import random;
def displayBoard(board):
for i in range(3):
... |
461460a9ab2875059815380e3aa5cc4cd36310c6 | nirajkumar27297/DataEngineering | /Python/Basic Python/LeapYearOrNot.py | 523 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 20:47:01 2020
@author: Niraj
Leap year or not
"""
try:
year = int(input("Enter the year "))
if ( len(str(year)) != 4 ):
raise Exception
#For a year to be a leap year,it should be divsible for 4 and not by 100 ar divisible for 400
if( (year % 4 =... |
564bf0cce8971b7336f2d2cc1d7a9a2d5ffc0418 | nirajkumar27297/DataEngineering | /Python/Object Oriented Programs/DeckOfCards.py | 2,199 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 00:45:43 2020
@author: Niraj Kumar
Initialize deck of cards having suit ("Clubs",
"Diamonds", "Hearts", "Spades") & Rank ("2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace"). Shuffle the cards using Random method and then
distribute 9 Cards to... |
16731153c76b627c3f8200f3cd021ba4c7e50cd9 | IAU-ADES/ADES-Master | /Python/bin/readxmlpy | 2,483 | 3.546875 | 4 | #!/usr/bin/env python
#
# readxml.py
#
# simple python script to demonstrate how to read xml
# files and walk though the elements and their children
# using the lxml library. The only slightly tricky
# thing is to remember to strip() the text to remove
# leading and trailing whitespace.
#
# as with all Python program... |
e37aeda0aa6f7d493dd27b2715d362a25138392a | maike-hilda/pythonLearning | /Ex2_5.py | 469 | 4.28125 | 4 | #Exercise 2.5
#Write a program that prompts the user for a Celsius temperature,
#convert the temperature to Fahrenheit, and print out the converted
#temperature
#Note: 0 deg C equals 32 deg F and 1 C increase equals 9/5 F increase
C = raw_input('Enter the current temperature in Degree Celcius:\n')
try:
C = f... |
767d08be4e912dd1824c4431dc5a4a047b53f805 | maike-hilda/pythonLearning | /Ex6_3.py | 326 | 4.21875 | 4 | #Exercise 6.3
#Write a function named count that accepts a string and a letter to
#be counted as an argument
def count(word, countLetter):
count = 0
for letter in word:
if letter == countLetter:
count = count + 1
print 'The letter', countLetter, 'appeared', count, 'times.'
... |
eee1982460684f6f36516e87a84434e2bfc2a5c7 | maike-hilda/pythonLearning | /Ex2_2.py | 173 | 3.9375 | 4 | #Exercise 2.2
#Write a program that uses raw_input to prompt a user for their
#name and then welcomes them.
name = raw_input('Enter your name:\n')
print 'Hello ' + name |
8b927cdecd6b849d899cda489974103815a5a6fb | kpahwani/DS-Algorithm | /data_structures/arrays/edit_distance.py | 778 | 3.59375 | 4 | def calculate_edit_distance(str1, str2):
n = len(str1)
m = len(str2)
matrix = [0]*(m+1)
for i in range(m+1):
matrix[i] = [0]*(n+1)
for i in range(m+1):
matrix[i][0] = i
matrix[0] = [i for i in range(n+1)]
for i in range(1, m+1):
for j in range(1, n+1):
... |
c22c5fd45a7c74096b96a0d4ec1aaa5badb679ce | kpahwani/DS-Algorithm | /data_structures/trees/level_order_traversal.py | 1,394 | 3.953125 | 4 | class Node:
def __init__(self, val):
self.right = None
self.data = val
self.left = None
class Tree:
def createNode(self, data):
return Node(data)
def traverse(self, root):
if root is not None:
self.traverse(root.left)
print(root.data, end=' ... |
8428716f8d9505ca72ed10bf6c7573d31c5603ba | kpahwani/DS-Algorithm | /data_structures/arrays/subset_sum.py | 641 | 3.53125 | 4 | # Subset Sum Problem
def recursive_implementation(arr, n, sum):
if sum == 0:
return True
if n == 0 and sum != 0:
return False
if sum < arr[n-1]:
return recursive_implementation(arr, n-1, sum)
return recursive_implementation(arr, n-1, sum) or recursive_implementation(arr, n-1, s... |
910474bb7c1dd3e2e70d7b24f2fb37f6b87fa164 | kpahwani/DS-Algorithm | /data_structures/trees/print_tree_in_vertical_order.py | 703 | 3.984375 | 4 | from trees.binary_tree import BinaryTree
def get_vertical_order(root, hd, mapping):
if not root:
return
if hd not in mapping:
mapping[hd] = []
mapping[hd].append(root.key)
get_vertical_order(root.left, hd-1, mapping)
get_vertical_order(root.right, hd+1, mapping)
def print_v... |
bc14903c3b2732af957a05937bb42ca77fab8e01 | woomurf/PythonStudy_2018 | /Algorithm/Level3/하노이의 탑.py | 254 | 3.78125 | 4 | def solution(n):
answer = []
def hanoi(a,b,c,n):
if n == 1:
answer.append([a,c])
else:
hanoi(a,c,b,n-1)
answer.append([a,c])
hanoi(b,a,c,n-1)
hanoi(1,2,3,n)
return answer
|
c362e44626893049bbf9753c7d46da60d4f07604 | fslaurafs/NanoCourses-FiapOn | /Python/Python/Cap3/Manipulação de Listas, Funções e Módulos/Ep01_listas.py | 410 | 4.125 | 4 | # Ep01 - INTRODUÇÃO: VARIÁVEIS E LISTAS
inventario = []
resposta = "S"
while resposta == "S":
inventario.append(input("Equipamento: "))
inventario.append(input("Valor: R$"))
inventario.append(input("Número Serial: "))
inventario.append(input("Departamento: "))
resposta = input("Digite ... |
479f2e7cea5d48e1552724906807e16469aa71ea | fslaurafs/NanoCourses-FiapOn | /Python/Python/Cap5/Manipulação de Arquivos e JSON/Ep06_arquivosIris.py | 294 | 3.546875 | 4 | # Ep06 - ARQUIVOS DE TERCEIROS! E AGORA?
basedados = []
with open("iris.data", "r") as arquivo:
for registro in arquivo.readlines():
basedados.append(registro.split(","))
print(basedados)
print(basedados[0][0])
print(float(basedados[0][0]) + float(basedados[0][1]))
|
fbda37076aa297d6d627f467a4d9a9c573c01a9d | fslaurafs/NanoCourses-FiapOn | /Python/Python/Cap2/Variáveis, Tomada de Decisão e Laços de Repetição/Ep01_variaveis.py | 857 | 4.1875 | 4 | # Ep01 - CONCEITUAÇÃO E TIPOS DE VARIÁVEIS
nome = input("Digite um funcionário: ")
empresa = input("Digite a instituição: ")
qtde_funcionarios = int(input("Digite a quantidade de funcionários: "))
mediaMensalidade = float(input("Digite a média da mensalidade: R$"))
print(nome + " trabalha na empresa " + empres... |
6f095a5fe94e3cf5749ca311cc42bdfc3e246e22 | gabrielfvale/python-sudoku | /board.py | 1,188 | 3.953125 | 4 | from util import getColors
def build(matrix: list, tips: list) -> str:
'''Builds the game board.
Retrives the game matrix and builds a
board that is easy for the end user to
understand.
Args:
matrix: The 9x9 game matrix.
tips: The list of tips on the board.
Returns:
A string containing the whole board... |
9b6daee27b4b2b2c286dd1bfe64dfd459f548dfe | HellRoads/python-2 | /Python_File/mathematics_black_2.py | 240 | 3.765625 | 4 | # -*- coding: utf-8 -*-
a = input("请输入两位数以上的整数: ")
s = a
while True:
f = a
if a == a[::-1]:
break
a = str(int(a)+int(a[::-1]))
print("%s + %s = %s" % (f,f[::-1],a))
print("%s 最后的回数是: %s" % (s,a)) |
de885c4c96ec164072e967ddccc2c2e3265c2407 | mounarajan/NLP | /01_Introduction.py | 2,578 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 1 00:00:00 2018
@author: Nikhil
"""
"""
NLTK - Natural Language Tool Kit.
$$ Introduction
Text-based communication has become one of the most common forms of expression.
We email, text message, tweet, and update our statuses on a daily basis. As a
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.