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 |
|---|---|---|---|---|---|---|
8f0ee10d0d9a1cf6cd73c9c16606062ce364aa07 | cmstas/NtupleTools-run1 | /dataTuple/getDirName.py | 331 | 3.625 | 4 | import sys
def find_nth(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
input = sys.argv[1]
start = find_nth(input, "/", 4)
end = find_nth(input, "/", 5)
reduced = input[start+1:end]
pri... |
aab1cf22009e8ff08dca39dd9ea5fbf56f1f8b3b | havefuncoding/Leetcode | /Python/5_longest_palindromic_substring.py | 1,364 | 3.71875 | 4 | class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest = "" # Keep track of longest substring
for i in range(len(s)): # Iterate each char in string using indices
curr = self.getL... |
0a87bbce8c8dd17e27d0bcdb239bf2933fce8f5b | aaravzen/DominFUN | /playercontrollers/big_money_bot.py | 946 | 3.546875 | 4 | from player_controller import PlayerController
class BigMoneyBot(PlayerController):
"""This is a simple bot that buys provinces/golds/silvers in that order when it can.
Actions are for the weak and nimble-minded. The face hunter of Dominion.
gg ez no re"""
# def pick_action(self, action_card... |
d6e6a549ca0469670ed0c00d9db65b1dffeee3e6 | Easybuoy/Sorting | /src/recursive_sorting/recursive_sorting.py | 1,066 | 4.09375 | 4 | # TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge(arrA, arrB):
# elements = len( arrA ) + len( arrB )
merged_arr = []
# TO-DO
while len(arrA) and len(arrB):
if(arrA[0] <= arrB[0]):
merged_arr.append(arrA.pop(0))
else:
merged_arr.append... |
0e4343ece7a4f3e8e7fce36bec0ca448abfcad52 | SiaJAT/cs378_p2 | /stereo.py | 6,136 | 3.5 | 4 | """Project 2: Stereo vision.
In this project, you'll extract dense 3D information from stereo image pairs.
"""
import cv2
import math
import numpy
def rectify_pair(image_left, image_right, viz=False):
"""Computes the pair's fundamental matrix and rectifying homographies.
Arguments:
image_left, image_... |
9ef464633983bd1c71ed5bb0d9766847c36e70e3 | zhongchaocheng/handwritten_numeral_recognition | /getFeature.py | 504 | 3.609375 | 4 | #提取手写数字位置
import numpy as np
def GetFeature(image):
img_array = np.array(image.convert('1'))
img_array = ~img_array
for i in range(32):
for j in range(32):
if img_array[i, j] == True:
print('1', end='')
else:
print('0', end='')
... |
f41d969f2435283b33c2c90858b752a7fe9a432a | SeongHyeonShin/programmers | /Greedy/큰_수_만들기.py | 655 | 3.609375 | 4 | # Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from collections import deque
def solution(number, k):
answer = deque(number[0])
for num in number[1:]:
while len(answer) and answer[-1] < n... |
bf20a71042ee8d5d9571be575c7aa1a095d58d1c | SeongHyeonShin/programmers | /스택_큐/프린터.py | 903 | 3.671875 | 4 | # Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from collections import deque
def solution(priorities, location):
sorted_pr = deque(sorted(priorities, reverse=True))
data = deque([[priorities[i], 1... |
0f5fe36f535273479c42ec5ebd34fb89bc1d7a22 | achuthanandGit/aderant-code-test-solution | /helper_fun.py | 1,747 | 4.0625 | 4 | import itertools
def overlap(arg_one, arg_two, min_length):
""" Return length of longest suffix of 'arg-one' matching a prefix of 'arg_two',
and the prefix is at least "min_length" characters.
If there is no such overlap, 0 is returned.
"""
start = 0
while True:
start = arg_on... |
77382e8831feff8d7850ae33b0115f5a5c5d2618 | leomrocha/sudoku | /sudoku/file_helpers.py | 1,087 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def parse_csv_from_text(csv):
"""
parse input and add it to an array of arays
"""
puzzle = [ [int(i.strip()) for i in j.split(',')] for j in csv.split()]
#verify dimension consistency
for c in puzzle:
assert len(puzzle) == len(c)
... |
d1a0c3a247942930a8c0bffef448db26a4006b48 | subiczadrian/python | /format/opera.py | 58 | 3.515625 | 4 |
print(5%2)
print(2**5)
szam=5
print(szam>3 or szam>5)
|
3ff9d2615107b992018fbe4a479ff08ee952d255 | dmitry-sumarokov/ASM.19.Lab1 | /asm1905/st14/Edit.py | 963 | 4 | 4 | class Edithuman:
def __init__(self):
pass
def edit(self):
print('Если не хотите менять судьбы людей, нажмите Enter животворящий')
new_name = input('Введите новое Имя (человек побегает по МФЦ): ')
self.name = new_name if new_name else self.name
new_race = input('... |
6b0a49b4c85990bbf6890912e574bbf425c59b0b | calebshortt/launch-calculator | /engine/base.py | 7,090 | 3.515625 | 4 |
import math
class CalculatorParameterException(Exception):
pass
class LaunchCalculator(object):
# ---------------------------------------------------------------------------------------------------------
# NOTE: ALL values are in standard units (kilometers, meters, etc)
# -----------------... |
eaff36013adac8a183672871f5f8a5ce841bbc64 | VENUJAN/code17 | /factnumber.py | 147 | 3.875 | 4 | v = int(input("enter the number"))
rev = 0
while( v>0)
rem = num % 10
rev = (rev *10)+rem
v = v//10
print("revers of enter the number is" revers)
|
58d34d94f58f56f4c1e8dbf9d3b8a97d23ed8e0e | Ry09/Python-projects | /Random Stuff/collatz.py | 1,142 | 4.65625 | 5 | # This is a program to run the Collatz Sequence. It will
# take a number from the user and then divide it by 2 if
# it is even, or multiply by 3 and add 1 if it is odd. It
# will loop through this until it reaches the value of 1.
def collatz(num):
try:
num = int(num)
print(num)
if num == 1:... |
d9b3fc04b94173f130bf85f46c84a138222965c1 | Ry09/Python-projects | /Programs & Challenges from Python for beginners book/Chapter 2/wordProblems.py | 1,208 | 3.84375 | 4 | #Program using word problems to demonstrate math and number operators
print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,")
print("but then eats 50 pounds of food, how much does she weigh?")
input("Press the enter key to find out.")
print("2000 - 100 + 50 = ", 2000 - 100 + 50)
print("\nIf an advent... |
833fb3231c9c1f91731d611f7523743e3997b4f5 | blandarch/area-shapes | /AreaShapes.py | 1,316 | 3.703125 | 4 | class triangle:
def __init__(self, base, height):
self.b = int(base)
self.h = int(height)
def comp_area(self):
ans = (1/2)*self.b*self.h
return ans
class rectangle:
def __init__(self, length, width):
self.l = int(length)
self.w = int(width)
def comp_area(... |
4cc2f1cd290a5d26840b9fbe9dcdd0aefa5d41c3 | Linazuban/be-qa-today-1 | /test 3.py | 218 | 3.703125 | 4 | class Human:
class Student:
def _init_(self, name):
self.name = name
def say_hello(self):
print("Say hello"+self.name)
student_Dima = Student("Dima")
student_Dima.say_hello()
|
27b2ec90967be7792f5e23ded1ba061661c97026 | benWindsorCode/signalGenerator | /signal_generator/condition/expression.py | 2,243 | 3.71875 | 4 | from expression_type import EXPRESSION_TYPE
class Expression:
def __init__(self, text: str):
self.text = text
self.value_1, self.expression_type, self.value_2 = self.process()
# e.g. for price > 50, return three values: 'price', 'GT', '50'
# Assume an expression is only three words?
d... |
afff95be5a3b323ddc88ea6ff4cdc62200e38d48 | CodecoolBP20172/pbwp-1st-si-game-inventory-weiliya | /gameInventory.py | 3,180 | 4.1875 | 4 | # This is the file where you must work. Write code in the functions, create new functions,
# so they work according to the specification
import csv
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
added_items = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
order = ""
# Di... |
ac538fa827775d549b3628fca67cd4e77592f10f | delabere/Skin-Tracker-FlaskApp | /comparison_logic.py | 3,053 | 3.578125 | 4 | import random as rnd
items = {}
items[1] = [6, 0]
items[2] = [5, 0]
items[3] = [4, 0]
items[4] = [3, 0]
items[5] = [2, 0]
items[6] = [1, 0]
new_items = {}
# sorting for new items
def newSorter(key):
items[key] = [0, 0]
octile = list(items)[int(len(items) * 0.125)] - 1
if octile == 0:
octile += ... |
c5184214e0daa2623467ba19929296893138d682 | denis-meshcheryakov/Learn_python_lesson_1 | /dicts.py | 308 | 4.1875 | 4 | dict1 = {"city": "Москва", "temperature": "20"}
print(dict1['city'])
dict1['temperature'] = int(dict1['temperature']) - 5
print(dict1)
if 'country' not in dict1:
print('country is not in keys')
print(dict1.get('country', 'Россия'))
dict1['date'] = '27.05.2019'
print(len(dict1))
print(dict1)
|
91d0d2793f8d07fb9b803b137784eddc16447c59 | session-id/mixtape-evaluator | /data-retrieval/chart_scraper.py | 717 | 3.53125 | 4 | import billboard
import datetime
# Gets all charts between the specified start and end dates.
# Start date must be a Saturday.
def get_charts(chart_name, start_date, end_date):
print('Getting charts...')
charts = []
# Scrape every week from start to end
cur_date = start_date
while (cur_date <= end_date):
... |
956e970048e8fcc7127735d33242fb2f2051c81d | HelenaMieszczak/Python_course | /code_me_5/zad9.py | 679 | 3.78125 | 4 | # Napisz grę ciepło - zimno tak, aby korzystać z funkcji.
import random
def users_win():
if users_num == comp_num:
return True
else:
return False
def comp_win():
if (counter == 6) and (comp_num != users_num):
return True
else:
return False
comp_num = (random.randi... |
0573e62a16be936b1c7fa95d3c48b86b70269269 | HelenaMieszczak/Python_course | /code_me_4/zad8.py | 424 | 3.71875 | 4 | # Utwórz listę zawierającą wartości słownika, bez duplikatów.
#
# >>> days = {'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sept': 30}
days = {'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sept': 30}
v_list = days.values()
new_list =... |
17271ed8ea0cc6e26ddcf5715e7cb0298270946a | HelenaMieszczak/Python_course | /code_me_4/zad7-todo.py | 370 | 3.65625 | 4 | # Napisz skrypt, który podaną listę podzieli na 3 równe listy i odwraca każdą z tych.
# input: [1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24]
# output:
# [4, 3, 2, 1]
# [14, 13, 12, 11]
# [24, 23, 22, 21]
#
numbers = [1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24]
new_numbers = []
for i in numbers:
new_numbers.append(0... |
83832ba1b4a2bd82288514013be2ce4f3e0971bc | HelenaMieszczak/Python_course | /code_me_8/zad3.py | 456 | 3.796875 | 4 | # Stwórz moduł, który przechowuje wzór na deltę. Skorzystaj z wbudowanego modułu math. W nowym pliku wykorzystaj moduł.
import delta
a = int(input("Podaj wartość a: "))
b = int(input("Podaj wartość b:"))
c = int(input("Podaj wartość c: "))
def main():
outcome = delta.count_delta(a, b, c)
if delta.check_delt... |
a66ae9ee61aa3c9e1c7e60d2669cf398f72f4ed1 | HelenaMieszczak/Python_course | /code_me_5/zad4.py | 378 | 3.890625 | 4 | # Napisać funkcję, która wypisze wszystkie parzyste z przekazanej listy elementów (wykorzystać funkcje z pkt 2)
def even_list(numbers):
return even_numbers
numbers = input("Podaj dowolne liczby: ")
numbers = numbers.split()
even_numbers = []
for n in numbers:
n = int(n)
if n % 2 == 0:
even_num... |
da76e80374d377896fe65324272653613f48ec5f | HelenaMieszczak/Python_course | /code_me_2/zad3.py | 232 | 3.65625 | 4 | #Stwórz dwie zmienne s1 i s2 przechowujące dowolne wyrazy, utwórz nowy łańcuch s3, dołączając s2 w środku s1.
s1 = input("słowo 1 = ")
s2 = input("słowo 2 = ")
mid = len(s1) // 2
s3 = s1[mid:] + s2 + s1[:mid]
print(s3) |
ba085a3285e85c3e112e670fa1b7b18dafce44f1 | ontheus3/aci-python | /Strings/string.py | 1,608 | 3.828125 | 4 | import os
os.system('cls')
# => prints This is simple quotes - "Really?"
print('This is simple quotes - \033[1;32;40m"Really?"')
# => prints Double quotes inside "double" quotes
print("Double quotes inside \033[1;31;40m\"double\" quotes")
# => prints Single quotes inside 'single' quotes
print('Single quotes inside \03... |
dafbc4213e02601a465414c12a526bb58772e6fb | ontheus3/aci-python | /Exceptions/exceptions.py | 672 | 4.0625 | 4 | import os
os.system('cls')
num1 = int(input("Enter a number >> "))
num2 = int(input("Enter another number >> "))
while True:
if num2 == 0:
print("Invalid entry")
num2 = int(input("Enter another number >> "))
else:
break
division = round(num1 / num2, 2)
print(f'''
Division is {division... |
8dd4dd31bbd1010013f48e5e446e2d19032a3b55 | Julialva/HowToSnake | /pokemons.py | 1,682 | 3.578125 | 4 | class Pokemon(object):
def __init__(self, nome ='',id=None):
self.nome = nome
self.id = id
self.golpes = []
def atribui_hp(self,health_points=39):
self.hp = int(health_points)
def atribui_at(self,attack_points=52):
self.at = int(attack_points)
def atribui_df(self,... |
7c369fcf4710b134b7437724685698895b2f50aa | ProgFuncionalReactivaoct19-feb20/clase03-Jdesparza | /Ejercicio3.py | 624 | 4.125 | 4 | """
Ejemplo 7
Jdesparza
Funcional - Aplicando función filter
Dadas las siguiente ciudades, filtrar aquellas que tienen un número par como longitud en sus caracteres.
Loja, Pichincha, Guayaquil, Zamora, Ibarra, Manabi, Machala, Portoviejo, Macas
"""
# se crea una lista con las ciudades
ciudades = ["Loja", "Pich... |
6af667beba298184c447008cfbf034efccd39ae6 | hans/langdetect | /nodule_features.py | 2,378 | 3.546875 | 4 | """Defines nodule-level feature extractors.
All feature extractors are functions which accept arguments
cur_segments, segments_by_feature, prev_nodule
and return a dictionary mapping from new feature keys to new feature
values.
`cur_segments` is a list of `Segment` tuples. `segments_by_feature` is a
dict mappin... |
32871cad8f6e2d852105b9c8bff0e94624a0b79c | hahaharshil/Tkinter | /Calculator/1.1(main).py | 994 | 3.5625 | 4 | from tkinter import *
def add():
res = float(e2.get()) + float(e1.get())
myText.set(res)
def sub():
res = float(e1.get()) - float(e2.get())
myText.set(res)
def div():
res = float(e1.get()) / float(e2.get())
myText.set(res)
def multi():
res = float(e1.get()) * float(e2.get())
myText.... |
24e622895360f03a66612436b5afb10d8df7980c | default-boring-name/python_2021 | /turtle_1/Task_11.py | 175 | 3.5 | 4 | import turtle as trl
trl.speed(0)
trl.shape('turtle')
trl.setheading(90)
r = 50
n = 15
dr = 8
for i in range(n):
trl.circle(r)
trl.circle(-r)
r += dr
input()
|
927170aae55b2529e503f3e1836cd0ac6d18516b | rayadamas/pythonmasterclassSequence | /coding exercise 14.py | 662 | 4.21875 | 4 | # Write a program which prompts the user to enter three integers separated by ","
# user input is: a, b, c; where those are numbers
# The following calculation should be displayed: a + b - c
# 10, 11, 10 = 11
# 7, 5, -1 = 13
# Take input from the user
user_input = input("Please enter three numbers: ")
# Sp... |
df8593af0c7d47c016af5585d1fbabd05c345f03 | alex10gauthier/PepperEncrypt | /Client.py | 1,461 | 3.734375 | 4 | # This is the skeleton class for the interface that will run the program for the user.
from User import User
from UserData import UserData
from Encrypter import Encrypter
from EncryptedData import EncryptedData
from Decrypter import Decrypter
class Client:
def __init__(self, online):
self.online = onlin... |
4c693ae454ec3c65f5e45256a93c8415ef46dc9e | liuqianjin/python_exercise | /数据库/学生管理系统.py | 3,961 | 3.84375 | 4 | import sqlite3
# 链接数据库,数据库名字是 mrsoft.db,没有就会创建
conn = sqlite3.connect('mrsoft1.db')
def menu(): # 菜单,显示主界面
print("-" * 30)
print("""
学生管理系统
1.添加学生信息
2.删除学生信息
3.修改学生信息
4.查询学生信息
5.显示所有信息
6.退出系统
""")
print("-" * 30)
def create_info():
# 创建cursor
... |
25154c8053231cf7ee16b49d657b3f72a861ab88 | liuqianjin/python_exercise | /函数/匿名函数.py | 492 | 3.609375 | 4 | # 获取的某商场的商品信息,保存在列表里面。进行排序,按照秒杀金额升序排列,有重复的,按照折扣比例降序排列
# 第一个是秒杀价,第二个是原价
bookinfo = [('不一样的卡梅拉',22.50,120),('零基础学python',65.10,89.90),
('摆渡人',23.4,36.00),('福尔摩斯全集',22.50,128)]
print('原来的信息:',bookinfo,'\n')
bookinfo.sort(key=lambda x:(x[1],x[1]/x[2]))
print('排序后的顺序:\n',bookinfo)
|
18dc7b492ddbd00dd4508dd3fbe157a32c8999c8 | s-andromeda/Design-5 | /Problem2.py | 1,238 | 3.609375 | 4 |
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
"""
Name : Shahreen Shahjahan Psyche
Time : O(N)
Space: O(N) [the hashmap]
Passed all the test... |
80240b2c2f119c62b0cb97d62c24a7b5cf673fe2 | tonyktliu/Excel_filtering_by_prefix | /scanning.py | 3,920 | 3.515625 | 4 | import csv
import openpyxl as xl;
import sys
from openpyxl.styles import Font
# This program converse the source file from CSV to XLSX. Extract rows when the prefix of particular cells matches with the Keywords.
# ===============Variables for the script=================#
targetExcel = "Test_Output.xlsx"
pref... |
ec3f0567d8595d7dc3a8b3cd5cf5fddda8f1342a | jinyoungch0i/learning_python | /3- Integers and Floats - Working with Numeric Data.py | 3,251 | 4.625 | 5 | # Arithmetic Operators:
# Addition
print(3 + 2)
# Subtraction
print(3 - 2)
# Multiplication
print(3 * 2)
# Division
print(3 / 2)
#returns: 1.5
# Floor Division (drops the decimal)
print(3 // 2)
#returns: 1
# Exponent (x to the power of y)
print(3 ** 2)
# returns: 9
# Modulus (to get the remainder after a division... |
9cfbad24ec9c22d063a92b4ef1d27d705f0b1171 | barzgara71961/Quiz | /04_page.py | 15,357 | 3.625 | 4 | from tkinter import *
from functools import partial # To prevent unwanted windows
import random
class Quiz:
def __init__(self):
# Formatting variables...
background_color = "#8FF7A7"
btn_color = "#51BBFE"
font_color = "black"
self.quiz_frame = Frame(width=500, height=50... |
8d6cd4a0e4b1213259acdace09b556d5872f3fc3 | fengqiang2008/mywork | /game001.py | 8,280 | 3.578125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#作者:Ferminal
#功能:射击类游戏
#说明:第一个python程序游戏
#1 - Import library
#Import random library, using random functions;导入random库,使用随机功能
import random
#Import math library, the use of mathematical functions;导入math库,使用数学函数功能
import math
import pygame
from pygame.locals import *
#2 - ... |
40be12d94695d57c867338f18b2a4d8070dfb2f8 | inkoon/CSE6428 | /Tabular_Parser/get_grammar.py | 841 | 3.609375 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True, type=str)
parser.add_argument("--output", default="grammar.txt", type=str)
args = parser.parse_args()
grammar_list = [] # grammar list
with open(args.input, "r") as f:
for line in f:
line = line.strip()
... |
8caf879fc187746ffd4d660bad5e0b82ec2e12a2 | AmaBayar/Amar | /count.py | 794 | 4.03125 | 4 | print('####Counting by 2####')
while True:
myName = input('your name?').capitalize()
if len(myName) <= 10:
break
else:
print("Too long! Try again")
if myName.isdigit():
print ("Not a name and you smell bad! GoodBye")
restart_program()
else:
print ("Hello " + myName)
while Tru... |
fa51b27924f4eb4eb0c79f04eff68a0f69e25a71 | Amsahari/Exploratory-data-analysis-in-Python | /WHO_stats.py | 2,492 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[119]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb
from scipy.stats import norm
# In[120]:
df = pd.read_csv('F:\WHO_stats.csv')
df.dtypes
# In[122]:
#To find out whether all the columns have values
df.count()
# In[12... |
80a145648281ecd3850dc565e6baf3da0e49f018 | layc41/us-states-game | /main.py | 1,173 | 3.96875 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
NUMBER_OF_STATES = 50
tim = turtle.Turtle()
tim.hideturtle()
states_data = pandas.read_csv("50_states.csv")
LIST_OF_STATES = states_data.state.to_list()
guesses... |
34cb14701b5e7d548f47c3a27b67d2ac07a50d7d | hatchingline/JetBrainsAcademy_Coffee-Machine | /Problems/Healthy sleep/task.py | 185 | 3.703125 | 4 | sleep_a = int(input())
sleep_b = int(input())
sleep_h = int(input())
if sleep_h < sleep_a:
print("Deficiency")
elif sleep_h > sleep_b:
print("Excess")
else:
print("Normal")
|
14d322c9a043dd9a7994082a2a4647f4e7266c67 | thomaspara/sortinghattask2 | /in.py | 266 | 3.53125 | 4 | #merged with task two
#increments the current number for the dataset list
import pandas as pd
df = pd.read_csv("./current_num.csv")
num = df['curr'][0] + 1
df['curr'] = num
print(num, "of", 263)
print(263 - num, "left")
df.to_csv("./current_num.csv", index=False)
|
a6428c1a70d4c0b13a7e7a59cb5f572c7636f572 | cha63506/Archive-132 | /MEAnalysis/gc/grid-control/packages/python_compat.py | 2,665 | 3.5625 | 4 | try: # str.rsplit >= Python 2.4
rsplit = str.rsplit
except:
def rsplit(x, sep, maxsplit = None):
""" Split from the right side
>>> rsplit('abc', '.', 1)
['abc']
>>> rsplit('a.b.c.d.e.f.g', '.', 1)
['a.b.c.d.e.f', 'g']
>>> rsplit('a.b.c.d.e.f.g', '.', 2)
['a.b.c.d.e', 'f', 'g']
"""
tmp = x.split(sep)... |
b34ebf20cab9bfbdc8fe09bee908251382610276 | JordanPottruff/ml-neural-nets | /src/centers/knn.py | 3,414 | 4.1875 | 4 | # knn.py
# Implementation of the K-nearest neighbor algorithm.
import src.util as util
# The implementation of the K-nearest neighbor algorithm. Given a test example in the "run" method, it will find the k
# nearest neighbors to that test example found in the training data.
class KNN:
# Creates an instance of th... |
f951360be8ab3a1dae211d93ea399f8502241ed5 | hesambeigy/cscircles | /Spy Coder.py | 385 | 3.578125 | 4 | n = input()
s = int(input())
def spyCoder(n,s):
a = []
for i in range (0,len(n)):
if (ord(n[i])+s)>= 90 or ord(n[i]) >= 90:
code = n.replace(n[i],chr(s+ord(n[i])-90+64))
a.append(code[i])
elif n[i] == ' ':
a.append(n[i])
else:
code = n.replace(n[i],chr(s+ord(... |
cf93e0cb33806575771b377f0b70684f14e32180 | DecisionNeurosciencePsychopathology/defeat_task | /snake3.py | 4,354 | 3.6875 | 4 | #!/usr/bin/python
from Tkinter import *
from random import randrange
def recoupeQ():
'''Go through the length of the snake and update its position'''
global x, y, snake, flag
i = 0
while i < len(snake):
tmp = snake[i]
if (tmp[0] == x) and (tmp[1] == y):
break
i += ... |
6f4912aef50c0316df4906eb9edbf3bc997f34a1 | surprise777/StrategyGame2017 | /Strategy/stonehenge.py | 12,952 | 3.984375 | 4 | """module: stonehenge game, with a class of game and a class of gamestate
"""
from typing import Any, List
from game import Game
from game_state import GameState
class StonehengeGame(Game):
"""a class representing a game called Stonehenge, a subclass of Game.
Cannot write example since class needs input.
... |
a6c5cc0f90f540202efa1c8f6b1098d99c3c4397 | surprise777/StrategyGame2017 | /Game/current_state.py | 1,959 | 4.3125 | 4 | """module: current_state (SuperClass)
"""
from typing import Any
class State:
"""a class represent the state of class.
current_player - the player name who is permitted to play this turn.
current_condition - the current condition of the state of the game
"""
current_player: str
current_condit... |
63a268de4f161a1616ff1d587e81a2e4e2ba334e | Selimcse98/BASE64_DECODE | /BASE64_DECODE.py | 813 | 3.59375 | 4 | import base64
import time
print ('''
This is a very basic python program to decode base64 encoded data.
With it you can see JWT info sent by the ALB to the targets.
All you need to do is to copy and paste the base64 string and
put into the box below and the decoder wo... |
ba2cd170e4f0530a83076eb1524e244889921079 | swativishnu/swati_demo_repo | /DataTypes/list_introduction.py | 5,724 | 4.0625 | 4 | # """
# append insert extend copy count ,pop,clear, reverse, sort, index
# """
# list1 = [1, 2, 3, 4, 5]
# print(list1)
# #list1.append([7, 8])
# print(list1)
# list2 = [344, 56, 78, 7880]
# list1.extend(list2)
# print(list1)
# count_of_list = list1.count(1)
# print(count_of_list)
# # index returns index of element
#... |
a863576112628bb9de1094aaedf57c9a8f1945b1 | Zai-Lucas/Work | /HangMan.py | 841 | 4 | 4 | myWord = "panda"
myList = list("_____")
Miss = ("b""c""e""f""g""h""i""j""k""l""m""n""o""q""r""s""t""u""v""w""x""y""z")
MissList = list("-----------------------")
while True:
choice = input("Type a word: ")
if choice == myWord:
print("That is the correct Word")
print("Congrats, You Win!")
break
el... |
ec1401ea95518fcb2f06f086edf5336019e5978f | mateusgomesc7/webscraping | /estadosBrasileiros.py | 1,100 | 3.546875 | 4 | # Fonte: https://goomore.com/blog/web-scraping-python/
from bs4 import BeautifulSoup
import requests
wiki = "https://pt.wikipedia.org/wiki/Lista_de_capitais_do_Brasil_por_%C3%A1rea"
html = requests.get(wiki).content
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table', class_='wikitable sortable')
... |
4a678d7dcf13fdcad8dc42a2dfb5ce8e3939a4dc | mohandev4066/milestone1 | /string_generate.py | 224 | 3.578125 | 4 | import string
import random
N = 10
res = ''.join(random.choices(string.ascii_uppercase +string.ascii_lowercase +
string.digits +string.punctuation, k = N))
print("The generated random string : " + str(res))
|
489898028371804fdffaca694c40954b3bf2a441 | rohitmendus/rock-paper-scissor | /code.py | 8,024 | 3.75 | 4 | from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import random
#Creating the RPS class
class RPS:
#set up the window
def __init__(self, master):
self.master = master
master.config(bg = "green")
master.title("Rock..Paper..Scissors")
master.iconbitmap("icon.ico")
master.maxsize(8... |
04b281742933c5a77e4dae396b1ed1f8ecdcde8d | eamartin/py-worldbank | /worldbank.py | 3,339 | 3.65625 | 4 | '''Python library to access World Bank's open data
The official World Bank API documentation can be found at
http://data.worldbank.org/developers .
'''
import urllib
try:
import json
except ImportError:
import simplejson as json
def _fetch(url):
'''Downloads data from a JSON page and ... |
91f75f2e4b3b7d15e929e598b5bdb35fc67a9b22 | yanchaomars/python_technical_interview | /basics/12_BST.py | 1,517 | 4.0625 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
self.insert_bst(self.root, new_val)
def search(self, find_val):
... |
8248fc5e8d254f3f36c40c1fb0fcadfd2a8bded2 | tfnsongs/Camisa | /C++/linearsearch.py | 263 | 3.84375 | 4 | def find(a,x):
for i in range (0,len(a)):
if(a[i] == x):
return i
return -1
n = int(input())
x = int(input())
a = []
for i in range n:
a.append(int(input()))
ans = find(a,x)
if(ans==-1):
print("UNABLE TO FIND")
else:
print("IS AT %d POSITION"%(ans)) |
936922b47e258b5ec4b87a2bf80f48c7d20a69c5 | nhanvanhuynh/Assignment1 | /checkWord.py | 985 | 3.75 | 4 | def freq_count(letters):
f_count = {}
for char in letters:
f_count.setdefault(char, 0)
f_count[char] += 1
return f_count
def exist(word,sourceWord):
sc = freq_count(sourceWord.lower())
wc = freq_count(word.lower())
for letter, count in wc.items():
if sc.get(letter, 0) ... |
6802d69408cceaaabc72e7b2db1170b53912e5c1 | ephracis/hermes | /utilities/strings.py | 983 | 3.984375 | 4 | """ This file contains code for working with strings. """
import re
def fixName(category):
""" Turn the category name into human readable form. """
exceptions = ['a', 'an', 'of', 'the', 'is', 'and', 'with', 'by']
fixed = title_except(re.sub('_',' ',category), exceptions)
if fixed == "App Wallpaper":
fixed = "Li... |
e7f6b425608097d4082c57bfdadfddf616692371 | naveen-srivastava/algorithm | /miscellaneous/maximum_concurrency.py | 1,477 | 3.65625 | 4 | # Given the number of current customer service staff n on the first line and the number of data set k on the second line.
# The next k lines are data. Each line contains 2
# point of time in EPOCH format separated by a space. The first number represents the start time and the second number represents
# the end time o... |
4eda1aa7b1de3c9c3b3420951cc90cffe1354988 | schnell18/play-python | /misc/unpack.py | 421 | 3.734375 | 4 | def total(galleons, sickles, knuts):
return (galleons * 17 + sickles) * 29 + knuts
if __name__ == "__main__":
first, last = input("What's your name? ").split(" ")
print(f"Hello, {first}")
coins = [100, 50, 25]
print(total(*coins), "Knuts")
coins2 = {"galleons": 100, "sickles": 50, "knuts": 25... |
1fd444135089c9bbad7a4c4bba4f60f40e3c5e33 | schnell18/play-python | /regex/format.py | 335 | 4.0625 | 4 | import re
def main():
name = input("What's you name? ").strip()
# matches = re.search(r"^(.+),\s*(.+)$", name)
# if matches:
if matches := re.search(r"^(.+),\s*(.+)$", name):
last, first = matches.groups()
name = f"{first} {last}"
print(f"Hello, {name}")
if __name__ == "__main__"... |
263d6d0635dd4d5471824d49be11b2caef35660e | schnell18/play-python | /oop/vault.py | 881 | 3.65625 | 4 | class Vault:
def __init__(self, galleons=0, sickles=0, knuts=0):
self.galleons = galleons
self.sickles = sickles
self.knuts = knuts
def __str__(self):
return f"Vault: galleons={self.galleons} sickles={self.sickles} knuts={self.knuts}"
def __add__(self, other):
galle... |
24f77560246777ba344400557e0593d9203fe533 | schnell18/play-python | /misc/sleep.py | 188 | 3.921875 | 4 | def main():
n = int(input("What's n "))
for s in sheep(n):
print(s)
def sheep(n):
for i in range(n):
yield "🐏" * i
if __name__ == "__main__":
main()
|
2b452fca9f1cb6ea285cae2d68d5047f5c26a5b8 | pycollabproject/realprice | /logic/pricesuggest/algorithm.py | 1,303 | 4.03125 | 4 | import json
class pricesuggest:
"""
ok so over here im just going to suggest the variables and try to classify them
Primary variable(variabels which affect each other):
-square feet
-amount of rooms
-amount of bathrooms
Secondary Variables(variables whose effect is constent... |
e46723297e937ce3e6f616d06282e21aaaa967d2 | lucasmpaim/pyMV2H | /pyMV2H/utils/normalize_list_size.py | 497 | 3.734375 | 4 |
def normalize_list_size(list_to_normalize: list, new_length: int, default_value=None):
"""
Fill the list to get a x length
:param list_to_normalize: list to have the new size
:param new_length: the new length for the list
:param default_value: the value to fill the list to get the new size
"""... |
a23930569e83eb420cc1f2290f35bb43853be0c2 | caboosecodes/Python_Projects | /python_If.py | 297 | 4.25 | 4 |
height = 200
if height > 150:
if height > 195:
print('you are too tall ride the roller coaster')
else:
print('you can ride the roller coaster')
elif height >= 125:
print('you need a booster seat to ride the roller coaster')
else:
print('where are your parents?')
|
2c03f61adf4a52b47a9b7c77af3b1d35232f0b33 | adamnicholson/naughts-and-crosses | /crosses/board.py | 1,734 | 3.578125 | 4 |
class Board:
positions = [1, 2, 3, 4, 5, 6, 7, 8, 9]
winners = [
[1,2,3],
[4,5,6],
[7,8,9],
[1,4,7],
[2,5,8],
[3,6,9],
[1,5,9],
[3,5,7],
]
def __init__(self):
self.used = {}
def move(self, player, pos):
self.used[int... |
099fb33cbcf3e1fee6ec6f2362dbacd52ac6dc01 | matbc92/learning-python | /vim_edited_files/shakesperian_tutorial.py | 853 | 3.546875 | 4 | import random
def genereate_one(strlen):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
res = ""
for i in range(strlen):
res = res + alphabet[random.randrange(27)]
return res
def score(goal, test_string):
num_same = 0
for i in range(len(goal)):
if goal[i] == test_string[i]:
... |
2590e80758fe499b1d133a86ac83a60b5185c350 | matbc92/learning-python | /Data Structures/ds_seq.py | 1,372 | 4.5 | 4 | # listas strings e tuples, são sequencias, uma vez que sequencias sao conjuntos ordenados
# uma vez que eles sao ordenados pode se utilizar uma operação chamada slicing,
# ou seja selecionar apenas alguns itens desta sequencia, para tanto é necessario dizer
# a posição do primeiro e do ultimo item que se quer slecionar... |
1b9d52fdc438d84c505063bc1a1cada3d6527277 | matbc92/learning-python | /flow control/continue expermientos.py | 426 | 3.71875 | 4 | parametro = True
while parametro:
coisa = input('continue a frase: coisa...')
if coisa == 'boa':
print('é legal mesmo não é?')
elif coisa == 'ruim':
print('poxa, ta dificil eim?')
elif coisa == 'não sei':
print('poxa pense em algo')
continue
elif coisa == 'cansei':
... |
8305a8bfae9ee64d3f446e485c8c602e50e6abb5 | matbc92/learning-python | /flow control/if_e_while.py | 1,619 | 4.25 | 4 | #if condiciona o programa a executar um bloco de instruções se certas condições forem atendidas
# e outro(s) se condições diferentes ocorrerem, as condições diferentes podem ser especificadas
# por meio do comando elif, que efetivamente cria um outro nó de if, ou simplesmente permanecerem
# como qualquer coisa diferen... |
4ef85b3373806e1e5b05cbfd22e85abff40b12fe | matbc92/learning-python | /input_output/io_input.py | 686 | 4.4375 | 4 | # programa simples com duas funções definidas,
# uma que inverte uma string de texto, usando um operador sobre sequencias
# que inverte a ordem, e uma função que utiliza esta função de
# reversão para testar se a string é palindromica ao comparar
# com o resultado da função que inverte o texto
def reverse(text):
r... |
1473707206a10f480abdccac6d38e6c7283dc2bd | NPettyjohn/Python | /Python_Fundamentals/list_to_dict.py | 803 | 3.765625 | 4 |
def listToDict(inputList1, inputList2):
newDict = {}
list1 = []
list2 = []
minListIndex = 0
if len(inputList1) >= len(inputList2):
list1 = inputList1
list2 = inputList2
minListIndex = len(inputList2)
else:
list1 = inputList2
list2 = inputList1
... |
70eb9195caf1f66fe173ccf73636a19459765ac5 | CharlyWelch/code-katas | /the_wall.py | 281 | 3.671875 | 4 | """ Kata: Who is going to pay for the wall
#1 best practices solution by gdebenito:
who_is_paying = lambda n: [n, n[:2]] if len(n)>2 else [n]
"""
def who_is_paying(name):
names = []
names.append(name)
if len(name) > 2:
names.append(name[:2])
return names |
cab940cf831f5c55e9d9bb1b5f48c74c6be19d98 | aslamup/thinkpython | /fermats.py | 307 | 3.9375 | 4 | import sys
def check_fermat(a,b,c,n):
if int(n)<2:
return "Enter a number greater than 2"
else:
if int(a)**int(n) +int(b)**int(n) == int(c)**int(n):
return "Holy smokes, Fermat was wrong!"
else:
return "No,that doesn't work"
print check_fermat(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
|
4ef425369d1a6341cdb8615181add99f5eae89ce | priya242/WarCardGame | /card.py | 868 | 4.09375 | 4 | # Card class consists of suit, rank and value of card
suits = {'Diamonds', 'Clubs', 'Spades', 'Hearts'}
# increasing order
ranks = {'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace'}
# dictionary to map ranks to values
values = {'Two': 2,
'Three': 3,
... |
0c181586c718edccce89ded31a35d0e3de7d921d | SmartChandru/GUVI-code-kata | /lcmOfN.py | 292 | 3.703125 | 4 | def gcd(x, y):
while(y):
x, y = y, x % y
return x
def lcm(n1, n2):
g = gcd(n1,n2)
lcm = int((n1 * n2)/g)
return lcm
n= int(input())
a= list(map(int,input().split()))
num1 = a[0]
num2 = a[1]
l = lcm(num1, num2)
for i in range(2, n):
l = lcm(l, a[i])
print(l)
|
d8e65baaf11de82c060c92e0a8ce71bddc39cff1 | approvers/wow-thats-big | /test/measurer/cyclomatic_complexity/testcase/not_big.py | 306 | 3.84375 | 4 | """
Expected value -> 7
"""
def main():
for i in [1, 2, 3, 4, 5]:
if i == 1 or i == 3 or i == 5:
print("Yes it's odd")
elif i == 2 or i == 4:
print("Great it's even")
else:
print("WHAT HAVE YOU DONE")
if __name__ == '__main__':
main()
|
c901a714e56f22c3f31fef767205df16ab561035 | ScottSko/Python---Pearson---Third-Edition---Chapter-5 | /Chapter 5 - Maximum of Two Values.py | 379 | 4.21875 | 4 | def main():
num1 = int(input("Please enter a value: "))
num2 = int(input("Please enter another value: "))
greater_value = maximum(num1, num2)
print("The greater value is", greater_value)
def maximum(num1,num2):
if num1 > num2:
return num1
elif num1 == num2:
print("The ... |
a2ed9aee671504c1af5be67ff00723f1aa026f33 | ScottSko/Python---Pearson---Third-Edition---Chapter-5 | /Chapter 5 - Property Tax.py | 452 | 3.9375 | 4 | def main():
actual_value = int(input("How much is the property valued at? "))
assessment_value = actual_value * .6
property_tax_value = property_tax(assessment_value)
print("The actual value is ", actual_value, "and the assessment value is", assessment_value)
print("The property tax is", proper... |
b9346b4fd33c43e82733fdd9cf60a1ac4f7a9b8f | ScottSko/Python---Pearson---Third-Edition---Chapter-5 | /Chapter 5 - Rock, Paper, Scissors Game.py | 1,768 | 4.09375 | 4 | import random
player_choice = input("Rock, Paper, or Scissors?")
def game(player_choice):
num1 = random.randint(1, 3)
if num1 == 1:
print("The computer chose rock.")
if player_choice == "rock" or player_choice == "Rock":
print("Stalemate.")
player_choice = inp... |
4375564f636433d096da7000a83fe180691cd86e | bbrincat/tasks | /task2.py | 642 | 4.09375 | 4 |
def is_palindrome(text):
strip = {" ", ".", ","}
length = len(text)
forward = 0
back = length-1
while forward < length and back >= 0:
if text[forward] in strip:
forward+=1
if text[back] in strip:
back -=1
if text[forward].lower() == text[back].lower... |
c8ed33471e413847b9d4456599e4183ac16d3572 | lilybhattacharjee5/COSMOS-2015-Final-Project | /rsa_brute_force_hacking_program.py | 3,020 | 4.21875 | 4 | # RSA BRUTE FORCE HACKING PROGRAM (SIMULATION)
# The libraries that will be used in the program are imported along with all of their functions.
import math, random, time
# Right after the program begins, the computer begins counting the number of seconds it takes to execute the program.
start = time.time()
# These val... |
ab1dd9502d51e82d7c0ce55b7d8ac82345136de0 | SamuelBaltz/eecs545_random_forests | /read_data.py | 951 | 3.8125 | 4 | #Import libraries
import pandas as pd
#Import data
cars = pd.read_csv('car.csv')
#Reshape data into a numeric array
#Replace car text data cells as follows:
#buying and maint variables
#vhigh -> 3
#high -> 2
#med -> 1
#low -> 0
cars = cars.replace('vhigh',4)
cars = cars.replace('hi... |
efdbcd39a5f09ee3776a32ae252ad37509e6cb9d | RobinOShiaa/2020-ca400-oshear23 | /src/DataSourcing/Source/Scripts/web_scrapers/supervalue_scraper/supervalue_to_sql.py | 1,393 | 3.65625 | 4 | import sqlite3
import csv
class Supervalue_sql():
def run(self):
print('Writing to database..')
conn = sqlite3.connect('../framework/Produce.db')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Supervalue')
cur.execute('''
CREATE TABLE "Supervalue"(
... |
041a6d57c14f1e4ee2124b82e79aa6117f0ab1d4 | Crystal-19/Final_project | /d.py | 1,126 | 3.578125 | 4 | from simpleimage import SimpleImage
import tkinter
from PIL import ImageTk
from PIL import Image
python = 'image/python.png'
standford = 'image/standford.jpg'
corona = 'image/coronavirus.jpg'
worldwide = 'image/worldwide.png'
online = 'image/online.png'
year = 'image/2020.jpg'
knowledge = 'image/knowledge.png'
funny =... |
1ba79198303113e5d132e1e5a871dcc1c8e4b6cb | mateusgs/rs_codec | /rs_codec/py_scripts/rs_helper_functions.py | 3,965 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Functions extracted from https://github.com/tomerfiliba/reedsolomon
# Copyright (c) 2019 Mateus Silva <matgonsil@gmail.com>
import itertools
from array import array
################### INIT and stuff ###################
try:
bytearray
except NameError:
from ar... |
06dc98d8564db27c2df9d7f307d29cee76d5acd9 | JoshuaPedro/1.1 | /Integer0-9.py | 223 | 3.890625 | 4 | # File: Hello_python.py
# Created 11/14/18 by Josh Pedro
# A simple program illustrating a loop.
def main():
print("This program illustrates a loop")
x=1
for i in range(10) :
print(x)
x=x+1
main()
|
0214e32938ada0c4b193c20ec22871ce1b5dc6a5 | gurhanc/coding-exercises | /Two Characters | 1,039 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from itertools import combinations
# Complete the alternate function below.
def alternate(s):
xList = []
finalList = []
for letter in s:
xList.append(letter)
xListCopy = xList[:]
allCombinations = list(set(combinations... |
a8a822c69bad9199cdbc345d6fc0ed7ed905162a | srikanthanagaraja/Python_Examples | /Scripts/List/List.py | 647 | 4.15625 | 4 | my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Error! Only integer can be used for indexing
# my_list[4.0]
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
print(n_list[0][1])
print("The index of Happy is ",n_li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.