blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f90ed31d9f6d5015783079006406b9add12de14b | haydenj/2018-Advent-of-Code | /Day 7 Puzzle 1.py | 2,240 | 3.515625 | 4 | def parse(filename):
""" Reads file into list while stripping away whitespace characters, expecting tuples """
with open(filename) as file:
lines = [line.strip() for line in file]
scrubbedlines = list()
for line in lines:
splitline = line.split(' ')
scrubbedline = (splitline[1]... |
6615b691d5806cb7c080374c0556b9a87a2f5298 | wulinlw/leetcode_cn | /中级算法/sorting-and-searching_7.py | 1,651 | 4.03125 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/50/sorting-and-searching/102/
# 搜索旋转排序数组
# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
# 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
# 你可以假设数组中不存在重复的元素。
# 你的算法时间复杂度必须是 O(log ... |
5fab561fc780840f47b6aa978b1b5bb2a7357001 | nhamlv-55/hde | /HDE.py | 477 | 3.71875 | 4 | sum=0
def func1(n):
global sum
if n==0:
return
else:
process_a_line()
n-=1
func1(n)
def process_a_line():
n=int(raw_input(""))
input = raw_input("").split()
print compute(n, 0, input)
def compute(n, i, input):
if i==n-1:
if int(input[i])>0:
return int(input[i])**2
else:
return 0
else:
if i... |
b6b2678e89fdfdfd3a5c2e1b4c9ee849fe73f9ad | omrawal/Studbud-Prep | /Week 2/LinkedList2/q2.py | 1,494 | 3.953125 | 4 | class Node(object):
def __init__(self, val):
self.data = val
self.next = None
def addEnd(head, val):
newNode = Node(val)
if(head == None):
head = newNode
else:
temp = head
while(temp.next != None):
temp = temp.next
temp.next = newNode
ret... |
c9635e41db28d46031d64387a9159d4e076422cb | arthurosipyan/Algorithms | /Python/two_element_sum.py | 467 | 4.03125 | 4 | # Question: Given an unsorted array, find 2 elements that sum to 15.
arr1 = [4, 12, 21, 1, 5]
arr2 = [12, 7, 2, 1, 10, 3]
def two_element_sum(arr):
arr.sort()
print("Sorted Array: " + str(arr))
for num, next_num in zip(arr[::], arr[1::]):
if num + next_num == 15:
return num, next_num
... |
a1629771647bbf9b0ae5087e3bdf73734b905c85 | ovasylev/dev-sprint2 | /chap6.py | 330 | 3.921875 | 4 | # Enter your answrs for chapter 6 here
# Name: Olha Vasylevska
# Ex. 6.6
def is_palindrome(word):
length = len(word)
for i in range (length/2):
if word[i]!=word[length-1-i]:
return False
return True
print is_palindrome("noon")
# Ex 6.8
def gcd(a, b):
if b==0:
return a
else:
r = a % b
return gcd(b, r... |
15b03e0d033bfed8c91756105705136a65df3aff | IshanDindorkar/machine_learning | /taming_big_data_apache_spark/src/friends-by-age.py | 1,454 | 3.953125 | 4 | # Summary of example
# Main attractions -
# Key, Value RDDs - An RDD can have data in the form of key, value pair
# mapValues() - If the intent is only to make computation with value and not key, use this function
# reduceByKey - Aggregate all values based on given Key
from pyspark import SparkConf, SparkContext
conf... |
22cc86ffccb8e08ded4546d49e9231b8df3d5a44 | HOL-BilalELJAMAL/holbertonschool-python | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 784 | 3.765625 | 4 | #!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
def test_integer(self):
self.assertEqual(max_integer([1, 2, 3, 6]), 6)
self.assertEqual(max_integer([7, -23, 5, 18, 3]), 18)
... |
6e4e24f3ef735a962f7c4fad6634f7b25ad061cb | 5h00T/mini_shooting | /mission_manager.py | 2,425 | 3.625 | 4 | from scene import Scene
class Mission():
"""
ミッション中のクラスを保持して管理、記録の更新を行う
"""
def __init__(self, mission, best_time):
self.mission = mission()
self.best_time = best_time
self.mission_number = int(''.join([ch for ch in self.mission.__class__.__name__[-2:] if ch.isdecimal()]))
... |
3394df1da66f3ba73e4e2ec7dd902bb062e5c66d | sunilnandihalli/leetcode | /editor/en/[328]Odd Even Linked List.py | 1,943 | 4.21875 | 4 | # Given a singly linked list, group all odd nodes together followed by the even
# nodes. Please note here we are talking about the node number and not the value i
# n the nodes.
#
# You should try to do it in place. The program should run in O(1) space comple
# xity and O(nodes) time complexity.
#
# Example 1:
... |
727b8438f778bf7f9c111924c4bc2d0edf0cdb6a | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/tammyd/lesson06/test_mailroom_pt4.py | 1,662 | 3.53125 | 4 | #!/usr/bin/env python
#Unit testing
import os
import mailroom_pt4 as mailroom
mailroom.donor_db = mailroom.donor_db
#Lots of failures but I did my best to show my work.
#Is it necessary to test every single function?
menu_dict = mailroom.main_menu()
menu_selection = menu_dict("T")
def test_donor_database():
... |
14303a3b4859d06a4e2eabe782cb6ba64eec9c79 | mudzso/4th-tw-mentors-life-oop | /event.py | 2,791 | 3.59375 | 4 | from codecool_class import CodecoolClass
import random
import time
class Event():
def __init__(self):
self.event_name = None
self.CClass = None
self.drink_alcohol = False
self.location = None
self.date = None
@classmethod
def organize_event(cls, CClass):
e... |
0e121fb46bed347c6fc317332ad1412102bf1f33 | Aishwarya4/selenium-python | /Selenium_Projects/Cookies.py | 950 | 3.765625 | 4 | from selenium import webdriver
driver = webdriver.Chrome(executable_path="E:\Selenium_using_python\chromedriver.exe")
driver.get("https://www.amazon.in/")
#capture all the cookies created by browser
cookies = driver.get_cookies()
print("Number of cookies before adding the cookie:",len(cookies)) #print number of coo... |
d2956c6ca3c93bcdb8656c79ad60c3bbdb0ed784 | DavisDataScience/DataInterviewPrep | /DataStructures/Chapter4_PythonStructure/special_methods.py | 1,336 | 3.78125 | 4 | # range()
# enumerate()
# make grep from enumerate
import sys
def grep_word_from_files():
word = sys.argv[1]
for filename in sys.argv[2:]:
with open(filename) as file:
for line_index, line in enumerate(file, start=1):
if word in line:
print("{0}:{1}:{2:.40}".format(filename, line_index, l... |
10db9bcca359c3baa74b07f13ba40bc91fc60bb1 | gabriellaec/desoft-analise-exercicios | /backup/user_182/ch62_2019_04_05_01_35_33_894383.py | 214 | 3.5625 | 4 | def filtra_positivos(x):
lista=[]
i=0
while i<len(x):
if x[i]>0:
a=x[i]
lista.append(a)
i+=1
return lista
y=[1,2,-1,-2]
print(filtra_positivos(y))
|
9cd649809c3aad9ed1e72a8cf903d8e25c3ffee6 | vinuthreddy/vinuthreddy | /cr7.py | 300 | 3.921875 | 4 | #subtraction of 3 numbers
input
p=20
q=60
r=90
print("the value of p=",p,)
print("the value of q=",q,)
print("the value of r=",r,)
result=p-q-r
print("subtraction of ",p,q ,"and ",r ,"is", result)
output
the value of p= 20
the value of q= 60
the value of r= 90
subtraction of 20 60 and 90 is -130
|
c9e076ba4f0e1dd57452646eca0236e31f418e6e | jennyChing/onlineJudge | /10019.py | 1,257 | 3.515625 | 4 | '''
10019 - Funny Encryption Method
1. Read the number N to encrypt : M = 265
2. Interpret N as a decimal number : X1 = 265 (decimal)
3. Convert the decimal interpretation of N to its binary representation : X1 = 100001001 (binary)
4. Let b1 be equal to the number of 1’s in this binary representation : b1 = 3
5. Interp... |
898427324a601bd629ecb8ad41748bec2bac633b | faturita/python-toolbox | /paralelpython.py | 1,459 | 4.0625 | 4 | '''
Python Multiprogramming example.
Using pool with 4 processors in a map reduce style.
The performance improvement should be noticed
Reference: https://towardsdatascience.com/a-hands-on-guide-to-multiprocessing-in-python-48b59bfcc89e
'''
import time
import multiprocessing
import os
def is_prime(n):
if (n ... |
2f23f6fd2f2a263bcf98e135d297c88e5b95ae2f | INRIA/scikit-learn-mooc | /python_scripts/datasets_ames_housing.py | 6,352 | 3.96875 | 4 | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# %% [markdown]
# # The Ames housing dataset
#
# In this notebook, we will quickly present the "Ames housing" dataset. We will
# see that this dataset is similar to the "California housing" dataset. However,
# it is more complex to... |
af3a33a616e7f4a2e48d547aa6df5b118ed415eb | DinksTM/EZTranslator | /Linux/master.py | 2,120 | 3.90625 | 4 | import sys
GoodChoice = 0
def TranslateGate():
print("I see, what language are you planning to translate into? Please do not include spaces.")
translatorLanguage = raw_input()
Translate(translatorLanguage)
def Translate(_lang):
#WIP
currentTranslation = open(_lang+"Translation.txt","a")
terms... |
433858f3a59cb54f6defcdca7be9dca04702ab16 | stern1978/IS-211-Software-Application-Progamming-II | /IS211_Assignment1/assignment1_part2.py | 701 | 4.40625 | 4 | #!usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 1 - Assignment 2"""
class Book(object):
"""Collection of books"""
author = ''
title = ''
def __init__(self, author, title):
"""Constructs a book.
Args:
author (str): name of Author
title (str): title of ... |
3e8e6c0158519c984df2adf845bf2d2eff4b995b | whyj107/Python | /Pygame/pygame_tutorial_01.py | 838 | 3.984375 | 4 | # https://techwithtim.net/tutorials/game-development-with-python/pygame-tutorial/pygame-tutorial-movement/
# Pygame Tutorial #1 - Basic Movement and Key Presses
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
x = 50
y = 50
w = 40
h = 60
vel = ... |
607278d9aed7d955b8e6d1a9bb144f301981783a | jmezzanotte/PyAlgorithms | /PyBytes/ByteUtil.py | 2,126 | 4.6875 | 5 |
def _print_ascii_byte_helper(num, bit_val=128):
"""
Helper function that builds a list that represents they byte for a given value.
Does not always return a list of length 8, depending on the most significant bit.
:param num: Number to represent as a byte
:param bit_val: The largest byte value in... |
48584be89039ce7795871057d009cdb21421f6eb | jennywei1995/sc-projects | /StanCode-Projects/boggle_game_solver/anagram.py | 4,110 | 4.34375 | 4 | """
File: anagram.py
Name: Jenny Wei
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each ... |
0f49a6c106f13cd7f2253fbe24708227ec96582c | Eugene0469/The-Python_Workshop | /3. Programs, Algorithms, and Functions/helperFunction.py | 818 | 3.921875 | 4 | """
The program calculates the total amount in USD
"""
'''
@brief: The function accepts amounts in GBP and AUD currencies and calculates the total in USD currency.
@param: amount_in_aud: the amount in AUD currency
@param: amount_in_gbp: the amount in GBP currency
@retVal: total: total amount in USD currency
'''
def com... |
d54cbe1e1df5045ee1dc175030fb53ce32e3b40b | pvargos17/pat_vargos_python_core | /week_05/mini_projects/Api_project.py | 558 | 3.75 | 4 | from pprint import pprint
import requests
c = requests.get("http://ip-api.com/json",json=True)
data = c.json()
pprint(data)
city = data['city'] # this is grabbing the city name from the city key in the dict
print(city)
r = requests.get(f"http://beermapping.com/webservice/locquery/44a8826612022c756825a7205f0b52a2/{ci... |
8299faf160ae7b25dfe702cdfc8df1b6143d1993 | Shreyas2409/Important-programs | /algorithms/list.py | 170 | 3.640625 | 4 | b=[]
while True:
a = input("enter done if u r done\n")
if a=="done":
break
b.append(int(a))
print(b)
print(sum(b)/len(b))
|
356f9c5194bfbaa3d300abe5b96eb37235286b28 | miminas/CodingBootcampExercises | /pythonTutorial2/exercise3.py | 283 | 3.921875 | 4 | x = input("Please enter an 10-digit number: ")
even, odd = [], []
if len(x) != 10:
print("Not a 10-digit number")
else:
for a in range (10):
if a%2 == 0:
even.append(int(x[a]))
else:
odd.append(int(x[a]))
print(*even)
print('',*odd)
|
46ebc2660769d28c223db26a9ca88b79466fb027 | Cheesepuffed/2-Rooms-and-a-Boom-Randomizer | /main.py | 3,240 | 4.09375 | 4 | # This is a sample Python script.
from Role import Role
import random
# makes the member list with commas separating each member
def make_memberlist():
longlist = str(input("Please paste everyone's names ensuring each name is separated by a comma (,)\n"))
return longlist.split(",")
# creates finallist in main... |
f1a90128438ceeb7e4930b1088e027d2695ffab1 | CollinsMuiruri/Project-Euler-Toy-Problems | /safe-cracker.py | 640 | 4.34375 | 4 | # When given a specific word, this function obtains all possibilities of the word
# in an order which starts from first letters eg: AAAA;
# By giving the number equal to repeat, the function will give the length of the
# string by the number given.
# It then breaks when the specified word is found.
# However, it will a... |
67c785684d06c3012c873431dcdecee53c01bee9 | aliahmadcse/Programming-Foundation_Algorithms | /binarySearch.py | 701 | 3.890625 | 4 | items=[2,13,16,33,55,67,77,78,89,90]
def binarySearch(item,itemList):
#get the list size
listSize=len(itemList)-1
#set the lower and upper index
lowerIdx=0
upperIdx=listSize
while lowerIdx<=upperIdx:
#calculating the middle point
mid = (lowerIdx+upperIdx)//2
#if the ite... |
c168ebed4e078a5927f1678c7019202bb6610b15 | daniel-reich/turbo-robot | /z3wYnBQPgBTzy87WA_2.py | 1,400 | 4.09375 | 4 | """
Create a function which simulates the game "rock, paper, scissors". The
function takes the input of both players (rock, paper or scissors), first
parameter from first player, second from second player. The function returns
the result as such:
* "Player 1 wins"
* "Player 2 wins"
* "TIE" (if both inputs are... |
f3d33580b6574288bd07f123c1c1cf19c963b0b3 | ckim42/sup1 | /4_Queues/Problem1.py | 897 | 3.90625 | 4 | """Number of Students Doing HW at a Given Time
Provided parameters:
(1) `start_time` -- integer array
(2) `end_time` -- integer array
(3) `query_time` -- integer
The `ith` student started their HW at time `start_time[i]` and finished it at the time `end_time[i]`.
Return the NUMBER OF STUDENTS doing their... |
4cd4145f1fe9a4d7753653027f2fb144dd73e2cb | Michael-Chao/hw1 | /chapter8/practice_8_7.py | 456 | 3.5 | 4 | def make_allbum(name, album, number=''):
"""描述音乐专辑"""
if number:
current_album = {'name': name, 'album': album, 'number': number}
else:
current_album = {'name': name, 'album': album}
return current_album
first_album = make_allbum('jay chou', '青花瓷', 9)
print(first_album)
second_album = ma... |
0bfb13c908ae70a58f857cbdc3ee4703fd8c161f | Bobbybushe/HW | /task_1_4.py | 158 | 3.84375 | 4 | import math
a = 10
b = 5
print('Среднее арифметическое: ', a+b/2)
print('Среднее геометрическое: ', math.sqrt(a*b))
|
0947ce93868bd6a4c46fbe8f2c68df3ee7902fe0 | golfdcd/pythonbasic | /PythonBeginner-master/Phase1/EP34.py | 512 | 3.859375 | 4 | # ตารางหมากฮอต
"""
xxx
xxx
xxx
x = สีน้ำตาล
o = สีขาว
"""
number=int(input("ป้อนขนาด = "))
for row in range(number) :
for column in range(number):
print("x",end="") if (row+column)%2 == 0 else print("o",end="")
print(" ")
# 3 x 3
# row = 0 + column = 0
# row = 0 + 1
# row = 0 + 2
# row = 1 ... |
de891a9d550e0182c3d5cef078b829b063709d1c | william01424/CodeWarsAnswers | /SumArrays.py | 286 | 4.09375 | 4 | # Write a function that takes an array of numbers and returns the sum of the numbers. The numbers can be negative or non-integer.
# If the array does not contain any numbers then you should return 0.
def sum_array(a):
total = 0
for x in a:
total += x
return total
|
189a235b0dc663c830716b11c5b36f18374bf07b | stuti-v4/DS_ALGO_DAILY | /Learn Code Online/Challenge_001.py | 110 | 4 | 4 | def product(n):
for i in range(1,11):
print(n*i)
n = int(input("Print a Number : "))
product(n) |
ee32eb4c5bf0fa3b9827e0a11a8b943fbb9b709d | jewerlykim/python_Algorithm | /codingtest/findCityBJ18352.py | 1,019 | 3.609375 | 4 | import sys
from collections import deque
# sys.stdin = open("/Users/jewerlykim/Desktop/python_Algorithm/codingtest/18352.txt", 'r')
cityNumber, roadNumber, distance, startCityNumber = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(cityNumber+1)]
visited = [False for _ in range(cityNumber+1)]
distan... |
012d479026767aa0b90d91e6398eb0e424e966f1 | emimuniz/URIONLINEJUGDLE | /1020 - Idade em Dias.py | 350 | 3.796875 | 4 | #Leia um valor inteiro correspondente à idade de uma pessoa em dias e informe-a em anos, meses e dias
dias = int(input(''))
anoindividuo = int(dias/365)
mesesindividuo = int((dias%365)/30)
diasindividuo = int((dias%365)%30)
print('{} ano(s)'.format(anoindividuo))
print('{} mes(es)'.format(mesesindividuo))
print('{} di... |
4ebd6397808e72063441368e18620b5a3dc43407 | gamesdaco18/sincronizado | /fut_prom.py | 1,824 | 3.609375 | 4 | from tkinter import *
#Configuracion de la ventana
root= Tk()
root.title("Fut Players %")
root.geometry("400x300")
root.config(bg="Gray17")
root.iconbitmap("python.ico")
root.resizable(0,0)
opcion = IntVar()
num = IntVar()
#Declaracion de funcion
def operacion():
numero = num.get()
if opcion.get()==1:
... |
993c47855f6db5c371a6e76b638d2941ef5b35fd | rishinkaku/python_course | /pycharm学习-基础篇/python基础知识/2.打印输出及运算符.py | 3,775 | 4 | 4 | num1 = 10
num1 = 10.9
num2 = num1
print(num1)
num3 = num4 = num5 = 10
print(num1, num2, num3, num4, num5)
num6, num7 = 6, 7
print(num6, num7) #直接打印多个变量
print('abc',num6, num7) #复合的打印
num1=input('输入一个数字') #通过input输入的都是字符串的格式
num2=input('输入一个数字')
print('num1+num2=',num1+num2) #注意此时的num1是字符串并不是数字,所以不能直接相加
print('num1+... |
fdd7f97749f473560d629419000c1f0fde1b3bc8 | HwiLu/learn-automate-stuff-with-python | /字符串操作.py | 3,679 | 3.859375 | 4 | # 双引号
# 转义字符
# 原始字符串
'''
在单引号之前加上r,使其成为原始字符串
'''
print(r'That is Carol\'s cat.')
# 用三重引号的多行字符串
# 多行注释
"""
多行注释
多行注释
"""
# 字符串下标和切片
spam = 'Hello world!'
spam[0:5]
# 字符串的in和not in操作符
>>> 'Hello' in 'Hello world'
True
# 字符串方法
upper()
lower()
isupper()
islower()
# isX方法
isalnum() # 字符和数字
isalpha() # 字母
issp... |
33b4f55ea3a4f79e24c3567aa0b772ed88b6ab60 | jellythefish/isd-hse-cs-project | /scripts/detect_encoding.py | 226 | 3.5 | 4 | import chardet
import os
def detect_encoding(file_path):
with open(file_path, 'rb') as fh:
result = chardet.detect(fh.read())
print("Initial Encoding: " + result["encoding"])
return result['encoding']
|
45a47c79160a813d031597ea9435036b1c2a584a | cvhs-cs-2017/practice-exam-Narfanta | /Loops.py | 330 | 4.3125 | 4 | """Use a loop to make a turtle draw a shape that is has at least 100 sides and
that shows symmetry. The entire shape must fit inside the screen"""
import turtle
shape = turtle.Turtle()
shape.pu()
shape.left(90)
shape.forward(200)
shape.right(90)
shape.pd()
for i in range(150):
shape.forward(10)
shape.right(2.4... |
219630135491520007799a1b750be50e2d14453f | gvvishwanath/cluedo-player | /test2.py | 350 | 3.75 | 4 | from interactiveGame import *
try:
n = int(raw_input("Welcome to Clue Master Detective! How many players in the game? "))
while n < 2:
n = int(raw_input("At least 2 players needed. How many players do you want? "))
game = InteractiveGame(n)
game.play()
except Exception as e:
print "Error w... |
cdad8f217abc3b34c2b8806595e348f43eff05f9 | zeziba/bmp280_pine64 | /src/combiner_csv.py | 767 | 3.53125 | 4 | """
This file is intended to add all the csv entries into the main sqlite file.
"""
import database
import csv
import os
#_path_ = '/home/ubuntu/pybmp180/pyscript/data'
_path_ = 'data'
with database.DatabaseManager('data') as db:
for file in os.listdir(_path_):
if 'csv' in file:
_p = os.path... |
e21da098d2ac21427f1e9774afa3d7d5658033d2 | algharrash/saudidevorg | /day018_019.py | 653 | 3.953125 | 4 | #Day 018 and 019 Challenge
#First part of the challange
prog_langs = ['java', 'python', 'swift']
print("print list prg_langs:")
print(prog_langs)
prog_langs.append("php")
print("print list prg_langs after appending a new item:")
print(prog_langs)
print("print how many php occured in prog_langs list:")
print(prog_lan... |
4f86aecccec0e84600eff76f24cdbe4a3135264e | thenavdeeprathore/LearnPython3 | /Programs/String_Programs/String_EvenAndOddIndexChars.py | 199 | 3.8125 | 4 | # Print the characters present at even index and odd index
s = 'pythonprogramming'
print(s)
print("Characters present at even index: ", s[0::2])
print("Characters present at odd index: ", s[1::2])
|
78805da310f1ef67f0078a1f6b11f09cd8fd614a | OussamaBouaziz/Task_3 | /extreme_cases.py | 945 | 3.765625 | 4 | import csv
print("what label are you looking for ?")
label_input = input()
def get_line(string): #to be applied for extreme cases null, www .. ,
father = ""
with open("onto_x.csv") as csvfile:
reader = csv.reader(csvfile)
i=1
for row in reader:
if string != row[1]:
... |
33e27ed71b182f01c4470456c689c556756a5f0d | KsaweryK92/MojeWypociny_MW | /kreator_postaci.py | 1,514 | 3.953125 | 4 | #w programie uzytkownik przeznacza 30pkt na 4 zdolnosci
#dopuki nie zakonczy on programu, moze dowolnie dodawac i odejmowac
#punkty dowolnej zdolnosci
zdolnosci = {'madrosc' : 0, 'sila' : 0, 'odwaga' : 0, 'spryt' : 0}
punkty = 30
wybor = None
mad = 0
sil = 0
odw = 0
spr = 0
while wybor != '0':
print(... |
2ffdf5b0c9979ddb65a15780f6535ba677a00941 | papaganesha/prog3 | /exercicio2/main.py | 1,530 | 3.9375 | 4 | from retangulo import *
if __name__ == '__main__':
retangulos = []
def insert_retangulo():
print("\n○ Inserindo novo retangulo")
try:
altura = int(input("○ Altura: "))
largura = int(input("○ Largura: "))
retangulo_Insert = Retangulo(altura, largura)
... |
b4917e27e2e33ebd3091f1eb4adbf34154a83aa1 | windyware/CTFTools | /tools/crypt/source/factorization_moudle.py | 172 | 3.640625 | 4 | #_*_ coding:UTF-8 _*_
num =0
def fac(num):
for i in range(2,num):
if num % i == 0 :
print(i),
fac(num//i)
return
print(num)
return
fac(num)
|
df1d8debbbfa52ca145d93f4d31d1faf6d312252 | Beira-BF/EatPytorch2 | /cluster_Davies_Bouldin_index.py | 1,175 | 3.59375 | 4 | # 聚类算法评价指标——Davies-Bouldin指数(DBi)
import math
# nc is number os clusters
# to be implemented without the use of any libraries (from the scratch)
def vectorDistance(v1, v2):
"""
this function calculates de euclidean distance between two vectors.
:param v1:
:param v2:
:return:
"""
sum = 0
... |
1082ae08b9a0bbe46ff5b2fcd46402c401553dc2 | mohammadzainabbas/AI-Decision-Support-Systems | /Lab 03/Task_7.py | 630 | 3.59375 | 4 | #Task No. 07
def FindAllPath(graph,start,end,path=[]):
path = path + [start];
if (start == end):
return [path]
if not graph.__contains__(start):
return []
paths = []
for node in graph[start]:
if node not in path:
new_paths = FindAllPath(graph,node,end,path)
... |
f80239746db051e688d69dd75ac05447187884dd | shakeelashaik/python | /inheritance/demo6.py | 220 | 3.84375 | 4 | #example on default constructor in inheritance
class A:
def __init__(self):
print("Default constructor of class A")
class B(A):
def display(self):
print("show method of class B")
b=B()
b.display() |
e0f9678ce38c5b414612d354b4cb86b1e8519a88 | ROHIT25082000/Banking-GUI-in-Python | /Bank.py | 42,373 | 3.59375 | 4 | from tkinter import *
import tkinter.messagebox
def tip():
root15=Tk()
root15.title("SUGGESTIONS & TIPS")
root15.geometry("500x500")
state="IMPROVING IS THE KEY TO SUCCESS ,FILL THE ENTRY TO HELP US IMPROVE"
msg= Message(root15,text=state)
msg.config(fg="white",bg="lightgreen",font=("ver... |
bcc7859afc81f94edbb9d8db1430e2a5b9a9e1a9 | Rahul1chandra/Design-Patterns-Using-Python | /Mediator/MediatorPattern.py | 1,443 | 3.546875 | 4 | from abc import ABC, abstractmethod
class IChatRoom(ABC):
@abstractmethod
def sendMessage(self, message, participant):
pass
@abstractmethod
def addParticipant(self, participant):
pass
class ChatRoom(IChatRoom):
def __init__(self):
self.participants = {}
d... |
9b4868bce6b05f1852b2e8b0783e0dcba0736fa4 | HarshitVerma1/Programs | /python_programs/gcd3.py | 167 | 3.765625 | 4 | def gcd(m,n):
i=min(m,n)
while(i>0):
if (m % i == 0 & n % i == 0):
return i
else:
i=i-1
print("GCD is : $$ ",gcd(18,3)) |
e3a44bf50fd0013d402f65c1b5417f52c1105e3e | zhangtianyu07/store | /day03/猜数字.py | 579 | 3.53125 | 4 | import random
#随机出数
num = random.randint(0,101)
#次数
count = 0
#金币
money = 0
#while循环
#True死循环
while True:
num1 = int(input("请输入您要猜的数字:"))
count = count + 1
money = money + 10
if count < 7:
if num1 > num:
print("大了!")
elif num1 < num:
print("小了!")
else:
... |
03ba9a5f48697f208478c979e725ff54d70f5d4e | Vjoglekar/programs | /DoubleLinkList.py | 517 | 3.609375 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class DoubleLinkList:
def __init__(self):
self.head = None
self.size = 0
def push(self,value):
temp = Node(value)
temp.next = self.head
if self.head... |
20e074a29170a0a1b94c7eeae44087ddc69e1e1d | edmolten/CC | /lab1/cc-lab1-II.1.py | 782 | 3.53125 | 4 | from math import sin, cos
from decimal import Decimal
def sec(x):
return 1.0/cos(x)
def tan(x):
return sin(x)/cos(x)
def y(x):
return (1.0 - sec(x))/((tan(x))**2)
def y1(x):
return (-1.0)/(1 + sec(x))
def y2(x):
return (-cos(x))/(1 + cos(x))
for t in range(1,21):
print "y(10^(-" ,t,")) = ... |
e8cd8007793902afbfe5449f860be9f0a935d954 | medva1997/bmstu | /Lab2 2015-09-26.py | 4,442 | 4.34375 | 4 | """Заданы координатывершин треугольника, вычеслить длинну биссектрисы из наменьшего угла треугольника
при вычислении длин сторон использовать целые подкоренные выражения. Далее ввести
координаты одной точки и определить находится она внутри треугольника или нет. Если находится,
то определить расстояние до ближайш... |
6ad467c6a8405c1025cbe6ea2e1dc499a277335c | KeepFloyding/DSToolboxpy | /DSToolbox/clf_help.py | 2,511 | 3.734375 | 4 | # Functions that help with classifiers
"""
General function to test any classifier
Inputs include:
- X: values of a dataframe (should be scaled)
- y: list of labels
- clf_class: machine learning classifier
- n_fold: Number of kfolds to iterate over
- **kwargs: Number of additional parameters that ... |
8f6e12f18aaa6f0e6cc7e4657dff163cd9a78eb2 | zatserkl/learn | /python/average_diameter.py | 3,369 | 3.9375 | 4 | # What Is The Distance Between Two Random Points In A Square.mp4
# https://www.youtube.com/watch?v=i4VqXRRXi68
# See these supplementary discussions:
# http://stackoverflow.com/questions/26412084/getting-the-cumulative-distribution-function-for-sqrtx-from-the-cumulative-dis
# http://math.stackexchange.com/questions/15... |
869c26d4dbf8b7b7a32a7549dcd68b7616116651 | Yanlusc/exo_python_yan | /chap_4.2_1exo.py | 409 | 3.9375 | 4 | n = int(input())
m = 2 * n
def catalan(n):
i = 1
ii = 1
iii = 1
deuxnfac = 1
nfacone = 1
nfac = 1
while i < m:
deuxnfac = deuxnfac * (i + 1)
i = i + 1
while ii < n + 1:
nfacone = nfacone * (ii + 1)
ii = ii + 1
while iii < n:
nfac = nfac * (ii... |
e2fc1fbd3119da37ec44f8d74d038412c6e9ea96 | BinFaisal/All-Py-Projects | /Power of number.py | 178 | 4.03125 | 4 | num = int(input("Enter a No. :- "))
pow = int(input("Enter Power :-"))
sum = 1
i =1
while(i <= pow):
sum = sum * num
i += 1
print(num,"To the power ", pow , 'is:', sum)
|
8c4b2f47ce5784b7efdb540291a46f2b52c0274e | aatul/Python-Workspace | /021_Tuples.py | 1,177 | 4.1875 | 4 | """
Tuple
Tuple is another type of collection such as List.
The difference is tuple is written with round brackets.
And it is ordered and unchangeble.
That means once tuple is created you cannot change the values.
This also means once tuple is created you cannot add items to it.
And you cannot remove items from ... |
9f737dd3188fa08adb3b1afc7a832b1a1c95b51f | bigpigbigpig/learning-python | /Python基础/3. 类中初始化方法.py | 707 | 4.15625 | 4 | # !/usr/bin/env python
# -- coding:utf-8 --
# 小猫爱吃鱼,小猫要喝水
class Cat:
'''cat link eat fish.
cat need drink water.
'''
def __init__(self):
print("This is a init function.")
def eat(self):
print("%s like eat fish." % self.name)
def drink(self):
print("cat need drink water... |
40d62050569c6d57ff9e7d5de33bd127297ad370 | yodigi7/kattis | /parking.py | 379 | 3.6875 | 4 | a, b, c = [int(x) for x in input().split()]
times = {"arrive":[], "leave":[]}
for i in range(3):
time = [int(x) for x in input().split()]
times["arrive"].append(time[0])
times["leave"].append(time[1])
cars = 0
mostRecent = None
while times["arrive"] or times["leave"]:
if not mostRecent:
mostRecent = times["arri... |
0316a470470b112820ff9a270d7287dadcdf2d36 | Alexanderklau/Algorithm | /Recursion_alg/leetcode/hanota-lcci.py | 1,421 | 4.0625 | 4 | # coding: utf-8
__author__ = 'Yemilice_lau'
"""
汉诺塔
在经典汉诺塔问题中,有 3 根柱子及 N 个不同大小的穿孔圆盘,盘子可以滑入任意一根柱子。一开始,
所有盘子自上而下按升序依次套在第一根柱子上(即每一个盘子只能放在更大的盘子上面)。
移动圆盘时受到以下限制:
(1) 每次只能移动一个盘子;
(2) 盘子只能从柱子顶端滑出移到下一根柱子;
(3) 盘子只能叠在比它大的盘子上。
请编写程序,用栈将所有盘子从第一根柱子移到最后一根柱子。
你需要原地修改栈。
"""
"""
算法最擅长的其实就是不说人话
你想一下,三个柱子就是三个列表
你要从列表A移动一个顶端盘子到列... |
3c96a51799403b785f7d91111bb25c078bc5736d | taostein/sigmamc | /miditools.py | 808 | 3.640625 | 4 |
# import sys
note_list = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
major_semis = [2, 2, 1, 2, 2, 2, 1]
minor_semis = [2, 1, 2, 2, 1, 2, 2]
errors = {
'notes': 'out of range',
'bad key' : 'key of major or minor'
}
def number_to_note(num):
o = num // 12
n = note_list[num ... |
057d16eeb37362f5e93a0a9f9f970922ddd97237 | daiyeyue/Python_Advanced_Grammar | /06-常用模块/时间datatime.py | 1,041 | 3.765625 | 4 | import datetime
dt = datetime.date(2018, 3,26)
print(dt)
print(dt.day)
print(dt.year)
print(dt.month)
help(datetime.date)
print(type(dt))
print(datetime.date)
from datetime import datetime, timedelta
t1 = datetime.now()
print( t1.strftime("%Y-%m-%d %H:%M:%S"))
# td表示以小时的时间长度
td = timedelta(hours=-1)
# 当前时间加上时间间隔后,把得... |
330d951317e819d545df8035f99a5a954b3139f1 | peterswillbentley/finalproject | /finalproject.py | 4,401 | 3.765625 | 4 | """
Name: William Peters
CS230: SN2S
Data: Used cars for sale on Craigslist
URL: Link to your web application online (see extra credit)
Description:
This program reads used car data from Craigslist.
It calculates displays the average price based on the type of car, paint color, year and manufact... |
b0fcae0ebac46219f4e63f3e08449e228de4aaa8 | legion49f/interview-practive | /Binary_tree.py | 1,582 | 4.0625 | 4 | class Node(object):
def __init__(self):
self.leftside = None
self.rightside = None
self.data = None
class Tree(object):
def __init__(self):
self.root = Node()
def insert(self, data:int):
new_node = Node()
new_node.data = data
if self.root.data == No... |
117d012a43ab00b125bdb55755324125c6d8cbce | qianelsali/Machine-Learning-Algorithms | /Time Series-SingleSeries.py | 989 | 3.8125 | 4 | '''Outline:
# how to load and format a single time series data
# how to index and plot the time series data '''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas import Series
# two ways to import the time series data: data == data3, but data != data2
data = Series.from_csv('D:/ML_Py... |
ff7976daffcce43df50b600202438021189ea9f6 | Antares7707/Tic-Tac-Toe | /Tic-Tac-Toe(Human_vs_Computer).py | 8,934 | 3.9375 | 4 | """
This is a program written in Python 3.6.
The human player must take the first turn and place "O" on the grid as desired by clicking on the grid.
The computer will take its turn next.
This comtinues until one wins or the game ends in a tie.
A message box will pop up, indicating the result of the game.
Click "O... |
bf5440f72bf1e5d176f9b7c8b665ca5ec1b1e969 | samaruchan/STEP_class5 | /solver_sa.py | 6,446 | 3.609375 | 4 | #!/usr/bin/env python3
import sys
import math
import random, copy
from common import format_tour, read_input, read_output
#Simulated Annealing
MAXITER = 20000
ALPHA = 0.99
#solve
#if challenge5 or challenge6: recommend COUNT > 100
#else: COUNT > 1
COUNT = 100
def distance(city1, city2):
return m... |
dc0c506727c06a55cf8170278654e03e6a3ba5cc | yusufsyarif/Quiz-4-Alpro | /Quiz43_Yusuf Syarif Iqbal_1201184320.py | 273 | 3.75 | 4 | ListofGPA = [2.1,2.5,4,3]
def fbonus (GPA):
bonus = 500000
fbonus = GPA*bonus
return fbonus
for GPA in ListofGPA:
if GPA > 2.5:
print("Congratulation! You win a Bonus : Rp", fbonus(GPA))
else :
print("Sorry, maybe next time!") |
78a4968dc9405962c4ede05f22243bb11d88c4c1 | JerBushau/omega_game | /score.py | 918 | 3.6875 | 4 |
class Score:
""" this class may or may not become how score is kept
for now it is used to pass the high score back and
forth between the game loop and the start menu loop
"""
def __init__(self):
self.top_score = self.fetch_score()
def write_score(self):
# open a text ... |
052f37db0eadda93bd0fa7db65981f36616b4cf0 | CKHa93/intro-programming | /Homework/lesson-2/p3.py | 710 | 4.28125 | 4 | import sys
fibonacci_dict = {}
def fibonacci_for(n):
if n < 2:
return [1]
result = [1,1]
for k in range(1, n-1):
result.append(result[k-1] + result[k])
return result
def fibonacci(n):
if n < 3:
return 1
if n in fibonacci_dict:
return fibonacci_dict[n]
... |
1490bbfab52c528781eb0f18a9f697bef5b0b712 | patton199/LearnPython | /chapter 3 exercise.py | 1,572 | 3.765625 | 4 | # answer 1
dairy_section = ["milk", "cottage cheese", "butter", "yogurt"]
# answer 2
print("First:%s and Last: %s" % (dairy_section[0], dairy_section[-1]))
# result First:milk and Last: yogurt
# answer 3
milk_expiration = ("2013", "02", "15")
# answer 4
print("This milk carton will expire on %s/%s/%s" % (milk_expira... |
ea7ea998bd2d25d3d4615e47926894b171540e5b | MattB17/googleMemoryAutoScaling | /MemoryAutoScaling/DataHandling/TraceGenerator.py | 8,492 | 3.640625 | 4 | """The `TraceGenerator` class is used to generate data traces for analysis.
It has several methods for generating different classes of traces
corresponding to different usage patterns.
"""
import numpy as np
from MemoryAutoScaling import utils
import random
class TraceGenerator:
"""Generates data trace for analy... |
f7396e3252a82ae18160081407199e0604aebe6a | kawaiikakadu/python_ice | /neo4j/retrieve_data_partenaires.py | 1,481 | 3.515625 | 4 | from retrieve_data_isg import *
# function to parse the sheet in the clients excel
def parse_partenaire(projects, sheet):
"""
Function to parse the clients excel file
:param projects: list of the projects
:param sheet: excel sheet the clients are on
:return: list of the projects given in argument... |
9d2a61454a420960efce2556ca75635aa8c83560 | micheloosterhof/lantern | /lantern/modules/atbash.py | 857 | 3.5 | 4 | """Automated breaking of the Atbash Cipher."""
from lantern.modules import simplesubstitution
from typing import Iterable
# TODO: Consider using an affine cipher for transformation in future
KEY = 'ZYXWVUTSRQPONMLKJIHGFEDCBA'
def decrypt(ciphertext: str) -> Iterable:
"""Decrypt Atbash enciphered ``ciphertext`... |
7199b7a593d8628e17149d2e6beac279e20831ec | amulya-balakrishnan/fintech_app | /app/db.py | 6,567 | 3.71875 | 4 | import sqlite3
from datetime import datetime
# import csv
# def init2():
# DB_FILE = "stocks.db"
# db = sqlite3.connect(DB_FILE)
# c = db.cursor()
# with open("sp5000.csv") as csvfile:
# command = "CREATE TABLE IF NOT EXISTS stocks(symbol TEXT, name TEXT, price REAL, market_cap REAL... |
1f832a34afc37d016443f98d9d2ca4739e70bd46 | TMJUSTNOW/python-for-everybody-1 | /chap4.py | 1,758 | 3.90625 | 4 | #Exercise 1
import random
for i in range(10):
x = random.random()
print(x)
Exercise 2:
repeat_lyrics()
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def repeat_lyrics():
print_lyrics()
print_lyrics()
#Exercise 3:
def repeat_ly... |
cd80fb46faab0690cb4408c710b020b3fe84fb56 | anooptoffy/MultiModalRoutePlanning | /find_route.py | 893 | 3.828125 | 4 | #This is a brute attempt to check if algo works
#It will be polished asap
"""
R= dictionary of routes {key=bus_stop : value= set of routes which crosses this stop}
mypath = [list of bus_stops] <= outcome of our shortest route path
"""
R={'a':[1,2,3,4],
'b':[2,3,4,5],
'c':[3,4,5,6],
'd':[6,7]
}
# node_routes = {"8... |
2bc1d78e21bb52996e7f098601705accb9a9570d | salesvictor/DesignPatterns | /state.py | 1,258 | 3.75 | 4 | from abc import ABC, abstractmethod
class StateMachine:
def __init__(self):
self._state = S1()
def set_state(self, state):
self._state = state
def action(self):
self._state.action(self)
class S1:
class __Singleton:
def action(self, machine):
print('Doing action with state S1')
ma... |
83d4379e700a5c3ba5aaf1c1cdd4016c3c539293 | rjk79/Data-Structures-Algorithms-System-Design | /engine/lca_bst.py | 862 | 3.65625 | 4 | def lowestCommonAncestor(root, p, q):
# look right
# import pdb;pdb.set_trace()
if root.val < p.val and root.val < q.val:
lowestCommonAncestor(root.right, p, q)
elif root.val > p.val and root.val > q.val:
lowestCommonAncestor(root.left, p, q)
else:
return root.val
cla... |
9d0670498184ac929d3fc489fe33bc7540062864 | bimri/learning-python | /chapter_38/descriptors.py | 5,657 | 3.625 | 4 | "Descriptors"
'''
Descriptors provide an alternative way to intercept attribute access; they are strongly
related to the properties. Really, a property is a kind of
descriptor—technically speaking, the property built-in is just a simplified way to create
a specific type of descriptor that runs method functions on attri... |
934c08cd746e2e847360e91ed60593f0f66a4cfb | hnsvill/hackerRankSolutions | /designerPDFViewer.py | 1,100 | 3.921875 | 4 | #!/bin/python3
# Designer PDF Viewer
# https://www.hackerrank.com/challenges/designer-pdf-viewer/problem
import math
import os
import random
import re
import sys
import string
# Complete the designerPdfViewer function below.
def designerPdfViewer(h, word):
# max height * number of letters = area of the highlight... |
46672b03e7581f85572f7406a1b6098fca9f0c3e | ctc316/algorithm-python | /Lintcode/Ladder_37_BB/medium/221. Add Two Numbers II.py | 981 | 3.84375 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param l1: The first list.
@param l2: The second list.
@return: the sum list of l1 and l2.
"""
def addLists2(self, l1, l2):
... |
d6f5c2494a3bbc947ceda08b3bb8f4177e1471f9 | Cytaa/pythonPlusGoogle | /menu.py | 2,772 | 3.546875 | 4 | import sys
from os import system
from connToGoogle import connToGoogle
class TextMenu:
def __init__(self):
self.createTxtMenu()
def createTxtMenu(self):
print("Welcome!")
print("press 1 to establishe a connection with google sheets")
print("press 2 to quit")
chooser... |
24aeb8edd9f160ef3d8979ff4821ed52fdc9df65 | xPhentom/rockpaperscissor | /RSP.py | 1,120 | 4.0625 | 4 | #!/bin/python
from random import randint
import sys
def winner():
print "You've won"
def draw():
print "It's a draw"
def loser():
print "You've lost"
def enemy(choice):
print "Your enemy chose " + choice
def exit():
print "Write rock, paper or scissor"
sys.exit()
def game():
rN = randint(1,9)
answer = raw... |
ce0a307e3bfab1861e1c5453bf07af0fb3ed99c8 | andrewnnov/tasks_py | /w3/variables/assign_multiple_values.py | 296 | 4.21875 | 4 | # Many Values to Multiple Variables
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
# One Value to Multiple Variables
x = y = z = "Orange"
print(x)
print(y)
print(z)
# Unpack a Collection
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
|
bae80197544cbf18f48a07764f8173d1257b9c45 | SetaSouto/torchsight | /torchsight/models/resnet.py | 14,825 | 3.578125 | 4 | """Module that contains ResNet implementation.
ResNet could contains several depths. The paper includes 5 different models
and the model_zoo contains pretrained weights for each one:
- ResNet 18
- ResNet 34
- ResNet 50
- ResNet 101
- ResNet 152
Each one of this different architectures is based on "blocks" that help ... |
e8e28c5fbc8f760c3ca31c14212e6ff97f45fe0e | aileentran/practice | /waterpipes.py | 3,355 | 4.09375 | 4 | """
See if water can flow through!
input: grid; 0 = pipe, 1 = wall
output: boolean - True if water can flow from top to bottom
water can only move down, left, or right!
"""
# clear path
good = [
[0, 0, 1, 1],
[1, 0, 1, 1],
[1, 0, 1, 1]
]
good2 = [
[0, 1, 0, 1],
[1, 0, 0, 1],
[0, 0, 0, 0]
]
good3 = [
[0, 0, 1,... |
58a7c6c453529dc2efdc40ab98a58cbdd617b933 | daniel-reich/turbo-robot | /F7iLaLDBHqshWSZz5_2.py | 432 | 3.96875 | 4 | """
Create a function that takes as a parameter a list of "stringified" numbers
and returns a list of numbers.
Example:
["1", "3", "3.6"] ➞ [1, 3, 3.6]
### Examples
to_number_list(["9.4", "4.2"]) ➞ [9.4, 4.2]
to_number_list(["99", "20"]) ➞ [99, 20]
to_number_list(["9.5", "8.8"]) ➞ [9.5,... |
7b1f0dde19927fc6af3baf068993a77186432701 | karneetarora/Server | /main.py | 1,541 | 3.609375 | 4 | import socket
from sys import argv
import argparse
parser = argparse.ArgumentParser(description="""This is a very basic client program""")
parser.add_argument('-f', type=str, help='This is the source file for the strings to reverse', default='source_strings.txt',action='store', dest='in_file')
parser.add_argumen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.