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 |
|---|---|---|---|---|---|---|
b5632888447e23f7c13bb2c13e96ee5cf585d879 | lblalyqwe/python | /ex15.py | 551 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from sys import argv
#将argv参数分包
script,filename = argv**
#打开指定文件,将内容返回给txt
txt = open(filename)
#打印文件名
print "Here's your file %r:" % filename
#txt的read方法,打印txt的文件内容
print txt.read()
print "Type the filename again:"
#显示提示符,输入文件名赋值给file_again
file_again
#打开指定文件,将内容返回给txt_again
txt... |
bf3481d263f2a2373ace81c736bddf7885d6e3a4 | bgwilf/PyCon2019 | /Circuit_Playground_Express_cpx_Library_Examples/cpx_touch.py | 707 | 3.5 | 4 | """This example uses the capacitive touch pads on the CPX. They are located around the outer edge
of the board and are labeled A1-A7. (A0 is not a touch pad.) This example prints "Touched (pad)"
to the serial console. Touch the touch pads to see the prints!"""
import time
from adafruit_circuitplayground.express import ... |
6e3f9e9d062c72000448b76f3b4f1ac4aaebb762 | zthottakara/Comcast-FruitMetadata | /solution.py | 3,505 | 3.640625 | 4 | #!/usr/bin/env python
#
#Author Zacharia Thottakara
#
#Program: Item Metric Evaluator
#
#Command Line Arguments:
#ARG1: Filename (optional)(default="./basket.csv")
#ARG2: AgeLimit (optional)(defautl=3)
import sys
import os
#FUNC
def trim(string):
return string.replace("\r","").replace("\n","")
def checkFileName(file... |
31e8cf5fcf312450972f33046ec6549aebe6fa91 | lurara/mini_eps | /mini_ep2/mini_ep2.py | 940 | 3.671875 | 4 | # Mini EP2 - Linguagem lenta
# Nome: Lara Ayumi Nagamatsu
# NUSP: 9910568
# como rodar:
# digite no terminal:
# 1.1 python3 mini_ep2.py
# obs: caso queira medir o tempo, rode no terminal:
# 1.2 time python3 mini_ep2.py
# implementado: contabilização apenas de ímpares
def main():
N = 1 << int(input("Digit... |
5a255285e2124af310dbfe2abc8656446c925327 | MINGJING-WU/Codes-and-Explanations | /Question 5 Answer/Q5_1.py | 585 | 3.828125 | 4 | l = 5 # The following sentence will be used
a = [[0 for i in range(l)] for i in range(l)]
# Create an empty grid without any beads
for i in range(l):
for j in range(l):
# The method to find the staggered coordinates
if (i + j) % 2 != 0:
a[i][j] = 'R'
else:
a[i][j] ... |
d63f6b2621592ff3ff2df6db4493df6dceba295d | CodecoolBP20161/python-pair-programming-exercises-2nd-tw-gubik_levente-balogh_daniel | /years/years_module.py | 311 | 3.90625 | 4 | from datetime import date
def years(age):
return (date.today().year+100-age)
def main():
name = input("What is your name?: ")
age = int(input("How old are you?: "))
print (name + ", you will be 100 years old this year: " + str(years(age)))
return
if __name__ == '__main__':
main()
|
ead4cd9620f823bcac506a2185e922a563aee7fe | to-grt/P4 | /P4 Classes + Sprites/Game.py | 2,712 | 3.578125 | 4 | ### IMPORT ##########################################################################
import random
from Grille import Grille
from Player_IA_Human import Human
######################################################################################
class Game:
def __init__(self, width, height):
self.players ... |
3a79b4b0332fae7be24baf7ad72daaea054a2724 | Tharshanamrt/Python-Programming | /alphabet.py | 112 | 4.15625 | 4 | r=raw_input()
print(r)
if(r>='a'):
print "alphabet"
elif(r>='A'):
print "alphabet"
else:
print "not a alphabet"
|
77801bb0afe84ba6c9ba06b6afeac55bcce505f2 | grootste/Networking | /stopand wait.py | 2,207 | 3.8125 | 4 | import time
#stop watch for checkig the time
def stopwatch(seconds):
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
print("The packets is being sent in has taken ---->", round(elapsed))
time.sleep(1)
return e... |
87fcf321a6b21c340dbb0087264fdc6739b86284 | Dant86/filesystem_queues | /ll.py | 3,284 | 3.90625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def append(self, newVal):
newVal = Node(newVal)
if self.head is None or self.tail is ... |
d01ce0e7833416205fba5520100b072a91e08c41 | Bridger45/class-stuff- | /time.py | 1,239 | 3.90625 | 4 | #bridger hope
#9/18
#get time
#import what is needed
import calendar
import time
from tkinter import *
from tkinter import ttk
from tkinter import font
def the_time():
seconds = calendar.timegm(time.gmtime())
current_seconds = seconds % 60
minutes = seconds // 60
current_minutes = minutes % 60
hou... |
7190818e21a4360f6ae5b05d29ab4c04dc715c91 | Bridger45/class-stuff- | /calculater.py | 502 | 3.75 | 4 | #bridger hope
#10/18
#basic calculater
def add(num1,num2):
sum_plus = num1 + num2
return sum_plus
def subtract(num1,num2):
diffrence = num1 + num2
return diffrence
def divide(num1,num2):
if num1 != 0:
quotient = num2 / num1
return quotient
else:
return 0
def remain... |
4023e0b04b4f1a8d624c224f050c31d0caeda075 | codecakes/random_games | /probability_combinatorics/iqr.py | 1,036 | 3.90625 | 4 | from numpy import median
def quartile_range(arr):
"""
Find out the Interquartile Range
"""
#if it is odd
if len(arr)%2 != 0:
left=median(arr[:len(arr)/2])
right=median(arr[len(arr)/2 + 1:])
else:
#if array is even
left = median(arr[:len(arr)/2])
right = m... |
eea5f70c53ebc65e680f7cfbfeedca1155fa8aee | codecakes/random_games | /pattern_matching_array.py | 661 | 3.5 | 4 | from collections import defaultdict
def int_repeating_pattern(alist):
l = defaultdict(int)
prev = ''
for num in alist:
prev += str(num)
l[int(prev)] += 1
sym1, sym2 = int(prev[:len(prev)//2]), int(prev[len(prev)//2:])
if sym1 == sym2 and sym1 in l:
l[sym1] += 1
... |
5663a8d062eb954ea42b7b34b23995a68710f2e6 | codecakes/random_games | /is_palindrome.py | 1,016 | 4.09375 | 4 | #another way of doing recursive palindrome
def is_palindrome(s):
ln = len(s)
if s != '':
if s[ln-1] == s[0]:
return True and is_palindrome(s[1:ln-1])
return False
return True
assert is_palindrome('abab') == False
assert is_palindrome('abba') == True
assert is_palindrome('madam')... |
54657c09a5d12aa5ea520f8e357e4a2e1e3816a7 | codecakes/random_games | /sorting/closest_pair.py | 4,423 | 4.03125 | 4 | """
Uncomment to see the flow of Operation.
"""
from math import sqrt
from numpy import inf
dist = lambda p1,p2: sqrt((p2[1] - p1[1])**2 + (p2[0] - p1[0])**2)
def bfd(alist):
"""
Given a presorted list in increasing order by x axis,
returns the minimum distance and its pair among the points.
alis... |
da88cb7843aecfce91e8e9a1238990cd8db8d563 | codecakes/random_games | /document_distance.py | 2,038 | 3.828125 | 4 | #!/usr/bin/python
"""
1. Given 2 strings
2. Convert them to lists
3. Get a word frequency counter of unique words
4. Get the dot product of common words
5. Get the product of the normalized dot products of each vector frequency
6. Divide step 4/5. That's the document distance
Detailed steps are as follows(Yes I stole... |
b966d98a422bf06c07a5e451d2a2a5721ccb5403 | codecakes/random_games | /snippets/resource_upgrade_time.py | 2,540 | 3.890625 | 4 | from math import log
from matplotlib import pyplot as plt
#more analysis here- http://www.codeskulptor.org/#user38_i4wi3LlKCS_0.py
def resources_vs_time(upgrade_cost_increment, num_upgrades):
"""
num_upgrades: num of upgrades=pairs of the form [current_time, total_resources_generated]
upgrade_cost_increme... |
1148929ddfa201cde4d2ebdf097c3663eced613e | codecakes/random_games | /simple_crawl_page.py | 17,643 | 3.5625 | 4 | # Simple page link crawler using PageRank. for academic purpose only.
import re
from string import punctuation
import requests
def get_page(url):
try:
if url == "http://www.udacity.com/cs101x/index.html":
return ('<html> <body> This is a test page for learning to crawl! '
'<p> I... |
f4b33448a5a87a62b6c818bc89676b2e3cd54b5f | aiswaryasankar/ggtts | /knapsack.py | 1,048 | 3.65625 | 4 | ## Aiswarya Sankar
## 4/21/17
## Knapsack Implementation
import numpy as np
def knapsack():
noItems = int(input())
totalWeight = int(input())
weights = int(input().split(','))
values = int(input().split(','))
table = np.zeros(totalWeight * noItems).reshape((totalWeight, noItems))
for item in noItems:
for w... |
cae23f0cad0203f75faa5c41f8b137a9911e408a | jaejunlee00/cs50-projects | /sentimental-mario/mario.py | 642 | 3.90625 | 4 | from cs50 import get_int, get_string
def main():
# Keep asking until the user gives a positive int
while True:
h = get_int("Height: ")
if h > 0 and h < 9:
break
counter1 = 1
counter2 = h-counter1
# print empty space first and then hash
for i in range(h):
for... |
a7b6bd48c9c81fb74a13b7f5d136985d44edd548 | razmikmelikbekyan/ACA_2019_python_lectures | /lectures/14_project_sample/b.py | 750 | 3.671875 | 4 | import ast
from typing import Dict, Tuple
import c
# print(f'type of "c"" object is: {type(c)}')
# print(f'name of "c"" object is: {c.__name__}')
def parse_string_dict(string_dict: str) -> Dict:
"""Convert a String representation of a Dictionary to a dict object."""
try:
return ast.literal_eval(str... |
fb5aa2fdac90911576ab24d0753fbb68b6729196 | razmikmelikbekyan/ACA_2019_python_lectures | /selected_solutions/matrix_determinant.py | 1,737 | 3.96875 | 4 | from typing import List
import numpy as np
def get_i_j_minor(matrix: List[List[int or float]], i: int, j: int):
"""Returns matrix by deleting its i-th row and j-th column."""
return [[x for k, x in enumerate(row) if k != j] for l, row in enumerate(matrix) if l != i]
def det(matrix: List[List[int or float]]... |
f65d0d677044624e03d82e2f43cb8c48a94f7226 | razmikmelikbekyan/ACA_2019_python_lectures | /homeworks/CapstoneProject/database/books.py | 1,422 | 4.28125 | 4 | from typing import Dict, List
BOOKS = "database/books.txt"
def create_books_data():
"""
Creates an empty txt file for storing books data. If the file already exists, it should
not do anything.
"""
pass
def get_all_books() -> List[Dict]:
"""Returns all books data in a list, where each item i... |
81f5967382b63f4cd65d80b1059b8fd881213d53 | jtacson/python-function | /function_stdoutput.py | 313 | 4 | 4 | #!/usr/bin/ env python
def myfuncOut():
name = raw_input ("Enter name:")
age = input ("Enter age:")
print "Hi! My name is", name + " and my age is", age
print "Hi! My name is %s and my age is %d" %(name, age)
print "Hi! My name is {} and my age is {}" .format(name, age)
print myfuncOut()
|
0bd00e6bd22ceef162a52946acf8c9947435789e | 1234zhangshuai/Basic-algorithm | /sum_two.py | 419 | 3.5 | 4 |
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[j] == target - nums[i]:
return [i, j... |
9219cece71372525cf58351d7fa23b5d4aecff4b | YellingF/Notes | /leetcode/Two_Sum.py | 2,709 | 3.578125 | 4 | # nums = [3,2,4]
# target = 6
# for i in range(len(nums)):
# if nums[i] >= target/2:
# mid_index = i
# break
# print([(nums[low], nums[high]) for low in range(mid_index) for high in range(mid_index, len(nums)) if nums[low]+nums[high] == target])
# class Solution:
# def twoSum(self, nums, target):
# ... |
281cd936e1d5d81f6e033e993b0c970435f9dba5 | YellingF/Notes | /leetcode/Remove_Duplicates_from_Sorted-Array.py | 2,665 | 3.8125 | 4 | # 我的代码
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
if len(nums) == 0:
return i
else:
for j in range(1, len(nums)):
if nums[j] != nums[i]:
i += 1
... |
f8ead2fccf58d986fe88279c0c350cd3a47cc9a8 | HwangSangBin/Level-Test | /2750-1.py | 712 | 3.8125 | 4 | def insertion(list, num):
for j in range(1, num):
key = num_list[j] # 얘를 조사해야돼
h = j - 1 # 인덱스값이 작은 값부터 비교해야지
while ((h != -1) and (list[h] > key)):
list[h + 1] = list[h] # key에 값을 저장해둬서 h + 1에 전에 있던 값을 고려하지 않아도 된다.
h -= 1
... |
27c9d127b0aed294d5eb142268731e7ed0b24a11 | HwangSangBin/Level-Test | /11729.py | 440 | 3.84375 | 4 | # 하노이의 탑 규칙
# 맨 밑에 있는 거를 옮길라믄 위에 있는 거 전부 다 다른 곳에 있어야됑
def hanoi(num, start, to, other):
if num == 1:
print("{0} {1}".format(start, other))
else:
hanoi(num - 1, start, other, to)
print("{0} {1}".format(start, other))
hanoi(num - 1, to, start, other)
floor = int(inp... |
9c168873474a6ecaa22f9e31ed4693e622d6f769 | HwangSangBin/Level-Test | /11720-1.py | 108 | 3.6875 | 4 | length = int(input())
num = input()
total = 0
for i in range(length):
total += int(num[i])
print(total) |
7dd07d9d331fff99614f2ca3355665e03907da54 | HwangSangBin/Level-Test | /2908.py | 99 | 3.53125 | 4 | num1, num2 = input().split()
num1 = num1[::-1]
num2 = num2[::-1]
print(max(int(num1), int(num2))) |
cc9f9dc9810af12141c6f005a9b951c25bffd1e0 | lowks/py-etlt | /etlt/cleaner/DateCleaner.py | 1,871 | 4.3125 | 4 | import re
class DateCleaner:
"""
Utility class for converting dates in miscellaneous formats to ISO-8601 (YYYY-MM-DD) format.
"""
# ------------------------------------------------------------------------------------------------------------------
@staticmethod
def clean(date):
"""
... |
5f59166ef3478ece7bb0bed7ea6e3fc02ef1ca44 | sb17027/ORS-PA-18-Homework07 | /task4.py | 1,336 | 4.34375 | 4 | """
=================== TASK 4 ====================
* Name: Number of Appearances
*
* Write a function that will return which element
* of integer list has the greatest number of
* appearances in that list.
* In case that multiple elements have the same
* number of appearances return any.
*
* Note: You are not allow... |
c30d355a9ead4b6ba11df99db3676bb7b6dd4d97 | kapoor-rakshit/BS4 | /parsing_tables.py | 592 | 3.5 | 4 | import bs4 as bs
import urllib.request
import pandas as pd
site=urllib.request.urlopen("https://pythonprogramming.net/parsememcparseface/").read()
soup=bs.BeautifulSoup(site,"lxml")
tablelist=soup.find_all("table")
for table in tablelist:
for row in table.find_all("tr"):
k=[]
for data in row.find_all("td"):
... |
d9fec576532335eae7f88fd233efd8093c830b22 | SkillfulGuru/Webscraping-BeautifulSoup-NZX | /web1.py | 872 | 3.625 | 4 | from urllib.request import urlopen
from bs4 import BeautifulSoup
#html = urlopen('http://www.pythonscraping.com/pages/page1.html')
#bs = BeautifulSoup(html.read(), 'html5lib')
# print(bs.h1)
from urllib.error import URLError
from urllib.error import HTTPError
# try:
# html = urlopen('https://pythonscrapingt... |
c189add0759752ef4d5e8783c2acdb963128ac76 | Rodrigo-neo/ProyectoComunicaciones2 | /QRdecode.py | 694 | 3.5 | 4 | import cv2
# read the QRCODE image
img = cv2.imread("output.png")
# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()
# detect and decode
data, bbox, straight_qrcode = detector.detectAndDecode(img)
# if there is a QR code
if bbox is not None:
print(f"QRCode data:\n{data}")
# display t... |
8b4b6deb1fe15edb1baee6b2adfd68dd198b7283 | Rhoana/windowed-prediction | /util/utils.py | 1,216 | 3.703125 | 4 | import numpy as np
import theano
import theano.tensor as T
def floatX(arr):
"""Converts data to a numpy array of dtype ``theano.config.floatX``.
Parameters
----------
arr : array_like
The data to be converted.
Returns
-------
numpy ndarray
The input array in the ``floatX``... |
479c33769655e9d6137f52968e471b0428687c39 | tsutterley/LSsurf | /LSsurf/matlab_to_year.py | 285 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 20:12:44 2019
@author: ben
"""
def matlab_to_year(t):
# approximate conversion of matlab date to year. Uses the matlab conversion
# datestr('jan 1 2000') -> 730486
return (t-730486.)/365.25+2000.
|
42358bf98f339e3bfafbb22868523d9e9191e949 | NZNathan/CyberRunner | /Documentation.py | 1,926 | 3.6875 | 4 | from Button import Button
class Documentation:
TEXT_SIZE = 20
HEADING_SIZE = 48
TEXT_COLOR = "#ffffff"
backBtn = None
tronImage = None
def __init__(self):
self.backBtn = Button("Back", 350, 550)
self.tronImage = loadImage("tron.jpg")
def draw... |
14dfbdb549baaeb8a8985d531344e56c523175e3 | harshvladha/Algorithms-and-Library | /SPOJ/MARBLES.py | 279 | 3.5625 | 4 | from math import factorial
def cleaninput():
return raw_input().strip()
def getint():
return int(cleaninput())
def getints():
return map(int, cleaninput().split())
for _ in xrange(getint()):
n, k = getints()
ans = factorial(n-1)/(factorial(n-k)*factorial(k-1))
print ans |
8e9fb29865bee4813760aeac342b13bda426b826 | harshvladha/Algorithms-and-Library | /SPOJ/codeagon1.py | 296 | 3.53125 | 4 | def cleaninput():
return raw_input().strip()
def getint():
return int(cleaninput())
def getints():
return map(int, cleaninput().split())
if __name__ == '__main__':
n, m = getints()
count = 0
while m>0 and n>0:
count+=1
m = m-n
n-=1
if n==0 and m>0:
print -1
else:
print count |
aa0267e91be06c76a467e498763fe281da9db1f0 | harshvladha/Algorithms-and-Library | /SPOJ/ONP.py | 1,088 | 3.640625 | 4 |
operators = set(['+', '-', '*', '/', '^'])
def cleaninput():
return raw_input().strip()
def toRPN(exp):
operandS = []
operatorS = []
for c in exp:
if c == '(':
operandS.append('(')
operatorS.append('(')
elif c == ')':
opS = []
while operandS[-1] != '(':
opS.insert(0, operandS.pop())
operan... |
ab42281357bdd9f0b415166c7f426a7b81ea2879 | sunny7697/Python | /clg ques/Q1.py | 623 | 3.921875 | 4 | # -*- coding: utf-8 -*-
#Q1. Number divisible by 7 not by 5 between two given inputs
"""
Created on Sat Aug 10 10:00:36 2019
@author: SUNNY THAKUR
"""
a = int(input("Enter 1st number "))
b = int(input("Enter 2nd number " ))
def func1(a,b):
print([i for i in range(a,b) if i%5!=0 and i%7==0])
#It will take lesse... |
8351596291ef3bc5df4f985740d29931552161c8 | mfreund/python_miniprojects | /rps_game/rps_game.py | 937 | 4 | 4 | import random
user = int(input("Enter a number from 0-2: "))
computer = random.randint(0, 2)
def get_hand(hand_number):
outcome = {0: "rock", 1: "paper", 2: "scissors"}
return outcome.get(hand_number)
def determine_winner(player_hand, comp_hand):
if player_hand == comp_hand:
return "Tie"
i... |
115490da841034c40a2c2c3029adede809f4c499 | mali0728/cs107_Max_Li | /pair_programming/PP9/fibo.py | 1,017 | 4.25 | 4 | """
PP9
Collaborators: Max Li, Tale Lokvenec
"""
class Fibonacci: # An iterable b/c it has __iter__
def __init__(self, val):
self.val = val
def __iter__(self):
return FibonacciIterator(self.val) # Returns an instance of the iterator
class FibonacciIterator: # has __next__ and __iter__
... |
78cd79fd8e494f15009f01ff6e464b136bfc0dba | mali0728/cs107_Max_Li | /homework/HW2/HW2_final/P3a.py | 1,454 | 4 | 4 | # Problem 3 Part a -- simple withdrawal function -- for Homework 2 of CS107
# Author: Max Li
def make_withdrawal(balance):
'''This function takes an account balance and pass it to its inner function which makes the withdrawal.
raise Value Error if the input is not allow (e.g. not a number)'''
if not isinst... |
5e6571759f3e916b1be59e8395871760f4aab60f | mali0728/cs107_Max_Li | /pair_programming/PP10/sentence.py | 460 | 3.890625 | 4 | #Collaborators: Max Li, Yujie Cai, Gabin Ryu, ChunChao Tseng
class Sentence: # An iterable
def __init__(self, text):
self.text = text
self.words = text.split()
def __iter__(self):
for word in self.words:
yield word
def __repr__(self):
return 'Sentence(%s)' % r... |
0ef36d3edf538d5e42fc751e8f321e8eebe6f61d | kali-linux-sh/4METHOD | /modulo/cifrado.py | 1,102 | 3.859375 | 4 | class Cesar(object):
def __init__(self, texto, opcion, clave=3):
self.clave = clave # clave < 26 obligatoriamente
self.texto = texto
# 'e' -> encriptar
# 'd' -> desencritar
self.opcion = str(opcion)
return self.getTraducirMensaje(self.opcion, self.texto, self... |
cf21ad3ffb354c425b3a16218ae1a6dde24832c4 | goulartw/noob_code | /curso-noob-python/repeticao/while.py | 455 | 3.78125 | 4 | x = 0
# while x <= 10:
# print(x)
# # x = x + 1
# x += 2
lista = ["banana", "maçã", "uva"]
# while x < len(lista):
# print(lista[x])
# x += 1
cod = 0
while True:
cod = int(input("número: "))
if cod == 1:
print(f"você digitou o número {cod}, vamos prosseguir!")
elif cod == 2:
print(f"você ... |
379181112c350d080fae6376a2cae3029ec35a9d | goulartw/noob_code | /curso-noob-python/variaveis-tipos-dados/hello.py | 1,409 | 4.3125 | 4 | # hello world
# print("hello world")
# string
# nome = input("Qual é o seu nome: ")
# print(nome)
# inteiros
# numero1 = int(input("Digite um número: "))
# numero2 = int(input("Digite um número: "))
# numero3 = int(input("Digite um número: "))
# calc = numero1 + numero2 * numero3
# print(calc)
# float
# numero1 = ... |
ada59bc04c4ce2767ae2fed7501a66fb7ab579fd | MiroslavPK/Python-OOP | /01 - Defining classes/Exercise/06 - Pokemon/project/trainer.py | 1,001 | 3.703125 | 4 | from project.pokemon import Pokemon
class Trainer:
def __init__(self, name: str):
self.name = name
self.pokemon = []
def add_pokemon(self, pokemon: Pokemon):
if pokemon in self.pokemon:
return 'This pokemon is already caught'
self.pokemon.append(pokemon)
r... |
a9bbf251e7d3e27ec4683a20f7e5bb69dc687c68 | ms-shakil/52-problems-and-solve | /problem_forty.py | 300 | 3.6875 | 4 | # The sum of the streams 2
inp = int(input("Enter the number:"))
def Myfunction(inp):
count= 0
for i in range(inp):
add =1
for j in range(i):
kk = j*add
add += kk
nn =i/add
count+=nn
return count
print(Myfunction(inp)) |
ae96f3c9099cb1140b2282676a00858794408e8e | ms-shakil/52-problems-and-solve | /problem_nine.py | 513 | 3.75 | 4 | # Run rate for ODI mathch
target = int(input("Enter the target run:"))
current_run = int(input("Enter the Current run:"))
current_over = input("Enter the current over:")
def Runrate(run,over,target):
Over = over.split(".")
ball = int(Over[0])*6 + int(Over[1])
bal_left = 300-ball
runleft = target - run... |
be75044e22e2e806ab98331b6e67781d08d71ea8 | ms-shakil/52-problems-and-solve | /problem_thirty_three.py | 303 | 3.671875 | 4 | inp = int(input("Enter divi 1: "))
inp2 = int(input("Enter divi 2 :"))
inp3 = int(input("Enter value:"))
def MyFunction(div1,div2,value):
for i in range(1,value,1):
mod = i % div1
mod1 = i % div2
if mod ==0 and mod1==0:
print(i)
MyFunction(inp,inp2,inp3)
|
492338fcadb8e926ef50ed7900039e0a02480ab7 | ms-shakil/52-problems-and-solve | /problem_twenty_nine.py | 340 | 3.90625 | 4 | # perfect number !
value = int(input("Enter the number:"))
def Perfect_Number(value):
count = 0
for i in range(1,value,1):
if value % i == 0:
count+= i
if count == value:
print(value,"is perfect number !")
else:
print(value,"is not perfect number !")
Perfect_Numbe... |
7c3c1cf40a029bb64f4326623d1ca826119879fd | ms-shakil/52-problems-and-solve | /problem_thirteen.py | 428 | 3.671875 | 4 | # how many inp caraacter have in there sentence
value= input("Enter a sentence:")
inp = input("Enter the cereter:")
def Myfunction(data,inp):
val = data.replace(" ", "")
lst = list(val)
count = 0
for i in lst:
if i == inp:
count+=1
if count == 0:
print(inp,"is not presen... |
007aef3079d586bfcfb0f558b8b057e10bac7ba5 | ms-shakil/52-problems-and-solve | /problem_fortheen.py | 304 | 3.53125 | 4 | # how many singal caraacter have this sentence.
value= input("Enter a sentence:")
def Myfunction(data):
val = data.replace(" ", "")
lst = list(val)
dic={}
for i in lst:
if i in dic:
dic[i]+=1
else:
dic[i]= 1
return dic
print(Myfunction(value)) |
f6a2fba853886d673af25fc5b152f3049f8e987c | royzamplus/idiomatic_py | /working_with_data/idiomatic.py | 1,164 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Use multiple assignment to condense variables all set to the same value
x = y = z = 'a'
# Avoid using a temporary variable when performing a swap of two values
foo = 'Foo'
bar = 'Bar'
(foo, bar) = (bar, foo)
# Chain string functions to make a simple series of transfor... |
46ba5f004a2f2168d10deb97f2c5f58445599d8d | purushotham91/Spotify-playlist-maker | /main.py | 1,515 | 3.53125 | 4 | import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pprint
# Authentication with spotify
client_id = "Your client id"
client_secret = "Your client secret"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
scope="playlist-modify-private",
redirect_uri="htt... |
1c74be7f4253b6b2d21b124dcea25059476c1ff3 | gatisnolv/planet-wars | /bots/rand/rand.py | 1,416 | 4 | 4 | #!/usr/bin/env python
"""
RandomBot -- A simple strategy: enumerates all legal moves, and picks one
uniformly at random.
"""
# Import the API objects
from api import State
import random
class Bot:
def __init__(self):
pass
def get_move(self, state):
# type: (State) -> tuple[int, int]
... |
6a98a213ff9063964adc7731056f08df3ac755ae | gatisnolv/planet-wars | /train-ml-bot.py | 2,062 | 4.25 | 4 | """
Train a machine learning model for the classifier bot. We create a player, and watch it play games against itself.
Every observed state is converted to a feature vector and labeled with the eventual outcome
(-1.0: player 2 won, 1.0: player 1 won)
This is part of the second worksheet.
"""
from api import State, uti... |
021827e2995fa8fa981ebe8220e4ab914fb9d008 | gatisnolv/planet-wars | /check_balance.py | 1,128 | 3.546875 | 4 | """
How biased are the generated states? Does one player have a clear advantage?
To check this for random-moving players we generate a random state, and play 100 random
games (ie. each move is a random choice). This gives us an estimate of the proportion
of terminal nodes in the game tree where player 1 wins. If this ... |
dd8339c3887150bb138bea20c41c1112b0b2e926 | bats64mgutsi/MyPython | /Programs/get_colour.py | 598 | 4.09375 | 4 |
# Extracts the an colour the colour of the fox in the string 'the quick brown fox jumps...'
# Batandwa Mgutsi
# 04/03/2020
sentence = 'The quick brown fox jumps over the lazy dog'
# The one is the size of the space before the colour
start = sentence.find('quick')+5+1
# The one is the size of the space after the col... |
09bfd4953bc24b2ab0eafac8b7bdb73074b1a4bf | bats64mgutsi/MyPython | /Programs/power.py | 205 | 4.40625 | 4 |
# Calculates a^b using a for loop
# Batandwa Mgutsi
# 25/02/2020
a = eval(input("Enter a: "))
b = eval(input("Enter b: "))
ans = 1
for _ in range(1, b+1):
ans *= a
print(a, "to the power of ", b, "is", ans) |
41895c829a967c20cb731734748fe7f407b364a3 | bats64mgutsi/MyPython | /Programs/graph.py | 2,244 | 4.28125 | 4 | # A program that draws the curve of the function given by the user.
# Batandwa Mgutsi
# 02/05/2020
import math
def getPointIndex(x, y, pointsPerWidth, pointsPerHeight):
"""Returns the index of the given point in a poinsPerWidth*pointsPerHeight grid.
pointsPerWidth and pointsPerHeight should be odd numbers... |
4e06c543a5ab069131cf634a14c5bf8f0d1bb53a | Gow965/Git_hub_workshop | /second.py | 101 | 3.875 | 4 | a = int(input("Enter the First number :"))
b = int(input("Enter the Second number :"))
c=a+b
print(c) |
081f6976fd0d4ef8fef033b6bd9fb63a5b9973df | alexlib/PyPostPiv | /pypostpiv/vorticity.py | 1,562 | 3.53125 | 4 | """A set of functions for analysis of vortex dynamics
"""
def vorticity(field, method=None):
"""Compute the vorticity of the field
Parameters
----------
field : Field2D
method: str, optional
A method for calculation of voritcity. Valid options are:
'circulation' -
...
... |
768ffb93219b9d95d73ec3075fbb191ed00837a6 | Tobi-David/first-repository | /miniproject.py | 625 | 4.15625 | 4 |
## welcome message
print("\t\t\tWelcome to mini proj! \nThis application helps you to find the number and percentage of a letter in a message.")
## User message input
user_message = input("This is my message ")
## user letter input
user_letter = input("this is my letter ")
## count letter in message
letter_fr... |
6b1193ba9091884c0b49e738f751574e35f74e37 | itamargru/CCD_Project | /algo/algoutiles/synthetic_data.py | 1,675 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
import os
from PIL import Image, ImageDraw
"""
this script creates a random circles on given images each with different color
tasks to fix on the script:
1. each circle should be be unique color and a dict between color to cl... |
734a16c6154e6563d4871861bbb31eb9ebb00191 | calmcoconut/Data-Structures | /8. Hash Tables/hashtable.py | 6,431 | 4.09375 | 4 | """
File: hashtable.py
Case study for Chapter 11.
# TODO ADD THE get AND remove METHODS
get will take the item requested as the parameter and will return the index of the item requested if the item is
found in the table; otherwise will return -1 for item not found
remove mehtod will take the item requested as the pa... |
e349f0efd7b72c038d6bf37fefbdc58dead3e116 | calmcoconut/Data-Structures | /4. Solving a grid BFS vs DFS/grid.py | 2,095 | 4.09375 | 4 | """
File: grid.py
"""
from arrays import Array
class Grid(object):
"""Represents a two-dimensional array."""
def __init__(self, rows, columns, fillValue = None):
self._data = Array(rows)
for row in range(rows):
self._data[row] = Array(columns, fillValue)
def getHeight(self):
... |
238fc1dafe6c26d86aa9e7265cd68c1092a16bb9 | zsoltibaba37/weight | /wsheet2.py | 2,994 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import os, sys
from termcolor import cprint
class Weight:
"""
Calculate the weight of plate
"""
def __init__(self, l, w, t):
"""
:param l: Length
:param w: Width
:param t: Thickness
"""
self.d = 7.85 # De... |
8c026a6cc6ae3afb497745eeb590d2d27fd06fb0 | ZionPF/python_class | /avengers/icon/Turtle_rance.py | 1,239 | 3.5 | 4 | import turtle
import random
import time
t = turtle.Pen()
t.speed(0)
t.up()
t.goto(-200,150)
for i in range(21):
t.write(i)
t.right(90)
t.down()
t.forward(300)
t.up()
t.backward(300)
t.left(90)
t.forward(20)
t.goto(0,180)
screen = t.getscreen()
cards = dict()
fhand = open('cards.txt'... |
e6d8a1e9346639e84121073324f9a791b80cb669 | Suskha/LinearRegressionGD | /test.py | 605 | 3.609375 | 4 | # y = ax + b
import dataParse
import calculationData
import fileOpen
#import downloadUrlFile
a = 0
b = 0
learningRate = 0.5
#Url = "https://s3.amazonaws.com/back-end-training/house-prices.csv"
# dataFileName=downloadUrlFile.download_file(Url,"data_number")
data_list = fileOpen.fileOpen("data_number.csv")
data_x, da... |
f6e981d720e75003b5c87277fcdd5aad2bbc71dc | mcafi/AdventOfCode | /days/day11/day11.py | 5,133 | 3.765625 | 4 | # DAY 11
# Part 1: arrange people in seats checking the 8 surrounding seats
# Part 2: arrange people in seats checking the 8 directions around each seat
import re
seats = []
# function for part 1
def occupiednearby(row, col):
count = 0
# top
if row > 0:
if seats[row-1][col] == "#":
c... |
637267a96a001520af71a7c748f1a05109726f5e | Colosimorichard/Choose-your-own-adventure | /Textgame.py | 2,513 | 4.15625 | 4 | print("Welcome to my first game!")
name = input("What's your name? ")
print("Hello, ", name)
age = int(input("What is your age? "))
health = 10
if age >= 18:
print("You are old enough to play.")
wants_to_play = input("Do you want to play? (yes/no) ").lower()
if wants_to_play == "yes":
... |
390fd7db51772e29e4641dcbd8542650065b0151 | CyanYoung/english_entity_recognize | /util.py | 285 | 3.5 | 4 | pos_dict = {'J': 'a',
'V': 'v',
'R': 'r'}
def map_pos(pos):
if pos[0] in pos_dict:
return pos_dict[pos[0]]
else:
return 'n'
def map_item(name, items):
if name in items:
return items[name]
else:
raise KeyError
|
efd77a79173dd359eafc4b6b0b2057c4242ec657 | JARE2001/programacion-competitiva-Gpo-120- | /NumberTheory/D.py | 359 | 3.65625 | 4 | #k is the final hour were we want to know the position of the cat
def catPosition(spots, k):
#if even cats will never cross
if( spots%2 == 0):
return (k%spots)+1
else:
return (((k//(spots//2))+k)%spots)+1
tests= int(input())
for test in range(tests):
temp = input().split()
print(ca... |
d3f40012da083979a5c97407e2e2b6a43346ece0 | december-2018-python/adam_boyle | /01-python/02-python/01-required/07-functions_intermediate_2.py | 2,453 | 4.15625 | 4 | # 1. Given
x = [[5,2,3], [10,8,9]]
students = [
{'first_name' : 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
z = [ {'x': 10, 'y': 20} ]
x[1][0... |
33a3a4156ddb9ce27d721afa209017390099e851 | NULL-POP/Problemas-de-Maratona | /Misc/Heap.py | 1,201 | 3.84375 | 4 | '''
verifica se uma arvore binaria representada como um array
é um heap balanceado - "balanceamento" é definido por:
1) é um heap
2) se uma subarvore à esquerda é incompleta, não pode ter ninguém na direita
3) a diferença nas profundidades das subárvores esquerda e direita deve ser no máximo ... |
b3aa58ce9eea323cc119822ed43ca761dbb866ab | entrkjm/pythonAlgorithms | /1065.py | 128 | 3.828125 | 4 | print(sum(i//100+i%10 == i//10%10*2 or i < 100 for i in range(1, int(input())+1)))
# why input() + 1 is used instead of input()? |
06764400005c798c17e7b86770f5a6f8087bdaa2 | mikebentley15/sandbox | /python/OptionalWriter.py | 1,831 | 4.03125 | 4 | import csv
class OptionalWriter:
'''
Mimics csv.writer interface but with optional filename. If the filename is
None, then methods do nothing.
If the file is given, opens the file in the __enter__() and closes in the
__exit__().
>>> with OptionalWriter(fname) as writer:
... writer.wr... |
2f964ab73c9acea070ac05b0265cae8144df5881 | mikebentley15/sandbox | /python/numpy/vecalign.py | 3,836 | 4 | 4 | #!/usr/bin/env python3
'''
Functionality to align two vectors together.
Provides the function vecalign(a, b) that takes two 3D vectors and returns a
rotation matrix that transforms b into a.
When this script is run directly, it runs its unit tests
'''
import numpy as np
from math import acos
def vecalign(a, b):
... |
1cd2d20b10dde66385384a91540e35a3f854c817 | mikebentley15/sandbox | /python/sockets/echo/echo_multiserver.py | 2,643 | 3.828125 | 4 | #!/usr/bin/env python3
'Simple server that listens and echos back any sent data'
import argparse
from select import select
from socket import socket, AF_INET, SOCK_STREAM
import sys
# AF_INET: means IPv4
# SOCK_STREAM: means TCP
def parse_args(arguments):
parser = argparse.ArgumentParser(
formatter_clas... |
dcfbbdf90ae41792f9bde19e940169a94c05eb61 | tomaccosheep/guild-class | /palindrome.py | 299 | 3.875 | 4 | pally = input("What is the palindrome you would like to input? ")
if (len(pally) % 2):
char_check = (len(pally) // 2) + 1
else: char_check = (len(pally) // 2)
print(char_check)
for i in range(char_check):
print(i)
if pally[i] == pally[(len(pally) - 1) - i]:
print('good')
else: print('bad')
|
5224c5700d5c67e3afad33fc572fb65261b1813f | tomaccosheep/guild-class | /dice3.py | 489 | 3.515625 | 4 | #from random import randrange
#
#def die(num_dice, num_sides=6, *args, **kwargs):
# for d in range(num_dice):
# print(text)
# print('Die #{} produces {}'.format(d, randrange(1, num_sides + 1)))
#
#
#die(text='hello', num_sides=6, num_dice=10)
#def make_list_of_strings(*args):
# return ' '.join(list(args))
#
#lst = ... |
62fa584bec5626b3b18d12bd8445ad8fa14053f2 | tomaccosheep/guild-class | /weather2.py | 1,420 | 3.75 | 4 | # search:{{ }}
import requests
# Declare a package with key parameter {{
package = {
'APPID': '61b3cff64285cad2b26550ab28e58fa8'
}
# }}
# Get parameters and then add them to the dictionary 'package' {{
# Use a while loop to force a choice between city or zip code {{
city_or_zip = 'unset'
while city_or_zip != '... |
f4d177d2cc6642ce8014083c4e4a5953e560fc7c | SeungHune/beakjun | /test_function.py | 818 | 3.515625 | 4 | def solution(n, delivery):
delivery.sort(reverse= True, key=lambda x:x[2])
# print(delivery)
mylist = ["?"] * n
# print(mylist)
for dv in delivery:
if dv[2] == 1:
mylist[dv[0]-1] = "O"
mylist[dv[1]-1] = "O"
elif dv[2] == 0:
if mylist[dv[0]-1] == "O... |
23680de4ab9ea69ebf5f8c7028a994392db8cbd3 | SeungHune/beakjun | /baekjun_2562.py | 166 | 3.71875 | 4 | mylist = []
max = 0
for i in range(9):
mylist.append(int(input()))
if mylist[i] > max:
max = mylist[i]
index = i + 1
print(max)
print(index) |
2b5ec5fd5435e237c4f4796caa1f6cc3c10100bb | SeungHune/beakjun | /exercise_coding_test_17.py | 2,213 | 3.65625 | 4 | # 연습문제 - 가장 긴 팰린드롬
def solution(s):
original = s
odd_max_num = 0
even_max_num = 0
for i in range(len(original)):
odd_check = True
even_check = False
odd_left = i
odd_right = i
letter_odd = original[i]
letter_even = original[i]
try:
if... |
a3f2c4e20f621a4c361fd21922c8e879b914db5f | SeungHune/beakjun | /kakao_2020_summer_1_1.py | 1,689 | 3.65625 | 4 | def solution(numbers, hand):
ans_list = []
numbers_ = []
r_pos, l_pos = 12, 10
for i in numbers:
if i == 0:
numbers_.append(11)
else:numbers_.append(i)
# print(numbers_)
for i in range(len(numbers_)):
if numbers_[i] == 1 or numbers_[i] == 4 or numbers_[i] == ... |
6d92a891992f6af7b4de9006ce4e62ea9be8b1ea | SeungHune/beakjun | /exercise_coding_test_6.py | 714 | 3.671875 | 4 | # 정렬 - 가장 큰 수
def solution(numbers):
if sum(numbers) == 0:
return "0"
new_numbers = []
for num in numbers:
new_numbers.append(str(num) * 3)
new_numbers.sort(reverse=True)
# print(new_numbers)
answer = ""
for num in new_numbers:
if len(num) == 3:
answer +... |
e0d467e8d0a3ce9067124f79dac4e580425b4371 | SeungHune/beakjun | /exercise_coding_test_9.py | 724 | 3.734375 | 4 | # 완전탐색 - 소수 찾기
from itertools import permutations
def isprime(num):
if num == 1 or num == 0:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def solution(numbers):
temp = []
for num in numbers:
temp.append(num)
mylist = []
... |
11187818dc98c885528b510a9c81db2bb63d05c5 | Seon2020/data-structures-and-algorithms | /python/code_challenges/fifo_animal_shelter/fifo_animal_shelter.py | 783 | 3.84375 | 4 | from code_challenges.stacks_and_queues.stacks_and_queues import Node, Queue
class Animal():
def __init__(self, type:str, name:str) -> str:
self.type = type
self.name = name
class AnimalShelter():
def __init__(self):
self.cats = Queue()
self.dogs = Queue()
def enqueue(self, animal:str) -... |
34533f19a443b7063a4637c798b97233006acc02 | Seon2020/data-structures-and-algorithms | /python/code_challenges/ll_zip/ll_zip.py | 698 | 4.375 | 4 | def zipLists(list1, list2):
"""
This function takes in two linked lists and merges them together.
Input: Two linked lists
Output: Merged linked list the alternates between values of the original two linked lists.
"""
list1_current = list1.head
list2_current = list2.head
while list1_current and list2... |
04f7f3d62fe77d102c4bf88ef08621bb6b0b1740 | Seon2020/data-structures-and-algorithms | /python/code_challenges/reverse_linked_list.py | 351 | 4.28125 | 4 | def reverse_list(ll):
"""Reverses a linked list
Args:
ll: linked list
Returns:
linked list in reversed form
"""
prev = None
current = ll.head
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
l... |
d7435573fb16e9215320450fdb2c24fa678dc75c | yifatBi/DataHandlingCourse | /task4.py | 710 | 3.640625 | 4 | # 1
def range_dict(a, b):
return {str(i): [i] for i in range(a, b + 1)}
# 2
def list_to_last_letter_map(str_list):
dictionary = {}
for word in str_list:
current_key = word[:1]
dictionary[current_key] = (dictionary.get(current_key) or []) + [word[1:]]
return dictionary
# 3
def most_co... |
6cc81047436aa509d6beef694e22dff113bc942a | done992/pscript | /kids/str_in_float.py | 409 | 3.9375 | 4 | #------------------------------------------
age = 10
age_str = str(age)
if age_str == '10':
print("age_str == \'10\'")
age_int = int(age_str)
if age_int == 10:
print("age_int == 10")
#------------------------------------------
money = 10.5
money_str = str(money)
if money_str == '10.5':
print("money_str == \'10.5\... |
a92b75897a46616a88aff9fc8079da3bef422701 | ToyasDhake/ENPM661-ProjectOne | /TextEightPuzzle.py | 1,799 | 3.734375 | 4 | from SolverLogic import Puzzle
from SolverLogic import Solver
# Get initial state from user
board = input("Enter borad:- ")
# Converts user input to 3x3 matrix used by solver algorithm
board = board.replace(" ", "")
board = list(board)
gameBoard = []
count = 0
for _ in range(3):
temp = []
for _ in range(3):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.