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 |
|---|---|---|---|---|---|---|
12906a6927074f22d90e2ee975a3957f0a3e69e0 | Ivychen99/AE402_KUKUO | /moving.py | 1,207 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 10:27:24 2021
@author: konan
"""
import pygame,random
Black = (0,0,0)
White = (255,255,255)
black = (0,0,0)
pygame.init()
size = (700,500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("方塊")
do... |
7ae2412ac6dfaa7b44f766c7419be8a80a9bd2d7 | svnikolaev/screen | /screen.py | 10,287 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pygame
from random import random
SCREEN_DIM = (800, 600)
class Vec2d():
"""Реализовать класс 2-мерных векторов Vec2d. В классе следует определить методы для основных математических
операций, необходимых для работы с вектором: Vec2d.__add__ (сумма), Vec2d... |
1dedea559afd628235f6c58e284e5b6193e08a9a | Alexito-01/lab-05-js-py | /greetings.py | 84 | 3.84375 | 4 | username = input("What is your name? ")
print("Hello there, " + str(username) + "!") |
74ae9c1c92272b3cd54e2a76269ddf32994c5822 | brentholmes317/Project_Euler_Problems_1-10 | /Project_Euler/13_adjacent.py | 1,086 | 4.34375 | 4 | from sys import argv, exit
from check_integer import check_input_integer
"""
This reads a file and finds the largest product that can be had by multiplying
13 adjancent numbers. The program needs the final line in the text to be blank.
"""
script, filename = argv
txt = open(filename)
reading = 1 #keeps track of if... |
a743aabc9ab1fc15f8f5264af3b59dcbad5fc870 | brentholmes317/Project_Euler_Problems_1-10 | /Project_Euler/Pallindrome.py | 1,250 | 4.53125 | 5 | """This program will find the largest pallindromic product of two three digit
numbers"""
#this program checks whether a 5-6 digit number is a pallindrome
def is_pallindrome(number):
#first we find if it is a 5 or 6 digit number
if number // 100000 == 0:
d5 = number // 10000
d4 = (number % 1000... |
ba55094bf9b20980ed3b20a7a31c8d63c375b5cb | saberhark/python_coding | /venv/programmers/02.StackQue/que_02.py | 639 | 3.5 | 4 | def solution(priorities, location):
answer = 0
cnt = 0
max_pri = sorted(priorities, reverse=True)
while priorities != []:
if priorities[0] == max_pri[0]:
priorities.pop(0)
max_pri.pop(0)
cnt += 1
if location == 0:
answer = cnt
... |
1ed7990f236bf48e38eb69f81ff76edf5a9d3d1b | jfangmeyerjr/TextMining | /use_nltk.py | 29,096 | 3.53125 | 4 | import nltk
# nltk.download() first time only
from nltk.book import * # necessary each time to put info in memory
print(list(set(text7))[:10])
Last login: Sat Aug 26 10:18:33 on console
Jamess-MBP:~ JamesFangmeyerJr$ cd '/Users/JamesFangmeyerJr/Documents/Python Data Science/Text Mining'
Jamess-MBP:Text Mining JamesFang... |
b388cd8d0981fd0398f06cfdfae1b95034ae8a0a | michaelkornblum/python-studies | /object-oriented/pets.py | 789 | 3.890625 | 4 | class Pets():
animals = []
def __init__(self, animals):
self.animals = animals
def walk(self):
for animal in self.animals:
print(animal.walk())
class Cat():
is_lazy = True
def __init__(self, name, age):
self.name = name
self.age = age
def walk(self)... |
459566e7965c5d3be1d8ad30959b342b8e5b19db | daleione/lintcode | /longest-palindrome.py | 977 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# http://www.lintcode.com/zh-cn/problem/longest-palindrome/
class Solution:
# @param {string} s a string which consists of lowercase or uppercase letters
# @return {int} the length of the longest palindromes that can be built
def longestPalindrome(self, s):
d = {}
f... |
4f281ea387fe45484a811a65dbcc2b1666ad6e41 | daleione/lintcode | /reverse-words-in-a-string.py | 166 | 3.59375 | 4 | def reverseWords(s):
"""
:type s: str
:rtype: str
"""
l = s.split()
l.reverse()
ret = ' '.join(l)
return ret
print reverseWords("")
|
f302df7720d5683de71e5dc14897c2d939268d76 | Aman2198/DSA_Combined | /Arrays/Union_Of_Array/unionArray.py | 1,202 | 3.890625 | 4 | from collections import Counter
arr1 = [85,25,1,32,54,6]
arr2 = [85, 2]
# Method 1 (Using inbuilt library)
count1 = Counter(arr1)
count2 = Counter(arr2)
print("Union of two array ", list((count1|count2).keys()))
print("Intersection of two array ", list((count1&count2).keys()))
# Metho 2 (Using dictionary in python... |
1c6ac6d8251889d2c0876c0ad856a9937a7f1644 | lapadolwcodium/exercise | /python/isogram/isogram.py | 1,086 | 3.53125 | 4 | from functional import seq
def is_isogram(string):
is_pass = False
if not string:
is_pass = True
if string.islower():
is_pass = True
if "-" in string:
is_pass = True
center_string = string[1:-1]
for cn in center_string:
if center_string.count(cn) > 1:
... |
4ba2ae391a57894cb7272e2d36d96e222b0c91d3 | lapadolwcodium/exercise | /python/sieve/sieve.py | 414 | 3.890625 | 4 | def sieve(limit):
re_primes = set()
primes = []
if limit > 1:
primes.append(2)
for counting in range(3, limit + 1, 2):
if counting not in re_primes:
primes.append(counting)
re_primes.update(range(counting ** 2, limit, counting))
# print ("re_prime", r... |
00856fb10a0633188e95522c65c1b65edd1dd51a | zapfdk/pyfootballscoring | /tests/test_gamestate.py | 5,817 | 3.640625 | 4 | import unittest
from footballscoring.definitions import Team, Score
from footballscoring.gamestate import GameState
class GameStateTest(unittest.TestCase):
def setUp(self):
self.game_state = GameState()
def testInitState(self):
print("Testing initialization of game state...")
self.as... |
fc2f625aa5540c5b677b49cbcc4e61980b5ded0c | iliescufm/pygame | /spacemax/generic/generic.py | 5,794 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: latin-1 -*-
import pygame,os,sys
from pygame.locals import *
pygame.font.init()
global rouge,vert,bleu,noir,jaune,orange,blanc
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
BLACK=(0,0,0)
YELLOW=(255,255,0)
ORANGE=(255,140,0)
WHITE=(255,255,255)
PINK=(255,0,255)
GREY=(128,128,128)
... |
9a7e5e40de47efccb9e8a3722c91c959ad5bfc7f | zhangxihao/longbow | /Code/ROBOT/cbms_order/Search&Assert/Assert.py | 420 | 3.734375 | 4 | # coding:UTF-8
class Assert(object):
def assertEquals(self, expected, actual):
'''比较两个值是否相同,相同返回True,不同返回False。
:param expected:预期结果。
:param actual:实际结果。
:return:返回值。
'''
if expected == actual:
return True
else:
return False
a = Asser... |
c2d079682609c142f9d690e369c788d17dc763ee | beyzakrklk/GlobalAIHubPythonHomework | /Proje/Proje.py | 2,008 | 3.921875 | 4 | class Student:
name =""
surname =""
course=[]
course_not={}
def __init__(self, studentName, studentSurname):
self.name = studentName
self.surname = studentSurname
def course_kayit(self,course_name):
self.course.append(course_name)
def course_yazdir(self):
for... |
0192eee5ea404e96cb16db8fab8a149cddbf541e | 36rahu/codewar_works | /21-4-2015/vowel_count.py | 216 | 3.859375 | 4 | '''
Return the number(count) of vowels in the given string. We will consider a, e, i, o, and u as vowels for this kata.
'''
def getCount(inputStr):
return len(inputStr)-len(inputStr.translate(None,'aeiou'))
|
b942302e280c289fceac406b562b7fb05b7cab36 | 36rahu/codewar_works | /22-4-2015/product_of_diagonal.py | 341 | 4.3125 | 4 | '''
Description:
Given a list of rows of a square matrix, find the product of the main diagonal.
Examples:
main_diagonal_product([[1,0],[0,1]]) => 1
main_diagonal_product([[1,2,3],[4,5,6],[7,8,9]]) => 45
'''
def main_diagonal_product(mat):
result = 1
for i in range(len(mat[0])):
result *= mat[i][... |
82691f635644e624723300e2bcaa7489983ded68 | ggorlen/nb_whiteboarding | /2018-12-12/concurrent_sum.py | 4,382 | 4.0625 | 4 | """
12/12/2018: Problem 4 solution
Given 100 computers that each gives you a number when you make
a function call with the computer's ID, sum up the numbers.
"""
NUM_COMPS = 100
def makeGetNumFromCompId(nums = None, failureLikelihood = 0):
"""
Make a function that simulates getting a number from some remote... |
068a3718e2e38c5f586d42ca1177bb073cf1b2f9 | PnS2019/Group_1_BOBO | /session6/rename.py | 996 | 3.53125 | 4 | import os
#Rename.py
#1. Place this file into the project folder
#2. Create another folder called "data" in the same directory
#3. In the data folder, create some more folders called by the objects of the traindata
#4. Fill the folders with pictures of the corresponding objects in .jpg format
#5. Run this script ONCE =... |
153705a0ea3ff05d7e59fcd5bee4f28ac60ce413 | muhammeta7/CodeAcademyPython | /strings_cons_output.py | 1,542 | 4.375 | 4 | # Create a string by surrounding it with quotes
string = "Hello there "
# For words with apostrophe's us a backslash \
print "There isn\'t flying, this is falling with style!"
# Accesing by index
print fifth_letter = "MONTY"[4] # Will return Y
# String methods
parrot = "Parrot"
print len(parrot) # will return numb... |
235c0fa2dd6f20a6f5caf016e59599a2bb24be13 | wlpzyx/pythonAdvace1811 | /day0212/homework1.py | 246 | 3.90625 | 4 | class person(object):
#类属性
name = "abc"
def __init__(self,_hp) -> None:
#实例属性
self.hp=_hp
s = person(10)
print(s.name,s.hp)
print(person.name)
#print(person.hp) #类属性不能操作实例属性 |
05c7ea173cb349f0c277ed0b5b5134e78d58a46e | danielhensilva/exercism | /python/rotational-cipher/rotational_cipher.py | 525 | 3.8125 | 4 | def rotate(text, key):
if text is None or len(text) == 0:
raise Exception('Invalid text')
if key < 0 or key > 26:
raise Exception('Invalid key')
cipher = ''
for char in list(text):
if not char.isalpha():
cipher += char
continue
if char.istitl... |
598768ac97d73068511606617b003142fcbcc7c1 | anbarasanv/PythonWB | /Merge Sort Recursive.py | 890 | 4.21875 | 4 | #Time complexity O(n log n)
def merge(left,right):
'''This Function will merge 2 array or list'''
result = []
i,j = 0,0
#Comparing two list for smallest element
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i +=1
else:
... |
2fddaa6b736b8434f302fda4e634ae0836e06004 | lintangpratama/machinelearning | /linear_regression/sales_revenue_predict/main.py.py | 1,384 | 3.859375 | 4 | # Import the library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Read the csv file
dataset = pd.read_csv('D:\Sales_Data.csv PATH')
# Make a X and Y variable that declares ... |
b6dead1776f9cef3d661f061612b86e9d2067952 | akshay399/pythonproject | /source/userdbcreator.py | 647 | 3.890625 | 4 | import sqlite3
def userCreator():
conn=sqlite3.connect('user.db')
c=conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS user (
passwd text,
name text PRIMARY KEY,
mail text,
receipt_code varchar
)""")
conn.commit()
conn.commit()
# print(c.fetchall())
conn.close()
# c.execute(""... |
e495f6990c1f590d7e835a0aae39ff8cb77f081c | dorb4r/algorithms_data_stuctures | /union_find/percolation.py | 1,381 | 3.515625 | 4 | from sys import argv
class Percolation:
# // creates n-by-n grid, with all sites initially blocked
def __init__(self, n: int):
self.grid = [[-1 for x in list(range(0, n))] for x in list(range(0, n))]
self.open_site_counter = 0
# // opens the site (row, col) if it is not open already
d... |
328e870a5e34b3f6c0495688b6b263a034f6f427 | lansevenit/520 | /carro.py | 188 | 3.65625 | 4 | #!/usr/bin/python3
class Car():
def __init__(self,cor,tipo):
self.cor = cor
self.tipo = tipo
car1 = Car('preto','crv')
print(car1.cor)
print(car1.tipo)
|
b6e0230e2a9b351a48a22670801882983e1200ff | lansevenit/520 | /teste2.py | 133 | 3.828125 | 4 |
while True
try:
n = int(input("Digite um numero:" ))
print(num)
except Exception as e:
print('Não é um inteiro')
|
6a16980d8a56c6fec79106e222c85559196cfd95 | onewns/TIL | /algorithm/etc/BOJ20309.py | 541 | 3.578125 | 4 | import sys
sys.stdin = open('../input.txt', 'r')
def is_possible_triple_sort(arr): # 짝수번 인덱스에는 홀수, 홀수번 인덱스에는 짝수 가 와야 정렬 가능
for i in range(len(arr)): # 숫자 배열을 둘러보면서
if not (arr[i] + i) & 1: # 해당 숫자와 그 인덱스의 합이 홀수가 아니면
return "NO" # NO를 출력
return "YES" # 불가능한 부분이 없으면 YES 출력
n = int(inp... |
2797b4bce7381ca5d0df5f47df68046bf75ad825 | onewns/TIL | /algorithm/BinarySearch/BOJ_2805.py | 1,399 | 3.671875 | 4 | import sys
sys.stdin = open('../input.txt', 'r')
"""
def binary_search(height, start, end):
left, right = start, end - 1
idx = -1
while left <= right:
mid = (left + right) // 2
if height < trees[mid]:
idx = mid
left = mid + 1
else:
right = mid - 1... |
73018554e8b2417f4299f7d335d692e6d6325d92 | onewns/TIL | /ps/BOJ_10988/solution1.py | 260 | 3.671875 | 4 | import sys
sys.stdin = open('PS/input.txt')
input = sys.stdin.readline
def solution(string):
if is_palindrome(string):
return 1
return 0
def is_palindrome(string):
if string == string[::-1]:
return True
return False
print(solution(input())) |
4b692ec03f38ed9071d7e43ba41eaac48f0b18d0 | onewns/TIL | /algorithm/BruteForce/PG_키패드누르기.py | 1,475 | 3.625 | 4 | """
시작 오후 5:56
끝 오후 6:11
"""
def solution(numbers, hand):
answer = ''
locations = {
1: (0, 0), 2: (0, 1), 3: (0, 2),
4: (1, 0), 5: (1, 1), 6: (1, 2),
7: (2, 0), 8: (2, 1), 9: (2, 2),
0: (3, 1)
}
right = (3, 2)
left = (3, 0)
for number in numbers:
if numb... |
a72588fbd74f8237348ed9e2cac47d30b1499caf | onewns/TIL | /algorithm/etc/BOJ_11653.py | 629 | 3.5 | 4 | import sys
sys.stdin = open('../input.txt', 'r')
# 에로토스테네스 => 느림
n = int(input())
prime_candi = [1 for _ in range(n + 1)]
for num in range(2, n + 1):
if prime_candi[num]:
while not n % num:
print(num)
n //= num
if n == 1:
break
for k in range(num * 2, n ... |
535d825a44a857da8ccb8e31ce2b451e9b8c0ec5 | orangecsy/CodeRepo | /Python/Sort/FastSort.py | 1,017 | 4.0625 | 4 | '''
目的:快速排序数组
算法:利用递归的思想,设第一个元素为中间值,从第二个元素开始遍历,
当小于中间值时放到左边,大于中间值时放到右边。然后对左右分别递归,
最后返回合并后的数组。
输入:待排序数组,如:[3, 7, 4, 8, 6, 1, 5, 2, 9]
输出:已排序好数组,如:[1, 2, 3, 4, 5, 6, 7, 8, 9]
时间复杂度:O(nlogn) 空间复杂度:O(nlogn)
算法不稳定
'''
def fast_sort(arr):
if len(arr) <= 1:
return arr
else:
middle_value = arr[0]
... |
d6f79f6c697343a797d1d353c0fcfbde6524abe2 | bimri/programming_python | /chapter_5/testexit_fork.py | 1,517 | 3.546875 | 4 | "Process Exit Status and Shared State"
"""
fork child processes to watch exit status with os.wait; fork works on Unix
and Cygwin but not standard Windows Python 3.1; note: spawned threads share
globals, but each forked process has its own copy of them (forks share file
descriptors)--exitstat is always the same here but... |
3000f9b65ad6926b0274a5d94ea41a7e2608781f | bimri/programming_python | /chapter_1/person_start.py | 1,107 | 4.125 | 4 | "Step 3: Stepping Up to OOP"
'Using Classes'
class Person:
def __init__(self, name, age, pay=0, job=None):
self.name = name
self.age = age
self.pay = pay
self.job = job
if __name__ == '__main__':
bob = Person('Bob Smith', 42, 30000, 'software')
sue = Person('Sue Jone... |
f304697778a5938976fa5588eadc062febe62399 | bimri/programming_python | /chapter_4/oswalk-visitor.py | 1,125 | 3.859375 | 4 | "The os.walk visitor"
'''
To make it easy to apply an operation to all files in a complete directory tree, Python
comes with a utility that scans trees for us and runs code we provide at every directory
along the way: the os.walk function is called with a directory root name and automatically
walks the entire tree at r... |
0d3385a3761677af6737688d400eb8a6a3e12a2e | bimri/programming_python | /chapter_8/buttonpics-func.py | 2,122 | 4 | 4 | "Fun with Buttons and Pictures"
from tkinter import * # get base widget set
from glob import glob # filename expansion list
import demoCheck # attach checkbutton demo to me
import random ... |
0d48f98eb1d5187263e3ea9ba18947c8c005ae82 | bimri/programming_python | /chapter_5/testexit_thread.py | 1,949 | 3.765625 | 4 | "Thread Exits and Shared State"
'threads run in parallel within the same process and share global memory'
"""
spawn threads to watch shared global memory change; threads normally exit
when the function they run returns, but _thread.exit() can be called to
exit calling thread; _thread.exit is the same as sys.exit and r... |
6da5e42f9e995ec5882cfa65f9a69c2505b92aa9 | bimri/programming_python | /chapter_8/demo-check-auto.py | 766 | 3.8125 | 4 | # check buttons, the easy way
from tkinter import *
root = Tk()
states = []
for i in range(10):
var = IntVar()
chk = Checkbutton(root, text=str(i), variable=var)
chk.pack(side=LEFT)
states.append(var)
root.mainloop() # let tkinter keep track
print([var.get() for var in stat... |
cde5561c9a4a2163414ff44ec2376cea432e3f97 | bimri/programming_python | /chapter_3/teststreams.py | 1,926 | 4.09375 | 4 | "Redirecting Streams to Files and Programs"
'''
standard output (and print) text appears in the console window where a
program was started, standard input (and input) text comes from the keyboard, and
standard error text is used to print Python error messages to the console window.
Redirection is useful for things lik... |
60f84f7c9fb4a353ec792cde86624ecdee114629 | bimri/programming_python | /chapter_5/thread-add-random.py | 1,408 | 3.625 | 4 | "Synchronizing access to shared objects and names revisited"
'''
threads need to synchronize their changes to any item that may be shared across thread
in a process—both objects and namespaces:
• Mutable object in memory
• Names in global scopes
• The contents of modules
For instance, even simple global va... |
8958fc2fccdfdd3bf5a556f1f346fe82fc34d26d | bimri/programming_python | /chapter_8/message.py | 634 | 4.0625 | 4 | "Message and Entry"
'''
The Message and Entry widgets allow for display and input of simple text. Both are
essentially functional subsets of the Text widget; Text can do everything
Message and Entry can, but not vice versa.
'''
"Message"
'''
The Message widget is simply a place to display text.
Message splits up long ... |
1b9044874045b57c872786830739618e66b062cc | bimri/programming_python | /chapter_8/demo-scale-simple.py | 677 | 3.96875 | 4 | "Scales and variables"
from tkinter import *
root = Tk()
scl = Scale(root, from_=-100, to =100, tickinterval =25, resolution =10)
scl.pack(expand=YES, fill=Y)
def report():
print(scl.get())
Button(root, text='State', command=report).pack(side=RIGHT)
root.mainloop()
"""
Its scale displays a
range from −100 to ... |
754c70ab0aa906f54d222730f5ee86f8ed708b71 | bimri/programming_python | /chapter_7/gui1-old.py | 1,272 | 3.828125 | 4 | "One More for Old Times’ Sake"
from tkinter import *
Label(None, {'text': 'Hello GUI world!', Pack: {'side': 'top'}}).mainloop()
'''
This makes the window in just two lines, albeit arguably gruesome ones! This scheme
relies on an old coding style that was widely used until Python 1.3, which passed
configuration opti... |
9ae6c269b41521b7ededa35ccae246557185174f | bimri/programming_python | /chapter_7/gui2.py | 492 | 4.28125 | 4 | "Adding Buttons and Callbacks"
import sys
from tkinter import *
widget = Button(None, text='Hello GUI world!', command=sys.exit)
widget.pack()
widget.mainloop()
'''
Here, instead of making a label, we create an instance of the tkinter Button class.
For buttons, the command option is the place where we specify a ca... |
f46676e4e06c7657a92b10f6ac48f8a13f199d02 | bimri/programming_python | /chapter_1/tkinter102.py | 964 | 4.15625 | 4 | "Step 5: Adding a GUI"
'Using OOP for GUIs'
'''
In larger programs, it is often more useful to code a GUI as a subclass
of the tkinter Frame widget—a container for other widgets.
'''
from tkinter import *
from tkinter.messagebox import showinfo
class MyGui(Frame):
def __init__(self, parent=None):
Frame._... |
0400516dd26d92a83e7bf74e31c085765785ed76 | bimri/programming_python | /chapter_8/demoDlg-print.py | 1,771 | 3.984375 | 4 | "Printing dialog results and passing callback data with lambdas"
"""
similar, but show return values of dialog calls; the lambda saves data from
the local scope to be passed to the handler (button press handlers normally
get no arguments, and enclosing scope references don't work for loop variables)
and works just like... |
3bd76f059220cdfa48dad678c9ce519dd8e1808b | RomellPineda/Algorithms | /for_loop_basic1.py | 1,264 | 4.0625 | 4 | # Basic for loops in Python
# 1 Basic - Print all the numbers/integers from 0 to 150.
for count in range(151):
print(count)
# 2 Multiples of Five - Print all the multiples of 5 from 5 to 1,000,000.
for count in range(5,1000001):
if count % 5 == 0:
print(count)
# 3 Counting, the Dojo Way - Print integ... |
14e97cb3c7f616ce949ed49e6a610b90859878b3 | mmcgreal/softdev2_hw | /hw07/quciksort.py | 594 | 3.734375 | 4 | ## Mary McGreal
## SoftDev2 pd3
## HW07: Quicksort
## 2016-04-06
import random
def quickSort(List):
if len(List) > 0:
p = List[0]
LH = [x for x in List if x < p]
RH = [x for x in List if x > p]
return quickSort(LH) + [p] + quickSort(RH)
return []
L1 = []
for x in range(0,15):
... |
73e6e2712fc736f21f7818bef2c63815de570750 | hymhanraj/lockdown_coding | /range.py | 266 | 4.40625 | 4 | ''' Given start and end of a range, write a Python program to print all negative numbers in given range.
Example: Input: start = -4, end = 5 Output: -4, -3, -2, -1 Input: start = -3, end = 4 Output: -3, -2, -1
'''
for num in range(-3,4):
if num<0:
print(num)
|
040cdf085336c553e8b0951a59a25028577999f7 | helper-uttam/Hacktober2020-5 | /Python/calc.py | 1,011 | 4.1875 | 4 | def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
num1 = int(input("Enter first number: "))
num2 = int(... |
d141ebfb0ec290f5ac9ccb9534b326db34dc130f | nealcox/Aoc2018 | /3a.py | 741 | 3.859375 | 4 | from collections import defaultdict
import re
INPUT = "3-input.txt"
cloth = defaultdict(int)
def place(claims):
global cloth
for claim in claims:
left = int(claim[2])
top = int(claim[3])
width = int(claim[4])
depth = int(claim[5])
for i in range(width):
for... |
6ff742aa90fcb8417717102ed6e0d9bb67cdf6c0 | davcs86/codefights | /arcade/Transformations/cipher26.py | 283 | 3.5 | 4 | def cipher26(m):
n = m[0]
a = ord(m[0]) - 97
#print a
for c in range(1, len(m)):
b = 26 - a + ord(m[c]) - 97
while b < 0:
b += 26
a += b
#print b
n += chr(b+97)
return n
print cipher26('taiaiaertkixquxjnfxxdh') |
543df9f68a43a2849f15426cd986a52e2e062a91 | davcs86/codefights | /arcade/IntegrationWell/switchLights.py | 626 | 3.578125 | 4 | def switchLights(a):
b = len([i for i in a if i])
print b
for k, v in enumerate(a):
a[k] = (v, (v + 1) % 2)[b % 2]
if v:
b-=1
return a
print switchLights([1,1,1,1,1])
print switchLights([0,0])
# Input:
# a: [1, 0, 0, 1, 0, 1, 0, 1]
# Output:
# [1, 0, 0, 0, 0, 0, 0, 0]
# Exp... |
88b3bf9d899c4d9f27f691d2139d00cbb436686a | davcs86/codefights | /challenges/170113/rubixCode.py | 2,787 | 3.546875 | 4 | import re
def printMatrix(r):
for i in r:
print "[" + ",".join([str(j) for j in i]) + "]"
def r(l, n, p, s):
f = -1 if p else 1
return l[(f*n) % s:] + l[:(f*n) % s]
def t(c, i, j, s, r):
#print i, j, s, r
m = [z[j:j+s] for z in c[i:i+s]]
#print m
n = zip(*reversed(m)) if r else li... |
177f55f045780c9db46475226f0762de128111f7 | bgilroy26/advent_of_code | /day05/string_checker1.py | 1,469 | 3.515625 | 4 | import sys
filename = sys.argv[1]
naughty_strings = {
'a':'b',
'c':'d',
'p':'q',
'x':'y',
'':False
}
naughty_keys = list(naughty_strings.keys())
vowels = 'aeiou'
last_char = ''
total = 0
print("{0} {1} {2} {3} ".format("line".center(16), "vowel_count", "has_double_le... |
04b33cc875ef72a394fb6222ba6939cafff80713 | bgilroy26/advent_of_code | /day07/CircuitBookletReader.py | 1,403 | 3.546875 | 4 | import sys
assignment_operator = '->'
gates = ['NOT', 'AND', 'OR', 'LSHIFT', 'RSHIFT']
'''
class Signal(object):
def __init__(self, value):
self.value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
value = int(value)
#w... |
d9339a916d8d6ff7969243f2b5a89217c04d70f0 | bgilroy26/advent_of_code | /day05/string_checker2.py | 1,121 | 3.671875 | 4 | import sys
filename = sys.argv[1]
two_chars_ago = ''
last_char = ''
total = 0
#New rules are:
# - palindromic triple
# - doubled pair
candidate_pairs = []
print("{0} {1} {2} ".format("line".center(16), "has_palindromic_triple", "has_doubled_pair"))
with open(filename, 'r') as f:
for line in f:
has_... |
eb70c4c15a9511b061ebab91c858cebbb7707b10 | bgilroy26/advent_of_code | /day12/brilliant_gens.py | 579 | 3.53125 | 4 | #from @Stranac Coding on Youtube
import sys
import ast
def all_numbers(data):
if isinstance(data, int):
yield data
if isinstance(data, list):
for value in data:
yield from all_numbers(value)
if isinstance(data, dict):
if 'red' in data.values():
return
... |
5c7306a5c3e299fa041c70b0ab6b3011c5d009c2 | dkdittoe/BIOL5153 | /parseGFF.py | 2,051 | 3.78125 | 4 | #! /usr/bin/env python3
import argparse
def parse():
parser = argparse.ArgumentParser(description = "examine any 2 files")
#add positional arguement
parser.add_argument("data1", help = "the gff file")
parser.add_argument("data2", help = "the fsa file")
#command line arguements
args = parser.... |
20e5713218979589bc452c464c4e9d52216d2b2b | mishra28soumya/Hackerrank | /Python/Basic_Data_Types/second_largest.py | 673 | 4.125 | 4 | #Find the Runner-Up Score!
# Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score.
# You are given n scores. Store them in a list and find the score of the runner-up.
# Input Format
# The first line contains N. The second line contains an array A[] of N in... |
57c1801d1c5fc4f3cb31d8b24aff3ec58a555fc9 | fepegar/advent-of-code-2017 | /day_04/day_04.py | 1,498 | 3.796875 | 4 | """
Solutions for day 4.
"""
from os.path import dirname, join
def is_valid(passphrase, anagram=False):
split = passphrase.split()
unique = set(split)
if not anagram:
return len(split) == len(unique)
sorted_words = [''.join(sorted(word)) for word in split]
sorted_set = set(sorted_words)
... |
2d2d2a08eae10ca231183da69d94386639c0ce99 | hubieva-a/lab9 | /l9z2.py | 1,594 | 3.71875 | 4 | import json
if __name__ == '__main__':
students_list = []
while True:
command = input("Add, list, exit, load <>, save <>: ").lower()
if command == 'exit':
break
elif command == 'add':
last_name = input('Your last name^ ')
class_name = ... |
91e6153e75db60860bd2f486effad5dd468c456a | nath-btx/hi-python | /ex03_rps/rps.py | 1,377 | 4.125 | 4 | import random
moves=['rock','paper','scissors']
def convert_input(move):
if (move == "r"): return 'rock'
elif(move == "p"): return 'paper'
elif(move == "s"): return 'scissors'
else: return move
def game():
tie = True
while tie:
tie = False
AI_move = random.choice(moves)
... |
c0cb1f07c0b325dd90da501fca7bab94f2105091 | sgmpy/TIL | /python/homework/05.py | 154 | 3.875 | 4 | # my_list = [1, 2, 3, 4]
# for index, n in enumerate(my_list,start=1):
# print(index, n)
d = {'a':1, 'b':2, 'c':3}
for i in d.items():
print(i) |
5dbd03273d5c20f6dd409b4140983b040c89ac73 | jasonliujiang/DataStructurePython | /Stringing/Replacement.py | 566 | 3.671875 | 4 | """
将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。
给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。
该题为模拟字符串的replace方法。要做到空间复杂度最低,遍历原数组,计算空格的数量,
则现字符串的长度为len+2*n.然后用倒序遍历,如果遇到' ',将空替换为‘20%’。
"""
|
fd18f7970129187901803d7cf2d887c818a86598 | jasonliujiang/DataStructurePython | /StackQueue/StackReverse.py | 920 | 3.890625 | 4 | """
实现一个栈的逆序,但是只能用递归函数和这个栈本身的pop操作来实现,而不能自己申请另外的数据结构。
给定一个整数数组A即为给定的栈,同时给定它的大小n,请返回逆序后的栈。
测试样例:
[4,3,2,1],4
返回:[1,2,3,4]
"""
class stackreverse:
# 获取栈底元素
def get(self, stack):
res = stack.pop()
if not len(stack):
return res
else:
last = self.get(stack)
... |
1cbf4a655e260c2e3ce872b8aaa41399826f5a6d | jasonliujiang/DataStructurePython | /Stringing/Parenthesis.py | 562 | 3.640625 | 4 | """
对于一个字符串,请设计一个算法,判断其是否为一个合法的括号串。
给定一个字符串A和它的长度n,请返回一个bool值代表它是否为一个合法的括号串。
仿照栈的思想做优化
"""
def chkParenthesis(StringA, n):
status = 0
for i in StringA:
if i == '(':
status = status + 1
elif i == ")":
status = status - 1
if status < 0:
return Fal... |
30ad2bcf790da33a679e59f4db83b10bf924ed04 | jasonliujiang/DataStructurePython | /Offer/10.py | 617 | 3.96875 | 4 | """
矩形覆盖 Q: 我们可以用2 1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2 1的小矩形无重叠地覆盖一个2 * n的大矩形,总共有多少种方法?
A: 依然是斐波那契数列的变形。代码参考跳台阶。
"""
# -*- coding:utf-8 -*-
class Solution:
def rectCover(self, number):
# write code here
if number == 0:
return 0
tempArray = [1, 2]
if number >= 3:
for ... |
745cd8970e0e4431ae21ba57de7079f0cd171bd7 | hellolzc/SpeechEmotionRecognition-emodb | /speechemotion/mlcode/data_manager.py | 9,018 | 3.703125 | 4 | import pandas as pd
import numpy as np
import random
import json
import os
import sys
from sklearn.preprocessing import StandardScaler
DEBUG = False
def set_debug_print(debug_print):
"""set DEBUG
"""
global DEBUG
DEBUG = debug_print
class DataSet():
"""
DataSet is the abst... |
56b07e23946bb13685df83f62ec9fcf9adb7a5bc | devblackpower/curso_python | /ex05.py | 326 | 3.796875 | 4 | #exe2
tamanho = input("Qual é a area a ser pintada em metros quadrados?")
cobertura = int(tamanho) * 3
custo_lata = 18
valor = 80
total_tinta = cobertura / custo_lata
total_valor = total_tinta * valor
print("A quantidade de latas de tintas é de {}, dando o valor total de {}".format(total_tinta, total_valor... |
262e34e624203ba14a6491de31fabd670efc05b8 | gui2one/python_playground | /function_test.py | 248 | 4.09375 | 4 |
def sqrt(x):
ans = 0
if x >= 0:
while ans<x :
if ans*ans != x:
print x, 'is not a perfect square'
return None
else: return ans
ans = ans + 1
else:
print x, 'is a negative number'
return None
print sqrt(33)
|
ce78fddcb1d50885eda2c6c6fbf3ef4f889a7fd5 | mbruzek/convert | /ascii.py | 2,566 | 3.875 | 4 | #!/usr/bin/env python3
"""
Convert strings to and from ASCII representation.
@copyright 2021 Matthew Bruzek
"""
import argparse
def ascii_to_binary(astring):
"""Convert an ASCII string to binary representation."""
return ''.join(["{:08b}".format(ord(c)) for c in astring])
def ascii_to_hex(astring):
... |
055040be966b8585805fe27f25f3550985bd33bd | yujie24/Fishc_Python | /p4_1.py | 448 | 3.953125 | 4 | # 条件分支,即 判断。常用if-else搭配
# 如果是 循环,一般用while语句。后面会用到。
score = int(input('请输入你的分数:'))
if score == 100:
print('哇!你得了满分!')
elif 100>score>=90:
print('A')
elif 90>score>=80:
print('B')
elif 80>score>=70:
print('C')
elif 70>score>=60:
print('D')
elif 60>score:
print('不及格哦!下次努力!')
elif 100<score or 0>score:
print('输入错误... |
69a91ae38bf17ca1b554324961d7588db0b69b8b | meenakshi-madan/MiscChallenges | /character_table_to_xhtml_v2.py | 2,185 | 3.546875 | 4 | """
http://codegolf.stackexchange.com/questions/11843/convert-this-character-based-table-into-html-one
Take a following character table:
-------------------------------------------------------
| |1233456 | abc | xyz | | |
|-------|--------|--------|--------|--------|---------|
| |abcd... |
fd4cab734938011dd0407fb8e5445adbe348e9d6 | tssovi/movies_info_portal | /data_processor/csv_downloader.py | 631 | 3.6875 | 4 | import os
import requests
'''
Purpose of this function is download and save movies.csv and ratings.csv for given urls.
'''
def download_csvs():
movie_csv_url = 'https://school.cefalolab.com/assignment/python/movies.csv'
movie_req = requests.get(movie_csv_url, verify=False)
rating_csv_url = 'https://schoo... |
7c65c588f84dcae223dd32fa274a90f26ed31daa | crypto4808/PythonTutorial_CoreySchafer-master1 | /comprehensions.py | 2,927 | 3.8125 | 4 | #Lesson5:-List Comprenehsions 05/16/18
#https://www.youtube.com/watch?v=3dt4OGnU5sM
#Easy to write and read lists in this format
nums = [1,2,3,4,5,5,7,8,9,10]
#i want 'n' for each 'n' in nums
my_list = []
my_list_squares = []
# for n in nums:
# my_list.append(n)
# print(my_list)
#LIST COMPREHENSION
#This is ... |
8763f32cd9ae69553a4554c0223283a51c5522be | crypto4808/PythonTutorial_CoreySchafer-master1 | /intro.py | 1,731 | 4.3125 | 4 | #import as a smaller name so you don't have to type 'my_modules' each time
# import my_modules
# #from my_module import find_index
# courses = ['history', 'math' , 'physics' , 'compsci' ]
# index = my_modules.find_index(courses,'math')#
# print(index)
#Use shorthand for my_modules so you don't have to type it out al... |
ec022a502128acdcdc7b933a49ee215814f39c71 | statusyaza/hacktoberfest2021-5 | /Python/diamond_star.py | 481 | 4.125 | 4 | rows = int(input("Enter you number:"))
n = 0
for i in range(1, rows + 1):
n = 0
# loop to print spaces
n = (rows - i)
print(" " * n, end = "")
# loop to print star
n = (2 * i - 1)
print(str(i) * n, end = "")
print()
####
for i in range(rows-1, 0, -1):
# loop to... |
986a8685fe3f41db5eaa4ea9d8dfe3e6d3cc24ba | statusyaza/hacktoberfest2021-5 | /Python/Learning_OpenCV/transformation.py | 1,006 | 3.515625 | 4 | import cv2 as cv
import numpy as np
img = cv.imread(r'C:\Users\PIYUS\Desktop\Image Processing\learning\Resources\Photos\park.jpg')
cv.imshow("img", img)
# def translate(img, x, y):
# # Translation matrix
# transMat = np.float32([[1,0,x], [0,1,y]]) # this 2X3 matrix is necessary
# dimension = (img.shape[1],... |
8558724a6981b9db9d1aa68625739d05a94d3ce0 | statusyaza/hacktoberfest2021-5 | /Python/Scientific Calculator | 8,630 | 3.515625 | 4 | import tkinter as tk
from tkinter import *
import time
import math
import parser
win=tk.Tk()
win.configure(bg="#000000")
win.title('JOSSY SCI CALC')
win.geometry("290x560")
win.resizable(0,0)
win.iconbitmap(r"Graphicloads-100-Flat-2-Calculator.ico")
def clock():
a=time.strftime("%H:%M:%S")
zero.config(tex... |
c803feb2a89bf0a96e5e769b779fe5313696069a | statusyaza/hacktoberfest2021-5 | /Python/Triangle_Pattern.py | 263 | 3.765625 | 4 | rows = int(input("Enter Triangle Rows = "))
print("Triangle Pattern ")
for i in range(0, rows):
alphabet = 65
for j in range(rows, i, -1):
print(end = ' ')
for k in range(0, i + 1):
print('%c' %(alphabet + k), end = ' ')
print()
|
b9b1a64e80fe8d1a4e9038e36d98f84b56f75ba8 | Cassie-bot/Module-3 | /Area.py | 340 | 4.40625 | 4 | #Casandra Villagran
#1/30/2020
#This is a program that computes the area of a circle using the radius and it prints a message to the user with the answer.
radius = int(input ("What is the radius of the circle? "))
Area= 3.14 * radius ** 2
print ("I loved helping you find the area of this circle, here i... |
b8c5e96e8833a034c53149362be235dc3871aa38 | ctec121-spring19/spring-2019-final-project-jhalnan | /src/Model.py | 3,647 | 3.796875 | 4 | # Model.py
#
# For TicTacToe
# Joel Halnan
# This imports the View class from the View file.
from View import View
class Model:
# Main part of the class.
def __init__(self, view):
self.v = view
# These two lists are the lists for each player's moves. These lists are appended from t... |
803b49a91142dcb51a3dbcf888c93ae7cda158f7 | Maoxiaoying/MY_hogwarts_python-2- | /1_3_MyClass.py | 946 | 4.09375 | 4 | """
作业1:定义5个类
my:
类3:陈情男孩
属性:名,字,门派,武器
方法:台词
"""
class ChenQingBoy:
def __init__(self,name,zi,menpai,wuqi):
self.name=name
self.zi=zi
self.menpai=menpai
self.wuqi=wuqi
def speak(self):
if(self.name=="魏婴"):
print("愿我魏无羡能够一生锄强扶弱,无愧于心")
if(self.name=="蓝... |
ca06113d518922612c34f2fdf2bbb25b58d5ed57 | Namyalg/C-DSA | /Sem3/INORDERWITHSTACK.py | 564 | 3.84375 | 4 |
#go to the utmost left, on hitting null print,
and then set the current to the right and continue the same process till the stack is not empty same as level order, use a queue
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
curr = root
stack = []
res = []
... |
e9e7609b7b1b2490613418e7b82f1d3eb98e80fc | AmritpalSaini1/StockRateOfChange | /plotter.py | 2,149 | 3.96875 | 4 | import matplotlib.pyplot as plt
import csv
def main():
# Main function
makePlot(getData())
def getData():
# uses csv library to make a list of the information in the given file
with open('BTC.csv', 'r') as f:
data = list(csv.reader(f, delimiter=','))
return data
# change to dictionary ... |
a99a114566f9b5b006028f437239b62a3388c08d | kimbomin/p2_201611060 | /w10Main.py | 2,532 | 3.78125 | 4 | def milk():
coffee=list()
coffee=[ ["Coffee","Water","Milk","Icecream"],
["Espresso","No","No","No"],
["Long Black","Yes","No","No"],
["Flat White","No","Yes","No"],
["Cappuccino","No","Yes - Frothy","No"],
["Affogato","No","No","Yes"]
]
data=coffee[1:]
fo... |
7ebc0455f487004466631a70679e0d1e37372637 | taabishshaikh/assignment | /assignment 3/break and continue.py | 253 | 3.921875 | 4 | #prime no with for loop
#n=int(input('enter a number: '))
#for i in range (1,n+1):
for i in range (5):
print (i)
continue
print ('python')
for i in range (5):
print (i)
break
print ('python')
|
c461e7db5b47809b32774f698d690d7011b3d4a4 | taabishshaikh/assignment | /assignment 7/max 3 values.py | 155 | 3.703125 | 4 | D={'a':10,'b':20,'c':42,'d':40,'e':15,'f':18,}
D1=list(D.values())
print(D1)
i=0
while i!=3:
print(max(D1))
D1.remove(max(D1))
i=i+1
|
a6ba4e39ae07e8cdcd6991ba8a1ae1550e404caf | taabishshaikh/assignment | /assignment 3/question 2.py | 131 | 3.71875 | 4 | #print all natural number from 100 to 1 using for loop
#n=100
for i in range (-100,0):
i=i*(-1)
print (i)
|
8325a13720abfe3b9528cc4e61f27f80fceb5248 | avijitkumar2011/My-Python-programs | /matrix_multiplication.py | 628 | 4.0625 | 4 | m1=[[0,0,0],
[0,0,0],
[0,0,0]]
m2=[[0,0,0],
[0,0,0],
[0,0,0]]
m3=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(0,3):
for j in range(0,3):
m1[i][j]=int(input("enter a number"))
for i in range(0,3):
print(m1[i])
for i in range(0,3):
for j in range(0,3):
m2[i][j]=int(i... |
13091fa05d4d93a37a34f95520e6de8746a93763 | avijitkumar2011/My-Python-programs | /middle_letter.py | 213 | 4.1875 | 4 | #To find middle letter in a string
def middle(strg):
if len(strg) % 2 == 1:
n = len(strg)//2
print('Middle letter in string is:', strg[n])
else:
print('enter string of length odd number')
middle('kuma')
|
11f19088bbce0a352d25caf04adb6ad2e892b5b5 | Gregox273/GLAM_thehorrorgame | /analyze.py | 860 | 3.515625 | 4 | import sys
# finds all the times when the level of fear is significant
def find_significant(scared_vals):
significant = []
threshhold = 10**(-3)
for i in range(len(scared_vals)):
if scared_vals[i] < threshhold:
continue
significant.append(scared_vals[i])
return significan... |
d4df543061383d1f6adffc0676b5e6675d0237e6 | AP-Atul/Chronic-Kidney-Disease | /lib/Naive_Bayes_Classifier.py | 3,028 | 4.15625 | 4 | import numpy as np
"""
Bayes’ Theorem provides a way that we can calculate the probability
of a piece of data belonging to a given class,
given our prior knowledge. Bayes’ Theorem is stated as:
`P(class|data) = (P(data|class) * P(class)) / P(data)`
Where P(class|data) is the probability of class given the pro... |
dcd1d7304fd1d7dbf55602f6f95150d98d92ea66 | Ma11ock/cs362-asgn4 | /avg_list.py | 226 | 4.125 | 4 | #!/usr/bin/env python
# Calculate the average of elements in a list.
def findAvg(lst):
if(len(lst) == 0):
raise ValueError("List is empty")
avg = 0
for i in lst:
avg += i
return avg / len(lst)
|
3d09c17d52ad2a76e7baa086ddf5efb0b26e481c | bakuganin/python | /Python/For/8.py | 93 | 3.59375 | 4 | n = int(input())
x = 1
y = 0
for i in range(1, n + 1):
x *= i
y += x
print(y)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.