blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b82e561e8a2986d4a523686db9acb5cac1f67900 | elinaldosoft/valid-zip-code-gotham-city | /app/main.py | 694 | 3.6875 | 4 | import re
def valid_zip_code(zip_code: str) -> bool:
zip_code = re.sub(r"[^\d]", "", zip_code)
valid = False
if (
len(zip_code) == 6
and zip_code[0] != zip_code[2]
and zip_code[1] != zip_code[3]
and zip_code[2] != zip_code[4]
and zip_code[3] != zip_code[5]
):
... |
5bd2a94a21b1cf83bd7bcc264f4ba6315a4554f5 | Cptgreenjeans/python-workout | /ch04-dicts/e15b3_word_lengths.py | 322 | 4.0625 | 4 | #!/usr/bin/env python3
"""Solution to chapter 4, exercise 15, beyond 3: word lengths"""
from collections import defaultdict
def word_lengths(filename):
output = defaultdict(int)
for one_line in open(filename):
for one_word in one_line.split():
output[len(one_word)] += 1
return outpu... |
a8717fd48f33946c281525ff0dc3670722024ef6 | Cptgreenjeans/python-workout | /ch05-files/e19_passwd_to_dict.py | 603 | 4.21875 | 4 | #!/usr/bin/env python3
"""Solution to chapter 5, exercise 19: passwd_to_dict"""
def passwd_to_dict(filename):
"""Expects to get a string argument, the name of a file in passwd format.
Returns a dictionary in which the keys are the usernames from the file,
and the values are the user IDs from the file. The user I... |
72644fdf639b46d5c7da118b6f2e67ef4aa68846 | Cptgreenjeans/python-workout | /ch09-objects/e42_flexible_dict.py | 498 | 4.09375 | 4 | #!/usr/bin/env python3
"""Solution to chapter 9, exercise 42: flexible dict"""
class FlexibleDict(dict):
"""Dict that lets you use a string or int somewhat interchangeably."""
def __getitem__(self, key):
try:
if key in self:
pass
elif str(key) in self:
... |
a8375cea3ea7e1e7358139cecc7bd57f94357b63 | Cptgreenjeans/python-workout | /ch10-iterators/e50b3_myrange_generator.py | 332 | 3.703125 | 4 | #!/usr/bin/env python3
"""Solution to chapter 10, exercise 50, beyond 3: myrange_generator"""
def myrange(first, second=None, step=1):
if second is None:
current = 0
stop = first
else:
current = first
stop = second
while current < stop:
yield current
curr... |
3d375e74aeff61f904c3317f11f12d6eb988ae81 | Cptgreenjeans/python-workout | /ch09-objects/e39b3_book_width.py | 988 | 4.09375 | 4 | #!/usr/bin/env python3
"""Solution to chapter 9, exercise 39, beyond 2: has_book"""
class TooManyBookOnShelfError(Exception):
pass
class Book:
def __init__(self, title, author, price, width):
self.title = title
self.author = author
self.price = price
self.width = width
cla... |
83550163c8f617795a4a8d47f0f19788bd57deb3 | Cptgreenjeans/python-workout | /ch09-objects/e40b3_transaction.py | 226 | 3.65625 | 4 | #!/usr/bin/env python3
"""Solution to chapter 9, exercise 40, beyond 3: transactions"""
class Transaction:
balance = 0
def __init__(self, amount):
self.amount = amount
Transaction.balance += amount
|
689a282fc66092174dba631e20e54a048c4062dd | Cptgreenjeans/python-workout | /ch05-files/e20_wc.py | 698 | 4.4375 | 4 | #!/usr/bin/env python3
"""Solution to chapter 5, exercise 20: wc"""
def wordcount(filename):
"""Accepts a filename as an argument. Prints the number of lines,
characters, words (separated by whitespace) and different words
(case sensitive) in the file."""
counts = {'characters': 0,
'words': 0,
... |
da60ff2b8bc8cd39854619a7f17ca731d905d84d | Cptgreenjeans/python-workout | /ch05-files/e19b2_factors.py | 594 | 4.21875 | 4 | #!/usr/bin/env python3
"""Solution to chapter 5, exercise 19, beyond 2: factors"""
from collections import defaultdict
def factors():
output = defaultdict(list)
numbers = input("Enter numbers, separated by spaces: ").split()
for one_number in numbers:
if not one_number.isdigit():
pr... |
53bef81a5c665113c79e5a4cf6c503fc9f35e49a | Cptgreenjeans/python-workout | /ch05-files/e22b2_dict_to_csv.py | 333 | 4.03125 | 4 | #!/usr/bin/env python3
"""Solution to chapter 5, exercise 22, beyond 2: dict_to_csv"""
import csv
def dict_to_csv(d, csv_filename):
with open(csv_filename, 'w') as output:
outfile = csv.writer(output, delimiter=delimiter)
for key, value in d.items():
outfile.writerow([key, value, t... |
fa2608d8f71d87f99212dd82ca721dac0fa95ef1 | Cptgreenjeans/python-workout | /ch03-lists-tuples/e09b3_largest_word.py | 402 | 4.3125 | 4 | #!/usr/bin/env python3
"""Solution to chapter 3, exercise 9, beyond 3: Longest word in file-like"""
def longest_word(f):
"""Takes a file-like object, and returns the longest
word it finds.
"""
longest_word = ''
for one_line in f:
for one_word in one_line.split():
if len(one_word) > le... |
0958884c5bc3d1f2e11fd24c7421d93220be807d | Cptgreenjeans/python-workout | /ch02-strings/e06b1_word_per_line.py | 557 | 4.09375 | 4 | #!/usr/bin/env python3
"""Solution to chapter 2, exercise 6, beyond 1: Word per line"""
def word_per_line(filename):
"""Given a text file, return a sentence from the nth
word for line n, for each of the first 10 lines.
"""
output = []
for n, one_line in enumerate(open(filename)):
words = one_line... |
5a41a45d648408c865e7ce885302265617c0aeb4 | Cptgreenjeans/python-workout | /ch04-dicts/e15_rain.py | 667 | 4.1875 | 4 | #!/usr/bin/env python3
"""Solution to chapter 4, exercise 15: rainfall"""
def get_rainfall():
"""Ask the user repeatedly for a city name and mm of rainfall.
If the city is blank, then stop asking questions,
and report all cities and rainfall.
Otherwise, ask for rainfall and add the current rainfall
to any previ... |
7dc21fac7a91e905341c96a7c5552bcb4d6edfb3 | Cptgreenjeans/python-workout | /ch05-files/e18b2_sum_mult_columns.py | 464 | 3.765625 | 4 | #!/usr/bin/env python3
"""Solution to chapter 5, exercise 18, beyond 2: sum_mult_columns"""
def sum_mult_columns(filename):
total = 0
for one_line in open(filename):
fields = one_line.split()
if len(fields) != 2:
continue
first, second = fields
if not first.isdi... |
731536896088e46077947daba6cb3e9bb847bbd7 | Cptgreenjeans/python-workout | /ch03-lists-tuples/e11b3_sort_by_sum.py | 300 | 3.890625 | 4 | #!/usr/bin/env python3
"""Solution to chapter 3, exercise 11, beyond 3: sort_by_vowel_sum"""
def sort_by_sum(list_of_lists):
"""Given a list of lists, in which the inner lists contain
numbers, return the outer list sorted by each inner list's sum.
"""
return sorted(list_of_lists, key=sum)
|
367abf836e3334f8f12218b05cce89296e097b15 | Fahadjudoon/Intro-self-driving-cars-udacity | /Project 5 - Implement Route Planner/path_planner_functions.py | 5,422 | 3.65625 | 4 | import math
import scipy
def create_closedSet(self):
""" Creates and returns a data structure suitable to hold the set of nodes already evaluated"""
# EXAMPLE: return a data structure suitable to hold the set of nodes already evaluated
return set()
def create_openSet(self):
""" Creates and returns a d... |
8053c4784812e6d17ac3ab0d3d9fd92edcad5b32 | Maxim-Deriuha/education_py | /test2/test7.py | 171 | 3.59375 | 4 | n = int(input())
for k in range(1, n + 1):
print(k)
my_list = [[0] * k] * n
print(*my_list)
for i in range(n):
my_list[0][i] = i + 1
print(*my_list, sep='\n')
|
1cb99f2e5d06b66f1a8e75adc7bab6291c15802e | Maxim-Deriuha/education_py | /test/test17.py | 827 | 3.8125 | 4 | def quick_merge(list1, list2):
result = []
p1 = 0 # указатель на первый элемент списка list1
p2 = 0 # указатель на первый элемент списка list2
while p1 < len(list1) and p2 < len(list2): # пока не закончился хотя бы один список
if list1[p1] <= list2[p2]:
result.append(list1[p1])
... |
03656e74ea80ae093d91acf50e92d9faad97c741 | Maxim-Deriuha/education_py | /test/text20.py | 426 | 3.640625 | 4 | # объявление функции
def convert_to_python_case(text):
k = [i.lower() for i in text]
l = [ i for i in text]
h=[]
h.append(k[0])
for i in range(1,len(k)):
if k[i]==l[i]:
h.append(k[i])
else:
h.append('_'+k[i])
return ''.join(h)
# считываем данные
txt = in... |
3c6395819b3838409e52fdf31e6f96cebc780bba | brcamp13/csBasics | /binarySearch/binarySearch.py | 802 | 4.25 | 4 | # Python binary search implementation sourced from geeksforgeeks
def binarySearch(arr, left, right, target):
# Check base case
if right >= left:
mid = int(left + (right - left)/2)
# If target is the middle element
if arr[mid] == target:
return mid
# If target is s... |
6239f8c83a9a39d5f7aa9dee0d5ec17362f341cd | ploffer11/Python3 | /1124.py | 1,176 | 3.640625 | 4 | class Underprime:
def __init__(self):
self.a, self.b = (
map(int, input().split())
)
def prime_list(self):
self.era = [True] * (self.b+1)
self.era[0], self.era[1] = False, False
prime = []
for i in range(2, int((self.b)**.5)+1):
if no... |
8574f07dbdd809afe3ce6aaecfaa03bd6edf6533 | ploffer11/Python3 | /_20190118 (6).py | 712 | 3.515625 | 4 | input_strings = ['1', '5', '28', '131', '3']
output_integers1 =[
int(num) for num in input_strings
]
output_integers2 = [
int(num) for num in input_strings if int(num) < 50
]
from collections import namedtuple
Book = namedtuple("Book", "author title genre")
books = [
Book("Pratchett", "Nightwatch", "fanta... |
719f592467d8d17b7e760e7080228d7bdc7c1415 | lucaslk122/Exercicios-com-string | /Exe8_Palíndromo.py | 256 | 4.03125 | 4 | def palindromo(frase):
if frase.replace(" ","") == frase[::-1].replace(" ",""):
print("É palindromo")
else:
print("Não é palindromo")
frase = input("Digite uma frase: ")
palindromo(frase)
print("O que é um para N, pra voce?") |
3da1de090369d0a0d83adf3d065d285565ae59ea | sanjay19/push | /arminterval.py | 205 | 3.65625 | 4 |
x=int(input())
y=int(input())
for num in range(x,y+1):
order=len(str(num))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**order
temp //=10
if num==sum:
print(num)
|
1be5cbb3eb4076b1b636f0829bdcbd0f94043cc0 | sanjay19/push | /factorial.py | 166 | 4.0625 | 4 | n=int(input())
fact=1
if n<0:
print('factorial does not exist')
elif n==0:
print('factorial of zero is 0')
else:
for i in range(1,n+1):
fact=fact*i
print(fact)
|
43460df9da9139fc57e0c1fb100906064a9de658 | sanjay19/push | /vowel.py | 162 | 3.765625 | 4 | n=str(input())
L=["a","e","i","o","u","A","E","I","O","U"]
if n.isnumeric():
print("invalid data")
elif n in L:
print("vowel")
else:
print("consonents") |
0fd19863ea93640482bdd4d6e64af86f4c9a2a6a | VinayakAsnotikar/Python_Snippets | /Bubble_Sort.py | 796 | 4.46875 | 4 | #Bubble sort method.
def bubblesort(unordered_list):
#Takes in the list to be sorted as a parameter.
for num in range(len(unordered_list)-1,0,-1):
#We iterate over the positions in the list.
#We start with the last element and move leftwards, one step upto the first element.
for idx in r... |
a1e9bfa2977b67d05b74108c225f7a1454c1049c | Rokon-Uz-Zaman/Photo-Editor- | /Blank and white image converter.py | 587 | 3.546875 | 4 | #author: rokon-uz-zaman roman
#Blank and white image converter
import tkinter as tk
import cv2
from tkinter import filedialog
root=tk.Tk()
root.geometry("400x300") #window size
label1=tk.Label(root,text='Black & White Image Converter ',width=40)
label1.grid(row=1,column=1)
button1=tk.Button(root,text... |
0582016be3ec200b0162847bace08573de53bd07 | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Algorithms/Miscellaneous/Python/N-th Tribonacci Number.py | 326 | 4.34375 | 4 | def Tribonacci_Number(n):
if n == 0 :
return 0
elif n == 1 or n == 2 :
return 1
else :
return (Tribonacci_Number(n-1) + Tribonacci_Number(n-2) + Tribonacci_Number(n-3))
N = input("Enter n for find nth Tribonacci Number : ")
print(N,"th Tribonacci Number is : ",Tribonacci_Number(int... |
9003748875eaf433adbb806575ac0c7130942a7a | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Algorithms/Miscellaneous/Python/Setbitposition.py | 963 | 4.375 | 4 | '''
Problem statement: Find position of setbit. If there are 0 or morethan 1 set bit then print as "Invalid number" else
print position of setbit.
If number is power of 2 then its binary representation contains only one ‘1’. So,check whether the
given number is a power of 2 or not. If given number is not a power ... |
a385cd43f156bc4ca5acfbb3ed576190a464c8bb | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Data Structures/Tree/postorder_traversal.py | 1,691 | 4.15625 | 4 | ans=[]
#create a new node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
#top of stack
def peek(s):
if len(s) > 0:
return s[-1]
return None
def postOrderTraversal(root):
# if tree is empty
if root is None:... |
a361a676cebdb6aaa06868e9bd7252a11e047da0 | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Leetcode/Python/Valid_Mountain_Problem.py | 633 | 3.828125 | 4 | def Valid_Mount(arr:list[int]):
if len(arr) < 3 :
return False
else :
for i in range(0, len(arr)-1 ):
if arr[i+1] > arr[i] :
continue
else :
break
for j in range(i , len(arr)-1 ) :
if arr[j+1] < arr[j] :
... |
e0dcb6d9ac235830ca55f46d9da077afa615e8ac | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Gfg/Python/max_subtree_sum.py | 1,643 | 4 | 4 | #Program to find Maximum possible subtree sum in a tree
class newNode:
def __init__(self, key):
self.key = key
self.left = self.right = None
def findLargestSubtreeSumUtil(root, ans):
# If current node is None then
# return 0 to parent node.
if (root == None):... |
c413eeccb068b1249f9d32f67dc148469b178b8a | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Data Structures/Array/Python/Intersection of two sorted array.py | 96 | 3.703125 | 4 | A=input()
B=input()
for i in A:
if(i in B):
print(i) # Take Input as list form
|
76aa9a3962120d01c9f5dcde2546512084fc3e59 | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Algorithms/Miscellaneous/Python/power_of_2_(Bit_Manipulation).py | 761 | 4.34375 | 4 | # Python program to check if given
# number is power of 2 or not
''' If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.
For example for 4 ( 100) and 16(10000), we get following after subtracting 1
3 –> 011
15 –> 01111
Input:
Enter Number
... |
7af5ccbd865c93033305f72d9b7a9b0b93ef3ad3 | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Gfg/gold_mine.py | 2,895 | 4.34375 | 4 | # Desccription Gold Mine Algorithm
# Given a gold mine of n*m dimensions.
# Each field in this mine contains a positive integer which is the amount of gold in tons.
# Initially the miner is at first column but can be at any row.
# He can move only (right->,right up /,right down\) that is from a given cell,
# the m... |
e34d08c5e26158c04e3303225143a4f7077b4922 | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Gfg/Python/rCircularLinked.py | 1,127 | 4.125 | 4 | #QUESTION: REVERSE THE CIRCULAR LINKED LIST
#SOLUTION:
import math
class Node:
def __init__(self, data):
self.data = data
self.next = None
def getNode(data):
newNode = Node(data)
newNode.data = data
newNode.next = None
return newNode
def reverse(head_ref):
if (head_ref == None):
return None
prev = ... |
e6465136ea5ea82a89236138e03489454d730167 | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Leetcode/Python/multiplyStrings.py | 237 | 3.875 | 4 | #Problem link : https://leetcode.com/problems/multiply-strings/
def multiply(num1, num2):
return str(int(num1)*int(num2))
num1,num2 = input().split();
print(multiply(num1,num2))
#Example test case
# Input : "2" "3"
# Output : "6"
|
434720caf0d2cb9854c5c623c8e13f6a958b951f | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Gfg/Python/union_arrays.py | 883 | 4.40625 | 4 | #program to find union of 2 sorted arrays
def printUnion(arr1, arr2, m, n):
i, j = 0, 0
while i < m and j < n:
if arr1[i] < arr2[j]:
print(arr1[i])
i += 1
elif arr2[j] < arr1[i]:
print(arr2[j])
j+= 1
else:
print(arr2[j... |
7f732ab5131e09895a2eb9a2bb8a22b3e2984d9e | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Data Structures/Array/Python/fenced_matrix.py | 1,178 | 4.28125 | 4 | # Short Description : FENCED MATRIX
# This problem provides to make understand others the concept of list,
# list comprehension, deep and shallow copy methods in Python.
# The project can be performed on Jupyter Notebook or Google Colab.
#take input without using library ast
in_str=input()
#as the input is in the ... |
c6f3e0e77ccfe3268420413b6116266c06beda8b | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Gfg/Python/Sort012.py | 552 | 3.8125 | 4 | def sort012( a, arr_size):
lo = 0
hi = arr_size - 1
mid = 0
while mid <= hi:
if a[mid] == 0:
a[lo], a[mid] = a[mid], a[lo]
lo = lo + 1
mid = mid + 1
elif a[mid] == 1:
mid = mid + 1
else:
a[mid], a[hi] = a[hi], a[mid]
hi = hi - 1
return a
# Function to print ar... |
28fef70bb0796b3111979b98d22e8f8af02593b3 | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Gfg/Python/Kthlargestelement.py | 338 | 3.65625 | 4 | class Solution(object):
def findKthLargest(self, nums, k):
nums.sort()
if k ==1:
return nums[-1]
temp = 1
return nums[len(nums)-k]
obj1 = Solution()
n=int(input("size "));
a=[]
for i in range(0,n):
ele=int(input("Enter array elements "))
a.append(ele)
k=int(input())
print(obj1.fi... |
1fc65bea4e8e27178dbda5017691e17c716ffac6 | ispastlibrary/Titan | /2016/AST2/Marija/poredjenje.py | 398 | 3.609375 | 4 | import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
fajl1 = input('Unesi ime fajla1:')
fajl2 = input('Unesi ime fajla2:')
r1, i1 = np.loadtxt(fajl1, unpack=True, delimiter=' ')
r2, i2 = np.loadtxt(fajl2, unpack=True, delimiter=' ')
r =abs (r2 - r1)
i = abs(i2 - i1)
gr=30
#print... |
3a063c25ed2a65655b7bfffcb29e400f6312f0f0 | ispastlibrary/Titan | /2016/AST2/Despot/programi/if1.py | 128 | 3.65625 | 4 | n = int(input("Broj? "))
if n < 0:
print("Apsolutna vrednost", n, "je", -n)
else:
print("Apsolutna vrednost", n, "je", n)
|
6634aa788dc543589d5eff1312f3a273301edbc3 | ispastlibrary/Titan | /2015/AST1/vezbovni/luka/hgh.py | 56 | 3.6875 | 4 | a = 1, 2, 5, 10
for i in range(3)
a = i+1
print (a)
|
a3ce4a49c3d6b344d92d38760ae04ec93f11952d | ispastlibrary/Titan | /2015/AST1/vezbovni/luka/lista3.py | 115 | 3.640625 | 4 | x = [0.3, 0.9, 0.11, 0.23, 50, 16]
y = x[0]
for i in range(len(x)-1):
if y>x[i+1]:
y = x[i+1]
print(y)
|
7d7beeb297a01ee241f02ee7628af28339f2f1aa | ispastlibrary/Titan | /2016/AST2/LukaJ/programi/if2.py | 307 | 3.921875 | 4 | number = 7
guess = -1
print("Pogodite broj!")
while guess != number:
guess = int(input("Da li je... "))
if guess == number:
print("Bravo! Pogodili ste!")
elif guess < number:
print("Broj je veci od toga...")
elif guess > number:
print("Broj nije toliko veliki.")
|
1b6c7733b37662e8d6edbfc6e2286d77466118ca | ispastlibrary/Titan | /2015/AST1/vezbovni/Dejan/5.py | 90 | 3.8125 | 4 | def f(x):
if x==1:
return 1
elif x==2:
return 1
else:
print(f*(f-1))
|
b53310d84912c2e23e0e0ec1ec9d1b05326d8b9e | ispastlibrary/Titan | /2015/AST1/vezbovni/vladan/dif1.py | 180 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 8, 0.3)
y = [0]
for i in range(1, len(x)):
y.append(y[i-1] - np.cos(x[i])*0.3)
plt.plot(x, y)
plt.show()
|
580cbfb7e883c2ecb288f2a2273a581e3f6aeb96 | ispastlibrary/Titan | /2015/AST1/vezbovni/Jelena/peti.py | 152 | 3.515625 | 4 | def faktorijel(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return n * faktorijel(n-1)
print(faktorijel(3))
|
3e17569e730aca632ec85f7f46af4b53a1159ce0 | monas1975/Python_UAM | /homework01/task08.py | 471 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Napisz funkcję sum_div35(n), która zwraca sumę wszystkich liczb podzielnych
przez 3 lub 5 mniejszych niż n.
"""
def sum_div35(n):
sum =0
for i in range(n): #sprawdzam w petli:
if (i%3==0 or i%5==0): #sprwdzam czy liczba jest podzi... |
e3b6bcfcf2616c4ea009b2ef0212c4481c32cc7c | Jeblii/Rush-Hour---Heuristics | /RushHour-Heuristics/rush_hour/algorithms/breadth_first.py | 1,830 | 3.90625 | 4 | from operator import attrgetter
def breadth_first_search(board, max_depth=100):
"""
An implementation of breadth first search; checks states on the order FIFO
function terminates, when solution is found or max depth is reached
:param board: call function with a board state
:param max_depth: max de... |
a1fc7dad367783c286b4d63496550fc552d4b3d9 | benn-123/Tic-tac-toe | /tic_tac_toe.pyde | 11,029 | 4.09375 | 4 | turn = 1 #Whether it's player 1 or 2's turn
board = [ [0,0,0], [0,0,0], [0,0,0] ] #Empty board at the start
mode = "title-screen" # used to switch between game modes
score1 = 0 #Player 1 score
score2 = 0 #Player 2 score
def setup():
size(600,600)
def draw():
global mode, counter, score1,... |
4291ae0a62561a21d5fee118a0092236d75f578c | aksh2804/Sorting-Visualizer | /Merge_sort.py | 1,640 | 3.6875 | 4 | import pygame
from arr_gen import *
# Importing the random array
generate_arr()
# Main Recursive function
def mergesort(array, l, r):
mid =(l + r)//2
if l<r:
mergesort(array, l, mid)
mergesort(array, mid + 1, r)
merge(array, l, mid, mid + 1, r)
# Helper function(Insort is taking pl... |
a42c289fb6b9faf4e246fe948af355cb9d1d2c3f | nghidali/Ghostwriter | /grammar.py | 2,337 | 3.703125 | 4 | from grammarbot import GrammarBotClient
'''
This program uses the grammarbot API
To install, just run 'pip install grammarbot'
To run the program, uncomment the last line at the bottom
'''
# Driver program
# Call this program with a specified file
# It will output an array of the scores and booleans for each line
# T... |
1731531fac2036b809617ab7e416c594c517b16b | ouroboroscoding/rest-oc-python | /RestOC/DictHelper.py | 5,609 | 3.734375 | 4 | # coding=utf8
""" Dictionary Helper Module
Several useful helper methods for use with dicts
"""
__author__ = "Chris Nasr"
__copyright__ = "Ouroboros Coding Inc."
__version__ = "1.0.0"
__email__ = "chris@ouroboroscoding.com"
__created__ = "2018-11-11"
# Python imports
import sys
def clone(src):
"""Clone
Goes thro... |
430afc8aec456de5275decc8fc12a92fc3808c39 | Mat4wrk/Introduction-to-Data-Science-in-Python-Datacamp | /3.Plotting Data with matplotlib/Tracking crime statistics.py | 450 | 3.828125 | 4 | # Change the color of Phoenix to `"DarkCyan"`
plt.plot(data["Year"], data["Phoenix Police Dept"], label="Phoenix", color="DarkCyan")
# Make the Los Angeles line dotted
plt.plot(data["Year"], data["Los Angeles Police Dept"], label="Los Angeles", linestyle=':')
# Add square markers to Philedelphia
plt.plot(data["Year"]... |
efbfd7dd2d89f7dda58015b0110a64661de67131 | Mat4wrk/Introduction-to-Data-Science-in-Python-Datacamp | /3.Plotting Data with matplotlib/Playing with styles.py | 1,293 | 3.671875 | 4 | #Change the plotting style to "fivethirtyeight".
# Change the style to fivethirtyeight
plt.style.use('fivethirtyeight')
# Plot lines
plt.plot(data["Year"], data["Phoenix Police Dept"], label="Phoenix")
plt.plot(data["Year"], data["Los Angeles Police Dept"], label="Los Angeles")
plt.plot(data["Year"], data["Philadelphi... |
88247e45f8f7a0a637be5ead9000bcdf17a58cca | MyGitHubSite/alarconpy | /alarconpy/convert_units.py | 27,558 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Demo of unicode support in text and labels.
"""
from __future__ import unicode_literals
from math import pi
import sys
def units_conversion( x, unit1, unit2 ):
"""
To Convert units
-------------------------------------------------------------------------
Created by Henning Ressing, P... |
66e7b1a6eff7b33e0b738cce0ab3e4417ebcae57 | yeshwindbz9/flask_crash_codes | /flask_databases/subjects_example/populate_database.py | 917 | 3.6875 | 4 | # This script will create some students, colleges, and owners!
from models import db, Students, Colleges, Subjects
# creating two students
sam = Students("Sammy")
pam = Students("Pammy")
# adding students to database
db.session.add_all([sam, pam])
db.session.commit()
# check with a query, prints all students
print(S... |
9d9ce3a57460159679bc60907032367c199b0942 | parka01/python_ex | /0222/ex4.py | 503 | 3.546875 | 4 | #1부터 사용자가 입력한 숫자 사이의 소수의 리스트와 개수가 몇 개인지를
#출력하는 프로그램을 작성하시오.
num=int(input('숫자를 입력: '))
pnum=[] #빈 리스트를 생성
for i in range(1,num+1):
dcnt=0 #약수의 개수
for j in range(1,i+1):
if i%j==0:
dcnt=dcnt+1
if dcnt==2:
pnum.append(i)
print('1부터 ',num,'까지의 소수의 리스트: ',pnum)
print('1부터 ',num,'까지의... |
ca7cf912b892585ae2c29bbae65b35bac292d4d7 | parka01/python_ex | /0223/def_ex5.py | 540 | 4 | 4 | #사용자로부터 3개의 숫자를 입력받아 가장 큰 수를 구하는 프로그램을
#작성하시오. 3개의 숫자를 매개변수로 받아서 가장 큰 수를
# 반환하는 부분을 findMax(a,b,c)함수로 작성시오.
def findMax(a,b,c):
if a>b:
biggest=a
else:
biggest=b
if biggest<c:
biggest=c
return biggest
a=int(input('첫 번째 숫자: '))
b=int(input('두 번째 숫자: '))
c=int(input('세 번째 숫자: '))
... |
9f76987f61923479ba5692511b95d82149f47dd9 | parka01/python_ex | /0219/ex10.py | 217 | 3.703125 | 4 | total=0
count=0
while True:
num=int(input('숫자를 입력: '))
total=total+num
count=count+1
if total>=1000:
break
print('1000을 넘은 수: ',total,end='')
print(', 평균은 ',total/count) |
7c6923a4f40248634a6393ee283eca2232275913 | parka01/python_ex | /0218/ex_if.py | 133 | 3.515625 | 4 | score=int(input("점수 입력: "))
if score>=80:
print('축하합니다.')
print('A입니다.')
print("프로그램 종료") |
0666f7419b692e423b18bf9f5536f96279a508ae | parka01/python_ex | /0218/ex_if10.py | 1,031 | 3.890625 | 4 | gender=input('당신의 성별은(M또는 F): ')
height=input('키는? ')
weight=input('몸무게는? ')
Mweight=height*height*22
Fweight=height*height*21
if gender==M:
if weight+weight*0.2 >=110:
if weight+weight*0.2 >=120:
print('비만체중')
else:
print('과체중')
#----------------모범답안--------------... |
f259ba18a5e987b0f64680b0655ada59ba63bbad | parka01/python_ex | /0224/poly.py | 546 | 3.546875 | 4 | import polyArea
print('**사각형 넓이**')
width=float(input('사각형 가로: '))
depth=float(input('사각형 세로: '))
print('사각형의 넓이: ',polyArea.recArea(width,depth))
print('**삼각형 넓이**')
base=float(input('삼각형의 밑변: '))
height=float(input('삼각형의 높이: '))
print('삼각형의 넓이: ',polyArea.triArea(base,height))
print('**원 넓이**')
r=float(input('반지름: '... |
afca9c59f7dd1207ad3e5de3031039ab42cb20d0 | parka01/python_ex | /0222/ex3_6.py | 320 | 4.0625 | 4 | num=input('좋아하는 월은? ')
month=int(input('현재 월 입력(정수): '))
if((month<1)or(month>12)):
print("잘못된 입력")
elif((month>=3))and(month<=5)):
print("봄")
elif((month>=6))and(month<=8)):
print("여름")
elif((month>=9))and(month<=11)):
print("가을")
else:
print("겨울") |
20f8c14c955430d12c2423bae3dcd6b3e17c8047 | shinbamba/shabonk | /20_anon-reduce/test.py | 421 | 3.875 | 4 | import re, functools
with open("text.txt", "rU") as txt:
inp = txt.read()
def freqWords(words):
return len([i for i in range(0, len(inp) - len(words)) if inp[i: i + len(words)] == words])
word = re.findall(r'\w+', inp)
words = list(set(word))
def mostFreq():
return functools.reduce(lambda a, b: a if a... |
203fb03e3a0e38d647677d2cad12ad1c5c1506bc | sayantanHack/Average_of_floats-taken-from-a-Textfile | /Average of float.py | 547 | 3.96875 | 4 | # Use the file name big.txt as the file name
fname = raw_input("Enter file name: ") #use input("Enter file name: ") if u r using python3
fh = open(fname,'r')
count =0
total=0
for line in fh:
line = line.rstrip()
if not line.startswith("X-DSPAM-Confidence:") : continue
num = line.split(" ")[1]
... |
01ad650e9afd14288b5bfc156e2be8ce20f48e05 | cavandervoort/Project-Euler-001-to-100 | /Euler_032.py | 820 | 3.5625 | 4 | # Problem 32
# Pandigital products
# get list of unusual products
import math
import time
start = time.time()
def is_pandigital(n1, n2, prod):
digitsStr = str(n1) + str(n2) + str(prod)
digitsArr = [char for char in digitsStr]
if len(set(digitsArr)) == 9 and '0' not in digitsArr:
return True
e... |
3eddf24f7b411acb8e1d50231792e7f1a759486d | cavandervoort/Project-Euler-001-to-100 | /Euler_005.py | 415 | 3.78125 | 4 | # Problem 5
# Smallest multiple
divisors = []
for num in range(1,21):
tempNum = num
for divisor in divisors:
if tempNum % divisor == 0:
tempNum /= divisor
if tempNum > 1:
divisors.append(int(tempNum))
# print(f'new divisor ({int(temp_num)}, from {num}) added to divisors... |
a3c64a94234bea7ad8558bf294e753d0633f4d1c | cavandervoort/Project-Euler-001-to-100 | /Euler_071.py | 597 | 3.625 | 4 | # Problem 71
# Ordered fractions
'''
I first solved this by using some intuition and guess and check. The
coding solution is similar to my solution to Problem 85. I start with 1/1
and then keep adding one to the numerator or denominator, based on
whether I was too high or too low.
'''
n = 1
d = 1
x = 3/7
min_diff ... |
831b5d95c0ece94310d9fe306029ad651c12d7f9 | cavandervoort/Project-Euler-001-to-100 | /Euler_082.py | 2,043 | 3.5625 | 4 | # Problem 82
# Path sum: three ways
import time
start = time.time()
print("This will take ~5 seconds")
def get_matrix():
f = open("p082_matrix.txt", "r")
matrix = []
while True:
line_temp = f.readline()
if line_temp == '':
break
list_temp = line_temp.split(',')
l... |
3f6a36143d52d92a278d2e313b0666bf58bdea18 | leocaodou/first | /Python2.1.py | 321 | 3.5 | 4 | a = eval(input("请输入需要计算的温度大小: "))
b = input("请输入温度的单位: ")
if b in ['F','f']:
C = (a - 32) / 1.8
print("转换后的温度是{:.0f}C".format(C))
elif b in ['C','c']:
F = 1.8 * a + 32
print("转换后的温度是{:.0f}F".format(F))
else:
print("抱歉,没有这个单位") |
36c223f87657646d8584eaed760705ae00e4362f | philoleben/HufsAlgorithm2021 | /10_Graph_Theory/여행계획(웅빈).py | 1,176 | 3.78125 | 4 | def find_parent(parent, x):
#루트 노드를 찾을 때까지 재귀 호출
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
# 두 원소가 속한 집합을 합치기
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
pare... |
3e0967082e398c88786305523c7d655f34914e9a | philoleben/HufsAlgorithm2021 | /04_Implementation/왕실의 나이트(김승범).py | 447 | 3.546875 | 4 | position = input() # 시작 위치
row = int(position[1]) # 행
column = int(ord(position[0])) - int(ord('a')) + 1 # 열(숫자로 치환)
moves = [(-2, -1), (-1, -2), (1, -2), (2, -1),
(2, 1), (1, 2), (-1, 2), (-2, 1)]
result = 0
for move in moves:
next_row = row + move[0]
next_column = column + move[1]
if next_... |
af178eff2bcaca8af9231e237ad04a8d23ac4e44 | sidheswar12/python-test | /string_ex.py | 1,086 | 4.1875 | 4 | #!/bin/env/python3
def string_split(s):
print("#" * 50)
print("{} : {}".format(s, s.split()))
print("#" * 50)
def remove_whitespace(s):
print("#" * 50)
print("'{}': '{}'".format(s, s.strip()))
print("#" * 50)
def fstream_func(name, company):
print("#" * 50)
print(f'I am {n... |
909f97027e77a11a08a79c5be4ab98685e97c5ed | VSablin/pandas_for_your_grandpa | /2_10_series.py | 3,436 | 4.25 | 4 | # In this script, we go through lesson 2.10 of Python Pandas for your
# Grandpa course: Series Challenges. Web link here:
# https://www.gormanalysis.com/blog/python-pandas-for-your-grandpa-series-challenges/
# %% Import libraries
import numpy as np
import pandas as pd
# %% Strings
# Given a Series of strings, count h... |
e61b269f233c88968787d925a50fa18bfc2e196a | toluwajosh/algos | /balanced_parenthesis.py | 919 | 4.09375 | 4 | """balanced parenthesis problem
check whether or not a string
has balanced usage of parenthesis.
Example:
(), ()(), (({[]})) <- Balanced.
((), {{{)}], [][]]] <- Not Balanced.
we will implement using a list's append and pop
"""
opening_dict = {"(": ")", "[": "]", "{": "}"}
closing_dict = {")": "(", "]": "[", ... |
5afda123c7d218bddbfec7d40efc755dedc7f19e | toluwajosh/algos | /fibonacci.py | 1,121 | 4.21875 | 4 | """n-th number in fibonacci series"""
def rec_fib(n, fibs):
"""Recursive fibonacci function
Arguments:
n {int} -- nth position of the sequence
fibs {dictionary} -- dictionary of already calculated positions
Returns:
int -- final fibonacci number
"""
if n < 2:
... |
d623546227db39695d3edaa84ec86d84b68bf5c6 | toluwajosh/algos | /palindrome_break.py | 1,877 | 3.859375 | 4 | """palindrome_break
Break the palindrome
"""
class Pal:
seen = {}
def is_pal(self, s):
if s in self.seen:
return self.seen[s]
reversed_s = ""
for sub in s:
reversed_s = sub + reversed_s
return reversed_s == s
# longes palindromic substring
def is_pali... |
8a935d0a4e6ff89c226960546e6103663d4dec9e | toluwajosh/algos | /repeating_dna_sequences.py | 832 | 3.953125 | 4 | """Repeating DNA Sequences
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once i... |
ba658b8c0186c1197ca1af0e9e2e529ec74494e3 | MarioYu1206/PythonStudy | /Chapter4/4.4_list_partial.py | 1,958 | 4 | 4 | players = ['charles','martina','michael','florence','eli']
print(players[0:3]) #['charles', 'martina', 'michael'],players[0:3],其中0是起始索引(包含),3是终止索引(不包含)
print(players[1:4]) #['martina', 'michael', 'florence']
print(players[:4]) #['charles', 'martina', 'michael', 'florence'],没有指定起始索引,默认从头开始
print(players[2:]) #['michael'... |
831175368225336327c3664cc16bd177160c533b | MarioYu1206/PythonStudy | /Chapter6/6.2_use_dictionary.py | 2,950 | 3.796875 | 4 | #字典是一系列键值对,用{}来括起来。通过使用键来访问与之相关的值,python中的任何对象都可以作为字典的值
alien_0 = {'color':'green','points':5}
new_points = alien_0['points'] #用字典中的键来找到相应的值,为变量赋值
print("you just earned " + str(new_points) + " points!")
#添加键值对
alien_0 = {'color':'green','points':5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
p... |
fced040b2ef1d2cd7c084406b51dbb3db26df811 | MarioYu1206/PythonStudy | /Chapter7/7.1_input_function.py | 1,736 | 4.375 | 4 | #input()函数让程序暂停运行,让用户输入一些文本,接受一个参数
message = input("tell me something, and I will repeat it back to you:")
print("\n" + message)
name = input("please enter your name: ")
print("Hello, " + name + ".")
prompt = "if you tell us who you are, we can personlize the message you see."
prompt += "\nWhat is your first name? " ... |
f1fdaf4750eb592c054a8f2a5883107c4a1639c0 | MarioYu1206/PythonStudy | /Chapter4/4.3_value_list.py | 1,291 | 4.4375 | 4 | for value in range(1,5): #range()可以让你从指定的第一个值开始数,并在到达你指定的第二个值后停止,但输出不包含第二个值
print(value) #1,2,3,4,
numbers = list(range(1,6)) #指定1-5作为list的元素
print(numbers)
even_number = list(range(2,11,2)) #range()中的第三个参数是指间隔为2(不断+2)
print(even_number) #[2, 4, 6, 8, 10]
squares = []
for value in range(1,11):
square = value... |
965a315c7439e0e5bc6276566aa22862d16190de | MarioYu1206/PythonStudy | /Chapter5/5.3_if_statement.py | 3,056 | 4.0625 | 4 | age = 19
if age >= 18:
print("you are old enough to vote!")
print("have you registered to vote yet?")
age = 17
if age >= 18:
print("you are old enough to vote!")
print("have you registered to vote yet?")
else:
print("sorry, you are too young to vote.")
print("please register to vote as soon as ... |
6565211c5d81a59e27006418b4f3f89fbcec4adb | RobertNguyen125/Udemy-Python-Bootcamp | /6_list/4_listComprehension.py | 503 | 3.953125 | 4 | names = ['Elie', 'Tim', 'Matt']
answer = [name[0] for name in names ]
print(answer)
numbers = range(1,7)
even = [num for num in numbers if num%2==0]
print(even)
l1 = range(1,5)
l2 = range(3,7)
#create intersection of the 2
intersection = [num for num in l1 if num in l2]
print(intersection)
names = ['Elie', 'Tim', ... |
20d86688c09842cece190b002974c761889a5c27 | RobertNguyen125/Udemy-Python-Bootcamp | /4_loop/2_loopAndRange.py | 63 | 3.6875 | 4 | x = 0
for num in range(19,10,-2):
x = x + num
print(x)
|
d1aadf6488bf274a8498c148971a5b7a2c2cdeb6 | RobertNguyen125/Udemy-Python-Bootcamp | /9_function/exercise/2return_day.py | 232 | 3.9375 | 4 | def return_day(num):
day = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
if num > 0 and num <= len(day):
return day[num-1]
return None
print(return_day(1))
print(return_day(23))
|
071565787ebae766223737a417c24a18f956a554 | RobertNguyen125/Udemy-Python-Bootcamp | /6_list/1_accessList.py | 317 | 3.515625 | 4 | # colors = ['purple', 'teal', 'magenta']
#
# for color in colors:
# print(color)
#
# i = 0
# while i < len(colors):
# print(f'{i} : {colors[i]}')
# i+=1
sounds = ["super", "cali", "fragil", "istic", "expi", "ali", "docious"]
results = ''
for sound in sounds:
results += sound.upper()
print(results)
|
d1bc419ddfbe741bacb88f4e8a80e533c175dbd6 | TheTiker/TechExercises | /ex45/bin/classes.py | 1,123 | 3.65625 | 4 | from sys import exit
import ex45
class Scene(object):
def enter(self):
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('escaped'... |
6b6b6ec5c38673140392f6e153cdede2e1d3db04 | underwhelmed-ape/hptextadv | /items.py | 1,472 | 3.546875 | 4 | from money_exchange import wizard_money
class Item:
def __init__(self, name):
self.name = name
raise NotImplementedError('Do not create raw Item objects')
def __str__(self):
return self.name
class Purse(Item):
def __init__(self, value):
self.name = "Standard Purse"
... |
0344dcc7d607ba0d64b784ca869b04304388af86 | patrekurorn/NaNAir39 | /LogicLayer/airplaneLL.py | 1,605 | 3.515625 | 4 | import csv
from DataLayer.airplaneDL import AirplaneDL
from LogicLayer.voyageLL import VoyageLL
import os
class AirplaneLL:
def __init__(self):
self.__voyageLL = VoyageLL()
self.__airplaneDL = AirplaneDL()
def get_all_airplanes(self):
return self.__airplaneDL.get_all_airplanes()
... |
3ac21d578e22c759c0a97b5beaec624333f236f9 | abhi1540/PythonConceptExamples | /getter_setter.py | 2,953 | 4.0625 | 4 |
class Employee(object):
def __init__(self, emp_id, first_name, last_name, salary, age):
self._emp_id = emp_id
self._first_name = first_name
self._last_name = last_name
self._salary = salary
self._age = age
@property
def emp_id(self):
return self._emp_id
... |
30f38e74ddae3d79a0e0f40fead17058aa200a6a | abhi1540/PythonConceptExamples | /playingwithjson.py | 1,982 | 3.96875 | 4 | json_data = """{ "office":
{"medical": [
{ "room-number": 100,
"use": "reception",
"sq-ft": 50,
"price": 75
},
{ "room-number": 101,
"use": "waiting",
"sq-ft": 250,
"price": 75
},
{ "room-number": 102,
"use": "examination",
... |
8ce1255a861756470725d9912b170d3e601ea57d | natnicha143/Minesweeper | /Program/MainMenu.py | 2,520 | 3.984375 | 4 | from tkinter import *
#Extends tkinter's Frame class
class MainMenu(Frame):
def __init__(self, master):
Frame.__init__(self, master)
# create main menu frame
self.menu_frame = Frame(master, borderwidth=2, bg="pink", width=650, height=600)
self.menu_frame.pack()
# create imag... |
2358937e1f775bea76ca5d7c432bb6c9f2511401 | EECS388-F19/lab-chrislun16 | /helloworld.py | 346 | 4.3125 | 4 | print("This line will be printed.")
students = []
students.append("Bob")
students.append("Joee")
students.append("Tom")
first_name = students[0]
print(first_name)
first_name = first_name[:-1]
print(first_name)
longest_name = ''
for student in students:
if len(student) > len(longest_name):
longest_name = stu... |
a85bfab3f3ced1027567a1d640ec8d4e7c0ce2c2 | canoi12/tinycoffee | /external/wren/test/benchmark/fib.py | 225 | 3.65625 | 4 | from __future__ import print_function
import time
def fib(n):
if n < 2: return n
return fib(n - 1) + fib(n - 2)
start = time.clock()
for i in range(0, 5):
print(fib(28))
print("elapsed: " + str(time.clock() - start)) |
7b22a14841ab7c66083591758cba95889f0d9769 | Gua-Ru-Lee/ycsh_python_course | /L06/bmi.py | 147 | 3.875 | 4 | h=float(input("請輸入身高(公分):"))
w=float(input("請輸入體重(公斤):"))
h=h/100
bmi=w/h**2
bmi=round(bmi,2)
print("BMI",bmi)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.