blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0a2f926346a3283f46f2816e72f9a2d82e578f1c | thirteenaladdins/andromeda | /recover_reading_order.py | 2,851 | 3.671875 | 4 | from operator import itemgetter
from itertools import groupby
import fitz
def recover(words, rect):
""" Word recovery.
Notes:
Method 'get_textWords()' does not try to recover words, if their single
letters do not appear in correct lexical order. This function steps in
here and creates ... |
95165e66937199321fa3a078d40daeb0d02f8616 | xeon123/medusa-1.0 | /medusa/qr.py | 1,526 | 3.671875 | 4 | """
File qr.py
Author Ernesto P. Adorio, Ph.D.
U.P. Clarkfield, Pampanga
Version 0.0.1 2009.01.16 first version.
"""
from math import sqrt
from matlib import matprint, matprod, transpose
def qr(A, method="gramm"):
# Performs a QR decomposition of A
# default is via gramm-schmidt orthogonalizatio... |
de5ea20a6fe3fe6435129c8ab88ea76ef326e07a | Grzegorz-Olszewski/dec_to_hex | /decimal_to_hex/utils.py | 808 | 3.671875 | 4 | DEC_TO_HEX = {
0: '0',
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
7: '7',
8: '8',
9: '9',
10: 'A',
11: 'B',
12: 'C',
13: 'D',
14: 'E',
15: 'F'
}
def is_integer(number):
try:
int(number)
return number
except ValueError:
... |
136a5fe989994669788363b9d7405f4f7589ee5a | contemn1/leetcode | /word_break.py | 1,415 | 3.5 | 4 | from typing import List
def wordBreak(s: str, wordDict: List[str]) -> List[str]:
def dfs(edge_map, index, res_string):
if index == 0:
yield res_string
else:
for children in edge_map[index]:
yield from dfs(edge_map, children, s[children: index] + " " + res_str... |
b610e5869343f394b7eeda9ba492ea06dd278eaa | dougscohen/my-lambdata | /my_lambdata/my_mod.py | 620 | 4.0625 | 4 | # my_lambdata/my_mod.py
def enlarge(n):
"""
Param n is a number
Function will enlarge the number
"""
return n * 100
# if in our global scope, this will mess up our ability to import other
## functions from this file. So we need to nest it under the main
# # x = 5
# x = int(input("Please choose a ... |
86169e60635e4cac1a1041d6a90f1c320e7199a6 | fionanealon/python-exercises | /euler5.py | 892 | 4.0625 | 4 | # Fiona Nealon, 2018-04-07
# A program that finds the smallest positive number that is evenly divisible by all of the numbers from 1 to 20
def factorial(upto):
# Create a variable that will become the answer
multupto = 1
# Loop through numbers i from 1 to upto
for i in range (1, upto):
# # Adapted from: ht... |
b0c9f6b59baa11d02077a32bdf8f48667f5932ae | sreedevi2906/sreedevii | /newlineusingloop.py | 134 | 4.15625 | 4 | 9.Write a program to print every character of a string entered by user in a new line using loop.
In [77]:
for i in "SIRI":
print(i) |
f74e35043f6ea699ee43f8252f870275f9476385 | ajmalmohad/simple-rest-flask | /linked_list.py | 1,627 | 3.984375 | 4 | # Linked List Node
class Node:
def __init__(self, data=None, next_node=None) :
self.data = data
self.next_node = next_node
# Linked List
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
# Linked List to Array
def to_list(self):
l... |
4b03d5eb55904e0a4f31ef81c90679c2b223fe6a | arnour/PAA-2926-2019 | /paa191t1/dijkstra/datastructs/heap/__init__.py | 967 | 4.0625 | 4 | from paa191t1.dijkstra.datastructs.tree import DistanceNode
class MinHeapNode(DistanceNode):
"""Estrutura de comparação de um nó da heap de mínimo."""
def __gt__(self, other):
if other is not None:
return (self.distance > other.distance) or (self.distance == other.distance and self.vertex... |
aeac235c0d5c9cc0eb5b2f0c14af4655d784e433 | Krosxx/CtAssistant_Server | /model/model.py | 2,129 | 4 | 4 | """
标准类
"""
class SchoolInfo:
def __init__(self, code, hintMessage):
self.schoolCode = code
self.hintMessage = hintMessage
'''
@:param teacher 教师
@:param weeks 周数组 int() #第1-6周 [1,2,3,4,5,6]
@:param className 课程名 str
@:param classRoom 教室 str
@:param node 节数 int()
@:param week 第几节
'''
class Clas... |
dbcbcae47e045f2aa4ef495bd919c7cef16c8948 | lordjack/oficina_introducao_programacao_python | /exercicios/ex03.py | 1,821 | 4.125 | 4 | # Desenvolva um programa que receba o raio (R) de uma circunferência,
# calcule e mostre a área desta circunferência.
# fórmula da área: A = PI * R2, sendo que PI vale 3,14.
# Exercício 03 - Q01
# Entrada de Dados
raio = float(input("Digite o raio da circunferencia: "))
pi = 3.14
area = pi * raio ** 2
# Saída de Dado... |
128ab31edbce21ccf030ef6ca5a921d9e43d863c | lordjack/oficina_introducao_programacao_python | /exercicios/ex04.py | 353 | 3.953125 | 4 | # Exercício 04 - Estrutura Condicional
# Entrada de Dados
nota1 = float(input("Entre com a primeira nota: "))
nota2 = float(input("Entre com a segunda nota: "))
# Processameno de Dados
media = (nota1 + nota2)/2
if media >= 5:
# Saída de Dados
print("Aprovado com média %.2f" % media)
else:
print("Reprovad... |
8809647b846ce7558c4f6fe525d384e54b8cff3e | wookeeda/study_python | /PyCharmProject/untitled/testClass.py | 816 | 3.90625 | 4 | class Animal:
is_alive = True
age = 1
def __init__(self, name):
self.name = name
print('=====================\nconstructor invoked')
def descript(self):
print('name : {0}\nage : {1}\nalive : {2}'.format(self.name, self.age, self.is_alive))
class Dog(Animal):
# 생성자는 상속 받지 ... |
10aec2feadd3d912325bb575ded8a71a1e7dcea2 | wookeeda/study_python | /PyCharmProject/untitled/testLog.py | 480 | 3.5 | 4 | import logging
logging.basicConfig(filename='log.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('start log')
def factorial(n):
logging.debug('start factorial(%s)' % (n) )
total = 1
for i in range(n + 1):
if not i:
continue
total *=... |
1efb41bf1a5a0fd861aa85645a23d3f8f0a1d2ac | mstapelberg/12.010-Final-Project | /neutron.py | 460 | 3.671875 | 4 | #Function that tracks the nergy and the position of the neutrons in the for loop.
#Inputs are a previous theta, phi, r, and energy value that is then converted to
#a new theta, phi, r and energy value
import numpy as np
import math
import random
def neutron(theta, phi, r, energy):
"""This is a function that tracks... |
4c719f9df45c152f56ba65e58bc6948d9fbafe4d | alinbabu2010/Python-programs | /File1.py | 353 | 3.515625 | 4 | f1=open('orginal.txt','w')
f2=open('duplicate.txt','w')
st=raw_input("Enter a string\n")
f1.write(st)
f1.close()
f1=open('orginal.txt','r')
st1=f1.read()
print"The contents of orginal file:\n{}".format(st1)
f2.write(st1)
f2.close()
f1.close
f2=open('duplicate.txt','r')
s=f2.read()
print"Content in duplicat... |
2b3985a018d793cc3c12022250313a8904d8d9f7 | alinbabu2010/Python-programs | /calculator.py | 770 | 3.734375 | 4 | import math
def add():
a,b=map(int,raw_input("Enter the two numbers\n").split())
c=a+b
print("Sum is {}").format(c)
def sub():
a,b=map(int,raw_input("Enter the two numbers\n").split())
c=a-b
print("Difference is {}").format(c)
def pro():
a,b=map(int,raw_input("Enter the two numbers... |
e89f722d0d629ef6e007eeb2f75942516851fd92 | alinbabu2010/Python-programs | /Graph.py | 543 | 3.703125 | 4 | import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
pos={0:(0,.5),1:(.2,.8),2:(.2,.5),3:(.2,.2),4:(.4,.8),5:(.4,.5),6:(.4,.2),7:(.8,.8),8:(.9,.5),9:(.8,.2),10:(1.0,.3)}
G.add_nodes_from(range(11))
G.add_edges_from([(0,1),(0,2),(0,3),(1,5),(1,6),(2,5),(3,4),(5,10),(4,7),(4,8),(6,9),(7,8),(8,9),(8,10)... |
97efe05e9964333b8a9bb3e89142fb6e53cc35c7 | pimoroni/icm20948-python | /examples/magnetometer.py | 2,609 | 3.671875 | 4 | #!/usr/bin/env python
from icm20948 import ICM20948
import time
import math
print("""magnetometer.py - Convert raw values to heading
Rotate the sensor (X-axis upwards) through 360 degrees to calibrate.
Press Ctrl+C to exit!
""")
X = 0
Y = 1
Z = 2
# The two axes which relate to heading, depends on orientation of ... |
06751188fcc57769014fffdb14dc52af36322b01 | f-prime/RiverHell | /src/River.py | 616 | 3.59375 | 4 | import pygame
from src.GameObject import GameObject
class River(GameObject):
"""
The main purpose of this object is to add a small vector to the
player object in the y dirgit@github.com:f-prime/RiverHell.gitection.
"""
id = "RIVER"
def __init__(self, x, y):
self.rect = pygame.Rect(... |
3f8c9fe6ee213c72fb6a1bd9ec43691d3e51bac3 | Edceebee/Buchalka_Python_project | /dictionaries.py | 419 | 4.125 | 4 | fruits = {"orange": "good for vitamins", "apple": "red and green", "pineapple": "i don't like it",
"watermelon": "chewable seeds"}
print(fruits)
while True:
snack = input("Enter name of fruit\n")
if snack in fruits:
description = fruits.get(snack)
print(description)
else:
... |
f15b40dfe0a1af6111971d4d3058a8d7adb20e5f | ayeyem/HRT19D-detection | /Python/function.py | 462 | 3.515625 | 4 | def greet_user(username):
print("hello,"+username)
def greet_user2(username,place="Hit"):
print("hello,",username,",welcome to",place)
def greet_user3(users):
for user in users:
print("hello",user)
users[0]="HRTer"
users=["Zhao", "Qian", "Sun"]
greet_user3(users)
greet_user3(users)
users[0]="... |
669411f10fc82aae7e277485df94c5f1d02c6074 | Arti22kesar/acad11 | /assignment11.py | 1,155 | 3.578125 | 4 | #Ques1.
import threading
import time
class Mythread(threading.Thread):
def __init__(self,value):
threading.Thread.__init__(self)
self.v=value
def run(self):
time.sleep(5)
print("value is" , self.v)
thread1=Mythread(4)
thread1.start()
#Ques2.
import threading
import time
class... |
a3d93db19bb28391d44256abc3139468bcc4ec8e | timothyshort/project_euler | /AmicableNumbers.py | 833 | 3.609375 | 4 | import time
max = int(input("Enter maximum number:"))
list = [1] * (max)
t1 = time.time()
#Start at 2 and go until square root of n
#We only need to go the square root because for each a * b = n, we don't need b * a
for a in range(2, int (max**.5) +1):
#Sieve method
#Now find the sum of i and j where i * j = n
fo... |
06372c3be716dfc1c5fe59b224d7d80ab2f8c765 | timothyshort/project_euler | /LargestPalindrome.py | 1,438 | 3.9375 | 4 | import time
def findPalindrome(digit):
palindromes = [[]]
maxNumber = 10**digit-1
minNumber = 0
x=maxNumber
#Start at the maximum number and decrement by one
#Loop while that number is greater than the minimum number
#This condition drastically reduces the number of iterations
while ((x) > minNumber):
x-=1
... |
a89d774e85f4f2ca92312c24b8ce53af9be1457b | judithboekee/ESC_DAY3 | /example.py | 1,753 | 3.765625 | 4 | import pytest
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add('space', 'ship') == 'spaceship'
def subtract(a, b):
return a - b # <--- fix this
# uncomment the following test
def test_subtract():
assert subtract(2, 3) == -1
#1
def factorial(n):
"""
Co... |
e0409efa00b156fe94060569bf1386eae7cc8414 | yashwanthguguloth24/Algorithms | /Greedy/fractional_knapsack.py | 1,263 | 4 | 4 | '''
Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
Note: Unlike 0/1 knapsack, you are allowed to break the item.
Example 1:
Input:
N = 3, W = 50
values[] = {60,100,120}
weight[] = {10,20,30}
Output: 240.00
Explanation: To... |
5352d4f887b3d3504a722937c18cee424d39b330 | yashwanthguguloth24/Algorithms | /Greedy/Shop_in_candy_store.py | 2,445 | 3.96875 | 4 | '''
In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you.
You are now provided with an attractive offer.
You can buy a single candy from the store and get atmost K other candies ( all are different types ) for free.
Now you have to... |
67a502ba1f2756502be6a36cd612ccb42a49980c | yashwanthguguloth24/Algorithms | /Dynamic Programming/edit_distance.py | 1,471 | 3.90625 | 4 | '''
Given two strings str1 and str2 and below operations that can performed on str1. Find minimum number of edits (operations) required to convert ‘str1′ into ‘str2′.
Insert
Remove
Replace
All of the above operations are of cost=1.
Both the strings are of lowercase.
Input:
The First line of the input contains an inte... |
aa9f1d56cbaca62ad694a300670147bf67d9fbc6 | yashwanthguguloth24/Algorithms | /Divide and Conquer/Sum of Middle Elements of two sorted arrays.py | 1,550 | 4.03125 | 4 | '''
Given 2 sorted arrays A and B of size N each. Print sum of middle elements of the array obtained after merging the given arrays.
Input:
The first line contains T denoting the number of testcases. Then follows description of testcases.
Each case begins with a single positive integer N denoting the size of array. Th... |
e7112d698f5bc8bf7f734b5c5844802e90ca2b39 | yashwanthguguloth24/Algorithms | /Sorting/Quicksort.py | 856 | 3.8125 | 4 | #Quick sort
def partition(arr,low,high):
pIndex = low
pivot = arr[high]
for i in range(low,high):
if arr[i] <= pivot:
arr[i],arr[pIndex] = arr[pIndex],arr[i]
pIndex += 1
arr[pIndex],arr[high] = arr[high],arr[pIndex]
return pIndex
def QuickSort(arr,low,high):
... |
448fd8a44689696e95817e624a3f37dd56f441c6 | yashwanthguguloth24/Algorithms | /Dynamic Programming/longest_common_subsequence.py | 1,103 | 4 | 4 | # Dynamic Programming
'''
Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase.
Input:
First line of the input contains no of test cases T,the T test cases follow.
Each test case consist of 2 space separated integers A and B denoting the size of string... |
e3c62c135fa9bd6d9af4a340932611004adb72de | yashwanthguguloth24/Algorithms | /week3/CarFueling_w3.py | 779 | 3.515625 | 4 | #Greedy Algorithm
#Car Fueling problem
#code by yashwanth G
import sys
def MinRefills(distance,full_tank,n,stops):
stops.insert(0,0)
stops.append(distance)
numRefill = 0
currRefill = 0
while currRefill <= n:
lastRefill = currRefill
while (currRefill<=n and (stops[currRef... |
f8398c7ad0678906c1e7eb2978952e02e96c7d3c | kp1129/cs-graphs | /projects/social/social.py | 6,305 | 4.09375 | 4 | class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
import random
... |
1e3db1e38bfb7d7142b76b71ab30c7598b6286e8 | GageOfLeon/python-the-hard-way | /ex13.py | 501 | 4.03125 | 4 | from sys import argv
# The first line allows use to add features from the python feature set. argv is the "arguement variable" It holds arguements that is pass to the script
script, first, second, third = argv
# The inputs here are saved until called on since its an argv
print "The script is called:", script
print "Yo... |
1d5606bd6dfada85d820361f02bc4ed703c7b2a0 | hannapcf/python-projects | /bomberman.py | 1,456 | 3.609375 | 4 | from random import randint
from random import seed
seed(1)
matriz = []
def criando_matriz(n):
for i in range(n):
matriz.append([])
for j in range(n):
matriz[i].append(randint(0, 1000))
for i in range(len(matriz)):
print(matriz[i])
def calcula_soma(matriz, linha, coluna, ... |
c5d2d4337b34251d3e90c190cd07cbb97cafe2d9 | priya-sudarshanam/PythonExperiments | /Queue.py | 847 | 4.125 | 4 | #queue class and its functions
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
if not self.isEmpty():
return self.items.pop()
else:
... |
e48a098f01287c8c771e3de1ebe7c7a988162570 | Sanjai-K/Basic_Examples_Python | /flames.py | 492 | 3.71875 | 4 | #Python code to check FLAMES for two strings.
a = raw_input("First string : ")
b = raw_input("Second string : ")
dicti = {'f':'Friends','l':'Loves','a':'Affection','m':'Marriage','e':'Enemy','s':'Sister'}
for i in a:
if i in b:
a=a.replace(i,'',1)
b=b.replace(i,'',1)
c=len(a) + len(b)
d="flames"
e=... |
6f2fb9f26e2087d2a5738939a1de195ebb02540a | chang-github-00/Lab-handout | /model.py | 1,066 | 3.671875 | 4 | import torch
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, n_categories,input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.n_categories = n_categories
self.i2h = nn.Linear( ... , ... ) # complete the dimens... |
033d89f9913e12a64d2565952fa2a12dc6acbaea | kbishop711/wordcount | /wordcount.py | 2,115 | 3.890625 | 4 | # Written by Kevin Bishop
import operator
import string
import sys
# These are all of our legal characters that can be in words
CHARS = string.ascii_letters + string.digits
"""This needs to take a text blob and tokenize it into words.
Words are delimited by anything other than a-z, A-Z, or 0-9.
Keyword arguments:
s... |
61e712a6149f19d3483d956e2bb649607ca6893f | iuc73663/PythonStuff | /Random Junk/SquareFractals.py | 1,895 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 19 11:32:56 2018
@author: Administrator
Square Fractals
"""
import turtle
import math
def getPoints(scale,shift, angle):
points = [[-20,-10],[-20,30],[20,30],[20,-10]]
for i in range(len(points)):
for j in range(len(points[i])):
points[i][j]... |
164fd09c208fd7907343ce00a0aff75e5c6233b4 | Anthonysalvador/PythonBasicoK2 | /clase0.py | 221 | 3.59375 | 4 | print("Hola mundo")
# Python 3: Serie de Fibonacci hasta n
def fib ( n ):
a , b = 0 , 1
mientras que a < n :
imprimir ( a , end = '' )
a , b = b , a + b
imprimir ()
fib ( 1000 ) |
ceced913de68d28315a2415791d10e6a3f25dd61 | HoangDevNull/Learn-AI | /first.py | 2,345 | 3.640625 | 4 | #
# ------------ 1 print number which is divisible for 7 and 5 between 1500 and 1800---------------
# for i in range (1500,1800):
# if (i % 7 == 0) and (i % 5 ==0)
# print (i)
# --------------------------------- 2 Count number digit----------------------------------------
# n = int(input('Enter your in... |
53af7eaa8be888f5655c162e75a58fce5d199fc6 | thomason-jesse/nlu_pipeline | /src/ParseNode.py | 1,009 | 3.5 | 4 | __author__ = 'jesse'
import sys
import copy
# these are used to represent nodes in a parse tree
# each has a semantic node member, which carries the semantic meaning at this point in the tree
# the parent and children relationships are to other ParseNodes, differentiating these from
# SemanticNodes, where the parent... |
0835b65610b733e22fec5934d4dc15bfa1b7b017 | lndaquino/data-structures-and-algorithms-using-python | /DataStructures/graph-listaAdjacencia.py | 459 | 3.8125 | 4 | class Graph:
def __init__(self, nodes):
self.nodes = nodes
self.graph = [[] for i in range(nodes)]
def add_edge(self, u, v):
self.graph[u - 1].append(v - 1)
def show(self):
for i in range(self.nodes):
print('%d: ' % (i+1), end = ' ')
for j in self.graph[i]:
print('%d -> ' % (... |
edfd13d0e4b12e5d747fd09f435fbfbb06eda2d0 | lndaquino/data-structures-and-algorithms-using-python | /ForFun/youtubeDownloader.py | 1,014 | 3.703125 | 4 | from tkinter import *
from youtubePytube import *
window = Tk()
window.title('Youtube Downloader')
window.geometry('500x200')
window.resizable(0, 0)
title = Label(window, text='Youtube Downloader', font=('Arial', 25), fg = 'Blue')
title.pack()
msg = Label(window, text='', font=('Arial', 15))
entry_url = Entry(windo... |
38aaa2f4b58df47872c819b836e7aec17eafa7ff | lndaquino/data-structures-and-algorithms-using-python | /ForFun/permutations.py | 192 | 3.75 | 4 | import itertools
'''
gerando todas as permutações
permutações de (1,2,3) =
(1,2,3)
(1,3,2)
(2,1,3)
(2,3,1)
(3,1,2)
(3,2,1)
'''
lista = [1,2,3]
print(list(itertools.permutations(lista))) |
9ad2685406662d0a9db0e7b39d0f6b1d34565822 | sanster9292/Daily-Algorithm | /migrating_birds.py | 798 | 3.890625 | 4 |
"""
PROBLEM URL:
https://www.hackerrank.com/challenges/migratory-birds/problem
PROBLEM DESCRIPTION:
In this problem, you will be given two inputs.
A number n the id numbers of birds migrating.
(For example, n= 6 means there are 6 different kinds of birds migrating.)
An array which is a record of how often a bird of... |
f8e9083f63ab74c1d38e138963aebce473e3680a | sanster9292/Daily-Algorithm | /divisible_sum_pairs.py | 1,401 | 4.03125 | 4 | """
PROBLEM URL
https://www.hackerrank.com/challenges/divisible-sum-pairs/problem
PROBLEM DESCRIPTION:
Given a number k and a list of intergers find the pair of values (i,j) in the
input array where
1. i<j
2. array[i]+array[j] is divisible by k
Return how many such pairs exits in a given array.
the first line of ... |
9b622b264679f86db92393ac115ff01bb321b1b2 | Myoldmopar/MyPyOpt | /mypyopt/return_state_enum.py | 1,866 | 3.78125 | 4 | from typing import List
class ReturnStateEnum(object):
"""
This class simply defines some constants for how functions return
"""
Successful = 0
"""Search returned successfully"""
InfeasibleDV = -1
"""Search failed because the decision variable went out of the valid parameter space range"... |
1f5442852dc52e15b095e474091ad70e8c390ac7 | neromike/Data-Structures | /queue_obj.py | 4,663 | 4.34375 | 4 | class queue_obj(object):
"""
queue_obj is a class that creates a queue (FIFO; standing in line) and supports:
add - an instance method to add a new node to the end of the queue.
remove - an instance method to return the value from the first node of the queue, and remove it.
peek - an instance method to return t... |
91200b26b67c3c4657d00ab9791a9798cfc210d3 | nidhiwalia/bch5884 | /20oct6/Readout_pdb.py | 505 | 3.53125 | 4 | #!/usr/bin/env python3
#Nidhi Walia
import sys
pdbname=sys.argv[1]
f=open(pdbname,'r')
lines=f.readlines()
list=[]
for line in lines:
words=line.split()
words[1]=int(words[1])
words[5]=int(words[5])
words[6]=float(words[6])
words[7]=float(words[7])
words[8]=float(words[8])
words[9]=float(words[9])
words[10]=fl... |
407c3232156a8e1517470d1cc0591d353bccb287 | Enestvedt/python-challenge | /PyPoll/main.py | 1,554 | 3.578125 | 4 | import os
import csv
#import csv file and parse data
csv_path = os.path.join("Resources", "election_data.csv")
with open(csv_path) as csv_file:
election_data = csv.reader(csv_file, delimiter=',')
print(election_data)
header = next(election_data)
candidates = []
for row in election_data:
... |
c7eda2fb5c3cd9d518c3819a977b5ef9ec97818b | hongaar/meterkast | /components/helpers/timer.py | 1,490 | 3.734375 | 4 | import threading
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _r... |
c1ef085fb357fd39251517346228b2cb69cf2094 | kittu2539/CF-solutions | /1374B.py | 384 | 3.734375 | 4 | #solve function takes care of individual test cases
def solve():
n=int(input())
flag=1;c=0
while n>1:
if n%6==0:
n//=6
c+=1
elif n%3==0:
n*=2
c+=1
else:
flag=0;break
if flag:
print(c)
else:
... |
fbcaa3528aa84e084c91b9b4e4847210d25544a2 | kenkuo/practice | /adventofcode2018/day1/day1-2.py | 346 | 3.59375 | 4 | with open('input.txt', 'r') as f:
total = 0
s = set()
found = False
while found == False:
for num in f:
total += int(num)
if total in s:
print("found duplicate total")
print(total)
found = True
break
else:
s.add... |
a7a1bb95ede2f1664532edc52772b1c63aec40e7 | kenkuo/practice | /adventofcode2018/day2/day2-2.py | 456 | 3.515625 | 4 | def compare_words(a, b):
same_letters = []
for i,c in enumerate(a):
if c == b[i]:
same_letters.append(c)
if len(same_letters) == len(a)-1:
return same_letters
else:
return False
with open('input.txt', 'r') as f:
data = f.read()
for line in data.split():
for line_inn... |
9bbe2ecd1722cd3079a3951b48aa8c6640bd23eb | stevedudek/Hexes | /fancy_shows/Driving.py | 9,029 | 3.546875 | 4 | from math import sin
from color import random_hue, hue_to_color, random_color, black, gradient_wheel, rgb_to_hsv
from random import random, randint, choice
import HelperFunctions as helpfunc
def get_cell(coord):
h, x, y = coord
x = int(x)
y = int(y)
x_half = int(x / 2)
if x == 0:
return ... |
409a288837501993eddc4853df62941d2a30b3a1 | stevedudek/Hexes | /shows/game_of_life.py | 4,616 | 3.71875 | 4 | from color import random_hue, hue_to_color, random_color, black, change_color
from random import random, randint
import HelperFunctions as helpfunc
class LifeModel(object):
def __init__(self, hexmodel):
# similar to the Hex Model
# this model contains a dictionary of hex coordinates
# but... |
aaf40c84fb191c559c7ad98a161fa4b4e3f997bf | stevedudek/Hexes | /shows/Volcano.py | 4,484 | 3.578125 | 4 | from color import random_hue, hue_to_color, random_color, black, gradient_wheel, rgb_to_hsv, random_color_range
from random import random, randint, choice
import HelperFunctions as helpfunc
class Rock(object):
def __init__(self, hexmodel, h, main_color):
self.hexes = hexmodel
self.h = h
s... |
7c9daf1895ef5e13c77e28b6385fe8569d60b0e6 | 63036/pythonprogramminglab | /pandu.py | 906 | 3.84375 | 4 | import random
p=0
d=0
snl={8:37,13:34,38:9,11:2,28:4,40:68,52:81,76:97,65:46,93:64,89:70}
def rolldice():
return random.randint(1,6)
while True:
r = input("press r to roll the dice, q to quit :")
if r == 'r':
d = rolldice()
print("you got",d)
if d==6 or d == 1:
p=d
print("congratulations,you're in t... |
ecf02910d00470fe23809e176efd84ee8bc24582 | TheJakov/dartsChallenger | /game.py | 5,968 | 3.765625 | 4 | from random import randint
from colorama import Fore
from colorama import Back
from colorama import Style
import os
class game:
playGame = True
numberOfRounds = 0
# Each challange has its own text, value to add to score if completed and
# a value to decrease the score if not completed.
#
# EP... |
0aa493a8471b81c62a387e541c2fe82724b713d3 | Cecilia-x/Openmap_cleaning | /solutions.py | 5,260 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This module contains functions needed to clean data, depending different feature
of data.
'''
import re
#These are solutions for formatting values.
def clear_space(v):
return re.sub('\s', '', v)
def clear_comma(v):
return v.replace(... |
3dce57b5046b196c2f4dc27838078df9d4c30af6 | cjcormier/AI_Final_Project | /secret_hitler_ai/strategies/shoot.py | 1,625 | 3.515625 | 4 | """
Strategies to decide who to shoot.
"""
import random
from secret_hitler_ai.player import Player, Name
from typing import List
def liberal_shoot(player: Player, valid_players: List[Name]):
"""
Shoot the player who is the most likely to be fascist.
:param player: The player who is choosing whom to ... |
a7fb3a30723f55e3dbdea3f8baf12a8cc42ae355 | sam2020-4/Password-Locker | /pass_locker.py | 6,779 | 3.515625 | 4 | #!/usr/bin/env python3.8
import pyperclip #importing pyperclip for copying to clipboard
from user_class import User #imporing user class
from credential_class import Credential #importing credential class
def create_user(fname, lname, password):
'''
Function to create a new user account
'''
new_user = User(fnam... |
140343469dc68a3af9449d2a063044cb07c5d6ec | vsx-gh/crypto | /Caesar_GUI.py | 3,719 | 3.828125 | 4 | #!/usr/bin/env python
'''
File: Caesar_GUI.py
Author: Jeff VanSickle
Created: 20151116
Modified: 22015111
Putting Tkinter front-end on Caesar shift cipher program.
UPDATES:
yyyymmdd JV - Changed something, commenting here
INSTRUCTIONS:
'''
from Tkinter import *
import ttk
import crypto
import tkMessage... |
62c0b26e1db2e45bbacc8c3e2cef167f60e541ee | CSchool/LKSH2019 | /Novice/translate-joke/solutions/solution.py | 461 | 3.59375 | 4 | text = input()
print("""Привет, ребята!
Сегодня вы пишете олимпиаду "Старт".
Надеемся, она оказалась легкой для вас и вы сделали абсолютно все задания, прежде чем начать это.
Так как эта задача не принесет вам баллов (шутка) ((нет)), а только потратит ваше время)""")
|
5b29552624a1d600109101a1dcc43c3f5b9d80a6 | CSchool/LKSH2019 | /Novice/Loop/coord-quater/solutions/solution.py | 376 | 3.546875 | 4 | if __name__ == '__main__':
x, y = map(int, input().split())
if x == 0 or y == 0:
print('NONE')
else:
if x > 0:
if y > 0:
print('FIRST')
else:
print('FOURTH')
else:
if y > 0:
print('SECON... |
6ddab40c8ee7995460d3c402bd96ed1c07bf1d0e | Zoolyn/Blackjack | /blackjack_no_gui.py | 7,181 | 3.6875 | 4 | import deck
import card
import player
def main():
print('Now playing blackjack!')
# There is only one player in blackjack, not including the dealer
player1 = player.Player()
dealer = player.Player()
main_deck = deck.Deck()
main_deck.createDeck()
main_deck.removeJokers()
main... |
199ea17012eb941aaa62ef4fd5ae69027c9bbf8d | AndreySalikov/lesson2 | /get_answer.py | 228 | 3.609375 | 4 | answers = {"привет": "И тебе привет!", "как дела": "Лучше всех", "пока": "Увидимся"}
def get_answer():
question = input()
return answers[question].lower()
print(get_answer()) |
7ba8b8fa64db5aff3af1df72235f75910322c5cf | jerrywaller/20180613-STEM | /002-button_detect.py | 447 | 3.640625 | 4 | #!/bin/python
# it's messy; it might not work; but aren't we here to learn?
import RPi.GPIO as GPIO
# use Broadcom (BCM) pin numbering
GPIO.setmode(GPIO.BCM)
# set the pin high by default
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
# use edge detection to see if pin is pulled low
GPIO.wait_for_e... |
36a615627d1171919e59f70e4dc854778153747b | KaranKamath/Orbital-Apollo11-ChallengeSolution | /Example/Orbital-OSRC.py | 3,301 | 3.5625 | 4 | import urllib2
import json
from operator import itemgetter
import datetime
instructorList = ["weesun", "knmnyn", "wgx731", "Leventhan", "franklingu", "Limy", "Muhammad-Muneer"]
"""
This function fetches the json data for a given username
"""
def fetchJSON(userName):
urlString = "http://osrc.dfm.io/%s.json" % ... |
a957addf38e7350e384e309475a9d2834604fd84 | hrahadiant/mini_py_project | /shopping_list_with_function.py | 1,745 | 4.34375 | 4 | # basic shopping list with function and clean code
# has 3 command in this apps
# SHOW, HELP, and DONE
# add new command to save the list to my_shopping_list.txt
print("enter a new list for you...")
shopping_list = []
file_name = "my_shopping_list.txt"
# function to show the help
def show_help():
print("typing ... |
d1f58c80cea947152689e7a58ed0b71f42959819 | FloatingShepherd/dag-query | /node.py | 603 | 3.734375 | 4 | # a node object, which has name and links connect to parent and children.
# in our design, we only care about children nodes, which are connected by outLinks.
class Node:
def __init__(self, name, links):
self.name = name
self.outLinks = links or []
# add link going out from the node.
def addLink(self, l... |
04561429ef7140053a945c4b0b638deead4293ca | keshavseksaria/Optum_Stratethon | /nearestorgfinder.py | 923 | 3.78125 | 4 | def nearest(latval,lonval):
from math import cos, asin, sqrt, pi
def distance(lat1, lon1, lat2, lon2):
p = pi/180
a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2
return 12742 * asin(sqrt(a))
import pandas as pd
df=pd.read_csv("csv/organizati... |
05a3b733e4bce4bf25d379399b43600bcb115cec | FZenji/Sudoku | /baseSudoku.py | 1,272 | 3.734375 | 4 | def possible(x, y, n, board):
if any([board[x][i] == n for i in range(9)]): return False
if any([board[i][y] == n for i in range(9)]): return False
if any([board[((x//3)*3)+i][((y//3)*3)+j] == n for i in range(3) for j in range(3)]): return False
return True
def print_board(board):
print("-"*25)
... |
93c01cf7af6e6ae73971a73181d0f3dda0a7786e | 2monsta/goblin_game | /game.py | 5,979 | 3.5 | 4 | #include pygame
#include pygame which we got from pip
import pygame;
import random;
import time;
# from the math module(build into python) get the fabs object
from math import fabs, hypot;
#init pygame
# inorder to use pygame, we have to run the init method
pygame.init();
pygame.mixer.init();
screenX = 512;
screenY =... |
b783e6c4fe08b99941aeb60fecfda612723e08af | sportelance/HashMapWTest | /data_structures/hashmap.py | 1,251 | 3.6875 | 4 | class HashMap:
def __init__(self, size):
self.size = size
self.hash_map = self.create_buckets()
def create_buckets(self):
return [[] for i in range(self.size)]
def find_val(self, key):
hashed_key = hash(key) % self.size
bucket = self.hash_map[hashed_key]
found_key = False
found_v... |
25529fd283359e8b6c82e17c4dd57f342c264d50 | agonopol/battleship-ai | /battleship/ship.py | 2,301 | 3.671875 | 4 | import random
import numpy as np
class Ship(object):
def __init__(self, start, end):
super(Ship, self).__init__()
if start[0] == end[0]:
miny, maxy = [start[1], end[1]] if start[1] < end[1] else [end[1], start[1]]
self.cells = [[start[0], i] for i in range(miny, maxy + 1)]
... |
ec09cd206bf0de811f5173a33e2f07a79250f8f3 | tstelzle/AdventOfCode2020 | /python/03_day/script.py | 1,567 | 3.828125 | 4 | import csv
list_data = []
def read_data():
with open('data.csv') as data:
csv_reader = csv.reader(data, delimiter=' ')
for row in csv_reader:
horizontal = split(row[0])
list_data.append(horizontal)
def print_matrix(list_input):
for horizontal in list_input:
f... |
fff90d7e74dcab72a5e2608a74c3ab8765a8c972 | tstelzle/AdventOfCode2020 | /python/12_day/script.py | 5,694 | 3.8125 | 4 | import copy
def integer_to_direction(direction_int: int):
if direction_int == 0:
return 'N'
elif direction_int == 90:
return 'E'
elif direction_int == 180:
return 'S'
elif direction_int == 270:
return 'W'
def direction_to_integer(direction: str):
if direction == "... |
1496e0aa92d2b55df7a015c6707e42e5abb2817f | iaminjun/programmers | /문자열 내림차순으로 배치하기.py | 180 | 3.5 | 4 | def solution(s):
answer = ''
temp =[]
for ss in s:
temp.append(ss)
temp.sort(reverse = True)
for t in temp:
answer += t
return answer
|
c2fa3cb870160ab6ee4050961ff935146f35e997 | WaffleMeister/crumb-search | /src/trigramIndexer/parser/query_parser.py | 1,861 | 3.546875 | 4 | from src.trigramIndexer.parser.query_parsing_exception import QueryParsingException
class QueryParser:
@staticmethod
def parse_search_query(search_query):
"""
Given a word, parse out the trigrams
associated with that word.
Ex: "batman" => bat, atm, tma, man
... |
75237fcfcf5da0071c82db9e15803cc35a29f146 | nasheed24/mytestusingtutorial | /pytrain1.py | 563 | 4 | 4 | start_value=1
n=int(input("enter the number:"))
print("prime numbers between",start_value,"and",n,"are :")
for num in range(start_value,n+1):
prime= True
for i in range(2,num):
if (num%i==0):
prime= False
if prime == True:
print(num)
print("done.......")
'''if num >1:
fo... |
f23453b6eb53727044f441c7c241fa4f4abac1b0 | kngngop/route_design | /check_data.py | 1,931 | 3.875 | 4 | #當前座標與方位相加
def list_add(a,b):
c = []
for z in range(0,2):
c.append(a[z]+b[z])
return c
#檢查使用者輸入錯誤
def check_error(c,width,height):
if c>=0 and c<height and c<width: #若輸入的數字大於0,並且不超過長寬,則輸入正確
check_input=True
else:
print("Your input is out of range,please input again!") #輸入錯誤
c... |
f91a0e396abca6a8c96f040ca8cf28f8bcea67ae | dwash72/python-classes | /dict.py | 405 | 3.765625 | 4 | # d = {"name":1, "age":20}
# # print(d["s"])
# # print(d.get("name"))
# # print(d.update(age=30))
# print(d.get("m"), "not found")
#for loop
# d = {"name":"dwash", "address":"purasaiwalkam"}
# empty = {}
# for d,v in d.items():
# empty[d] = v
# print(empty)
# user_d = {"name":"dwash","phone number":"0889279272"}
#... |
ad1a1ffc94ad4761a0ecf250efbc57dc811646b0 | vontman/8_Puzzle_Ai | /puzzle.py | 5,331 | 3.96875 | 4 | from typing import List, Tuple, Iterable
from gamestate import GameState
N: int = 3
PuzzleBoard = Tuple[Tuple[int, ...], ...]
Move = Tuple[int, int, str]
State = Tuple[PuzzleBoard, str]
GOAL_STATE: GameState = GameState(board=((0, 1, 2), (3, 4, 5), (6, 7, 8)))
class InvalidPuzzleError(Exception):
'''
Error ... |
a9f439d13f781b47499ffd56d5b4108394ab7ec0 | ommanjrekar/om-repo | /scripts/data_to_csv.py | 771 | 3.515625 | 4 | import re
import csv
with open('info.txt') as file:#opens the input file contains raw data
x = file.read()#read the input file
content = re.split('\n', x)#split by using newline
example=csv.writer(open('emp.csv', 'w'), delimiter=',')#creates emp.csv file in write mode
example.writerow(['Id', 'Name', ... |
c718068a7ce876cd006f0a0a4347f8292aac96c2 | annusingh100995/bioinformatics_algorithms | /MATCHING_READS_TO_REFERENCE_SEQUENCE/Suffix_Tree.py | 2,126 | 3.734375 | 4 | class SuffixTree:
def __init__(self):
# root node
# -1 is used to indicate a leaf
self.nodes = {0:(-1,{})}
# index of the root node
self.num = 0
def print_tree(self):
for k in self.nodes.keys():
if self.nodes[k][0]<0:
print(k... |
c666f62182fa36c8282a02b8d4ed2365935158ae | tpgmartin/projectEuler | /python/problem1.py | 145 | 3.96875 | 4 | def multiples(num):
ans = 0
for x in range(1, num):
if (x % 3 == 0 or x % 5 == 0):
ans += x
return ans
print multiples(1000) |
a8059947d3baf94bdb10cbfe86b2d5caf32cdddd | cfcooney/EEG_data | /functions/useful_functions.py | 809 | 3.5 | 4 | # Convert labels to one-hot encoded values
def one_hot(y):
y = y.rehape(len(y))
n_values = np.max(y)+1
return np.eye(n_values)[np,array(y, dtype=np.int32)]
"""
Converts exponential numbers to floating point values.
e.g. 6.65714259e-04 to 0.00066571.
"""
def convert_to_float(value):
converted... |
d93964ac5a2ef4d0c4eba38b1f395195035094d0 | pallsv227/For | /Git_verkefni.py | 823 | 3.671875 | 4 | #Páll Gunnar Svansson 25.1.17
#dæmi 1
tala_1 = int(input("sláðu inn eina tölu: "))
tala_2 = int(input("sláðu inn aðra tölu: "))
svar = ((tala_1)+(tala_2))
print ("útkoman af þessum tölum er ", svar)
#dæmi 2
fornafn = input("sláðu inn fornafnið þitt: ")
eftirnafn = input("sláðu inn eftirnafnið þitt: ")
print ("halló",... |
df48ba62d4619969f29250ee1945d3596f012d69 | Hzz-hub/demo | /dictionary.py | 891 | 4.15625 | 4 | # customer = {
# "1": "one",
# "2": "two",
# "3": "three",
# "4": "four",
# "5": "five",
# "6": "six",
# "7": "seven",
# "8": "eight",
# "9": "nice",
# "0": "zero"
# }
# result = ""
# numbers = input("what is number.....")
# print(numbers)
# for number in numbers:
# a = type(... |
a957dcad16d95beabfddaff5b070fc4793a00f13 | minyisme/HBIntroProject | /projectbaseball.py | 10,104 | 3.78125 | 4 | #project for intro to python HB class
#will play a virtual baseball game
'''importing'''
#all imports
import random
'''end importing'''
'''scoreboard'''
#list of hits to fill in the visual scoreboard
#range 0 to 19 where 18 and 19 are total hits for each team
hits_by_team = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... |
150ff6e5826aa4b4f5f2c893ef75ff174c8b07a0 | lileowang/Python | /a11_Demo/a07_loop_with_enum.py | 142 | 4.1875 | 4 | """
Description:
- Loop with enum for index and value
"""
names = ['a', 'b', 'c']
for i, name in enumerate(names):
print(f'{i}: {name}')
|
fcd870e235dbd7d2b562b789956d4d233147cebc | bayajid/circinus_orbit_propagation | /python_runner/access_utils.py | 16,148 | 3.578125 | 4 | import sys
import numpy as np
from astropy.time import Time
def find_eclipse_times(start_time,timesteps,sat_ECI_t,u_from_sun ):
"""Based off Kit Kennedy's MATLAB version
simple first order approximation to find eclipse times for a satellite in
orbit around the earth. Assumes sun rays are parallel at earth'... |
5d50bc46a824750786f058f77a8a7b3d29a72db7 | yinhui1150/Program-life | /python/4-2.py | 523 | 3.75 | 4 | import random
secret = random.randint(1,10)
print(secret)
print('-----------------我爱鱼c工作室----------------------')
temp = input('猜一下数字\n')
guess = int(temp)
while guess != secret:
if guess > secret:
print('大了大了')
else:
print('小了小了')
temp = input('猜错了 猜一下数字\n')
guess = int(temp... |
f03d35d357fc4a75c7adbcad308cf7be5c5e52a2 | fishercoder1534/RandomPython | /oop_programming.py | 1,670 | 4.21875 | 4 | # class names are always capitalized while function names are always lowercase
class Sample:
pass
x = Sample()
print(type(x))
class Dog():
# CLASS OBJECT ATTRIBUTES
species = "mammal"
def __init__(self, breed, name):
self.breed = breed
self.name = name
my_dog = Dog("Lab", "Sammy")... |
2478c9a765eb051773bd86c38d7c60f1202a3821 | fishercoder1534/RandomPython | /dict.py | 972 | 3.828125 | 4 | # How to run this program:
# In terminal, run $python3 dict.py
print("Hello world!")
my_dict = {"key1": 123, "key2": "a_string", "key3": 123.32,
"key4": {'123_321': ['abc', 1, True, 'grabMe']}}
print("first_item: ", my_dict['key1'])
print("second_item: ", my_dict['key2'])
print("third_item: ", my_dict['key... |
18941903d5f843ddc4263c87b57dc407be77573a | fishercoder1534/RandomPython | /collections_examples.py | 879 | 3.734375 | 4 | from collections import Counter
from collections import namedtuple
from collections import defaultdict
my_list = [1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 3, 'a', 'abc', "fish"]
print(Counter(my_list))
sentence = "This is a super cool sentence, how cool is this?"
print(Counter(sentence.split()))
letters = "aaaaaaaabbbbbbbccccc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.