blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6ba28e19c47d6893cf37f71828da58edebf56d79 | smfriedman/undergrad-courses | /multi-agent systems/final_project/code/my_bot4.py | 7,265 | 3.65625 | 4 | import random
import other_bots
import traders
import run_experiments
import plot_simulation
import numpy
import math
class MyBot(traders.Trader):
name = 'my_bot'
def simulation_params(self, timesteps,
possible_jump_locations,
single_jump_probability):
... |
07ce1d5137aef88d2be6511d735f7474a2c40395 | harshildarji/Python-HackerRank | /Built-Ins/Athlete Sort.py | 296 | 3.609375 | 4 | # Athlete Sort
# https://www.hackerrank.com/challenges/python-sort-sort/problem
n, m = map(int, input().split())
details = []
for _ in range(n):
details.append(list(map(int, input().split()))[:m])
k = int(input().strip())
for i in sorted(details, key = lambda x: x[k]): print(*i, sep = ' ')
|
1a390671c34421e1ea191148fed476108fe7ee22 | harshildarji/Python-HackerRank | /Itertools/Compress the String!.py | 246 | 3.875 | 4 | # Compress the String!
# https://www.hackerrank.com/challenges/compress-the-string/problem
from itertools import groupby
data = input()
groups = []
for key, value in groupby(data):
groups.append((len(list(value)), int(key)))
print(*groups)
|
a0d3f0f2ea50e5f404bc02a921f7322c76894649 | harshildarji/Python-HackerRank | /Basic Data Types/Second Largest Number.py | 212 | 3.796875 | 4 | # Find the Second Largest Number
# https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem
n = int(input().strip())
a = set([int(i) for i in input().split()][:n])
print(sorted(a)[-2])
|
6a319576cbb3084b5a2ca0b93c24323af853a2fe | harshildarji/Python-HackerRank | /Strings/Merge the Tools.py | 285 | 3.765625 | 4 | # Merge the Tools!
# https://www.hackerrank.com/challenges/merge-the-tools/problem
s = [i for i in input()]
n = int(input().strip())
for i in range(0, len(s), n):
string = s[i:i+n]
word = ""
for w in string:
if w not in word:
word += w
print(word)
|
d898348a8f52aa55f35613b035ec6ce947bf7d80 | harshildarji/Python-HackerRank | /Collections/Piling Up!.py | 677 | 3.546875 | 4 | # Piling Up!
# https://www.hackerrank.com/challenges/piling-up/problem
r = []
for _ in range(int(input().strip())):
n = int(input().strip())
l = list(map(int, input().split()))[:n]
left, right = 0, n - 1
top = -1
failed = False
while right - left > 0 and failed == False:
if l[left... |
e6fc2ca1a9b1daeed30e57161f9e5b53e4642c7e | harshildarji/Python-HackerRank | /Errors and Exceptions Challenges/Exceptions.py | 360 | 3.53125 | 4 | # Exceptions
# https://www.hackerrank.com/challenges/exceptions/problem
r = []
for _ in range(int(input().strip())):
try:
a, b = map(int, input().split())
r.append(a//b)
except ZeroDivisionError as e:
r.append('Error Code: ' + str(e))
except ValueError as e:
r.append('Error ... |
ed904badf7a4fdcf1610ced88bcd15adfdf89a02 | harshildarji/Python-HackerRank | /Strings/Find a string.py | 265 | 3.90625 | 4 | # Find a string
# https://www.hackerrank.com/challenges/find-a-string/problem
string = input().strip()
substring = input().strip()
count = 0
for i in range(0, len(string)):
if string[i:i + len(substring)] == substring:
count += 1
print(count)
|
9c7c447cc0fcd053eb097674402173425feaac63 | harshildarji/Python-HackerRank | /Python Functionals/Map and Lambda Function.py | 229 | 3.703125 | 4 | # Map and Lambda Function
# https://www.hackerrank.com/challenges/map-and-lambda-expression/problem
fib = lambda y: y if y < 2 else fib(y - 1) + fib(y - 2)
print(list(map(lambda x: x**3, map(fib, range(int(input().strip()))))))
|
c5001da9f5f226a7111b8cd72b8a060d5b7494d6 | aayush2601/Assignment | /1.py | 145 | 3.5625 | 4 | text = list()
filename = 'text.txt'
with open (filename) as fin:
for line in fin:
text.append(line.strip())
print(text)
|
333bbd25226d2e513cb3de79f2181037520359c4 | Liuzehui1995/teresa | /exercise_code/define_function.py | 1,548 | 4.40625 | 4 | # defining functions
# Use keyword def
# e.g. function to compute Fibonacci series upto n, returned as a list
# (stops when next value would be >= n)
def fib(n): # compute Fibonacci
a, b = 0, 1 # seriesupton
series = []
while b < n:
series.append(b)
a, b = b, a + b
return series
# ... |
6326ab9b379348302aa86d54b874727eff91ed56 | ssd2192/Python | /Calculate Total Bill.py | 2,537 | 4 | 4 | #This program calculate the total price
#This program uses funtions and while condition and if condition
#the main function
def main():
endProgram, endOrder, totalBurger, totalFry, totalSoda, total, tax, subtotal, option, burgerCount, fryCount, sodaCount = declareVariable()
while endProgram == 'no':
e... |
56ffc26da86a2e9ffa9191f3ed4405084b96d324 | ssd2192/Python | /How to use function.py | 1,156 | 4.15625 | 4 | """This program demonstrate how to use variables and functions"""
#This program uses funtions and variables
#the main function
def main():
print('Welcome tho the tip calculator program')
print() #Print a blank statement
mealprice=input_meal()
tip = calc_tip(mealprice)
tax = calc_tax(mealprice)
... |
0a9c9f90d0fb4aa1bc343289dafdf6fda189076e | ssd2192/Python | /forNested.py | 222 | 3.96875 | 4 | def multTable():
maxNum = int(input("Enter Max Number: "))
for row in range(1,maxNum+1):
print()
for col in range(1,maxNum+1):
print(format(row*col,'5d'), ' ')
multTable()
|
1a45534ce08dcdcab7e939d098b7e8944f0a5d23 | J-woooo/Coala_Univ | /Week3/review_homework1.py | 705 | 3.578125 | 4 | # Bing에서 코알라를 검색하고 나오는 뉴스 타이틀과 요약기사를 수집하기
import requests
from bs4 import BeautifulSoup
for page in range(1,8,3):
raw = requests.get("https://www.bing.com/news/search?q=%EC%BD%94%EC%95%8C%EB%9D%BC&qs=n&form=QBNT&sp=-1&pq=%EC%BD%94%EC%95%8C%EB%9D%BC&sc=8-3&sk=&cvid=B6AFF8D626B44942BEB23110B8D6DE72"+str(page))
h... |
1a1ec1a4e35c7ee63edf06b56bfc148c73e7e3eb | oskarblo02/parprogramering | /edabit_challenges.py | 237 | 4.09375 | 4 | def rem_vowel(string):
vowels = ('a', 'e', 'o', 'å', 'i', 'y', 'ä', 'ö', 'u')
for x in string.lower():
if x in vowels:
string = string.replace(x, "")
print(string)
string = "hejsan grabbar"
rem_vowel(string) |
94610a9fccce54e34623363d2943a64ca5f699c4 | Saifullahshaikh/LAB-04 | /program 6.py | 340 | 3.921875 | 4 | print('saifullah 18B-092-CS')
print('Lab 4, Program 6')
row_num = int(input("Input number of rows:"))
col_num = int(input("Input number of columns:"))
multi_list = [[0 for col in range(col_num)] for row in range(row_num)]
for row in range(row_num):
for col in range(col_num):
multi_list[row][col]=row*col
... |
8917a09cd6618bb311da6fcf04da3ff2ed579b5d | Saifullahshaikh/LAB-04 | /program 5.py | 317 | 3.984375 | 4 | print('saifullah 18B-092-CS')
print('Lab 4, Program 5')
initial_value = eval(input('Enter the initial value for the range:'))
final_value = eval(input('Enter the final valuefor the range:'))
numbers = range(initial_value,final_value)
sum = 0
for value in numbers:
sum = sum+value
print('The sum is',sum)
|
d33f804d03cc9f7bc379748739f543284f3c7cf9 | Saifullahshaikh/LAB-04 | /Exercise/Ex.3.py | 287 | 4.0625 | 4 | print('saifullah- 1bB-092-CS A')
print('Lab-04, P.Ex.3')
print('palindrome or not')
word = 'CIVIC'
word = word.casefold()
rev = reversed(word)
if list(word) == list(rev):
print('Yes your string is palindrome')
else:
print('Sorry your string is not palindrome')
|
e14730dba3f725434590c9d337362c81a331d905 | nikilselvam/riseclassrooms | /bin/testKeyword.py | 1,033 | 3.921875 | 4 | import string
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
import re
##notes: 1. reduce words to its root form 2. implement if loops if noun is not present
# text=input('Type in your question: ')
#punc. + sep multiple sent.
def pre_filter(sentence):
sentence = sentence.lowe... |
27668e65e748934a491affc3905b68fb982484e9 | adambemski/TDD_Meetup | /main.py | 277 | 4.09375 | 4 |
def check_year_leap(year):
# check type
if type(year) is int:
if ((year % 4) == 0) and (((year % 100) != 0) or ((year % 400) == 0)):
result = True
else:
result = False
else:
result = "Wrong Input"
return result
|
acd3b96bb1d757134d9bb542ea4387980612ab72 | gauravsb/neural-models-with-attention-nlp | /experiments.py | 4,619 | 3.515625 | 4 | import random
from pprint import pprint
line = ""
output = ""
'''
with open('range-1-25.txt', 'w') as test_file:
for x in range(2000):
line = ""
for j in range(10):
line += str(random.randint(1, 25))
if j != 9:
line += " "
#print(line)
#line.r... |
4ed11552b97c5deea488398241ec55831a0a29d1 | Stephen-Njoroge/CP1_Room_Allocation | /app/amity.py | 15,824 | 3.609375 | 4 | import random
from app.rooms import OfficeSpace
from app.rooms import LivingSpace
from app.people import Staff
from app.people import Fellow
from termcolor import cprint, colored
class Amity(object):
def __init__(self):
self.all_people = []
self.staff_list = []
self.fellows_list = []
... |
af7f2c94aa7be08dcab4bf1bcf9643dcd72c89c3 | infinixaco/WAY-TO-PLACEMENT | /covering_segments.py | 755 | 3.65625 | 4 | # Uses python3
import sys
from collections import namedtuple
def optimal_points(n,segments):
points = []
i = 0
flag = [True] * n
while i < n-1:
if flag[i]:
points.append(segments[i][1])
j = i+1
while j < n:
if flag[j]:
if segments[i][1] in range(segments[j][0], segments[j][1... |
a45ba0fbfe9cb5b3dae0982f092504b72e6d278c | kirbalbek/mipt_3sem_contest_pyth | /4cont_task1.py | 441 | 3.75 | 4 | '''
Выяснить, является ли заданное число простым.
Формат входных данных
На вход подается натуральное число.
Формат выходных данных
Вывести 1 - число простое, 0 - число составное.
'''
num = int(input())
flag = int(1)
for i in range (2, num//2+1):
if num%i==0:
flag = int(0)
print(flag)
|
719b433c1a63d7cf88c14f43ebe11cef6464d68f | kirbalbek/mipt_3sem_contest_pyth | /2cont_task1.py | 105 | 3.671875 | 4 | N = int(input())
if (N%4 == 0 and not N%100 == 0) or N%400 == 0:
print("YES")
else:
print("NO")
|
37cf6b9e9945bb418b3f4e85e6a92e78d510027f | sarahcstringer/skills-assessment-2 | /skills-oo/classes.py | 4,703 | 4.3125 | 4 | class Student(object):
def __init__(self, first_name, last_name, address):
"""Initialize object with first name, last name, address"""
self.first_name = first_name
self.last_name = last_name
self.address = address
class Question(object):
def __init__(self, question, correct_a... |
2654d0ccf37cd899de1cda3a45772e22df47d891 | xueery/Python.practice | /Set.py | 642 | 4 | 4 | #集合可以使用两种方式进行定义
#一种使用{,,,}
#一种使用set函数来定义
A={"python","hhh"}
print(A)
B={"py123",1,2,3,4,5}
print(B)
#A交B
C=A&B
print(C)
#A并B
C=A|B
print(C)
#A减去B
C=A-B
print(C)
#A与B的交集的补集
C=A^B
print(C)
#A集合是否包含B集合
C=A>=B
print(C)
A.add(5)
print(A)
#删除集合B中的元素1,如果不存在,则不删除
B.discard(1)
print(B)
#随机删除集合B中的一个元素,更新S,如果集合B为空,则抛出异常
B.pop()
p... |
5cb6697548dbaef69e862c3d8ec495dd0d12ad90 | jafranswa/web-caesar | /caesar.py | 1,345 | 4.125 | 4 | from helpers import alphabet_position, rotate_character
def rotate_string(text, rot):
encrypted_str = ''
for l in text:
rotated = rotate_character(l,rot)
encrypted_str = encrypted_str + rotated
return encrypted_str
def main():
text = input('Type a message: ')
rot = input('Rotate b... |
504a29f646b79111a08804a73f3db51f2fb96e42 | zhugaocen/python | /test/day2/demo2.py | 506 | 4.0625 | 4 | name="hello oldamy"
# print(name[1])
# print(name[11])
# print(name[:])
# print(name[::2])
# print(name[::3])
# print(name[1::2])
# print(len(name))
# print(name[::-1]) #ymadlo olleh 逆向输出
# print(name[::-2])
# name= 'jack'
# age=23
# # print('%s的年龄是%d'%(name,age))
# print('{}的年龄是{}'.format(name,age))
# print('{1}的... |
68dbca2b12cff2e5203eb9918b422113dee3561e | zhugaocen/python | /test/day9/demo1.py | 918 | 3.6875 | 4 | class PanCake():
def __init__(self):
self.cookedString = '生的'
self.cookedLevel = 0
self.zuoliao = []
def __str__(self):
return "煎饼的状态:{},烤了的时间:{},作料是:{}".format(
self.cookedString, self.cookedLevel, self.zuoliao)
def cook(self, cooked_time):
self.cookedL... |
b1751b7b496ad7b09fb6b43d43d5e8875671f0dc | zhugaocen/python | /test/day4/demo1.py | 676 | 3.84375 | 4 | # i = 1
# while i <= 5:
# print("hello amy")
# i += 1 # 计数器
'''
求1~100之间的和
'''
# n = 1
# num_sum = 0
# while n <= 100 :
# # num_sum = num_sum + n
# num_sum += n
# print(n)
# n += 1
# if n == 8:
# break #退出循环
# # continue #退出当前循环,进入下次循环
# else:
# #else是指条件为false的时候执行... |
db7d8d6000ee2d55d10ad1707f5c77e4df07316e | zhugaocen/python | /test/day1/demo2.py | 1,571 | 4.40625 | 4 | # print(3*3)
# print(3**3) #3*3^2
#print(10/3) #二进制的有穷性
# print(9/3) #float 3.0
# print(10//3) #取整
# print(10.0//3)
#print(-10//3) #向下取整
# print(10%3) #1 10//3 3 10-9=1
# print(-10%3) #2 -10//3 -4 -10-(-12)=2
# print(0.1+0.1+0.1-0.3) #科学及算法 转为二进制
# from decimal import Decimal
# import decimal
# decima... |
332d9c5f41d3ba6085eb52dbcf9269c9c26dc2a9 | helanan/bangazon-05-aggregation | /employee.py | 516 | 3.5625 | 4 |
# NEW METHODS:
# Add an employee to the set.
# The employee parameter accepts an existing instance of an employee.
add_employee(self, employee)
# Removes an employee from the set.
# The employee parameter accepts an existing instance of an employee.
remove_employee(self, employee)
# Returns the set of employees.
ge... |
a21b679b2dad9cc1573458d3082880818b0487fe | factorsofx/SuperTribble | /bridge.py | 768 | 3.71875 | 4 | from math import atan2
class TrussNode(object):
def __init__(self, x, y, anchor):
self.x = x
self.y = y
self.anchor = anchor
self.beams = set()
def __str__(self):
return "TrussNode({}, {}, {})".format(self.x, self.y, self.anchor)
class TrussBeam(object):
def __... |
82596b42ac9b3369958e5156c095b668eab3d7ee | h-rathee851/Weather_Station | /submission 4/weather.py | 3,231 | 3.53125 | 4 | import urllib.request
import time
import numpy as np
import pylab
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import datetime
from webiopi.devices.sensor.onewiretemp import DS18S20
"""""""""""
Assign the Temperature sensor
"""""""""
tmp0 = DS18S20(slave="10-000802de680d")
""""""""""
Functi... |
b8414c8d500de7d9aedd5a7f491ff7df0918f995 | ashwinlokkur/blackjack | /deck.py | 1,074 | 3.578125 | 4 | import random
import itertools
from card import Card
class Deck:
__suits = ("Diamonds", "Spades", "Clubs", "Hearts")
__ranks = (2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace")
__values = {2:2, 3:3, 4:4, 5:5, 6:6, 7:7,8:8, 9:9, 10:10, "Jack":10, "Queen":10, "King":10, "Ace":11}
__cards = []
... |
77472fe75b4741179552cd380b1f6c1b51b02e66 | abs51295/Python-Summer-School | /OOPS/CODE/9_properties.py | 427 | 3.90625 | 4 | import math
class Circle:
def __init__(self, radius):
self.radius = radius
# Some additional properties of Circles
@property
def area(self):
return math.pi * self.radius ** 2
@property
def perimeter(self):
return 2 * math.pi * self.radius
c = Circle... |
ede5cc3cd75e714a96c9181aa8a597b075ed6aa5 | shanawas1112/hacker-rank | /If_else.py | 201 | 3.921875 | 4 | n=int(input())
if n%2==1:
print("weird")
elif n%2==0 and (n>=2 and n<5):
print("not weird")
elif n%2==0 and (n>=6 and n<=20):
print(" weird")
elif n%2==0 and (n>20):
print("not weird")
|
52534cfc3058d58c80db000c2946537a020630e8 | Szacsi5622/odd-_-numbers | /3_feladat.py | 2,024 | 3.578125 | 4 | import random
class Card:
COLOURS = ('Hearts', 'Clubs', 'Spades', 'Diamonds')
VALUES = ('none', 'Ace','2','3','4','5','6','7','8','9','10', 'Jack','Queen','King')
def __init__(self, colours = 0, values = 0 ):
self.colours = colours
self.values = values
def __str__(self):
return '{0} {1}'.format(Car... |
856ec8765a1cb9c9d979167347a8070f9e988cd1 | rodolfoams/projeto-atal-unifacisa | /experiencia/solucao.py | 637 | 3.953125 | 4 | from typing import List, Tuple
def melhor_experiencia(L: int, C: List[Tuple[str, int, int]]) -> List[str]:
"""Função que determina qual escolha de pratos, dentro dos descritos no
cardápio C, resulta na melhor experiência gastronômica possível, respeitando
o limite de valor L.
Parâmetros
---------... |
6f1e51d50ba8813f479b6ae5ffc7ed92c3655771 | SergioVenicio/POO | /chapter_4/Point/point.py | 615 | 4.0625 | 4 | class TwoDimensionalPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def toString(self):
return (f"""\
I'm a 3 dimensional point.
My x coordinate is: {self.x}
My y coordinate is: {self.y}""")
class ThreeDimensionalPoint(TwoDimensionalPoint):
... |
7e80ab9bc2b1a6ec7224826b97eeed3e4dc8ebb6 | drutauvlad/PEP20G04 | /first.py | 1,991 | 3.984375 | 4 | print(True < 2)
print(True + False + 1)
myvar1 = [1,2]
myvar2 = [3]
print(myvar1 + myvar2)
print(dir(myvar1))
print(dir(3))
sumlist = myvar1 + myvar2
# print(sumlist - 3)
print(bin(10))
print(True & True)
print(True & False)
print(10 & 10)
print(11 | 9)
print(11 >> 2)
print(11 << 1)
print(~ 11)
pri... |
1037cea99bfa68f031cdb3236aceeafaa4735cbf | delowarsikder/pythonCoding | /randomNumber.py | 180 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 00:33:14 2020
@author: DelowaR
"""
import random
for i in range(5):
print(random.randint(1,9))
# print(random.choice(3))
|
be891a539f02293edbc454836de5b52b581fca44 | delowarsikder/pythonCoding | /TablePrint.py | 615 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 20 00:02:31 2020
@author: DelowaR
"""
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(data):
maxLen=-1
for i in range(len(data)):
for j in range(len(data[i])... |
9c0dadda45d38ab9d34b17730e3d33b30e59684f | delowarsikder/pythonCoding | /guessGame.py | 777 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 01:27:20 2020
@author: DelowaR
"""
import random
#import sys
secret_number=random.randint(1,20)
print('I am thinking a number between 1 and 20.')
#while True:
#Ask the player to guess 6 time
for guessTaken in range(1,7):
print('Take a guess .')
i = int(input())... |
342c7f1340f327128fa91c7fb1489008993e2b8a | andresfvb/python | /roman-numerals/roman_numerals.py | 939 | 3.75 | 4 | number_roman = {
1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M', 10000: '-'
}
def roman(number):
if number == 0:
return ''
denominators = [1000, 100, 10, 1]
for denominator in denominators:
if number >= denominator:
biggie, smalls = number // d... |
9f7f23230a46a53393ba6a38081bc816dd73d3dc | cosmicTabulator/python_code | /mpDisplacment.py | 746 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 28 22:08:11 2016
@author: Graham Cooke
"""
import matplotlib.pyplot as pyt
import random
pt = [(-1,0), (1,0)]
def displace(points, d):
newPoints = []
for x in range(len(points)-1):
newPoints.append(points[x])
rand = random.uniform(-d,d... |
5ceaa92f72e31eacb819cf669fe8eb580a882019 | cosmicTabulator/python_code | /9-19-16.py | 377 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 19 15:41:02 2016
@author: Graham Cooke
"""
print("Let's begin")
length = 11
width = 27
area = length * width
perimeter = 2 * (length + width)
print("If a rectangle has length:", length)
print("and width:", width)
print("Then it will have area:", area)
print("It will ... |
7955eb0b0d7367f4ecbaf82e9134d77ee8bac4f1 | Xiuyu-Li/images-preprocessing-kit | /imgtools/rename.py | 1,235 | 3.96875 | 4 | # -*- coding:utf-8 -*-
import os
import sys
def renameImg(fileDir):
"""Rename the images to target names"""
filelist = os.listdir(fileDir)
total_num = len(filelist)
i = 0 # Order of the images to be renamed
for item in filelist:
src = os.path.join(os.path.abspath(fileDir), item)
... |
84bde05884b6992a6264a6bb9d79974f9a999aad | Emuniz11/future-ready | /pythonBasics2/classExample.py | 1,505 | 4.0625 | 4 | # Uses Pascal naming convention
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print('move')
def draw(self):
print('draw')
# point1 = Point()
# point1.x = 10
# point1.y = 20
# print(point1.x)
# point1.draw()
# point1.move()
#
# point2 = Point... |
30df9872a74b3f94936c5074fdce5cd1fa2997f8 | DanielSank/advent-of-code | /2018/day9/python/marbles.py | 2,616 | 3.9375 | 4 | import itertools
class Node:
"""A single node in a linked list."""
def __init__(self, value, back=None, forward=None):
self.value = value
self.back = back
self.forward = forward
def insert_after(self, node):
temp = self.forward
self.forward = node
node.bac... |
0d101ecf5d68d3ef0d9027eee4ce153b9d4c594d | Ccepero/Craps | /crapsGame.py | 1,156 | 3.71875 | 4 | #! /usr/bin/env python
__author__ = 'Cindalis Cepero'
from die import *
class Craps(object):
def __init__(self):
self.die1 = Die()
self.die2 = Die()
self.firstRoll = True
self.lastRoll = 0
def __str__(self):
return("Die1: {0} Die2: {1}".format(self.die1.ge... |
ab5c388344fcb8819cba45c40139fa7c13f3b110 | Sibiryak82/MarkLutzLearningPython2. | /metaclass3.py | 691 | 3.71875 | 4 | # Файл metaclass3.py
# Простая функция тоже может служить в качестве метакласса
def MetaFunc(classname, supers, classdict):
print('In MetaFunc: ', classname, supers, classdict, sep='\n...')
return type(classname, supers, classdict)
class Eggs:
pass
print('making class')
class Spam(Eggs, meta... |
e1c4b346bae9e203e459f2755ac01549834d9e57 | Sibiryak82/MarkLutzLearningPython2. | /person.py | 5,229 | 4.1875 | 4 | # Файл person.py (начало)
class Person: # Начало класса
def __init__(self, name, job, pay):
self.name = name
self.job = job
self.pay = pay
# Добавление стандартных значений для аргументов конструктора
class Person:
def __init__(self, name, job=None, pay=0):
self.nam... |
d68f6554d4355fde41c737f1f2b82d9fa11bd5a2 | Sibiryak82/MarkLutzLearningPython2. | /multiset.py | 1,722 | 3.625 | 4 | # Файл multiset.py
from setwrapper import Set
class MultiSet(Set):
"""
Насдедует все имена Set, но расширяет intersect и union для поддержки
множества операндов;
обратите внимание, что self - по-прежнему первый аргумент (теперь хранящийся
в *args);
кроме того, унаследованные операции & и | здесь в... |
c2626e8f10b3a34a540145dde20be23ea28c6dd0 | Sibiryak82/MarkLutzLearningPython2. | /validate_descriptors1.py | 2,687 | 3.96875 | 4 | # Файл validate_descriptors1.py использование разделяемого состояния экземпляра дескриптора
class CardHolder(object): # В Python 2.X требуется (object)
acctlen = 8 # Данные класса
retireage = 59.5
def __init__(self, acct, name, age,... |
91310f1355902e8768ee9423cf5b52fcb463bb36 | Sibiryak82/MarkLutzLearningPython2. | /desc-person.py | 1,384 | 3.796875 | 4 | # Файл desc-person.py
class Name:
"name descriptor docs" # Документация по свойству name
def __get__(self, instance, owner):
print('fetch...') # извлечение
return instance._name
def __set__(self, instance, value):
print('change...') ... |
4dd8c7a7a2f4e0a4d64a979eba4c3c054646e47b | Sibiryak82/MarkLutzLearningPython2. | /lunch.py | 1,840 | 3.859375 | 4 | # Файл lunch.py
class Lunch:
def __init__(self): # Создать/внедрить Customer, Emloyee
self.cust = Customer()
self.emp1 = Employee()
def order(self, foodName): # Начать эмуляцию заказа
... |
733b82aff8388836657fea4ca208cb238bf144be | kiitos00/18.1_Python_Introduction- | /words.py | 710 | 4.5 | 4 | def print_upper_words(words):
"""For a list of words, print out each word on a separate line, but in all uppercase. """
for word in words:
print(word.upper())
def print_Eore_words(words):
"""only prints words that start with the letter ‘e’ (either upper or lowercase)."""
for word in words:
... |
8bf69aadd348c6ad7678e6017a89b368832d9d79 | Askfk/maca | /macacripts/utils_graph.py | 4,558 | 3.515625 | 4 | """Utilities for graph implementation"""
import tensorflow as tf
import numpy as np
def apply_box_deltas_graph(boxes, deltas):
"""Applies the given deltas to the given boxes.
boxes: [N, (y1, x1, y2, x2)] boxes to update
deltas: [N, (dy, dx, log(dh), log(dw))] refinements to apply
"""
# Convert to... |
69001192009d120d2b06471a06aae2e5d07813f4 | Javirandu/CodeWars | /maxComunDivisor.py | 807 | 3.890625 | 4 | def numero(n):
r=n
contador = 0
divisores = [] #numerosprimos
factores_exponentes = {}
for i in range (2,int(n)+1):
while n%i == 0:
divisores.append(i)
factores_exponentes[i]=0
contador +=1
factores_exponentes[i] = contador
... |
16cb13bacdd11c5a141f84a7c547d8aba790f317 | mayur2402/python | /Pattern1234.py | 206 | 3.875 | 4 | import os
try:
row = int(raw_input('How many rows'))
col = int(raw_input('How many column'))
if(row <= 0 or col <= 0) :
print('Enter valid number of rows and column')
os.exit(-1) |
9eff27f57acb36b5f76ae83bc605e86f92db8a7e | mayur2402/python | /Perfect.py | 596 | 3.609375 | 4 | class Perfect:
def __init__(self,iNo):
self.iNo = iNo
def ChkPerfect(self):
if(self.iNo < 0):
self.iNo = -self.iNo
if(self.iNo == 1 or self.iNo == 0):
return False
iAdd = 1
iCnt = 0
for iCnt in range(2,self.iNo):
if(self.iNo % iCnt == 0):
iAdd = iAdd + iCnt
if(iAdd > self.iNo):
b... |
de326ae2510455b72ae597264df769bf971a8434 | mayur2402/python | /Binary.py | 334 | 3.734375 | 4 | try:
num = int(raw_input('Enter number to convert in binary'))
binary = bin(num)
print(binary)
num2 = int(raw_input('Enter number to convert in binary'))
binary2 = bin(num2)
print(binary2)
band = num & num2
print(band)
print("binary of num & num2 is ",bin(band))
except:
print('In... |
63ab5834d083363052a1984340f5ca428578cdb7 | mayur2402/python | /GreateSmall.py | 779 | 3.546875 | 4 | num = int(raw_input('Enter number'))
temp = num
temp2 = num-1
temp1 = num+1
count = 0
while(temp != 0):
rem = temp % 2
if(rem == 1):
count+=1
temp = temp/2
temp3 = temp2
while(True):
count1 = 0
while(temp3 != 0):
rem = temp3 % 2
if(rem == 1):
count1+=1
... |
114fe38419d615180126c410b7335e1eda3d918c | cosmoscope/cosmoscope | /cosmoscope/operations/operation.py | 3,366 | 3.640625 | 4 | import abc
import logging
from functools import wraps
class Operation(metaclass=abc.ABCMeta):
"""
Operations are reversible actions that are performed on data sets. In order
to implement an operation, the inheriting class must override both the
`__call__` method (the forward operation), and the `undo`... |
45afa1939ff2cc5f4a57e131d1bc64d1e9e34b49 | vaibhavvarunkar/DSA | /SelectionSort.py | 1,566 | 4.1875 | 4 | # Its a simple in place comparison based algorithm.
# using min function
# ############################### Time Complexity: O(n2) ########################################
list1 = [1, 4, 6, 9, 2, 3, 8]
# print("Unsorted List is :", list1)
# last value will be sorted automatically that's why length -... |
aa19d6b2694d5c28b6b3179f083a4b855e585db1 | vaibhavvarunkar/DSA | /priorityQueue.py | 940 | 4.28125 | 4 | from queue import PriorityQueue
q = PriorityQueue()
strength = 2 # capacity of queue
def func(): # for add operation
if len(q.queue) == strength:
print("queue is full can't add...")
else:
num = input("enter queue element:")
num2 = int(input("enter priority of the element:"))
... |
66440e27c1e8acb4c8b5fc53315a3bd689cc3717 | Shubhamsharda/Competetive-Programming | /runningmedian3.py | 1,013 | 3.640625 | 4 |
# Running median hackerrank
# https://www.hackerrank.com/challenges/find-the-running-median/problem
import heapq
def runningMedian(a):
# switch=True
maxheap=[]
minheap=[]
heapq.heapify(maxheap)
heapq.heapify(minheap)
res=[]
# print('a: ',a)
median=0
for i in range(len(a)):
# print(res)
# print('medi... |
4046934181952f12f4722dd2d9e5e9487058c2c1 | Shubhamsharda/Competetive-Programming | /LvlOrdTreTraver.py | 636 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def levelOrder(root):
def func(a):
# print('func(',a,')')
if len(a)==0:
return
r=[]
for i in a:
if i.left is not None:
r.append(i.left)
if i.right is not None:
r.... |
a2d195c1a2b9fc0b25c118f22b8c784210185775 | Shubhamsharda/Competetive-Programming | /ClimbingLeaderBoard.py | 1,008 | 3.625 | 4 |
def climbingLeaderboard(scores, alice):
lens=len(scores)
lena=len(alice)
res=[]
i=lena-1
j=0
pos=0
# print('alice[',i,']:',alice[i],'##','scores[',j,']:',scores[j],'## pos:',pos,'## res:',res)
while i>=0 and j<lens: # and alice[i]<=scores[-1]:
# print('before:','alice[',i,']:',alice[i],'##','scores[',j,']:',... |
97a220f46e488c4133d85996911b6b05064a661a | anilsaini06/python | /s.py | 169 | 3.96875 | 4 | While(True)
inp = int(input("Enter a Number"))
if inp>100:
print ("congrats you have entered a number greater than 100") \n
else:
print("Try again")\n
continue |
af234ef6d2c740c7b753f1d7318bb4ded2e88a9b | waimanwong/ClassicComputerProblems | /Python/1.4.pi_calculation.py | 305 | 3.75 | 4 | def calculatePi(n:int) -> float:
pi : float = 0.0
numerator = 4
for i in range(n):
sign = 1 if i % 2 == 0 else -1
denominator = sign * (2*i + 1)
pi += (numerator / denominator)
return pi
if __name__ == "__main__":
pi = calculatePi(1000000)
print (pi)
|
68dacbb7b99353b85bc91ec05714244b8cb9420b | jacktraf/mypylib | /mypylib.py | 572 | 4.21875 | 4 | def is_divisible(DIVIDEND, DIVISOR):
# Is DIVIDEND divisible by DIVISOR? Divide DIVIDEND by DIVISOR. If the remainder is 0, return True. Else, return False.
# "%" is the modulo operator, it's like division, only it returns the remainder, not the quotient.
if DIVIDEND % DIVISOR == 0:
return True
else:
return ... |
9ee5a91261a56ab60776d8762cce95367f9082a6 | rohit8pix/Algorithms | /print_dupli_char.py | 392 | 3.65625 | 4 | '''method1'''
def dupli(arr):
duplicates = []
for char in arr:
if arr.count(char)>1:
if char not in duplicates:
duplicates.append(char)
'''method2'''
def dupli_dictionary(arr):
duplicates={}
for char in arr:
if char in duplicates:
duplicates[char]+=1
else:
duplicates[char]=1
fo... |
3570030243c09706b33d42c5ccd57d492bfb6a01 | antony251996/BasicoPython | /10.Bucles.py | 351 | 3.875 | 4 | def run(num,final):
cont = 0
pot=0
while cont < final:
print(f'{num} elevado {pot} = {num ** pot}')
pot+=1
cont = num ** pot
if __name__ == '__main__':
num = int(input('Ingresa el numero que quieres conocer su potencia: '))
final = int(input('Ingres hasta que numero deseas ... |
a520d5d1dd15732c9101504bc19882b55084b1db | tmuweh/python-basics | /structures.py | 862 | 4 | 4 |
#lists
players = ["gk", "md", "cf", "mf"]
#change list values
players[0] = "ngk"
#add list temporally
print(players + ["ff", "lf"])
print(players)
#permament add
players.append("nff")
print(players)
#print list
print(len(players))
#slicing
print(players[2:5])
#delete elements
players[0] = []
print(players)
play... |
5d5df7b302d3ea587543e1c4292b7a68f7f96d02 | bibongbong/pythonDataScience | /src/PythonDataScience.py | 5,325 | 3.8125 | 4 | # map()
# 根据提供的函数对指定序列做映射
# map(function, iterable, ...)
people = ['Dr. Christopher Brooks',
'Dr. Kevyn Collins-Thompson',
'Dr. VG Vinod Vydiswaran',
'Dr. Daniel Romero']
import re
def split_title_and_name(person):
words = re.split(r'(\.|\s)', person)
return words[0]+words[1]... |
913335ed92814cf2e058c942d68f0726aab6c1d6 | leexiulian/learn-python | /user_name.py | 435 | 3.9375 | 4 | user_names = ['Admin','Jack','Tom','Lily','Frank']
#删除列表中的所有元素
del user_names[-len(user_names):]
#判断列表是否为空
if user_names:
for user_name in user_names:
if user_name.lower() == 'admin':
print("Hello " + user_name.title() + ",would you like to see a status report?")
else:
print("Hello " + user_name.title() + ",... |
4f686e72b6994bdbb7206776adcda981d1b0663b | antojose/thelycaeum-python-problems | /solutions.py | 1,263 | 4.25 | 4 | # Problem Statement:
#
# a. Write a function that will print the times tables for a given
# number from 1 to 10.
# Sample output:
# tables(4) should display
# 1 x 4 = 4
# 2 x 4 = 8
# 3 x 4 = 12
# 4 x 4 = 16
# 5 x 4 = 20
# 6 x 4 = 24
# 7 x... |
c26dd19476ea14ae4b153a2d70a82d6a2747260a | tmendonca28/Practice-Projects | /draw_square.py | 755 | 3.625 | 4 | import turtle
def create_window():
window = turtle.Screen()
window.bgcolor("blue")
draw_square()
draw_circle()
draw_triangle()
window.exitonclick()
def draw_square():
anthony = turtle.Turtle()
anthony.shape("turtle")
anthony.color("black")
anthony.speed(7)
movement = 0
... |
e1fcd22a960dca401977cf2d12caae541aa5d6c6 | vidhya567/ctci | /sucessorBST.py | 1,251 | 3.984375 | 4 |
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.parent = None
self.value = value
# sucessor of node A is a node with lowest value higher than value of A
def sucessor(node):
if (node.right):
return minBST(node.right)
else:
# percolate up till a parent has the ... |
3a94801b501634d118ab4e72094b5c2cbcbf7948 | marcelov-aguiar/capacitacao_python | /codigos-capacitacao-python.py | 4,719 | 4.15625 | 4 | #Variáveis
a = 10
# esta variavel eh do tipo inteiro (int)
b = 1.2
# esta variavel e do tipo real (float)
c = "Ola mundo"
'''esta variavel e do tipo string (conjunto de caracteres)
Digite type(a) e veja o resultado'''
#Entrada e saída de dados
nome = input("Digite o nome do usuario: ")
#Conversão de var... |
6e0eb243fe59a4c9ac473f87491f25de45d23692 | Frazzle5388/Week_2_day_2_lab | /bus_lab_start_code/src/bus.py | 886 | 3.609375 | 4 | class Bus:
def __init__(self, route_number,destination, price, capacity):
self.route_number = route_number
self.destination = destination
self.price = price
self.capacity = capacity
self.passengers = []
self.till = 0
def drive(self):
return "Brum brum"
... |
30febd683a3b705a6e5370e03fe91d6deb0a37e4 | samudero/PyNdu001 | /Namespaces.py | 778 | 4.09375 | 4 | # Namespaces [163]
# Global variables --> defined in main program
# local variables --> defined e.g. in functions
# built-in functions
"""
Created on Tue 20 Mar 2018
@author: pandus
"""
# ------------------------ global - local
def f():
x = 'I am local'
print(x)
x = 'I am global'
f() ... |
dd4a5ff0b1504e90bd537864aefdc8b540eb13ba | FabioCZ/Cs1400Demos | /Section3/pythonDemo.py | 995 | 3.703125 | 4 | class MyFunClass:
x=3
y=4
def memberFunc(self):
def myFunFunction(in1,in2):
if in1 < 0:
in1 = 5
return in1+in2
x=3
y= x + 4
y= "y is a string now"
#z=input()
intDiv= 7 // 3 # 2
floatDiv = 7 / 3 #2.3333
exp = 2 ** 4
print("Int div value is " + str(intDiv))
t=True
f=False
if t or f: # ||
print("or exampl... |
e2b80c61fba59e1445c5781afbc5b2f5a0aac1fd | batooldshilleh/treasure-map | /treasure_map.py | 355 | 3.734375 | 4 | row1= ["⬜️","⬜️","⬜️"]
row2= ["⬜️","⬜️","⬜️"]
row3= ["⬜️","⬜️","⬜️"]
map = [row1,row2,row3]
print(f"{row1}\n {row2}\n {row3}")
position = input("where do you want to put the treasure? \n")
h = int(position[0])
v = int(position[1])
select_row = mab[h-1]
select_row[v-1] = "X"
print(f"{row1}\n{row2}\n{row3}")
|
66f41d775d6ea92353a536f3e9d0122143ebcdbf | HarigovindV10/LinearRegression | /LinearRegression.py | 2,572 | 3.8125 | 4 | import numpy as np
import pandas as pd
import math
from scipy.stats.stats import pearsonr
import matplotlib.pyplot as plt
class LinearRegression:
"""
Linear regression
slope, intercept :argument
"""
slope = 1
intercept = 0
actual_output = []
error_threshold = 0
def __init__(self, slope = 1, intercept = 0):... |
5538c7def3b9e0ca2ce8bdda49a671b3ac880bcf | OliverCarr/MachineLearning_and_DataScience | /MachineLearning_and_DataScience/Quick_tutorials/2DataProcessing/Skewness.py | 801 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 3 20:00:42 2021
@author: olive
"""
# 7 Ways to summaries a dataset
#1 Peek at data
#2 Dimentions of data
#3 Data types
#4 Class Distributions
#5 Data Summary
#6 Correlations
#7 Skewness*****
'''Used to descrive Bell Curves
-Normal distri... |
5c2989d3fd22845a4d90ace0382aa1327a92ff5b | arsalan0004/SYSC_3310_Introduction_To_Realtime_Systems | /Assignment 1/linked_deque.py | 10,845 | 4.1875 | 4 | # SYSC 2100 Summer 2021 Assignment 1
# ADT Deque (Implementation using a singly-linked list.)
from typing import Any
class LinkedDeque:
"""An implementation of a deque (double-ended queue).
The methods for adding items to the left and right sides of a deque are O(1).
The method for removing an item fro... |
78094e2d32992ef89574e7b8ae33021d9052a865 | dos09/PythonDesignPatterns | /src/design_patterns/structural/composite.py | 761 | 3.578125 | 4 | """
composite = contains group of objects of the same type
"""
class Orc:
def __init__(self, name):
self.name = name
self.killed_orcs = []
def add_killed_orc(self, orc):
self.killed_orcs.append(orc)
@staticmethod
def show_killed_orcs(orc, indent=''):
print('%... |
244fd8aaee26441438a3abd41f46ce8ca805c0e9 | dos09/PythonDesignPatterns | /src/design_patterns/structural/flyweight2.py | 1,990 | 4.375 | 4 | """
Flyweight is a structural design pattern that lets you fit more objects
into the available amount of RAM by sharing common parts of state between
multiple objects instead of keeping all of the data in each object.
When object has mutable and immutable fields and the immutable fields
take RAM, when having many ob... |
38b4747181330852a1f85e3d22f1a27ba58ffb4b | yogicat/python-crash-course | /LPTHW/capitalize.py | 75 | 3.8125 | 4 | s = input("name: ")
for c in s:
print(c.upper(), end='')
print('\n')
|
850efdf9e9928a34fa008f5d5f371fabc029f4b9 | yogicat/python-crash-course | /Python-Crash-Course/dictionary.py | 955 | 3.875 | 4 | # Dictionary is a collection which is unordered, changeable and indexed.
# No duplicate members
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 30
}
print(person, type(person))
# get value
print(person['first_name']) # JS에서 person.first_name
print(person.get('last_name'))
# add key/value
person['... |
2a5b316d728a8d18aa3b1c6e7acbc34ffeff5c2c | yogicat/python-crash-course | /Python-Crash-Course/strings.py | 559 | 4.34375 | 4 | name = 'Arya'
age = 22
# 1. Concat
# print('hello, my name is '+ name + 'i am ' + age) => age 포매팅 필요
# 2. Arguments by position
print('My name is {name} and age is {age}'.format(name=name, age=age))
# 3. F-Strings (3.6 +)
print(f"My name is {name} and age is {age}")
##### String Methods
s = 'hello world'
s1 = 'pyth... |
0dd3dbe879f5f27c6a4149789574d1048abb8d22 | mareikeThieben/pythonintro | /moodchecker.py | 497 | 4.1875 | 4 | user_name = input("Please enter your name: ")
print("Hello " + user_name + "!")
mood = input(user_name + "," + " " + "how are you feeling? ")
if mood == "happy":
print("It is great to see you happy!")
elif mood == "nervous":
print("Take a deep breath 3 times.")
elif mood == "sad":
print("Cheer up, Mate!"... |
3269cf87f2eb384a6cb30c84360dbc69b77e5b84 | LucasBalbinoSS/Exercicios-Python | /ExerciciosPython/ex008.py | 275 | 3.5 | 4 | n = float(input('\033[1;35mDigite uma quantia em metros para que a mesma seja convertida em centímetros e milímetros: \033[m'))
print('\033[34m%.3f metro(s) equivale a %.3f centímetros\n%.3f metro(s) Equivale a %.3f milímetros \033[m'
% (n, n * 100, n, n * 1000))
|
d53d269e3640c9f06555d3192a251c3b266b9e86 | LucasBalbinoSS/Exercicios-Python | /ExerciciosPython/ex27.py | 215 | 3.6875 | 4 | nome = str(input('\033[35mDigite seu nome completo: ')).strip()
print(nome)
nome2 = nome.split()
print(len(nome2))
print('Seu primeiro nome é %s' % nome2[0])
print('Seu último nome é %s' % nome2[len(nome2)-1])
|
bf45e219ffcc626d8b16e18904285023b2d32a0f | LucasBalbinoSS/Exercicios-Python | /ExerciciosPython/ex030.py | 149 | 3.875 | 4 | n = int(input('\033[35mDigite um número: '))
if n % 2 == 0:
print('%i é um número par!' % n)
else:
print('%i é um número ímpar!' % n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.