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 |
|---|---|---|---|---|---|---|
8a0aee6f500923fb1644a6ea02531c1b49c0d535 | jiobu1/Hash_Table | /Hash_Table_3/Beej/3_collision.py | 1,463 | 3.75 | 4 | import hashlib
import random
def hash_function(key):
return int(hashlib.md5(str(key).encode()).hexdigest()[-8:],16) & 0xffffffff
def how_many_before_collision(buckets, loops):
for i in range(loops):
tries = 0
tried = set()
while True:
random_key = random.random()
... |
f23916c0eb2f8632dfad61b2fcda58565bafe570 | uiqkos/yandex-cup-2021 | /algorithm/dmatrix.py | 2,520 | 3.75 | 4 |
def solve(rows, cols):
n, m = rows, cols
first_range = 1
set_ = set()
if rows != 1 or cols != 1:
horizontal = False
vertical = False
# начальная инициализация
# если строк больше, то складываем по горизонтали
if rows >= cols:
# если же сложить по го... |
f3b560682a93750bdc8a175e04dd22f1fecc599c | miki-tororo/flask_test | /sql.py | 476 | 3.578125 | 4 | import psycopg2
print(1)
import psycopg2
# connect postgreSQL
users = 'postgres'
dbnames = 'flask'
passwords = 'postgres'
#host、port are not need on local
conn = psycopg2.connect(" user=" + users +" dbname=" + dbnames +" password=" + passwords)
# excexute sql
cur = conn.cursor()
cur.execute('SELECT * FROM Test;... |
0cc84668295730ce071352724328b35fccb6409a | bmarkovic1/bazel_example | /complex_lib.py | 898 | 3.75 | 4 | from math import sqrt
class Complex(object):
def __init__(self, real, imag=0.0):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real,
self.imag + other.imag)
def __sub__(self, other):
return Complex(self.... |
99f508ed8ea8259cd4b0926a3ce06952f2f63c32 | SunnyJay/study_python | /python_exception.py | 2,726 | 3.625 | 4 | #-*- coding:utf-8 -*-
'''
Created on 2016年3月24日
错误和异常
BaseException 是所有异常的基类 Exception是常规错误的基类
@author: Administrator
'''
#常见异常
#NameError name 'foo' is not defined
#AttributeError 尝试访问未知的对象属性
#try语句两种:tryexcept tryfinally
try:
f=open('blah', 'r')
except Exception,e: #这里e指异常参数
print 'could not open f... |
efad3ebafbe2c1e17931802fc103816b922b980d | JustinWayneOlson/Air-Traffic-Analysis | /data/data/data_downloader.py | 821 | 3.8125 | 4 | from urllib.request import urlopen, URLopener #imports urlopen, urlopener
from time import time
if __name__ == "__main__":
years = [2015]
months = [x for x in range(1,13)]
start = time()
#Iterate through years and months
for cur_year in years:
for cur_month in months:
url = "http://tsdata.bts.g... |
b9dba957de152c0e324784b72a7975d78762c3d1 | ritopa08/Daily-Coding | /daily_coding_challenge_10.py | 1,092 | 3.859375 | 4 | 10.
'''
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".
'''
#import packages
from itertools import combinations,permutations
... |
9e705bfdfb55cf38c111b24ac114458150c4ec44 | Juless89/tutorials-aoc | /part_5/main.py | 988 | 4 | 4 |
def part_1(string):
filtered = ['']
# loop over each character inside the string
# if the next character is the opposite case
# discard both characters, else append to result
for c in string:
c2 = filtered[-1]
# check by ASCII values
if c2 != '' and (abs(ord(c) - ord(c2)... |
17d8a240e7fc87692e17988f80e1001505f426c4 | basilanathan/Python | /PythonFun/try_python.py | 194 | 3.703125 | 4 | # myname= "Basila"
# myname= "Amanda"
# print myname
# print 4+5
# print "Hi my name is" + " Basila"
# print "my favority number is" + " 7"
my_string = "hello world"
print my_string.find("ll")
|
b29422cc19a87034380526c3cb0cfdc36975f5bf | basilanathan/Python | /PythonFun/mult_sum_avg.py | 245 | 3.625 | 4 | # Multiples
# part I
for odds in range(1, 1000, 2):
print odds
# part II
for x in range(5, 1000000, 5):
print x
# Sum List
a = [1, 2, 5, 10, 255, 3]
x= sum(a)
print x
# Average List
a = [1, 2, 5, 10, 255, 3]
y= sum(a)/len(a)
print y
|
c20920c683a16327f6bebbe63d1d057ac7ac394b | fqx9904/Python_Game_Autoplay_Strategy--CSC148 | /Assignment/a1/state.py | 9,185 | 3.9375 | 4 | """
state module
"""
from typing import Any
class State:
"""Represent the state of a general two-player, sequencial-move, zero-sum
and perfect-information game.
is_p1_turn - if the current turn is p1
moves - the possible moves that current player can pick
"""
is_p1_turn: bool
moves: Any
... |
4d300c1b473e432ae31c73665b47931ada411964 | fqx9904/Python_Game_Autoplay_Strategy--CSC148 | /Assignment/a2/strategy.py | 6,435 | 4.25 | 4 | """
A module for strategies.
NOTE: Make sure this file adheres to python-ta.
Adjust the type annotations as needed, and implement both a recursive
and an iterative version of minimax.
"""
from typing import Any
# TODO: Adjust the type annotation as needed.
def interactive_strategy(game: Any) -> Any:
"""
Retu... |
c8fd1862080aacf5a80f02abff4b319a3e481380 | fqx9904/Python_Game_Autoplay_Strategy--CSC148 | /Test/Test#1/LinkedList_ex.py | 6,336 | 4.21875 | 4 | """ practice on linked lists
"""
class LinkedListNode:
"""
Node to be used in linked list
=== Attributes ===
@param LinkedListNode next_: successor to this LinkedListNode
@param object value: data this LinkedListNode represents
"""
def __init__(self, value, next_=None):
"""
... |
7765d51fd059b85e4d4c45f0b5b3aeee3f7675cc | HongguJeong/Digital_Video_Processing | /3. Motion Estimation/Assignment_3_ME.py | 10,719 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 4 00:32:16 2019
@author: Ibrahim El-Shal
Assignment 3:
- Develop a Motion Estimation algorithm using Window Search to encode two images in YUV format.
- Use 8x8 block.
- Reconstruct the images using Motion Compensation.
- Compute PSNR between the Source Image and the... |
7ba371c27849ae80cdafed471089f588f61df08a | cormacdoyle/Music-Interface | /user_interface.py | 6,262 | 4.125 | 4 | import commands
'''
This function acts as the menu, it takes user inputs and direct them to a respective function
This function takes subscriber_ratings as a paramter, this function allows the nested list
of subscriber preferences to be moved across functions. This function also has the option for
a test parametre whi... |
db188733063d2315b9ba8b8906b24576fc5883cc | SourabhSaraswat-191939/ADA-BT-CSE-501A | /Assignment-2/Insertion_Sort.py | 1,740 | 4.5 | 4 | #Insertion sort is used when number of elements is small. It can also be useful when input array
# is almost sorted, only few elements are misplaced in complete big array.
import time, random, sys
sys.setrecursionlimit(3010)
def insertionSortRecur(arr,n):
if n<=1:
return
insertionSortRecur(arr,n-... |
971b298da092cb3d24845d01a3cb6251f48ef8c8 | smartniz/python-tips-book | /decorators.py | 3,784 | 4.625 | 5 | # everything in Python is an object
def hi(name="sujay"):
return "hi " + name
print(hi())
# output: 'hi sujay'
# We can even assign a function to a variable like
greet = hi
# We are not using parentheses here because we are not calling the function hi
# instead we are just putting it into the greet variable. Let... |
c2be31530a43d2d5531e6b394fa43224c5004906 | parinita08/Hacktoberfest2020_ | /Python/sieve.py | 658 | 3.9375 | 4 | #Sieve Of Eratosthenes
#Author - https://www.github.com/yatocodes
'''
About - The programme is created for the purpose of calculating
prime numbers; between two of the user given numbers.
'''
print("Welcome To Sieve Of Eratosthenes \n")
print("Plese Dont't Enter 1 as Starting Number\n")
starting_num = int(i... |
279eaa1adb84a6362e50c16cbcf77fdb96b8c710 | parinita08/Hacktoberfest2020_ | /Python/wordGuess.py | 1,664 | 4.3125 | 4 | import random
# This lib is used to choose a random word from the list of word
# The user can feed his name
name = input("What's your Name? ")
print("Good Luck ! ", name)
words = ['education', 'rainbow', 'computer', 'science', 'programming',
'python', 'mathematics', 'player', 'condition',
'reverse', ... |
219e28fdf06a48559e48fbf383a45660446fa9a8 | yizhong120110/CPOS | /cpos/foundation/substrate/utils/interval.py | 1,300 | 3.546875 | 4 | # -*- coding: utf-8 -*-
import time
class TimeoutInterval(object):
def __init__(self, timeout_interval=-1):
self.interval = timeout_interval
self.first_step = 0
self.time_delta = 0
def step(self, sleep=None):
self.first_step = time.time() if self.first_step == 0 else self.fir... |
b14eef97d4d6504ca2737358cabfc75648fc1b52 | Apentz49/approximate-square-root | /square_root.py | 781 | 4.03125 | 4 |
#This is trying to see if you enter a number or not
while True:
try:
your_number = int(input("Please enter a Positive Number ")) #This is where we get a Number
except:
print("Sorry that is not a valid entry")
continue
else:
break
# Figure out how to take your_number and chec... |
2d9fe8637530e8d698198c8f1c120cf4ec259deb | vtminhvt/python | /cvs.py | 310 | 3.546875 | 4 | import csv
header = ['Full Name', 'Birthday', 'Email', 'Mobile', 'Language']
data = ['Vo Thanh Minh', 1981, 'abc@gmail.com', 'HaNoi', 'Python beginner']
with open('data.csv', 'w', encoding='utf-8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
# write the data
writer.writerow(d... |
e85e87c46ae920779f2190977231fc1bf15f4413 | 0102-sd/ai | /water_jug.py | 641 | 3.84375 | 4 | jug1=int(input("enter capacity of 1st Jug\n"))
jug2=int(input("enter Capacity of 2nd Jug\n"))
t1=int(input("enter goal state of first Jug\n"))
t2=int(input("enter goal state of second Jug\n"))
def water_jug(cap1,cap2):
print("\n",cap1,cap2)
if (cap1==t1 and cap2==t2) or (cap1==t2 and cap2==t1):
... |
ed5a8486063a1333dbc8ba82614cf8fc0f0a4ffa | wangfp1145834208/Fluent-Python | /Chapter_21/metaclass_test.py | 1,042 | 3.8125 | 4 | class TestMetaClass(type):
def __init__(cls, name, bases, dict):
pass
class Test(metaclass=TestMetaClass):
pass
class SubTest(Test):
pass
class SubMeta(TestMetaClass):
pass
if __name__ == '__main__':
result_1 = issubclass(Test, TestMetaClass)
print('*** Is Test the subclass of T... |
c5d67e57641084048c9d8c881d86e4fcabfbc143 | geekhub-python/cycles-valiknet18 | /task9.py | 270 | 3.796875 | 4 | #!/usr/bin/env python3
alpha = str(input("Write letter: "))
indexAlpha = ord(alpha)
steps = 3
startAlpha = 97
endAlpha = 122
while (steps > 0):
indexAlpha += 1
if indexAlpha > endAlpha:
indexAlpha = startAlpha
print(chr(indexAlpha))
steps -= 1
|
44002906fbef43cd6214a1affa637d6662f8eb0f | seanwbarry/thinkful_flask | /hello_world_original.py | 1,142 | 3.71875 | 4 | from flask import Flask
from os import environ
app = Flask(__name__)
#tell the Flask application where it is being run from
#@app.route("/")
@app.route("/hello")
def say_hi():
return "Hello World!"
#only one of the below functions will run - why is that???
"""
@app.route("/hello/<name>")
def hi_person(name):... |
0aa3f8d82d563897fccc1d728afc3357d6e415da | zongtong009/pythonDesktop | /iMoocpython/017异常处理.py | 417 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 11 17:28:05 2018
@author: Administrator
"""
try:
num=eval(input("please input a integer: "))
print(num**2)
#except:
#print("please input right integer")
except NameError:
print("please input right integer")
'''
try:
<right part>
exc... |
b7c7276f824f7bb654f1b80da194fac71254b3f2 | zongtong009/pythonDesktop | /iMoocpython/021定义函数.py | 214 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 13 17:54:10 2018
@author: Administrator
"""
#a,b=eval(input())
def fact(n,m=1):
s=1
for i in range(1,n+1):
s*=i
return s//m
print(fact(10,5))
|
67241702f96b46488bd279d100976895838c41aa | zongtong009/pythonDesktop | /iMoocpython/018BMI.py | 273 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 11 17:51:53 2018
@author: Administrator
"""
# <18.5 thin 18.5-24 normal
# 24-28 overweight 25-more fat
height,weight=eval(input(""))
print("height:{0} \nweight:{1}".format(height,weight))
|
7224bcbab7d87f6fa00a6de8d4ad5818071afe05 | seeyouxiyou/first | /bfs.py | 886 | 3.78125 | 4 | #-*- coding:utf-8 -*-
import datetime
class BFS(object):
def __init__(self):
self.num = 0
def fun(self,s,m,n):
stack=[[s,m]]
stack_s =set()#用来存储字符串s的长度
while True:
if n in stack_s:
break
stack_temp=[]
while stack:
... |
acb054199fb41d5adabec6307f4d2e7ba1681a2b | radhikam01/Data-Analysis-Using-Python | /Assignment_3/Assignment 3_PY files/Q4_PARTONE.py | 5,070 | 3.578125 | 4 |
# coding: utf-8
# # Extract data from the Awards column and split it into its specific columns
# In[1]:
#Importing all required packages
import pandas as pd
from pandas import DataFrame
import numpy as np
import calendar
pd.options.mode.chained_assignment = None #'warn'
# In[2]:
#Reading the 'Movies Awards' data... |
7f667261bec1351a74f5e7b98890e58642755903 | SunghyunChoi/DataStructure | /Queue.py | 1,968 | 3.5625 | 4 | class FixedQueue:
class Full(Exception):
pass
class Empty(Exception):
pass
def __init__(self, c : int):
self.capacity = c
self.front = 0
self.rear = 0
self.no = 0
self.queue = [None] * self.capacity
def is_full(self) -> bool:
if sel... |
8e92fd56fb9466f445560732c2be7a023978bec1 | KoKosna/PyProject | /1.py | 3,101 | 4.09375 | 4 | list = ["Кролик",
"Волк",
"Лиса",
"Слон",
"Жираф",
"Дельфин",
"Кит",
"Корова",
"Коза",
"Хомяк",
"Тигр",
"Лев",
"Олень",
"Кабан",
"Медведь",
"Енот"]
print(list[:])
print("Это хищное животное?")
ans = i... |
6431de1896812ed12a38788669ed21e6cdf67d7c | Angelica137/mitx600_problem_set_3 | /scripts/hangman.py | 2,390 | 3.953125 | 4 | import string
from getAvailableLetters import getAvailableLetters
from getGuessedWord import getGuessedWord
from welcomeMsg import welcomeMsg
from isWordGuessed import isWordGuessed
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
*... |
80d74910940346639e47e13a878b0e1894526208 | treilly94/wrapper-writer | /wrapper_writer/structure.py | 1,972 | 4.03125 | 4 | import os
class Structure:
"""The Structure Class contains the details and functionality associated with a particular structure.
.. note:: A structure is a group of wrappers that would use the same template, follow the same naming convention, and be placed in the same directory.
:param project_root: Thi... |
b3ec77e4759ce603a313e6266769d64ee4107034 | chvbs2000/SpringBoard | /Capstone_Project1/capstone1_analysis.py | 30,916 | 3.640625 | 4 |
# coding: utf-8
# # Analysis in Medicare Provider Utilization and Payment Data: From the Prospectives of Average Difference between Submitted and Charged Medicare Amount from Physician in California
# ## Data Input
# In[1]:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as s... |
be0066abb56f247d88e7ab2ffa327ee06480dd68 | Georgewqz/CS235-A2 | /movie_web_app/domainmodel/genre.py | 537 | 3.5625 | 4 | class Genre:
def __init__(self, genre: str):
if genre == "" or type(genre) is not str:
self.__genre = None
else:
self.__genre = genre.strip()
@property
def genre_name(self) -> str:
return self.__genre
def __repr__(self):
return f"<Genre {self.__... |
e9958c2817a63419482cd59df408a156cd3264ae | SwiftBean/Test1 | /Name or Circle Area.py | 656 | 4.40625 | 4 | #Zach Page
#9/13
#get a users name
##def get_name():
### step one: ask user for name
## name = input("what's your name")
###step two: display the name back for user
## print("the name you entered was", name)
###step three: verify the name
## input("is this correct? yes or no")
##
##print("this is our fu... |
371dac480ff3652597724ea59acfc9d43528fd13 | solandmedotru/stepic_Python | /3369-11-952.py | 914 | 3.96875 | 4 | side = int(input())
'''заполняем квадратную матрицу нулями'''
matrix = [[0 for j in range(0, side)] for i in range(0, side)]
def go(chetnost):
number = 1
stroka = 0
stolbec = side-1
n=1
while number < side**2-chetnost:
for k in range(0, 2):
for j in range(stroka, stolbec, n):
... |
eb3856fb00a5fdee73b077017b26aa689ac6ec0b | solandmedotru/stepic_Python | /3364-12-947.py | 87 | 3.5625 | 4 | a = int(input())
b = int(input())
d=1
while (d%a!=0 or d%b!=0):
d = d + 1
print(d) |
cadd5f5bd7dfcdab3fceeaf8e55da9c93c3fa22a | solandmedotru/stepic_Python | /5047-7-1086.py | 199 | 3.578125 | 4 | num = input()
n0,n1,n2,n3,n4,n5 = int(num[0]),int(num[1]),int(num[2]),int(num[3]),int(num[4]),int(num[5])
if n0+n1+n2 == n3+n4+n5:
print("Счастливый")
else:
print("Обычный") |
a9dfc364d9fe490615c43c6dcbd452bafba5dede | yuedackg/javaq2 | /python/a001.py | 427 | 3.765625 | 4 | class AbstractGreeting(metaclass=ABCMeta):
@abstractmethod
def greeting(self, name):
pass
class EnglishGreeting(AbstractGreeting):
def greeting(self, name):
return 'Hello, %s' % name
class JapaneseGreeting(AbstractGreeting):
def greeting(self):
return 'こんにちは、%sさん' % ... |
b7c8e7825e2d7cb1ab81acb033e71c099e32cac9 | BergC/shortest-path | /shortest.py | 3,962 | 4.34375 | 4 | import numpy as np
from collections import deque
def shortest_path(maze):
"""
Function to calculate the shortest path between coordinate (0, 0) of a matrix and the number 9,
where it may fall.
:param maze: 2d array where values of 1 are traversable, values of 0 aren't, and value of 9 is goal.
:ret... |
2b8bf97ff20abddb6f84a17ea452738685df5b04 | three-stones-lei/Smart-Calculator | /Smart Calculator/task/calculator/calculator.py | 6,343 | 3.796875 | 4 | # write your code here
from _collections import deque
class Calculator:
saved_variables = {}
is_exit = 0
def __init__(self):
pass
def deal_with_command(command):
if command == '/exit':
print('Bye!')
Calculator.is_exit = 1
elif command == '':
p... |
9a5e8ef15e26a635281266fed942e15f291cba35 | jangler/scripts | /python/finances | 2,271 | 3.546875 | 4 | #!/usr/bin/env python
import argparse
import collections
import json
import sys
DESCRIPTION = "Analyze financial information from a JSON file."
def die(msg):
sys.stderr.write(str(msg) + '\n')
exit(1)
def parse_args():
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('... |
a0b4c3361f8ac65e51c281ce3176230c17b4de64 | thesagargoyal/PYTHGON_LAB | /tuple8.py | 130 | 3.609375 | 4 | to avoid changes in previous tuple just like deepcopy case of list
t=(1,4,[])
d=eval(str(t))
d[-1].append(100)
print(d)
print(t)
|
71ba5d496ce3ed9a3552360b2b81ad1e14dc81eb | lvillen/Deck | /deck.py | 432 | 3.640625 | 4 | import random
def createDeck(suits, numbers):
deck = []
for suit in suits:
for number in numbers:
deck.append(number+suit)
return deck
def shuffle(list):
for ix in range(len(list)):
new_position = random.randrange(len(list))
#Swapping items (cards) with empt... |
bdc48e3f61129454dc31d0b38ef6e6908cd2dbb7 | mhamwala/SnakesLadders | /Tic Tac Toe.py | 6,544 | 3.703125 | 4 | #Kyle Nicol- Tic Tac Toe
Height = 3
Width = 3
connect = 4
import copy
def get_players():
global Player1
global Player2
Player1 = input("Player 1, Please enter your name: ")
Player2 = input("Player 2, Please enter your name: ")
def create_board(wdt=10,lng=10):
line = []
for x in range(wdt)... |
d18cc844d16aa6d00391ab3d2276e266bc9f326c | ailise/KanjiGame | /Assets/makeJson.py | 1,330 | 3.84375 | 4 | import csv
# Establish our three file streams
krad = open('reducedkradfile.txt')
readings = open('kanjiReadings.csv')
outfile = open('moon_speak.json', 'w')
# Get an array of all the lines in kradfile
rads = krad.readlines()
# Create an empty dictionary
radDict = {}
# for loop iterates over each line in the kradfile
... |
3889e046394a464510662bb41598f078dff844b9 | italocampos/simulacao-discreta | /random-simulation-simpy/random_numbers_python.py | 1,269 | 3.5625 | 4 | # Gerando distribuições de números aleatórios em Python
import scipy.stats as st
import matplotlib.pyplot as chart
import math
# Distribuição unifome
conjunto = st.uniform.rvs(size=2000, loc=75, scale=2)
'''
> 'loc' significa que os números aleatórios serão gerados a
partir de 'loc'
> 'scale' diz respeito à variaç... |
b190d07fa425724a39089852b42f7273565e74b1 | Bryan-GF/Algorithms-Intro | /recipe_batches/recipe_batches.py | 784 | 3.59375 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
prevMax = math.inf
ingVal = list(ingredients.values())
for i,val in enumerate(recipe.values()):
if ingredients.keys() != recipe.keys():
prevMax = 0
elif ingVal[i]/val < 1:
prevMax = 0
elif ingVal[i]/val < prevMax:
... |
2056dd0e69f6d06c418c03381110c974ec6a0108 | xingzhis/pretendFLR | /pFLR.py | 6,380 | 3.890625 | 4 | """
@ Xingzhi Sun
June 26 2021
Class definitions of logistic regression.
two aggregation modes:
1. aggregating gradients.
2. aggregate weights.
Aggregate gradients:
Guest
- Owns a partial dataset.
- Computes gradient, then send to the arbiter.
- Receives the aggregated gradient from the arbiter, then u... |
c29243af0486a9a0df49e81f6664fa360d38a87d | abhikrish06/PythonPractice | /LC_n_Misc/LC_112_Path_Sum.py | 675 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root, sm):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
... |
388745f90b17a158e0f57f1645c0071754fa0acd | abhikrish06/PythonPractice | /LC_n_Misc/LC_451_Srt_Chrtrs_by_Freq.py | 484 | 3.59375 | 4 | from collections import Counter
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
res = ''
dct = Counter(s)
sorted_dct_val = sorted(dct.items(), key=lambda kv:kv[1], reverse=True)
for tpl in sorted_dct_val:
... |
297443115f368f6f74954748aea31cf38fdb3aad | abhikrish06/PythonPractice | /CCI/CCI_1_09_isSubstring.py | 732 | 4.15625 | 4 | # Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one
# call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat").
def isRotation(str1, str2):
if len(str1) != len(str2):
return False
return isSubstring(str1 + str1, str2)
def isSubstring(st... |
8c762e14ef1ba9895fa010c2ab1c29e644d26a65 | abhikrish06/PythonPractice | /LC_n_Misc/LC_832.py | 641 | 3.75 | 4 | class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
res, fin = [], []
for arr in A:
res.append(arr[::-1])
# print(res)
for ar in res:
res2 = []
for i in ar:
... |
91942c33b5512ceeabeb3674f3a971d34f81c6db | abhikrish06/PythonPractice | /LC_n_Misc/LC_90_SubsetsII.py | 575 | 3.53125 | 4 | class Solution:
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return [[]]
nums = sorted(nums)
res = [[nums[0]]]
for n in nums[1:]:
rlen = len(res)
if [n] not in... |
cd4db3969555a69a27a2d050a1ce54d86e8e2820 | abhikrish06/PythonPractice | /HR/HR_10D_D1_std_dv.py | 351 | 3.75 | 4 | import statistics, math
if __name__ == '__main__':
n = int(input())
sum_val = 0
numbers = map(int, input().split())
nums = sorted(numbers)
# print("numbers: ", nums)
u = statistics.mean(nums)
for i in nums:
sum_val = sum_val + (i - u)**2
std_dev = math.sqrt(sum_val/n)... |
d8d225977b045e19823e3c26ab12fd251e7eb533 | abhikrish06/PythonPractice | /LC_n_Misc/LC_845_Lngt_Montn_In_Arr.py | 246 | 3.59375 | 4 | class Solution:
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
res = []
i,= 0
bol = True
while bol:
while (A[i] < A[i+1]):
pass
|
28cc807d024c28136d96ec175241a2357e0dbded | abhikrish06/PythonPractice | /LC_n_Misc/LC_Intrsctn2LL.py | 679 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA i... |
d4ead625f9808349781289be3191c1acdc8f6a50 | abhikrish06/PythonPractice | /HR/HR_Alg_Eqlz_Arr.py | 404 | 3.828125 | 4 | #!/bin/python3
import sys
from collections import OrderedDict
def equalizeArray(arr):
# Complete this function
d = {}
for i in arr:
d[i] = arr.count(i)
print(d)
v = list(sorted(d.values()))
return sum(v[:-1])
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(... |
b89bce7b8bf83977d61711ec831803eee16fa427 | abhikrish06/PythonPractice | /HR/dasdad.py | 1,396 | 3.546875 | 4 | import collections
def winner(erica, bob):
dct = {'S':0, 'E':1, 'M':3, 'H':5}
erica_score, bob_score = 0, 0
erica_questions = collections.Counter(erica)
bob_questions = collections.Counter(bob)
for i in range(3):
if erica[i] == 'S':
erica_score += dct['S']
elif erica[i... |
0e63c7bf7243a0ded38ce2815e4560d0df5d4c49 | abhikrish06/PythonPractice | /CCI/CTCI_2_2_kth_last_frm_LL.py | 948 | 3.890625 | 4 | import unittest
class Node():
def __init__(self, data, next=None):
self.data = data
self.next = next
def kthNodeFrmLast(head, k):
if head is None or k < 1:
return None
leader = head
follower = head
for i in range(k):
if leader is None:
return None
leader ... |
ebdcca72fc6f89f816ea37e3aacf66d8c0d017d8 | abhikrish06/PythonPractice | /LC_n_Misc/LC_TR_Min_Dpth_BTree.py | 817 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
retur... |
2ed8f7ae1632f77b29f45076b503f4eda87a7e6b | abhikrish06/PythonPractice | /HR/HR_10D_D1_intr_qrtl.py | 899 | 3.640625 | 4 | import math
def cal_med(num):
#print(num)
n = len(num)
if n % 2 == 0:
return (int(num[(n // 2) - 1]) + int(num[(n // 2)])) / 2
else:
p = math.floor(n / 2)
return int(num[p])
if __name__ == '__main__':
#numbers = []
#frequency = []
final_list = []
... |
d0e9420c3d3b1c2123dbe67d99e60ca4aaaab9cf | abhikrish06/PythonPractice | /HR/HR_stu_scr_nst_lst.py | 575 | 3.921875 | 4 | # from operator import itemgetter
if __name__ == '__main__':
student_list = []
for _ in range(int(input())):
name = input()
score = float(input())
student_list.append([name, score])
# sorted(student_list, key=itemgetter(0))
# student_list.sort(key=itemgetter(1))
# ... |
5baf18e53a608ab4a932d1f97b1d3f7b330abd86 | abhikrish06/PythonPractice | /HR/HR_Py_Str_Rngoli.py | 543 | 3.703125 | 4 | # import string
#
# def print_rangoli(size):
# letter_dict = {}
# for i in range(size):
# letter_dict[i + 1] = string.ascii_lowercase[i]
# print(letter_dict)
# for i in range(size, 1, -2):
# for j in range():
# print(("-" * size) + letter_dict[i] + ("-" * size))
#
# pr... |
5d724e8bfdd9c2974394ff6e1c51fda801430dc5 | abhikrish06/PythonPractice | /HR/HR_Rookie_ServerRoomSafety.py | 1,428 | 3.71875 | 4 | #!/bin/python3
import sys
def checkAll(n, height, position):
# Complete this function
zip_h_p = list(zip(position,height))
# print(list(zip_h_p))
res, resl, resr = "", "", ""
for i in range(len(zip_h_p)-1):
if zip_h_p[i][0] + zip_h_p[i][1] >= zip_h_p[i+1][0]:
for j in range(i+... |
68bb787a93a631796b81ea41e1500a7f4238e9c2 | abhikrish06/PythonPractice | /HR/Twitter_Prime_In_Sbtree.py | 1,892 | 3.78125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the primeQuery function below.
def sieveOfEratosthenes(n):
"""sieveOfEratosthenes(n): return the list of the primes < n."""
if n <= 2:
return []
sieve = list(range(3, n, 2))
top = len(sieve)
for si in siev... |
0c344fa8c42ebe9f6dc6fe7811b850bdbd8e27d2 | erikkinding/adventofcode | /aoc2016/day17.py | 2,944 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import hashlib
class Day17:
def __init__(self):
self.passcode = ''
self.best_path = []
self.target = (3, 3)
self.skip_check_distance = False
self.paths = []
# Answer: DRDRULRDRD
def part1(self):
self.passcode = 'vwbaicqe'
sel... |
55da03dbc82ac7b21eba99ba214050c552176216 | erikkinding/adventofcode | /aoc2016/day23.py | 3,076 | 3.75 | 4 | # -*- coding: utf-8 -*-
import time
class Day23:
def __init__(self):
self.registers = {}
# parse instructions
self.instructions = []
self.get_instructions()
# Answer: 11004
def part1(self):
self.registers = {'a': 7, 'b': 0, 'c': 0, 'd': 0}
t0 = time.time(... |
7407fa3049479ad4e4cbebf3e9aead2d8461592c | rebbrunner/Queues-Stacks | /dequeue/dequeue.py | 2,016 | 3.96875 | 4 | #Dequeue Class
#Rebecca Brunner
#29 August 2018
#Implement Dequeue class
class Dequeue():
def __init__(self):
self.items = []
def pushFront(self, item):
self.items.append(item)
def pushBack(self, item):
self.items.insert(0, item)
def popFront(self):
return self.items.... |
fd305480c91af107219c3d96a59cd882579cc8b2 | Bijan-Massoumi/Algorithms-in-Python | /Elementary-Data-Structures/linked_list.py | 1,160 | 3.96875 | 4 |
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class List:
def __init__(self):
self.head = None
self.tail = None
def push_front(self, data):
if self.head == None:
self.head = Node(data)
self.... |
f2ebf39e5a30b46b536c1c65f11a16dfbb00ba84 | priitohlo/prog | /week5/kodu2.py | 3,231 | 3.515625 | 4 | from pykkar import *
import math
def get_input(message, type, max = 0):
if (type == 'M'):
while True:
try:
inp = int(input(message))
if (inp < 3):
raise Exception('lessthanthree')
elif (inp % 2) == 0:
raise ... |
1a1817b6bda36a0c0296bfdeb4394a2512b6b177 | priitohlo/prog | /lisa/lisa1.py | 1,515 | 3.640625 | 4 | import turtle
from random import randint
s = turtle.Screen()
t = turtle.Turtle()
idx = 0
with open('lisa/lisa1.txt', 'r', encoding='utf-8') as f:
for r in f:
try:
idx += 1
print(idx)
cmd = r.strip()
if cmd == 'mine_otse':
repeat = int(next(f... |
1e25833c1a1aa4a351497b326e1807bc3aa8b27d | zt4096/Beginner-Coding-Challenges | /question_marks_test.py | 427 | 3.84375 | 4 |
# Take an input string parameter and determine if exactly 3 question marks exist between every pair of numbers that add up to 10.
# If so, return true, otherwise return false.
s = '?a?b1236???4'
q = '???'
if q in s:
for i in s:
ix = int(s[s.find(q) - 1])
iy = int(s[s.find(q) + 3])
if ix + iy ... |
8fc231b9c85626a55e01bd274f97e5147408bba2 | MartinsAngers/EDIBO | /Python/python_script_time.py | 1,152 | 3.8125 | 4 | #! /usr/bin/python3.8
print("Ievadiet skaitli: ")
# a=2**2000000
#a=int( input() )
#if (type(a) == int):
# print("a**10000000")
# print("complete")
#if (a == 5):
# print(a**100)
#if isinstance(a, int): #works
# print(a**100)
# print("complete")
paziime = False
#Šie trīs ir derīgi varianti
#while paziime==False: ... |
1780e10830c017618f13f79de43c0b0cc983a2ed | pkgpl/gpl | /gpl/py/io.py | 1,541 | 3.53125 | 4 | #!/usr/bin/python
#
# Program :
# Date :
from numpy import *
### binary file input/output
# from_stdin
# from_bin
# to_bin
def from_stdin(n1=0,dtype=float32):
"""read an array from stdin, return a numpy array"""
from sys import stdin
s=stdin.read()
arr=fromstring(s,dtype=dtype)
try:
arr.shape=-1,n1
except:
... |
41ff7008af18b7623f3ea3ecadcae2e4dd1fd505 | shawnwanderson/Python201CodeSnippets | /countWordsDefaultDict.py | 445 | 3.640625 | 4 | from collections import defaultdict
import argparse
default_sentence = "hey checkout this cool default sentence"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-w")
args = vars(parser.parse_args())
sentence = args['w'] if args['w'] else default_sentence
words = sentence.split(... |
3dcb01dd3114066d514d3b2d27ec55d208720a0d | soloasiedu/PythonBeginnerProjects | /degreesToFahrenheit.py | 167 | 4.09375 | 4 | temp = float(input("Enter temperature in degree celsius"))
fahrenheit = (1.8 * temp) + 32
print(str(temp) + " degree celsius is " + str(fahrenheit) + "fahrenheit")
|
f1f1fd4d16594e37e238ae1d570af66cfa1f0543 | hillshadow/time_series_recognition | /storage/save.py | 1,843 | 4.09375 | 4 | # coding: utf-8
"""
:author: Philippenko
:date: Juil. 2017
This module is devoted to conveniently save the different manipulated data.
In particular : the list, the double-list or the segments.
"""
import csv
import pickle
def save(data, filename):
"""
Saves any type of data in txt file using... |
5efa5ba0708c0383c74988a47a9be6f09fa6fc70 | enderquestral/Reed-CSCI121 | /Week7/sum_power2.py | 129 | 3.640625 | 4 | def sum_power2(n):
if n ==0:
return "1"
return ( "(" + str(sum_power2(n-1)) + "+" + str(sum_power2(n-1)) + ")")
|
c6bd89b9caf193c482b849660c0f5f5aa3950155 | enderquestral/Reed-CSCI121 | /menu.py | 827 | 3.984375 | 4 | restname = input("Restaurant name? ") #Remember: menu is 40 columns wide
item1name = str(input("First entree? "))
item1price = str(input("First entree price? "))
item2name = str(input("Second entree? "))
item2price = str(input("Second entree price? "))
item3name = str(input("Third entree? "))
item3price = str(input("Th... |
f59dbdaf06e9e9986100df7c8311a0a0f89d3cd7 | enderquestral/Reed-CSCI121 | /Week10/DLinkedList.py | 5,278 | 3.75 | 4 | class DLLNode:
def __init__(self,value):
self.value = value
self.next = None
self.prev = None
class DLinkedList:
def __init__(self):
self.first = None
self.last = None
#Write the prepend, append, and remove methods of DLinkedList so that they modify both next and prev
... |
570bc3391c4ad115804f67cc3c1a1f34b8a5455e | enderquestral/Reed-CSCI121 | /Week5/has_duplicates.py | 626 | 3.671875 | 4 | #takes a list xs and determines whether some value appears more than once.
#It should return True if so, and False if there are no reoccurring values. Note that the list xs could be empty.
#consider strings? bools?
def has_duplicates(xs):
newlist =[]
if len(xs) >1:
x = 0
while x < len(xs):
... |
9862091f38013712981cc8c4667498a468bc0d81 | enderquestral/Reed-CSCI121 | /Week6/Week 6 Notes:Example Code/rational_as_list.py | 852 | 3.75 | 4 |
def createRational(n,d):
return [n,d]
def numerator(r):
return r[0]
def denominator(r):
return r[1]
def sameRationals(r,s):
nr = numerator(r)
dr = denominator(r)
ns = numerator(s)
ds = denominator(s)
return (nr * ds == ns * dr)
def outputRational(r):
n = numerator(r)
d = den... |
4e7ea26e414c08bc16fcbdcee7b162da16b28d31 | enderquestral/Reed-CSCI121 | /Hawkdove project/hawkdove.py | 12,045 | 3.890625 | 4 | import random
import tkinter
random.seed()
def plot(xvals, yvals):
# This is a function for creating a simple scatter plot. You will use it,
# but you can ignore the internal workings.
root = tkinter.Tk()
c = tkinter.Canvas(root, width=700, height=400, bg='white') # Was 350 x 280
c.grid()... |
b4012787b8a93e832cfae65fe6cf0d735ad8fb0b | enderquestral/Reed-CSCI121 | /project1/greed.py | 31,122 | 4.28125 | 4 | import random
import math
import pr1testing
random.seed()
# CSCI 121 Fall 2017
#
# Project 1: Game of Greed starting code.
#
# See the project description on the web.
#
# You can play an game of Greed with an opponent by running
# something like the following in the terminal:
#
# python3 -i greed.py
# >>> p... |
89b896ca702f2ae6943ebcf6959cb4b0b8c596bc | Cheget/python | /1stLession/2.py | 291 | 3.984375 | 4 |
inputed_seconds = input('Введите время в секундах: ')
print(f'Вы ввели: {inputed_seconds}')
seconds = int(inputed_seconds) % 60
minutes = (int(inputed_seconds) // 60) % 60
hours = int(inputed_seconds) // (60*60)
print(f"Время {hours}:{minutes}:{seconds}") |
1fd7e4b19ab0908604978c13d2b365002abb9060 | NathanielOy/EOSA-NAS-Auto-CNN-Design-for-Digital-Histology-Images | /testplots.py | 986 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 14 10:37:41 2021
@author: 77132
"""
# importing libraries
import matplotlib.pyplot as plt
import numpy as np
import math
# Get the angles from 0 to 2 pie (360 degree) in narray object
X = np.arange(0, math.pi*2, 0.05)
# Using built-in trigonometric f... |
5495d2a08dc18021ac22deaf1e774ebc0c8190aa | Alichegeni/tamrin-jalseh5 | /tamrin3-5.py | 601 | 3.828125 | 4 | import turtle
import time
import math
pi = math.pi
colors = ['red', 'blue', 'yellow', 'green', 'purple', 'orange']
win = turtle.Screen()
pen = turtle.Pen()
pen.shape('turtle')
x = -20
size = 100
for i in range(1, 7):
for j in range(i+2):
pen.forward(size)
pen.lef... |
5502403c52ea745b0fcd823e676e6c91e7aeb450 | babdenour/Python | /FacPython/TD2/td2ex6.py | 547 | 3.90625 | 4 | #coding: utf-8
#division euclidienne
dividende = input("entier positif ou nul (dividende) : ");
dividende = int(dividende);
diviseur = input("entier strictement positif (diviseur) : ");
diviseur = int(diviseur);
if ((diviseur != 0 and dividende >= 0)):
quotient = dividende // diviseur;
reste = dividende ... |
33647b321134ce23c44179e420fcaa328f3948b1 | babdenour/Python | /FacPython/TD6/td6ex4.py | 471 | 3.71875 | 4 | #coding: utf-8
import turtle;
#screen init
screen_width = 800;
screen_height = 600;
turtle.setup (width=screen_width, height=screen_height);
#moving
turtle.up();
turtle.goto(-200,0);
turtle.down();
#draw
for i in range(0, 8, 1):
turtle.forward(100);
turtle.left(90);
turtle.forward(40);
turtle.right(90... |
b1f496ce6d71a98cdeb6f618885ecabc073a8f8e | babdenour/Python | /FacPython/TD3/td3ex7.py | 215 | 3.75 | 4 | #coding: utf-8
#somme des entiers
nb1 = int(input("Donner le premier entier: "));
i = 0;
somme = 0;
n = 0;
while (n != 0):
print("Donner l'entier suivant");
print("La somme des entiers saisis est de ", somme); |
b1581c3beab7c9c20fa430a6ad7e558754cfab01 | Aranh4/EP2-AC | /Movimentospossiveis.py | 490 | 3.625 | 4 | import ExtraiNaipe
import EXTRAIVALOR
def lista_movimentos_possiveis(baralho,i):
movimentos = []
if i == 0:
return movimentos
if extrai_valor(baralho[i]) == extrai_valor(baralho[i-1]) or extrai_naipe(baralho[i]) == extrai_naipe(baralho[i-1]):
movimentos.append(1)
if i>=3:
i... |
51e76c95acd1187460bee1b3f6cd12cf3e1a1845 | ceshihao/leetcode | /python/merge_sorted_array.py | 681 | 3.65625 | 4 | class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing
def merge(self, A, m, B, n):
ia = m - 1
ib = n - 1
index = m + n - 1
while ia >= 0 and... |
076614579cdc9a97487097d2c255e8c054d2ee6a | abirjameel/Artificial_Intelligence_8_puzzle | /driver_3.py | 11,169 | 3.59375 | 4 | import queue as Q
import time
import resource
from heapq import heappush, heappop, heapify
import sys
import math
#### SKELETON CODE ####
## The Class that Represents the Puzzle
class PuzzleState(object):
"""docstring for PuzzleState"""
def __init__(self, config, n, parent=None, action="Initial", cost=0, k... |
a83d1d8eccb744206995bf4979ef51e69e2f652a | guillesiesta/advent_of_code_2020 | /day4/part2_d4.py | 2,166 | 3.671875 | 4 | import re
# abrir y leer archivo
f = open ('input.txt','r')
mensaje = f.read()
f.close()
# he visto en internet que con esto divides por los espacios en blanco
# funciona
output = mensaje.split('\n\n')
# elimino el \n de todos los elementos de la lista
passports = [i.replace('\n',' ') for i in output]
... |
555e792f5150171ad1dfdd1ed4715b8bcd0b13da | alex-straw/FCP_project | /covidsim/transmission.py | 6,120 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tues Apr 6 12:25:03 2021
Author: Alex Straw
Description:
This piece of code receives the 'people' object and interactions for a given step.
Contagious interactions where one individual has COVID-19 and the other does not are
extracted from this data. Transmission cha... |
7604ff97b36b47de6637d50185ed5c7251c0874a | syahdeini/extreme_computing | /assigment1/task3/mapper.py | 352 | 3.59375 | 4 | #!/usr/bin/python
import sys
def find_max_token(line):
len_max = 0
for token in line.split():
len_token = len(token)
if len(token) > len_max:
len_max= len(token)
return len_max
for line in sys.stdin:
line = line.strip()
print("{0}\t{1}".format(l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.