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 |
|---|---|---|---|---|---|---|
34f43bf294d27961b95985ae2b5f7faa15b74802 | 1170300523/code | /python/agriothm homework/Biscuit allocation.py | 453 | 3.53125 | 4 | # 贪心策略: 先满足贪婪因子小的孩子
def Biscuit_allocation():
k = 0
s = list(map(int, input("input s: ").split()))
f = list(map(int, input("input f: ").split()))
s = sorted(s)
f = sorted(f)
while len(s) and s[0]<f[-1]:
for j in f:
if j >= s[0]:
f.remove(j)
s.... |
daf53b3106c31636b177f41c936fba2e75e304e5 | MboyaDan/Number_guessing_game | /main.py | 2,942 | 3.890625 | 4 | from random import randint
import pywhatkit
from sys import exit
import datetime
# Generate random number ffrom 0-99
rand_num = randint(0, 99)
count = 10
# phone_number= input("Enter your phone number: ")
def recurr_func(guesses=[], num=[]):
# Declare count as global to change its value inside of this function
... |
eed1f9fdc9124c94c1654a5d52b6d53b2c40bab2 | afraenkel/project-euler | /python/prob023.py | 838 | 4.09375 | 4 | #!/usr/bin/env python
from __future__ import print_function
abundants = {}
def is_abundant(n):
'''returns a list of all divisors of a number n > 0'''
global abundants
try:
return abundants[n]
except KeyError:
ab = sum(x for x in range(1, n) if n % x == 0) > n
abundants[n] = ab
... |
3554dd9910e76d6ebca2d75787781cee2c17e77d | afraenkel/project-euler | /python/prob028.py | 1,022 | 3.578125 | 4 |
from __future__ import print_function
import itertools as it
def make_grid(N):
move_dict = [
lambda x,y: (x+1,y),
lambda x,y: (x,y-1),
lambda x,y: (x-1,y),
lambda x,y: (x,y+1)
]
loc = (0,0)
D = {loc: 0}
t = 1
step_dists = it.zip_longest(
... |
c7a5d62ff9c478f7430982313345c1f0adb82459 | kanatnadyrbekov/Ch1Part2-Task-31 | /task31.py | 470 | 4.28125 | 4 | # Напишите функцию которая подсчитает количество строк, слов и букв в текстовом
# файле.
text = """Hello my name is Kanat, and I study in Maker's course
mjdbvzjk zkjvasukz ksbvzu ubvu jbvab ajbvuzb """
string = text.count("\n")
print(f"Text has: {string + 1} string")
words = ' '
a = text.count(words)+1
print(f"Text has... |
158b7350e9ad0138b32882cc0f3e1cee08ddde6f | wakabayashiryo/Library | /python/Practice/function.py | 1,071 | 4.125 | 4 | #動物の最高速度を辞書型で定義
animal_speed_dict = {
"チーター":110,"トナカイ":80,
"シマウマ":60,"ライオン":58,
"キ リ ン":50,"ラ ク ダ":30,
}
#東京から各都市までの距離を辞書型で定義
distance_dict = {
"静 岡":183.7,
"名古屋":350.6,
"大 阪":507.5,
}
#時間を計算する関数を定義
def calc_time(dist,speed):
t = dist /speed
t = round(t,1)
return t
#動物の各都市までの時間を... |
35fa52e80f100cf25c6f301ff0efa36b015de541 | keirospl/json2xml | /json2xml/utils.py | 1,151 | 3.84375 | 4 | """Utils methods to convert XML data to dict from various sources"""
import sys
import json
import requests
def readfromjson(filename: str) -> dict:
"""
Reads a json string and emits json string
"""
try:
json_data = open(filename)
data = json.load(json_data)
json_data.close()
... |
3f7a6222951ca70884efadf7edc9b1b228420d66 | pawan12kamboj/python | /assignment5.py | 1,581 | 3.953125 | 4 | #decision and flow control ques 1
year=int(input("enter the year you want to check"))
if(year%4)==0:
if(year%100)==0:
if(year%400)==0:
print("{0} is a leap year ".format(year))
else:
print("{0} is not a leap year ".format(year))
else:
print("{0} is a leap year ".format(yea... |
a70776f76104a7303867525bcff4659aea34b171 | pawan12kamboj/python | /assignment4.py | 669 | 3.96875 | 4 | #question number-one
list1=[1,4,5,"pawan","preet","kaur"]
list1.reverse()
print(list1)
#question number-two
str="Hello World"
for i in str:
if i==i.upper():
print(i,end="",sep="")
#question number-three
list3=list(map(int,input("enter the elements:").split(",")))
print(*list3)
#question nu... |
0a27ddf38098a23ec20436c37b0615ba16e9cf19 | elgaridhomaulana/PythonFundamental-DS | /Class Python Fundamental/Day8(Exercise2).py | 1,405 | 4.0625 | 4 | def capitalize(string):
ganjil_besar = ''
genap_besar = ''
for i in range(len(string)):
if i % 2 == 0:
genap_besar += string[i].upper()
ganjil_besar += string[i]
else:
genap_besar += string[i]
ganjil_besar += string[i].upper()
print([genap_... |
eafc7405d86a0e97d7098ac152f5f30a6c7e1480 | elgaridhomaulana/PythonFundamental-DS | /Class Python Fundamental/Day10(Exercise4).py | 1,964 | 3.765625 | 4 | def numOfPairs(givenlist):
dictionary = {}
for element in givenlist:
if element in dictionary.keys():
dictionary[element] += 1
else:
dictionary[element] = 1
pairs = 0
for value in dictionary.values():
pairs += (value // 2)
print(pairs)
def numOfPairs... |
b423e0857a700249d3e134b98a4a0f86f1539b4f | elgaridhomaulana/PythonFundamental-DS | /Class Python Fundamental/Day1(Variable,Operator,Kondisi,Input).py | 1,887 | 3.859375 | 4 | # COMMENT '#'
# Variable adalah wadah untuk menyimpan suatu value
# TIPE DATA PRIMITIF
a = 'Elga' #string
b = 18 #integer
c = True #boolean
# TIPE DATA BUKAN PRIMITIF
d = 18.2 #float
e = [a, b, c, d] #list
f = {'nama': 'elga', 'alamat':'Bandung'} #dictionary
#OPERATOR MATEMATIKA
# + - * / %
angka1 = 15
angka2 = 3
a... |
aa65c8d6e8593508777b0ab0071d4e24f4fa858d | LewisRan/wang_yaran-newstudy | /2-OOP__WANGYARAN/黑马程序员案例-1.py | 1,689 | 4.09375 | 4 | class HouseItem():
def __init__(self, name, area):
self.name = name
self.area = area
def __str__(self):
return "[{}] 占地面积 {:.2f}".format(self.name, self.area)
class House():
# 需要外部传入的参数,才在函数中定义成形参,内部自己决定的参数不需要定义成形参,比如下面的剩余面积,家具名称
def __init__(self, house_type, area):
... |
49e2d580a846b11af73610812b3fe66f9eb584f2 | lewis00001/byui_CS241 | /week_9/check09b.py | 726 | 3.8125 | 4 | """
Author: Lewis Lockhart
Assignment: check09b.py
"""
class NegativeNumberError(Exception):
""" Raised when the value is negative. """
pass
def get_inverse(n):
""" """
if n == 0:
raise ZeroDivisionError
elif n < 0:
raise NegativeNumberError
return 1 / n
def main():
try... |
bc72eb8d9fe59495c8fecf8f349854bb34540137 | lewis00001/byui_CS241 | /week_11/asteroids_w11/asteroids_w11.py | 25,809 | 3.90625 | 4 | """
Author: Lewis Lockhart
Assignment: Asteroids
Extras Added:
1. Game Over Screen when ship is destroyed
2. Score Counter
3. 'Bring out your dead" Monty Python dialog in console when
dead bullets, alien ship, or asteroids are removed
4. Player Ship speed control (limits)
5. Background image
6. Arcade bug work aro... |
685f8aa8c39454eaf5db2bcdcf33e811344660b3 | lewis00001/byui_CS241 | /week_4/data_struct_04.py | 1,334 | 4.03125 | 4 | from collections import deque
class Song:
def __init__(self):
self.title = None
self.artist = None
def prompt(self):
self.title = input("Enter the title: ")
self.artist = input("Enter the artist: ")
print("")
def display(self):
print("Playing song:")
... |
45324af14928f8571f041489daae9ffa34cc70e5 | lewis00001/byui_CS241 | /week_12/pandasPract.py | 4,326 | 4.28125 | 4 | import matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('max_columns', 50)
# %matplotlib inline
# # http://www.gregreda.com/2013/10/26/intro-to-pandas-data-structures/
#
# """ Series """
# # create a Series with an arbitrary list
# print("---> basic output <---")
# s = pd... |
0099390c5071ff2dcede2affe9e39a495064882f | lewis00001/byui_CS241 | /week_2/assign02b.py | 823 | 3.828125 | 4 | # Lewis Lockhart :: CS-241
def get_file_name():
# gets the file name from the user
file_name = input("Enter file: ")
return file_name
def process_file_data():
# opens the file in read mode
file = open(get_file_name(), "r")
# result vars
line_count = 0
word_count = 0
# loops over ... |
894bd719d8a9cb2df54bef49f26677dadf6e8aa6 | Jkize/LearnPython | /clase.py | 825 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 13 12:16:01 2019
@author: Jhoan Saavedra
"""
Colores=['Azul','Rojo','Verde']
class Carro:
nPuertas=2
nLlantas=3
def __init__(self,nVentanas=5,color=None):
if not isinstance(nVentanas,int):
raise ValueError('Ventanas debe ser un entero')
... |
aeb170d8004a8e6968695db65a0403ed0cb36d69 | umerzia-7001/Web_Scraping_guide | /main.py | 2,053 | 3.765625 | 4 |
# importing required libraries for web scraping
import requests
import nltk
from bs4 import BeautifulSoup
import requests
import lxml
from nltk import *
import pandas as pd
## For this example, we are going scrape Flipkart website to extract the Price, Name, and Rating of Laptops.
products=[] #List to store name of... |
c60a7a82555ba569d58dec50d0ad5065f460d343 | mhgharieb/MILP_Division_Property | /algorithm1-greedyAlgorithm-for-differential/sbox.py | 3,072 | 3.625 | 4 |
class Sbox:
def __init__(self, sbox):
self.sbox = sbox
self.SBOXSIZE = self.SboxSize()
def SboxSize(self):
"""
This function is used to calculate the size of a given sbox
"""
s = format(len(self.sbox), "b")
num_of_1_in_the_binary_experission_of_the_len_of_sbox = s.count("1")
assert num_of_1_in_the_... |
2093742f4c669964c4fe43dcc6cccd75fb4dc0c8 | eastc5/advent_of_code_2017 | /day_3.py | 1,270 | 3.765625 | 4 | def get_number_of_steps(number):
number_list = [x for x in range(number+1) if x % 2 == 1]
for i,value in enumerate(number_list):
if number <= (value)**2:
return i
def get_number_of_jumps(number):
if number == 1:
return 0
ring_number = get_number_of_steps(number)
ring_l... |
fb3fa6692e71667160681e4ad9945f9962aa9d0d | aborda38/python_begginner | /07_list_comprehensions.py | 383 | 3.890625 | 4 | #Write one line of Python that takes this list a
#and makes a new list that has only the even
#elements of this list in it.
import random
def run():
a = random.sample(range(1, 300), 13)
# a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
c=[i for i in a if i % 2 == 0]; print("Random list -->", a); print("List ... |
4b001eba9aeb3de5451e881f88f400fed5625275 | sixou/Four_in_a_Row | /game.py | 7,829 | 3.765625 | 4 | import copy
import alphaBetaPruning
VICTORY=10**20 #The value of a winning board (for max)
LOSS = -VICTORY #The value of a losing board (for max)
TIE=0 #The value of a tie
SIZE=4 #the length of winning seq.
COMPUTER=SIZE+1 #Marks the computer's cells on the board
HUMAN=1 #Marks the human's cells on the boar... |
d3974643c6a099e32abe5fba2baa9041f93bc1dd | JSAbrahams/mamba | /tests/resource/valid/control_flow/while_check.py | 148 | 3.640625 | 4 | b: bool = False
e: str = "Hello world"
while b:
print(b)
d: bool = True
while d:
print(d and False)
print(d and True)
print("hello")
|
4e2d71bf573a5debf496a0c6f3b08440bd67eabb | JSAbrahams/mamba | /tests/resource/valid/class/multiple_parent_check.py | 294 | 3.625 | 4 | class MyType:
def __init__(self, a: str):
self.a = a
class MyType2:
def __init__(self, b: str):
self.b = b
class MyClass1(MyType, MyType2):
other: int = None
def __init__(self):
MyType.__init__(self, "asdf")
MyType2.__init__(self, "qwerty")
|
95b549c39072f6cc6ad2cab9602f9522ff012079 | tamanna-c/Python-Internship | /Day2.py | 1,490 | 4.25 | 4 | #Task-1
"""print("Hello World")"""
''' This is an example of multiline comment'''
""" This is also an example of multiline comment"""
#Task-2
"""
a=10
b=20.5
c="Tamanna"
print(a)
print("Value of b is:",b)
print("My name is",c)"""
#Task-3
"""name="Tamanna"
print("Name is:",name)
#assigning a new va... |
87c54cf94840160380305cc8d78f48f0bf251372 | pythonthings/doublyLinkedLists | /driver.py | 271 | 3.703125 | 4 | from DoublyLists import Lists
def main():
list = Lists()
list.push(6)
list.push(3)
list.push(3)
list.push(3)
list.push(3)
list.insert_after(list.head.next,55)
list.append(100)
list.print_list()
if __name__ == '__main__':
main()
|
47d6f4bc56b2d14ea098e3eec54d70e0f1dcb8ad | seysn/aoc2016 | /06/day6.py | 597 | 3.828125 | 4 | from collections import Counter
test = '''
eedadn
drvtee
eandsr
raavrd
atevrs
tsrnev
sdttsa
rasrtv
nssdts
ntnada
svetve
tesnvt
vntsnd
vrdear
dvrsen
enarar
'''.strip()
def combine_chars(text, most_common = True):
res = ""
for line in zip(*(text.split())):
c = Counter(line)
res += c.most_common(... |
e1bb5191d4c7ac28abe9aa94eee06345e2db837a | robophilosopher/bddb | /tests/file_scan_test.py | 652 | 3.578125 | 4 | # From project root run:
# python -m unittest tests/file_scan_test.py
import unittest
from iterators.file_scan import FileScan
class TestFileScan(unittest.TestCase):
def test_scan(self):
fs = FileScan('movie_test_data.csv')
test_result = []
row1 = ['1', 'Toy Story (1995)', 'Adventure|Ani... |
60309353144de8e6b78b1b74cc4e3dfbc24ca758 | kidonrage/FESTU_Web | /PR_11/2.py | 6,333 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import math
# 29. Известно значение угла a в градусах (0 < a < 360). Определить значение того же угла в радианах, учитывая, что 180 градусов = pi радианов
def getRadiansFrom(degrees):
return math.radians(degrees)
print(getRadiansFrom(180))
# 47. Известны два числа. Вывести порядковый номе... |
6df7df02b1654a6f8a83e8ff4d3bbcd9950200f0 | achandru/Python | /udemyexa.py | 276 | 3.796875 | 4 | """emails = ['me@gmail.com','you@yahoo.com','yes@gmail.com']
for item in emails:
if 'gmail' in item:
print(item)"""
"""for i in (1,2,3):
print(i+1)"""
"""a="Tricky"
for i in a[:3]:
print(i)"""
lst=["Terribly Tricky"]
for word in lst:
for letter in word[-6:]:
print(letter) |
39af3c0fb91db6938ef0072d41ecfab44484802b | achandru/Python | /sam.py | 6,406 | 4 | 4 | # github.com/www.programiz.com/coderbyte.com/Youtube
print ('Hello Chand')
#-----------------------------------------------------------------
a = 3
b = 4
print (a + b)
#-----------------------------------------------------------------
#IF else program
a=1 #variable declaration
if a==1:
print"Correct"
e... |
3384654a7af693def67cb635d6535fd4538ba281 | achandru/Python | /examp.py | 222 | 4.09375 | 4 | input_num = input("\nEnter a Number:")
a,b,c = 0,0,1
if input_num == 1:
print "The Number is 0"
else:
fib = 1
while fib < input_num:
a = b + c
b = c
c = a
fib = fib + 1
print "The Number is : "+str(a)
|
bb35b35b879fd7328141ea839a0bcd7c1a969572 | Ewenwan/Kaggle | /Advanced/1.2Tanic_passenger_Feature_filter.py | 4,510 | 3.671875 | 4 | #-*- coding:utf-8 -*-
#!/usr/bin/python
'''
泰坦尼克号 数据 特征筛选
'''
# 导入pandas用于数据分析
import pandas as pd
# 利用pandas的read_csv模块直接从互联网收集泰坦尼克号乘客数据
# titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
# titanic.to_csv('raw_titanic.csv')
titanic = pd.read_csv('../Basic/2_supervised_Clas... |
95a64047500f2e84db52015836ef9cefa9f27267 | Risksany78/Sanjeet_Python | /First_Lastchar.py | 98 | 3.671875 | 4 | string=eval(input("Enter a String"))
x=string[0:2:1]
y=string[-1:-3:-1]
z=y[::-1]
print(x+z)
|
4632426e3d409d0ee2a055eb59f507604d994ba4 | princyalex/princ | /ponoz.py | 104 | 3.984375 | 4 | a=int(input("Enter a no"))
if(a>0):
print("Positive")
elif(a==0):
print("Zero")
else:
print("Negative")
|
cc3bf1286904124d585b7ea992970f67e7731253 | stellakaniaru/practice_solutions | /list_copy.py | 161 | 3.609375 | 4 | '''
Write a program that clones or copies a list.
'''
#function definition
def clone(list1):
#initialize a new list from the original one
return list(list1)
|
047638de234a37c895d55b1aa6f571f72d2c9f4c | stellakaniaru/practice_solutions | /learn-python-the-hard-way/ex16.py | 877 | 4.3125 | 4 | '''Reading and writing files'''
from sys import argv
script, filename = argv
print "We're going to erase %r."%filename
print "If you don't want that, hit CTRL-C(^C)."
print "If you don't want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
#when you open the file in writ... |
cf1285088904c04298b3f07d06cfc30722ca636a | stellakaniaru/practice_solutions | /learn-python-the-hard-way/ex19.py | 1,035 | 3.90625 | 4 | '''Functions and Variables.'''
'''there different ways to pass values to the
function:can be math,variables, straight numbers or a combination.
'''
#define a function
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" %cheese_count
print "You have %d boxes of crackers!" %boxes_of... |
e670461879bb35a19b25ef3b8ca5364d2fd3c007 | stellakaniaru/practice_solutions | /dict_learn.py | 266 | 4.15625 | 4 | '''
A program that iterates through dict items and prints them out.
'''
classmates = {'Mary :' : ' Sweet but talks too much',
'stella :' : ' cool,calm and collected',
'Mark :' : ' code ninja on the block'}
for k, v in classmates.items():
print(k + v)
|
649f1c1d37c723c67be32d50c5c48cbddce4ea56 | stellakaniaru/practice_solutions | /string_repeat_function.py | 268 | 4.0625 | 4 | '''
Create a function that takes in two parameters where one is
a string and the other is the number of times which the string
should be repeated.
'''
def string_repeat(x, y):
if type(x) == str:
return x * y
else:
return 'First parameter should be a string!'
|
b1025eb52f8c374fecd1458fe6e151f38eb8ec1a | stellakaniaru/practice_solutions | /overlapping.py | 500 | 4.1875 | 4 | '''
Define a function that takes in two lists and returns True
if they have one member in common.False if otherwise.
Use two nested for loops.
'''
#function definition
def overlapping(list1, list2):
#loop through items in first list
for i in list1:
#loop through items in second list
for j in list2:
#check... |
5b49cf35ea8a0c178691c729f4275a93519be37c | stellakaniaru/practice_solutions | /learn-python-the-hard-way/ex7.py | 849 | 4.40625 | 4 | '''more printing'''
#prints out a statement
print 'Mary had a little lamb.'
#prints out a statement with a string
print 'Its fleece was as white as %s.'%'snow'
#prints out a statement
print 'And everywhere that Mary went.'
print '.' * 10 #prints a line of ten dots to form a break
#assigns variables with a characte... |
053d3a417ab0f05a201f9999917babd870869561 | stellakaniaru/practice_solutions | /years.py | 664 | 4.25 | 4 | '''
Create a program that asks the user to enter their name and
age. Print out a message addressed to them that tells them
the year they will turn 100 years old.
'''
from datetime import date
#ask for user input on name and age
name = input('Enter your name: ')
age = int(input('Enter your age: '))
num = int(input('... |
f96e2b9362b83e7f832054a5c0c4eada550406e4 | stellakaniaru/practice_solutions | /char_freq_func.py | 563 | 4.09375 | 4 | '''
Write a function char_freq() that takes a string and
builds a frequency listing of the characters contained in
it. Represent the frequency listing as a python dictionary.
Try it with something like char_freq('abbabcbdabdbdbababababcbcbcbab')
'''
#class Counter(__builtin__.dict)
#Dict subclass for counting hasha... |
1f42e53223e2ec4d0ce3f185cf5e4919985e0f0c | stellakaniaru/practice_solutions | /max_three.py | 364 | 4.3125 | 4 | '''
Define a function that takes in three numbers as
arguments and returns the largest of them.
'''
#function definition
def max_of_three(x,y,z):
#check if x if the largest
if x > y and x > z:
return x
#check if y is the largest
elif y > x and y > z:
return y
#if the first two conditions arent met,z becom... |
2cc767c5f8dfd6cf5303c33271880fab42c24d22 | sourcery-ai-bot/UBB-Y1-S2-GRAPH | /Lab1/vertex.py | 1,438 | 3.5625 | 4 | from __future__ import annotations
from typing import Optional
from edge import Edge, EdgeIteratorDirection, EdgeIterator
class Vertex:
"""
Class that defines a Vertex
"""
first_in: Optional[Edge] # First Edge in the list that arrives to this vertex
first_out: Optional[Edge] # First Edge in t... |
489ef4d24383e996e684213959478ad64b6b73c2 | rokeshragav/python-coding | /findlargestno.py | 251 | 4.0625 | 4 | a,b,c = (input("Enter first number: "))
# = (input("Enter second number: "))
#c = (input("Enter third number: "))
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
print("The largest number is",largest)
|
db13251097081677d2ec242811804f5f36d37792 | berkgedik92/mastermind_solver | /mastermind.py | 8,193 | 3.84375 | 4 | import random
import copy
import itertools
import sys
class Mastermind:
def __init__(self, color_names, code_length, possibilities_for_code=list()):
self.number_of_colors = len(color_names)
self.code_length = code_length
self.color_names = color_names
self.current_prediction = ["" ... |
5ed2e6eda8c3987c97165452fe9688a773c558f3 | mitchellsayer/alea | /alea/discrete/randvar.py | 5,843 | 4.09375 | 4 | from ..randvar import RandVar
import itertools
import copy
class DiscreteRandVar(RandVar):
'''
A discrete random variable is a strict classification of random
variables. It fits either one of these two criteria:
1. Has a well-defined probability mass function and corresponding
sample spac... |
018a08b6cc48d47cfd8ebb53a572d50403c1bb47 | saisreegowdacheruvu/Final_DE_project | /com/pg/utils/aws_utils.py | 4,143 | 3.546875 | 4 | # function to read all necessary info from mysql and return a dataframe
def read_from_mysql(spark, src_config, conf_secret_dir):
jdbc_params = {"url": get_mysql_jdbc_url(conf_secret_dir),
"lowerBound": "1",
"upperBound": "100",
"dbtable": src_config["mysql_co... |
d3b3b842686d62d102ef89dfdffb0fefdc834343 | prabhatpal77/Adv-python-oops | /refvar.py | 475 | 4.1875 | 4 | # Through the reference variable we can put the data into the object, we can get the data from the object
# and we can call the methods on the object.
# We can creste a number of objects for a class. Two different object of a same class or different classes
# does not contain same address.
class Test:
"""sample cla... |
80d0dafe8c5f6604e94c34dca7d6aeefc9acbf9b | prabhatpal77/Adv-python-oops | /abstraction4.py | 543 | 4.125 | 4 | # We can access the hidden properties of a super class within the subclass through special syntax.
class X:
__a=1000
def __init__(self):
self.__b=2000
def __m1(self):
print("in m1 of x")
class Y(X):
__c=3000
def __init__(self):
self.__d=4000
super().__init__()
def... |
3d26c22fc04be9a94814cb340213327f8dd7fdd8 | prabhatpal77/Adv-python-oops | /isarelationship3.py | 198 | 3.6875 | 4 | class X:
def __init__(self):
print(" in constructor of x")
def m1(self):
print("in m1 of x")
class Y(X):
def m2(self):
print("in m2 of y")
y1=Y()
y1.m1()
y1.m2()
|
77ef27d2dbfa8c29d27cc55b8235fba4d256705e | prabhatpal77/Adv-python-oops | /docstring.py | 539 | 3.53125 | 4 | # Documentation String:- Documentation string of a class is used to provide description about the class.
# Within the class syntax documentation string is optional but it is highly recommended to define documentation
# string with in the class syntax. We can access documentation string of a class by, "__doc__" default ... |
930d77afc8eab4724dafad344e6fd968b837d3d8 | teruto725/atcoder | /162/162a.py | 109 | 3.640625 | 4 | s=input()
for i in range(len(s)):
if s[i] =="7":
print("Yes")
break
else:
print("No") |
a562274b519094c246dd1f53a06e760f19958982 | teruto725/atcoder | /152/152a.py | 143 | 3.703125 | 4 | x,y = map(int,input().split())
if y > x:
for i in range(y):
print(x, end="")
else:
for i in range(x):
print(y, end="") |
67f3d2d8af3cb173886b20459bbc1d62eebdeaa0 | teruto725/atcoder | /146/146d.py | 220 | 3.84375 | 4 | import math
a,b,x = map(float,input().split())
bottom = (x/(a*a))/b * a * 2.0
if bottom <= a:
print(math.degrees(math.atan2(b,bottom)))
else :
high = (b - (x/(a*a)))*2
print(math.degrees(math.atan2(high,a)))
|
bdb3a622e69b26bb7fabd3f00e2fdd9c4581bd5d | teruto725/atcoder | /145/145a.py | 102 | 3.703125 | 4 | s=input()
if len(s) % 2 == 0 and s[:len(s)/2] == s[len(s)/2:]:
print("Yes")
else:
print("No")
|
eda1b61e7cf5cada031b51d591bf68b379bba831 | teruto725/atcoder | /Mitubishi/Mituia.py | 522 | 3.53125 | 4 | x=int(input())
items = [100,101,102,103,104,105]
list = [1]
if x == 100 or x == 101 or x == 102 or x == 103 or x == 104 or x == 105:
print(1)
elif x <100:
print(0)
else:
for i in range(99):
list.append(0)
for i in range(6):
list.append(1)
for i in range(94):
list.append(0)
... |
62dde4331e40af8d31e62b4c715d7c2e5e0a438a | teruto725/atcoder | /145/145b.py | 122 | 3.546875 | 4 | n=input()
s=input()
if len(s) % 2 == 0 and s[:int(len(s)/2)] == s[int(len(s)/2):]:
print("Yes")
else:
print("No")
|
b3bc2c1c417feb568096f49dfecb9de5ec063988 | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/ArgsAndKwargs/args_kwargs.py | 1,610 | 3.90625 | 4 | # *args and **kwargs
# *args
#def func_with_args(*args):
# print(args)
#func_with_args(1, 2, 3)
#def ten_percent_of_product(x, y, z):
# return (x * y * z) * 0.1
#print(ten_percent_of_product(10, 20, 7, 2))
#def ten_percent_of_product_with_args(*args):
# product = 1
# for number in args:
# product ... |
7228bbbadce87aab955d344b396d8583fd27a833 | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/AdvancedModules/collections_default_dict.py | 219 | 3.6875 | 4 | from collections import defaultdict
#my_dict = defaultdict(lambda : 1)
#my_dict[1] = 'a'
#my_dict = {1: 'a'}
#print((my_dict[2]))
s = 'Hello'
d = defaultdict(int)
for k in s:
d[k] += 1
print(sorted(d.items()))
|
11798eae8c0b637e250a4b6bba0ca08dc0b47b16 | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/BuiltInModules/built_in_modules.py | 298 | 3.65625 | 4 | #import random
#x = random.randint(1, 10)
#print(x)
from random import randint
x = randint(1, 10)
print(x)
#from random import shuffle
#my_list = [1, 2, 3]
#shuffle(my_list)
#print(my_list)
from random import shuffle as shuffle_my_list
my_list = [1, 2, 3]
shuffle_my_list(my_list)
print(my_list) |
607f3daf4e5a638a13a10bc5ac356f4be723b5a8 | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/WrapsDecorator/wraps_decorator.py | 683 | 3.96875 | 4 | from functools import wraps
def print_function_data(function):
'''
This is decorator function
:param function:
:return:
'''
@wraps(function)
def wrapper(*args, **kwargs):
print(f"You are using {function.__name__}")
print(f"Function documentation {function.__doc__}")
... |
d44590a99b9fb3e3cc011c8747624ae4bd1accfa | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/AdvancedModules/collections_nametuple.py | 548 | 3.828125 | 4 | from collections import namedtuple
#jake = ('Jake', 'Smith', 19, 'male')
#jim = ('Jim', 'Blade', 23, 'male')
#jane = ('Jane', 'Morrison', 20, 'female')
Person = namedtuple("Person", "name surname age gender")
jake = Person(name='Jake', surname='Smith', age=19, gender='male')
jim = Person(name='Jim', surname='Blade', ... |
61cc995462a5c55564d0b803ba8bad9e39e9423d | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/csv_reader.py | 1,109 | 3.9375 | 4 | import csv
#with open('cars.csv') as file:
# csv_reader = csv.reader(file)
# next(csv_reader)
# for car in csv_reader:
#print(car)
# print(f'{car[1]} {car[2]} costs {car[4]}')
# for car in csv_reader:
#print(car)
# print(f'{car[1]} {car[2]} costs {car[4]}')
#with open('cars.csv') as file:
# csv_reader = csv.re... |
69996ed2547992a8a7b8eb86e554740f0ac3647b | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/TryExcept/else_finaly.py | 855 | 4.34375 | 4 | # If we have an error - except block fires and else block doesn't fire
# If we haven't an error - else block fires and except block doesn't fire
# Finally block fires anyway
#while True:
# try:
# number = int(input('Enter some number'))
# print(number / 2)
#except:
# print('You have to ent... |
b7c8c1f93678be20578422e02e01adeba36041f9 | Ballan9/CP1404-pracs | /Prac01/asciiTable.py | 420 | 4.25 | 4 | LOWER = 33
UPPER = 127
print("Enter a character:")
character = input()
print("The ASCII code for g is", ord(character))
number = int(input("Enter a number between {} and {}:".format(LOWER,UPPER)))
if number < LOWER or number > UPPER:
print("Invalid number entered")
else:
print("The Character for {} is ".format... |
fcb99b5af722f0e73daf056b9b0e15db40389cea | krutijan1/freecodecamp | /scientific_computing_with_python/scientific_computing_with_python_projects/arithmetic_formatter/arithmetic_arranger.py | 2,102 | 3.609375 | 4 | def dump_line(result, array, add_line_end=True):
for elm in array:
result += elm
result += ' '
result = result.rstrip()
if add_line_end is True:
result+= '\n'
return result
def check_int(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
... |
ba70492a7d7bb7cd40f6e8d067bebb86c03c9153 | Hinojosa129502/Beginning- | /test_17.py | 363 | 3.921875 | 4 | #Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
#Suppose the following input is supplied to the program:
#9
#Then, the output should be:
#11106
numInp = input('Enter a number: ')
numInp = int(numInp)
numTrc = numInp
count = 0
for x in range(4):
count += numInp
nu... |
af72de49b1725bd5a62e099b66ae3ba35f3dda02 | Hinojosa129502/Beginning- | /test_15.py | 434 | 3.90625 | 4 | #Write a program that accepts a sentence and calculate the number of letters and digits.
#Suppose the following input is supplied to the program:
#hello world! 123
#Then, the output should be:
#LETTERS 10
#DIGITS 3
wordInp = input('Input a sentence: ')
numCt = 0
alpCt = 0
for x in wordInp:
if x.isdigit() == True:... |
4ae031dffeb9caed0229ca7238692637a248cd7d | BALaka-18/IEM_Coding-5th-Semester | /B_126_Day3.py | 1,030 | 3.515625 | 4 | # Each question is attached here. 1 is uncommented, the rest two are commented out.
# 1
def longEven(s):
l = list(filter(lambda x: len(x)%2 == 0, s.split()))
word,m = l[0],len(l[0])
for w in l[1:]:
if len(w) > m:
m = len(w)
word = w
else:
continue
ret... |
da2de13dd881e711913866ef47551b01c293b28d | the-py/the | /test/test_the_matchers.py | 3,726 | 3.53125 | 4 | import unittest
from the import *
class TestTheMatchers(unittest.TestCase):
def setUp(self):
self.eq = self.assertEqual
self.neq = self.assertNotEqual
self.true = self.assertTrue
self.false = self.assertFalse
self.r = self.assertRaises
def test_equal(self):
sel... |
2f04e0fafbdfe3e16f05eb711240770f09488b3a | pbhadani-chwy/AllState-Insurance | /Input_file/Main_file.py.py | 3,250 | 3.59375 | 4 | # rows = []
# # number of rows in the file
# datapath="sqlfile.txt"
# with open(datapath) as file:
#
# rows=file.readlines()
#
# #
# # #Dividing the dataset into single rows of string
# my_data=[] # is the List of List
# for singlerow in rows:
# columns=singlerow.split(" ") # I have taken the rows as a string... |
82b1b76a67d899523d77c2ee9d6fdea0812cbd67 | catherinelee274/Girls-Who-Code-2016 | /Python Projects/fahrenheittocelsius.py | 356 | 4.28125 | 4 | degree = input("Convert to Fahrenheit or celsius? For fahrenheit type 'f', for celsius type 'c'")
value = input("Insert temperature value: ")
value =int(value)
if degree == "c":
value = value-32
value = value/1.8
print(value)
elif degree == "f":
value = value*1.8 + 32
print(value)
else:... |
8ee13771e508a57d3b6d8a957803bee7c72cb414 | kononeddiesto/Skillbox-work | /Module29/05_singleton/main.py | 645 | 3.828125 | 4 | import functools
def singleton(cls):
"""Декоратор класса. Превращает класс в синглтон (может иметь только один инстанс) """
@functools.wraps(cls)
def wrapper_singleton(*args, **kwargs):
if not wrapper_singleton.instance:
wrapper_singleton.instance = cls(*args, **kwargs)
return... |
c1fe77512584b1241b0dcfdaf27d0d9178ad0a68 | kononeddiesto/Skillbox-work | /Module22/08_frequency_analysis/main.py | 545 | 3.609375 | 4 | text = open('text.txt', 'r').read().lower()
words_dict = {}
num = 0
for i_word in text:
if ord('a') <= ord(i_word) <= ord('z'):
get_word = words_dict.get(i_word, 0)
words_dict[i_word] = get_word + 1
num += 1
words_list = [(index, '{:.3f}'.format(words_dict[index] / num)) for index in words_d... |
7a809dd5a5d30923f583d100e79a6389bc417ccd | kononeddiesto/Skillbox-work | /Module18/12_message/main.py | 1,035 | 3.8125 | 4 | def revers(word):
reverse_word = word[-1::-1]
return reverse_word
def symbol(next_word):
new_text = ''
new_text2 = ''
for i in next_word:
if i not in ".,:;!_*-+()/#¤%&)":
new_text += i
elif i in ".,:;!_*-+()/#¤%&)" and new_text.isalpha():
new_text2 = revers(... |
0a28ac59730057977d660f30be55804e83184c0a | kononeddiesto/Skillbox-work | /Module22/06_paranoia/main.py | 962 | 3.84375 | 4 | def caesar_cipher(string, user_shift):
char_list = [(alphabet[(alphabet.index(sym) + user_shift) % 26] if sym != ' ' else ' ') for sym in string]
new_str = ''
for i_char in char_list:
new_str += i_char
return new_str
alphabet = ' abcdefghijklmnopqrstuvwxyz'
new_file = open('text.txt', 'w')
fo... |
b6a22ff5b295a1b6afb93cf297a51be5a6d7766c | kononeddiesto/Skillbox-work | /Module16/10_simmetrical_seq/main.py | 852 | 3.859375 | 4 | def palindrome(num_list):
revers_list = []
for i_num in range(len(num_list) - 1, -1, -1):
revers_list.append(num_list[i_num])
if num_list == revers_list:
return True
else:
return False
nums = int(input('Кол-во чисел: '))
all_num = []
new_num = []
answer = []
for _ in range(num... |
ee4a9ad6fa32ce86d3e05f4bb31f51bd53e75d25 | kononeddiesto/Skillbox-work | /Module26/01_num_squares/main.py | 638 | 3.65625 | 4 | from collections.abc import Iterable
num = int(input('Введите число: '))
class Iterator:
def __init__(self, sym: int) -> None:
self.counter = 0
self.sym = sym
def __iter__(self) -> Iterable[int]:
return self
def __next__(self) -> Iterable[int]:
if self.counter < self.sym... |
13073076659ca339c3fc5883175b9d906f3da3bc | kononeddiesto/Skillbox-work | /Module24/04_fathers_mothers_kids/main.py | 2,017 | 3.953125 | 4 | class Parents:
def __init__(self, name, age):
self.name = name
self.age = age
self.childs = []
def info(self):
all_children = [i_name.name for i_name in self.childs]
print('Имя родителя {}, возраст родителя {}, список детей {}'.format(
self.name, self.age, a... |
77a30e9dc9d474a27928153ebef45acfccfcbbfa | kononeddiesto/Skillbox-work | /Module20/07_sort_function/main.py | 306 | 4.25 | 4 | def sort(some_tuple):
for i_int in some_tuple:
if type(i_int) != int:
return some_tuple
elif type(i_int) == int and i_int == some_tuple[-1]:
new_tuple = sorted(list(some_tuple))
return tuple(new_tuple)
my_tuple = (4, 3, 2, 1)
print(sort(my_tuple))
|
359859acc6314a10385d32d320257be7881b3a58 | kononeddiesto/Skillbox-work | /Module18/01_restaurant_menu/main.py | 190 | 3.59375 | 4 | menu = input('Доступное меню: ').title().split(';')
print('На данный момент в меню есть: {0}, {1}, {2}, {3}'.format(menu[0], menu[1], menu[2], menu[3]))
|
7e387bdc0c92b06ed654fbf111b0ba51703117d5 | kononeddiesto/Skillbox-work | /Module19/08_guess_number/main.py | 942 | 3.8125 | 4 | import random
max_num = int(input('Введите максимальное число: '))
num = int(random.randint(1, max_num))
answer = set()
while answer != 'Помогите!':
first_answer = input('Нужное число есть среди вот этих чисел?: ')
if first_answer == 'Помогите!':
print('Артём мог загадать следующие числа: {0}'.format(... |
b2a293e3a4b70d46473c03a43ded1996257eee03 | kononeddiesto/Skillbox-work | /Module27/02_slowdown/main.py | 587 | 3.515625 | 4 | import time
from typing import Callable
def decorator(func: Callable) -> Callable:
"""
Декоратор, ожидание в 2 секунды
:param func:
:return:
"""
def wrapped() -> None:
start = time.time()
time.sleep(2)
result = func()
end = time.time()
timing = round(en... |
012a89adea300114d6d06b0a1035e5d2149e79aa | kononeddiesto/Skillbox-work | /Module15/06_word_analysis/main.py | 249 | 3.734375 | 4 | text = input('Введите слово: ')
unique_letters = []
for i in list(text):
if i in unique_letters:
continue
else:
unique_letters.append(i)
print('Кол-во уникальных букв: ', len(unique_letters))
|
c42c463b4cc15dce457eb07ff2338d8e9c52c391 | kononeddiesto/Skillbox-work | /Module18/13_anagram/main.py | 384 | 4.125 | 4 | first_word = list(input('Введите 1 слово:'))
second_word = input('Введите 2 слово:')
for i in second_word:
if i in first_word:
first_word.remove(i)
if not first_word:
print('Слова являются анаграммами друг друга')
else:
print('Слова не являются анаграммами друг друга')
|
a50b0e7d869474b39397366427b78d9584883a64 | kononeddiesto/Skillbox-work | /Module16/09_friends/main.py | 589 | 3.578125 | 4 | friends = int(input('Кол-во друзей: '))
debt = int(input('Долговых расписок: '))
ious = [[0, 0]]
for _ in range(friends - 1):
ious.append([0, 0])
for i_debt in range(debt):
print(i_debt + 1, 'расписка')
who = int(input('Кому: '))
from_whom = int(input('От кого: '))
how = int(input('Сколько: '))
... |
a37cb53f8afc5ca945f6ecfd8e1149b067220449 | ernestoalarcon/competitiveprogramming | /SuperReducedString.py | 663 | 3.78125 | 4 | # Solution for https://www.hackerrank.com/challenges/reduced-string
import sys
def reduce_string(val):
'''reduce_string documentation'''
result = []
i = 0
while i < len(val) - 1:
if val[i] != val[i + 1]:
result.append(val[i])
i += 1
else:
i += 2
... |
7b8dfc5b2187b7dd16d82ebda10d676fa6f8db1b | ernestoalarcon/competitiveprogramming | /ip-address-validation.py | 873 | 3.6875 | 4 | #!/bin/python
# Solution for https://www.hackerrank.com/challenges/ip-address-validation
import re
def is_ipv4(val):
v4_pattern = r'\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b'
match = re.search(v4_pattern, val)
if match:
for v in (int(x) for x in match.groups()):
if not (0 <= v <= ... |
7a0cd64eb505d50648310c7c586f6b27ffecd7c2 | ernestoalarcon/competitiveprogramming | /game-of-thrones.py | 498 | 3.984375 | 4 | #!/bin/python
# Solution for https://www.hackerrank.com/challenges/game-of-thrones
string = raw_input().strip()
def can_be_palindrome(data):
odd_requencies = 0
for l in set(data):
current_frequency = data.count(l)
if current_frequency % 2:
odd_requencies += 1
if... |
c73af6f52c05cdeaddb85d0609aa6d5dd5ad0e9b | nhu2/text-mining | /Assignment 2/Markov _text_synthesis.py | 1,017 | 3.8125 | 4 | import numpy as np
walden = open('Assignment 2/Walden.txt', encoding='utf8').read()
#Split text file into single words (keeping all the punctuation)
corpus = walden.split()
def make_pairs(corpus):
'''
Return all the pairs of words in the Walden.
'''
for i in range(len(corpus)-1):
yield (corpu... |
3775cb6c2e02e1b142b14ef88f2cadd57fd47d3e | blakerbuchanan/algos_and_data_structures | /datastructures/datastructures/queues.py | 697 | 4.1875 | 4 | # Impelement a queue in Python
# Makes use of the list data structure inherent to Python
class Queue:
def __init__(self):
self.Q = []
def remove(self):
try:
self.Q.pop(0)
except:
print("Error: queue is empty.")
def add(self, item):
self.Q.append(ite... |
f2a24021bc1c5b8f4a86e6a8df65aa6221b086a7 | blakerbuchanan/algos_and_data_structures | /algorithms/bfs.py | 1,916 | 3.984375 | 4 | # Implement a breadth-first search algorithm for tree or graph search
# This implementation will utilize adjacency lists (probably in the form of a Dictionary)
from datastructures import graphs
def breadthFirstSearch(G, root):
Q = [] # Let Q be a queue in the form of a list (lists are slow due to pop operations)... |
531147cb9b4edba05c652a0b79ba4ef7609aeb07 | bombthanthap/SKILL_63 | /week1/corner.py | 105 | 3.671875 | 4 | N = int(input(''))
last = N%10
while(N>=10):
N/=10
first = int(N)
print (str(first)+str(last))
|
654af8adb13deead28d17f1bdb40902ad5760732 | bombthanthap/SKILL_63 | /week4/robots.py | 1,481 | 3.59375 | 4 |
order = input()
#arr = []
Rb = 'N'
for i in order:
if(i == 'N'):
if(Rb == 'N'):
Rb = 'N'
elif(Rb == 'E'):
print('RRR',end="")
#arr.append('RRR')
elif(Rb == 'S'):
print('RR',end="")
#arr.append('RR')
elif(R... |
5d07df4ca26d34f207d90111c26f2993561d9938 | GiwrgosN/FourRussiansAlgorithm | /FourRussians.py | 11,235 | 3.671875 | 4 | """
This module is an implementation of the Four Russians Algorithm for
matrix multiplication and complementary graph.
One of the main requirements was to implement this algorith without
using any external libraries (use only built in libraries).
Algorithm Description:
The main idea of the method is to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.