blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
13aa25d7b7180ab8801be99ee71fcc216c6a1e6b | adamchipmanpenton/BlackJack | /db.py | 406 | 3.5 | 4 | db = "money.txt"
import sys
def openWallet():
try:
wallet = open(db)
wallet = round(float(wallet.readline()),)
return wallet
except FileNotFoundError:
print("count not find money.txt")
print("Exiting program. Bye!")
sys.exit()
def changeAmount(winnings):
w... |
aa7282b1a04d086834b1f734014eb3747128ccbd | aggy07/Leetcode | /1-100q/67.py | 1,162 | 3.78125 | 4 | '''
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
'''
class Solution(object):
def addBinary(self, a,... |
15f0f2b2686291cbd5c8be606a95e25517f3abaa | aggy07/Leetcode | /300-400q/317.py | 2,355 | 3.96875 | 4 | '''
You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
Each 0 marks an empty land which you can pass by freely.
Each 1 marks a building which you cannot pass through.
... |
33c960afb411983482d2b30ed9037ee6017fbd34 | aggy07/Leetcode | /600-700q/673.py | 1,189 | 4.125 | 4 | '''
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing su... |
9ee533969bbce8aec40f6230d3bc01f1f83b5e96 | aggy07/Leetcode | /1000-1100q/1007.py | 1,391 | 4.125 | 4 | '''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are th... |
8bdf3154382cf8cc63599d18b20372d16adbe403 | aggy07/Leetcode | /200-300q/210.py | 1,737 | 4.125 | 4 | '''
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you s... |
4705b012a25fe956c96fc78cc949a305c9e6ad0f | aggy07/Leetcode | /900-1000q/999.py | 3,053 | 4.125 | 4 | '''
On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.
The rook moves as in the rules of Ches... |
fe6472a92a73038fff7fd05feb100394b18805a8 | aggy07/Leetcode | /1000-1100q/1026.py | 1,766 | 3.90625 | 4 | '''
Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.
(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)
Example 1:
8
/ \
3 10
/ \ ... |
c1e4eb821ec69861f1ff694e6f7c4cf2e9d68ca8 | aggy07/Leetcode | /100-200q/118.py | 655 | 3.984375 | 4 | '''
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
'''
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[i... |
e9d57ebf9fe9beec2deb9654248f77541719e780 | aggy07/Leetcode | /100-200q/150.py | 1,602 | 4.21875 | 4 | '''
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression... |
f33a0bed8cf001db76705264cf5e73f91233c69b | aggy07/Leetcode | /300-400q/347.py | 749 | 3.875 | 4 | '''
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2]
'''
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not... |
8f83262573f48ba2f847993cc9ba7ffeb5fc1b17 | aggy07/Leetcode | /1000-1100q/1035.py | 1,872 | 4.15625 | 4 | '''
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw a straight line connecting two numbers A[i] and B[j] as long as A[i] == B[j], and the line we draw does not intersect any other connecting (non-horizontal) line.
Return the maximum number of connectin... |
d16eafea8552970b70b46db21f3a8db069814a0c | aggy07/Leetcode | /300-400q/395.py | 1,141 | 4.0625 | 4 | '''
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
Input:
s = "aaabb", k = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
... |
781daf201b2e2f04d1ad4b398e958355afeca707 | aggy07/Leetcode | /100-200q/159.py | 953 | 3.90625 | 4 | '''
Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb".
'''
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:r... |
8f212585e03771a5123c4b00aabe2edddff3c9ef | aggy07/Leetcode | /900-1000q/926.py | 1,105 | 3.90625 | 4 | '''
A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)
We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.
Return the minimum number of flips to make S monotone increasing.
... |
0d8b2738c5025a35f5144557f8645fe358ae3f0e | aggy07/Leetcode | /1000-1100q/1015.py | 829 | 3.921875 | 4 | '''
Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.
Return the length of N. If there is no such N, return -1.
Example 1:
Input: 1
Output: 1
Explanation: The smallest answer is N = 1, which has length 1.
Example 2:
Input: 2... |
d8709a64545e1b7a7171225cb9ea1fa5bf1693c0 | aggy07/Leetcode | /1000-1100q/1054.py | 1,207 | 3.890625 | 4 | '''
In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
Example 1:
Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
Example 2:
Input: [1,1,1,1,2,2,3,3]
Ou... |
6d9a6317730a7a5ec42a2ad70a17fec62a525d9e | aggy07/Leetcode | /1000-1100q/1004.py | 1,007 | 4 | 4 | '''
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest sub... |
52a4191848017bfeff5304299b2c8f27b559ae0f | Amohammadi2/python-pluginsystem-tutorial | /src/main.py | 708 | 3.65625 | 4 | from jsonDB import DBConnection
import os
class Program:
def main(self):
self.db = DBConnection(f"../JSON/{input('enter your class name: ')}.json")
try:
while True:
self.db.insertData(self.getInput())
except KeyboardInterrupt:
print ("opening json f... |
b47cc4edb6b26bc8d86fc960a19c521e7896d19b | IrsalievaN/Homework | /1.py | 697 | 3.796875 | 4 | '''
import random
while True:
command = input(">>> ")
phrases = ["Никто не ценит того, чего слишком много.","Где нет опасности, не может быть и славы.","Сердце можно лечить только сердцем.","Красотой спасётся мир","Каждый день имеет своё чудо."]
if command == "Скажи мудрость":
print(random.choice(phrases))
elif... |
fe6681006dca45b41fd2ce1a4715decda8b4ce76 | IrsalievaN/Homework | /homework5.py | 578 | 4.125 | 4 | from abc import ABC, abstractmethod
from math import pi
class Figure(ABC):
@abstractmethod
def draw (self):
print("Квадрат нарисован")
class Round(Figure):
def draw(self):
print("Круг нарисован")
def __square(a):
return S = a ** 2 * pi
class Square(Figure):
def draw(self):
super().dr... |
6b886ad93e6e9e5d05a2c5503f4b2cade76cfe49 | swapnadeepmohapatra/mit-dsa | /Stack/stack.py | 379 | 3.96875 | 4 | # Self Implementation
class Stack:
def __init__(self):
self.items = []
def push(self, data):
self.items.append(data)
def pop(self):
if len(self.items) == 0:
print("Stack is Empty")
else:
self.items.pop()
s = Stack()
s.push(5)
s.push(6)
s.push(7)
pr... |
8d95c66ede3e8c525ad625c63383723517437852 | swapnadeepmohapatra/mit-dsa | /ins.py | 302 | 3.96875 | 4 | def sort(arr):
for right in range(1, len(arr)):
left = right - 1
elem = arr[right]
while left >= 0 and arr[left] > elem:
arr[left + 1] = arr[left]
left -= 1
arr[left + 1] = elem
return arr
arr = [1, 2, 6, 3, 7, 5, 9]
print(sort(arr))
|
64f7eb0fbb07236f5420f9005aedcbfefa25a457 | JATIN-RATHI/7am-nit-python-6thDec2018 | /variables.py | 730 | 4.15625 | 4 | #!/usr/bin/python
'''
Comments :
1. Single Comments : '', "", ''' ''', """ """ and #
2. Multiline Comments : ''' ''', and """ """
'''
# Creating Variables in Python
'Rule of Creating Variables in python'
"""
1. A-Z
2. a-z
3. A-Za-z
4. _
5. 0-9
6. Note : We can not create a variable name with numeric Value as a... |
356b0255a23c0a845df9c05b512ca7ccc681aa12 | JATIN-RATHI/7am-nit-python-6thDec2018 | /datatypes/list/List_pop.py | 781 | 4.21875 | 4 | #!/usr/bin/python
aCoolList = ["superman", "spiderman", 1947,1987,"Spiderman"]
oneMoreList = [22, 34, 56,34, 34, 78, 98]
print(aCoolList,list(enumerate(aCoolList)))
# deleting values
aCoolList.pop(2)
print("")
print(aCoolList,list(enumerate(aCoolList)))
# Without index using pop method:
aCoolList.pop()
print("")
... |
29d770237ec753148074d79ef96ef25287fde94a | JATIN-RATHI/7am-nit-python-6thDec2018 | /loops/for_decisionMaking.py | 853 | 4.375 | 4 |
"""
for variable_expression operator variable_name suit
statements
for i in technologies:
print(i)
if i == "AI":
print("Welcome to AI World")
for i in range(1,10): #start element and end element-1 : 10-1 = 9
print(i)
# Loop Controls : break and continue
for i in technologies:
print(i... |
e23ca223aef575db942920729a53e52b1df2ed4d | JATIN-RATHI/7am-nit-python-6thDec2018 | /DecisionMaking/ConditionalStatements.py | 516 | 4.21875 | 4 | """
Decision Making
1. if
2. if else
3. elif
4. neasted elif
# Simple if statement
if "expression" :
statements
"""
course_name = "Python"
if course_name:
print("1 - Got a True Expression Value")
print("Course Name : Python")
print(course_name,type(course_name),id(course_name))
print("I am ou... |
07f477c82976a39cd4ac94ac95acc6b5f96c7d7d | JATIN-RATHI/7am-nit-python-6thDec2018 | /Date_Time/UserInput.py | 396 | 3.984375 | 4 | import datetime
currentDate = datetime.datetime.today()
print(currentDate.minute)
print(currentDate)
print(currentDate.month)
print(currentDate.year)
print(currentDate.strftime('%d %b, %Y'))
print(currentDate.strftime('%d %b %y'))
userInput = input('Please enter your birthday (mm/dd/yyyy):')
birthday = datetime.dat... |
71fb2e89c852750f33e2512e2f83ab1f9a021b68 | JATIN-RATHI/7am-nit-python-6thDec2018 | /datatypes/basics/built-in-functions.py | 2,190 | 4.375 | 4 | # Creating Variables in Python :
#firstname = 'Guido'
middlename = 'Van'
lastname = "Rossum"
# Accesing Variables in Python :
#print(firstname)
#print("Calling a Variable i.e. FirstName : ", firstname)
#print(firstname,"We have called a Variable call Firstname")
#print("Calling Variable",firstname,"Using Print Funct... |
47d9ba9ec790f0b9fde1a350cf8b240e5b8c886a | JATIN-RATHI/7am-nit-python-6thDec2018 | /OOPS/Encapsulation.py | 1,035 | 4.65625 | 5 | # Encapsulation :
"""
Using OOP in Python, we can restrict access to methods and variables.
This prevent data from direct modification which is called encapsulation.
In Python, we denote private attribute using underscore as prefix i.e single
“ _ “ or double “ __“.
"""
# Example-4: Data Encapsulation in Python
... |
9f6536e8d1970c519e84be0e7256f5b415e0cf3e | JATIN-RATHI/7am-nit-python-6thDec2018 | /loops/Password.py | 406 | 4.1875 | 4 |
passWord = ""
while passWord != "redhat":
passWord = input("Please enter the password: ")
if passWord == "redhat":
print("Correct password!")
elif passWord == "admin@123":
print("It was previously used password")
elif passWord == "Redhat@123":
print(f"{passWord} is your recent ... |
36f0a7f05fba28b2feddb9e1ec0195c252dd1a53 | storrellas/pygame_ws_server | /snake.py | 4,783 | 3.671875 | 4 | """
Sencillo ejemplo de serpiente
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
"""
import pygame
from flask import Flask, jsonify, request, render_template
from gevent import pywsgi
from geventwebsocket.hand... |
27663a08442eadf6741dec65943edb03782f4963 | CS-Developers/Python | /Tip-Calculator/tipCalculator.py | 665 | 4.09375 | 4 | # Basic Printing Function
print("Welcome to the tip calculator.")
totalBill = input("What was the total bill? $")
totalPeople = input("How many people to split the bill? ")
percentChoice = input(
"What percentage tip would you like to give? 10, 12, or 15? ")
total = 0
def allInAll():
global total
total ... |
216bdcda887541ba32eb1e8b656b8bb00c7f3a5c | Saianisha2001/pythonletsupgrade | /day2/day2 assignment.py | 1,123 | 3.8125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
List = [1,2,3,4]
List.append(5)
print(List)
List.insert(2,6)
print(List)
print(sum(List))
print(len(List))
print(List.pop())
# In[7]:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.get(3))
print(squares.items())
element=squares.pop(4)
print('del... |
d0fc6d4c351f801b5f15ee2d9824c90f0cdd6206 | guifurtado/cursopython | /Fluxo/0-if.py | 258 | 4.03125 | 4 | #A = int(input())
txt = input()
A = float (txt)
if A == 20:
print("= 20")
if A > 5 and A < 15:
print ("5 < A < 15")
if A > 20:
print("A > 20")
else:
print("A < 20")
if A == 10:
print("A = 10")
elif A == 20:
print("A = 20")
print( 5 < A < 15)
|
e1c9995fbac0c7c7e792959b8351894e77626a1b | Nesterenko-Andrii/pr2 | /pr2_1.py | 169 | 4 | 4 | print('enter the number')
num1 = float(input())
print('enter another number')
num2 = float(input())
if num1 > num2:
print('True')
else:
print('False') |
917e4eb5d5a629a581b6f952275d69ba61016ee6 | idubey-code/Data-Structures-and-Algorithms | /SelectionSort.py | 272 | 3.828125 | 4 | def selectionSort(array):
for i in range(0,len(array)):
minimum=array[i]
for j in range(i+1,len(array)):
if array[j] < minimum:
minimum=array[j]
array.remove(minimum)
array.insert(i,minimum)
return array
|
436120f034d541d70e2373de9c3a0c968b47f7ad | idubey-code/Data-Structures-and-Algorithms | /InsertionSort.py | 489 | 4.125 | 4 | def insertionSort(array):
for i in range(0,len(array)):
if array[i] < array[0]:
temp=array[i]
array.remove(array[i])
array.insert(0,temp)
else:
if array[i] < array[i-1]:
for j in range(1,i):
if array[i]>=array[j-1] a... |
ef7beb682047faded1e6e4c8e323387c7bf68ff1 | BonIlcer/Daily-Coding-Problem | /m07y20/day19.py | 1,096 | 3.875 | 4 | # Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
# Bonus: Can you do this in one pass?
def subList(sourceList, num):
subList = []
for elem in sourceList:
subList.append(num - el... |
35a424ef1171e034d6b0092e9fceb9802c3baf73 | diogofernandesc/ctci-answers | /linked_lists/remove_duplicate.py | 691 | 3.671875 | 4 | def remove_duplicates(node):
seen = set()
previous_node = None
while (node is not None):
if node.data in seen:
previous_node.next = node.next
else:
seen.add(node.data)
previous_node = node
node = node.next
# No buffer solution
def remove_duplica... |
190b073ac866811194433c3dc043b9320b949ec7 | HerrDerNasn/AdventOfCode | /TwentyNineteen/Day10/monitoring-station-part-two.py | 1,702 | 3.53125 | 4 | import math
def calc_angle(orig_coord, target_coord):
return math.atan2(target_coord[1] - orig_coord[1], target_coord[0] - orig_coord[0])
def sort_by_dist(val):
return math.sqrt(val[0]*val[0]+val[1]*val[1])
def sort_angles(val):
return val if val >= calc_angle((0, 0), (0, -1)) else val + 2 * math.pi
... |
a5bd02624e4a4a500dae264b4ff7ebedf2e040c0 | ishine/tacotron_gmm | /tacotron/utils/num2cn.py | 3,985 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def num2cn(number, traditional=False):
'''数字转化为中文
参数:
number: 数字
traditional: 是否使用繁体
'''
chinese_num = {
'Simplified': ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
'Traditional': ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒'... |
e78ce73faa96ebdc50f1071613253e221a024f33 | rahmanifebrihana/Rahmani-Febrihana_I0320082_Aditya-Mahendra-_Tugas7 | /I0320082_Soal1_Tugas7.py | 538 | 4 | 4 | str = "Program Menghitung Jumlah Pesanan Makanan"
s = str.center(61,'*')
print(s)
nama_pemesan = input("Nama pemesan :")
print("Selamat datang", nama_pemesan)
print("\nMenu makanan : NASI GORENG , BAKSO, SATE")
str = input("Masukkan menu makanan yang dipesan dengan menuliskan menu sebanyak jumlah yang dipesan :")
pes... |
92221bfa79730508918f7774fe24cffd71627150 | rhutuja3010/json | /meraki Q1.py | 494 | 3.734375 | 4 | # Q.1 Json data ko python object main convert karne ka program likho?. Example: Input :- Output :
import json
x='{"a":"sinu","b":"sffhj","c":"frjkjs","d":"wqiugd"}'
# a=json.loads(x)
# print(type(a))
# print(a)
a=open("question6.json","w")
json.loads(x,a,indent=4)
a.close()
# with open("question1.json","r") as ... |
9441cb892e44c9edd6371914b227a48f00f5d169 | hospogh/exam | /source_code.py | 1,956 | 4.21875 | 4 | #An alternade is a word in which its letters, taken alternatively in a strict sequence, and used in the same order as the original word, make up at least two other words. All letters must be used, but the smaller words are not necessarily of the same length. For example, a word with seven letters where every second let... |
0d59e175ec5a00df9c3349909782dce3720c63ee | andrehoejmark/Classify-paying-customers | /data_cleaning_functions.py | 5,107 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import sklearn
from sklearn import preprocessing
# for data visualizations
import matplotlib.pyplot as plt
import seaborn as sns
categorical_labels = ["Month", "Weekend", "Revenue", "VisitorType"]
def get_data_cleaned():
data_frame = read_data()
data_size = len(d... |
24568901f1ad26e90a52c2fc1c74449d17c0b9bc | kms121999/homework12_13 | /12C/ks_assignment_12C.py | 709 | 3.84375 | 4 |
def main():
myFunc(5, True)
def myFunc(myInt, increasing):
if increasing:
for n in range(1, myInt + 1):
print("*" * n)
myFunc(myInt, False)
else:
for n in range(myInt - 1, 0, -1):
print("*" * n)
'''
if increasing:
if myInt > 1:
... |
8ed6ce79985a8de478c66c068e96e9637d0124e8 | shivam5750/DSA-in-py-js | /DSA-python/4.Stacks/stackswitharray.py | 508 | 3.53125 | 4 | class Stacks:
def __init__(self):
self.array = []
def __str__(self):
return str(self.__dict__)
def peek(self):
return self.array[len(self.array)-1];
def push(self,value):
self.array.append(value)
return self.array
def pop(self):
self.array.pop()
return self.array
mystacks ... |
c386b02127f2cde6e4f5a7c97b946b0a48f2284b | Awerito/data-structures | /sequences/feigenbaum.py | 493 | 3.578125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from random import random as rnd
logistic = lambda x, r: r*x*(1 - x)
def conv(x0, r, niter):
x = x0
for i in range(niter):
x = logistic(x, r)
return x
if __name__=="__main__":
iterations = 100
r_range = np.linspace(2.9, 4, 10**6)
x =... |
ad9508df76aa677a1a83c411022c98de253861f2 | Awerito/data-structures | /probability/angle.py | 582 | 3.640625 | 4 | import random, math
def distance(point1, point2):
""" Return the distances between point1 and point2 """
return math.sqrt((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2)
# Estimate of the probability of P(x>pi/2)
obtuse = 0
total = 100000
points = [[0, 0],[1, 0]]
for i in range(total + 1):
a, b = 0, 0... |
0700ad8689cf66bd15fb59efd286cb3266ea8d35 | Awerito/data-structures | /sequences/primes.py | 392 | 3.921875 | 4 | def prime(n):
"""Return True if n is primes, False otherwise"""
if n == 2:
return True
if n <= 1 or n % 2 == 0:
return False
maxdiv = int(n ** (0.5)) + 1
for i in range(3, maxdiv, 2):
if n % i == 0:
return False
return True
if __name__=="__main__":
total ... |
4ddb35db33cb67aa252449224265e0d0472a70fa | TiesHogenboom/PythonAchievements | /PYTB1L3SchoolTool/tool.py | 409 | 3.953125 | 4 | Weekdag = "Woensdag"
dag1 = "Je moet vandaag naar school toe. " + "Mis je bus niet.."
dag2 = "Online les! " + "probeer wakker te blijven.."
dag3 = "Een vrije dag!"
if Weekdag == "Maandag":
print(dag1)
elif Weekdag == "Dinsdag":
print(dag2)
elif Weekdag == "Woensdag":
print(dag1)
elif Weekdag == "Dond... |
2986fc6e6a795c6fcb19424cebd0a611e883ced5 | TiesHogenboom/PythonAchievements | /PYTB1L5ShuffleAndReturn/shuff.py | 271 | 3.75 | 4 | import random
def original(word):
randomised = ''.join(random.sample(word, len(word)))
return original
print(original(input("Voer je eerste woord in: ")))
print(original(input("Voer je tweede woord in: ")))
print(original(input("Voer je derde woord in: "))) |
3be4ac78c65418caaebfd653f0ce58575ca2c7de | gokcelb/xox | /tictactoe.py | 2,331 | 3.75 | 4 | X = 'x'
O = 'o'
EMPTY = ' '
class NotEmptyCellException(Exception):
pass
board = [[EMPTY for _ in range(3)] for _ in range(3)]
def is_full(board):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == EMPTY:
return False
return True
def place... |
0138f9431c2c80332feeacd67c1c015d1abe9245 | ishandutta2007/corporateZ | /model/post.py | 7,721 | 3.859375 | 4 | #!/usr/bin/python3
from __future__ import annotations
from typing import List, Dict
from csv import reader as csvReader
from functools import reduce
'''
Holds an instance of a certain PostOffice of a certain category
Possible categories : {'H.O', 'S.O', 'B.O', 'B.O directly a/w Head Office'}
Now there's... |
5a41308a38717b1b1add0dc4ad40116ca4ca8c07 | spriteirene/BC-homework | /BC Homework 4 Heros.py | 6,800 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
from collections import Counter
# In[2]:
heros = pd.read_csv("/Users/wuyanxu/Desktop/CWCL201901DATA4/04-Pandas/Homework/Instructions/HeroesOfPymoli/Resources/purchase_data.csv")
# In[3]:
heros.head()
# In[4]:
#Total num... |
16e862e17eb3115db1e308a19c34ea1ac5981f57 | tamirYaffe/ShortestPath | /aStar.py | 4,451 | 3.609375 | 4 | import math
from heapq import heappush, heappop
from pyvisgraph.shortest_path import priority_dict
import queue as Q
from ass1 import print_maze, a_star
def euclidean_distance(start, end):
return math.sqrt((start[0] - end[0]) ** 2 + (start[1] - end[1]) ** 2)
class Node:
def __init__(self, parent=None, posit... |
aa81c49b435383d4971f67d96e379c026876504f | RexTremendae/AdventOfCode | /archive/Source/2020/Day23_1.py | 1,365 | 3.640625 | 4 | exampleInput = [3,8,9,1,2,5,4,6,7]
puzzleInput = [6,4,3,7,1,9,2,5,8]
inputData = puzzleInput
class Node:
def __init__(self, label):
self.label = label
self.next = None
def assignNext(self, nextNode):
self.next = nextNode
def printList(node, separator = " "):
first = node
it = f... |
56f5058e466751de997a9b4c8a63cc42848a3522 | RexTremendae/AdventOfCode | /archive/Source/2021/Day8_2.py | 1,698 | 3.71875 | 4 | def tostring(arr):
return "".join(sorted(arr))
def get_output(line):
parts = line.rstrip().split('|')
inputs = [tostring(s) for s in parts[0].split(' ')]
outputs = [tostring(s) for s in parts[1].split(' ')]
all = inputs + outputs
digit_by_segments = {}
oneseg = ""
threeseg = ""
sixseg = ""
# 4
... |
f4bc5176e017297ab06cf67186f73809232b04d2 | rsd1244/hello-world | /newfile.py | 142 | 4 | 4 | #!/usr/bin/env python3
print("Hello World")
for x in range(10):
print(x)
greeting = "Hey There"
for ch in greeting:
print(ch, end="")
|
ac4983b74f137778773f150040b42b6b2d00fa92 | ustcchenjingfei/ProgrammingOnline | /Python100例(菜鸟教程)/4.py | 703 | 3.703125 | 4 | """
题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:
"""
year = int(input('year:'))
month = int(input('month:'))
day = int(input('day:'))
months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
# 平年2月28天
# 闰年2月29天
# 四年一闰
if 0 < month <= 12:
sum = months[month... |
ae12b7429e9f6146850eff57798aaa54a65021f3 | ustcchenjingfei/ProgrammingOnline | /Python100例(菜鸟教程)/17.py | 681 | 3.859375 | 4 | """
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用 for 语句,条件为输入的字符不为 '\n'。
"""
def cnt(string):
letters = 0
space = 0
digit = 0
others = 0
for i in string:
if i.isalpha():
letters += 1
elif i.isspace():
space += 1
elif i.isdigit():
digit ... |
ddc33ee98f6925d8f980808d417e02d593b5b0f6 | danielhones/context | /python/tests/test_pycontext.py | 738 | 3.671875 | 4 | import os
import sys
import unittest
from helpers import *
from context import BLUE, END_COLOR, insert_term_color
class TestInsertTermColor(unittest.TestCase):
def test_color_whole_string(self):
teststr = "some example test string\nwith some new lines\tand tabs."
colored = insert_term_color(tests... |
0aaa4ee638da2375395796a927cdb2526ca23afa | msharsh/skyscrapers | /skycrapers.py | 5,331 | 4.03125 | 4 | """
This module works with skyscrapers game.
Git repository: https://github.com/msharsh/skyscrapers.git
"""
def read_input(path: str) -> list:
"""
Read game board file from path.
Return list of str.
"""
with open(path) as board_file:
board = board_file.readlines()
for i in range(len(... |
01b36affb80f458190d9f1f61c2ce4d98db1c807 | ly2/codeBackup | /FifthPythonProject/environment.py | 6,696 | 3.890625 | 4 | # COMP3620/6320 Artificial Intelligence
# The Australian National University - 2014
# COMP3620 and COMP6320 - Assignment 4
""" This file implements the following environments for use in Assignment 4.
You should familarise yourself with the environments contained within,
but you do not need to change anything ... |
ebefa282a41ac08aeb4ef5a54c675c44da5a907c | ly2/codeBackup | /FifthPythonProject/visualisation.py | 14,513 | 3.53125 | 4 | # COMP3620/6320 Artificial Intelligence
# The Australian National University - 2014
# COMP3620 and COMP6320 - Assignment 4
"""
This file defines a Visualisation which can be imported and used
in experiments.py to help visualise the progress of your RL algorithms.
It should be used in the following way:
... |
a387177160524693b15dbcca98ee463c02d24a90 | ly2/codeBackup | /FifthPythonProject/experiments.py | 18,408 | 3.796875 | 4 | # COMP3620/6320 Artificial Intelligence
# The Australian National University - 2014
# COMP3620 and COMP6320 - Assignment 4
""" Student Details
Student Name: Sai Ma
Student number: u5224340
Date: 25/05/2014
"""
""" In this file you should write code to generate the graphs that
you include in your repor... |
ec1702cf85a90917a4a41d498ef06d5bb2c13a28 | purohitprachi72/Encrypt-Decrypt | /encrypt-decrypt.py | 2,761 | 3.578125 | 4 | import random
import tkinter
from tkinter import *
from tkinter import messagebox
MAX_KEY_SIZE = random.randrange(1,26)
# def getMessage():
# print('Enter your message:')
# return input()
def getKey():
key = MAX_KEY_SIZE
while True:
if (key >= 1 and key <= MAX_KEY_SI... |
b3ebf46f74f88ddfa8a4a688de107dd6af5ead70 | naiera-magdy/Abbreviation-Coding | /abbrev_utility.py | 6,484 | 3.828125 | 4 | import bitstring
import math as math
# Node class
class Node:
# Constructor magic
#
# Arguments:
# symbol {str} -- The node's key
# freq {int} -- The number of occurences
#
def __init__(self, symbol, freq):
self.symbol = symbol
self.freq = freq
self.left = None
self.right = None
# Comparison magi... |
97f8d21ba55780327cf92909b1a73be2f26359f1 | shubhampurohit1998/test | /Problem51.py | 171 | 3.703125 | 4 | class American:
class NewYorker:
def City(self):
print("I used to live Queens but now it is New york city")
obj = American.NewYorker()
obj.City() |
725034f34dd558fd0fd870ab324ba15379dc4dff | lyse0000/Leecode2021 | /420. Strong Password Checker.py | 1,655 | 3.609375 | 4 | class Solution:
def strongPasswordChecker(self, password: str) -> int:
missing = 3
if any('a'<=char<='z' for char in password): missing -= 1
if any('A'<=char<='Z' for char in password): missing -= 1
if any(char.isdigit() for char in password): missing -= 1
... |
848b371cef43494f37540513995bcc39f15b984a | lyse0000/Leecode2021 | /74.240. Search a 2D Matrix I II.py | 1,311 | 3.609375 | 4 | # 240. Search a 2D Matrix II
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
M, N = len(matrix), len(matrix[0]) if matrix else 0
y, x = 0, N-1
while y<M and x>=0:
if matrix[y][x] == target:
return True
... |
4320b576cef32f3e9cd9ad9ed8da31e16c5a20cb | lyse0000/Leecode2021 | /616. Add Bold Tag in String.py | 1,313 | 3.796875 | 4 | class TrieNode():
def __init__(self):
self.next = {}
self.word = None
class Trie():
def __init__(self):
self.root = TrieNode()
def insert(self, w):
node = self.root
for c in w:
if c not in node.next:
node.next[c] = TrieNod... |
23a8b778535be8bae4377a991f703457267ee32b | acjensen/project-euler | /0027_QuadraticPrimes.py | 470 | 3.90625 | 4 | import math
def isPrime(n):
if n < 0:
return False
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
nMax = 0
a_ = range(-999, 999)
b_ = range(-1000, 1000)
for a in a_:
for b in b_:
n = 0
while isPrime(n**2 + a*n + b)... |
d1a86520bb97baeca04fde56f66330bce4265de8 | acjensen/project-euler | /0037_TruncatablePrimes.py | 1,388 | 3.859375 | 4 | import primetools as pt
import timeit
def problem():
primes = pt.getPrimes(1000000)
def truncate(p: int, from_left=True):
''' Repeatedly truncate the number. Return false if any truncated number is not prime. '''
digits = [c for c in str(p)]
while len(digits) != 0:
if int(... |
9530947bdcad6104ba7c5ce7a0fd544a2dde2a34 | JuanTovar00/Aprendiendo-con-Python | /Tablas.py | 390 | 3.65625 | 4 | #Tablas.py
#Autor: Juan Tovar
#Fecha: sabado 14 de septiembre de 2019
for i in range(1,11):
encabezado="Tabla del {}"
print(encabezado.format(i))
print()
#print sin agurmentaos se utiiza para dar un salto de linea
for j in range(1,11):
#Dentro de for se agrega otro for
salida="{} x... |
ea68edbe1b2025798079fc03ff4376c3282f9c9f | RFenolio/leetcode | /61_rotate_list.py | 1,099 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if k == 0 or head is None:
return head
end = head
newEnd = head
distance ... |
8a55ad8adca4388d396e7ad73ab121f190dcc082 | krniraula/Python-2019-Fall | /Exams/exercise_3.py | 641 | 3.890625 | 4 | #Homework 4
odd_numbers = [x for x in range(1,50,2)]
for number in range(0,8):
print(odd_numbers[number])
#Homework 3
grocery_items = ['Chicken', 'Steak', 'Fish', 'Apple']
grocery_items_prices = [10, 15, 25, 2]
print("Items: " + grocery_items[2] + " Price: " + grocery_items_prices[2])
prnt("Items: " + grocer... |
3953866e18727048006993f01cef67059b622cbf | krniraula/Python-2019-Fall | /Attendance/check_string_numbers.py | 433 | 3.921875 | 4 | #Name: Khem Niraula
#Student ID: 0644115
#Due Date: November 10, 2019
#MSITM 6341
# Problem of the day
def check_num(num1,num2):
#first_num = str(input("enter First No.:"))
#Second_num = str(input("enter Second No.:"))
if int(num1)==int(num2):
print("The Numbers are equal..")
else:
prin... |
9cca97a531a76aad89d5300c6a331ab85afc1149 | krniraula/Python-2019-Fall | /Assignments/homework_assignment_8/menu_builder.py | 1,628 | 4.09375 | 4 | #Name: Khem Niraula
#Student ID: 0644115
#Due Date: November 3, 2019
#MSITM 6341
menu_item_name = []
def ask_user_for_menu_item_name():
continue_or_not = True
while continue_or_not == True:
item_name = input('Item name: ')
item_name.lower()
if item_name.lower() in menu_item_name:
... |
b825f1d76605fce12876d5a0bb1d57e82cb54a50 | niyaspkd/python-unit-test-example | /sort.py | 327 | 3.796875 | 4 | class ElementTypeError(Exception):pass
class TypeError(Exception):pass
def sort(l):
if type(l) != list: raise TypeError,"Input must be list"
for i in l:
if type(i) != int: raise ElementTypeError,"Invalid list element"
for i in range(len(l)):
for j in range(i,len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
ret... |
ee60c5f80a219159605ae413834ce60e2c4ab4a7 | sumanth-hegde/Conversions | /speech-to-text-via-microphone.py | 493 | 3.5 | 4 | # Speech recognition using microphone
# importing speech_recognition module
import speech_recognition as sr
r = sr.Recognizer()
# Using microphone as source
with sr.Microphone() as source:
print("Talk now")
audio_text = r.listen(source)
print("Times up")
try:
print("Text: "+r.recognize_google... |
e371e74a4207ade3b0d5f5e152b71be78bb0ff3f | Ryuk17/LeetCode | /Python/394. Decode String.py | 939 | 3.5 | 4 | class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
num_stack = []
char_stack = []
res = ""
t = ''
for c in s:
if c == '[':
char_stack.append(c)
num_stack.append(int(t)... |
dca69aca43dac3f61cbab1b286ecd2e260b2b405 | Ryuk17/LeetCode | /Python/448. Find All Numbers Disappeared in an Array.py | 515 | 3.5625 | 4 |
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.insert(0, 0)
res = []
for i in range(1, len(nums)):
while nums[i] != i and nums[i] != nums[nums[i]]:
tmp = nums[nu... |
4c6e1574243bee2e3bf997da8d728f52ee2973d2 | Ryuk17/LeetCode | /Python/297. Serialize and Deserialize Binary Tree.py | 1,318 | 3.515625 | 4 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if root is None:
return []
queue = [root]
res = []
while len(queue) > 0:
node = queue.pop(0)
if nod... |
07bb7a86ff930cb9f0d955b2c5569838836526dc | Ryuk17/LeetCode | /Python/141. Linked List Cycle.py | 535 | 3.578125 | 4 | class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return False
p = head.next
q = head.next.next
while p.next is not None and q is not None:
if q.n... |
b7ad81e0c65022aa16a1a817b0c520252f7cfefc | skmamillapalli/fluentpython-exercises | /Ch01/Frenchcard.py | 1,129 | 4.0625 | 4 | #!/usr/bin/env python
import collections
import random
# card can have suit(Heart, Diamond, Spade, Club) and rank
card = collections.namedtuple('Card', ['suit', 'rank'])
class FrenchDeck:
"""Represents Deck of cards"""
def __init__(self):
self._cards = [card(rank, suit) for rank in ['Heart', 'Diamond', '... |
e516ba068e730f8c2337acf71d762018c6822975 | edvin328/EDIBO | /Python/dec2bin.py | 536 | 3.9375 | 4 | #!/bin/python3.8
n=int(input("Please enter decimal number: "))
given_dec=n
#jauna massīva array izveidošana
array=[]
while (n!=0):
a=int(n%2)
# array.append komanda pievieno massīvam jaunu vērtību
array.append(a)
n=int(n/2)
string=""
# lai nolasītu massīvu array no gala izmanto [::-1]
for j in array[::-1]... |
bb4af43132c6d9246049362f3f5b554ad9a629cf | prashanthag/webDevelopment | /fullstack/projects/capstone/heroku_sample/starter/database/models.py | 3,569 | 3.5 | 4 | import os
from sqlalchemy import Column, String, Integer
from flask_sqlalchemy import SQLAlchemy
import json
from flask_migrate import Migrate
db = SQLAlchemy()
'''
setup_db(app)
binds a flask application and a SQLAlchemy service
'''
def setup_db(app):
db.app = app
db.init_app(app)
migrate = Migrat... |
8be8e2bb46caf8a70c82b41172390c7403733085 | RajatVermaz/pytho | /madlibs.py | 293 | 3.578125 | 4 | # Madlibs game based on string concatination
adj1 = input('Adjective : ')
adj2 = input('Adjective : ')
verb1 = input('Verb : ')
verb2 = input('Verb : ')
print(f'Computer programming is so {adj1} it makes me {verb1}, and some day it will be {adj2} and \
computer will {verb2}.')
|
5d702c3b01d662249f704099ee85a8cc703d1c02 | CompPhysics/ComputationalPhysics | /doc/Programs/LecturePrograms/programs/NumericalIntegration/python/program1.py | 1,001 | 3.71875 | 4 | # -*- coding: utf-8 -*-
#Example of numerical integration with Gauss-Legendre quadrature
#Translated to Python by Kyrre Ness Sjøbæk
import sys
import numpy
from computationalLib import pylib
#Read input
if len(sys.argv) == 1:
print "Number of integration points:"
n = int(sys.stdin.readline())
print "Integ... |
1fbcf671cd4884007549a8e1c08685329c616e30 | CompPhysics/ComputationalPhysics | /doc/Programs/PythonAnimations/animate2.py | 876 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen(t=0):
cnt = 0
while cnt < 1000:
cnt += 1
t += 0.1
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
def init():
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 10)
del xdata[:]
de... |
df00204272fad9115ea527d137cb7a06df1f16cd | CompPhysics/ComputationalPhysics | /doc/Programs/LecturePrograms/programs/PDE/python/2dwave/pythonmovie.py | 2,018 | 3.5 | 4 | #!/usr/bin/env python
# This script reads in data from file with the solutions of the
# 2dim wave function. The data are organized as
# time
# l, i, j, u(i,j) where k is the time index t_l, i refers to x_i and j to y_j
# At the end it converts a series of png files to a movie
# file movie.gif. You can run this movi... |
54fa124eaace5d831d897f932615c57182404218 | CompPhysics/ComputationalPhysics | /doc/Programs/LecturePrograms/programs/MCIntro/python/program1.py | 628 | 3.90625 | 4 | # coding=utf-8
#Example of brute force Monte Carlo integration
#Translated to Python by Kyrre Ness Sjøbæk
import math, numpy, sys
def func(x):
"""Integrand"""
return 4/(1.0+x*x)
#Read in number of samples
if len(sys.argv) == 2:
N = int(sys.argv[1])
else:
print "Usage:",sys.argv[0],"N"
sys.exit(0)... |
23b5fb07ddbe64e1434cb1bfcfdb35d883dc3a6f | raymag/forca | /mag-forca.py | 6,486 | 4.34375 | 4 | #Sendo o objetivo do programa simular um jogo da forca,
#Primeiramente importamos a biblioteca Random, nativa do python
#Assim podemos trabalhar com números e escolhas aleatórias
import random
#Aqui, declaramos algumas váriaveis fundamentais para o nosso código
#Lista de palavras iniciais (Default)
palavras = ['abacat... |
e9158dd3a5cd39959a07f8244e3268da819d253e | dustylee621/PythonBootCamp | /inheritance.py | 523 | 3.78125 | 4 | class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def __repr__(self):
return f"{self.name} is a {self.genus}"
def make_noise(self, sound):
print(f"this animal says {sound}")
class Snake(Animal):
def __init__(self, name, genus, toy):
super().__init__(name,... |
58473b9b8f3bef88617060c78c084b85be492631 | irfan-ansari-au28/Python-Pre | /Lectures/lecture9/dictinary.py | 527 | 4.03125 | 4 | """
dict = {
"BJP":32,
"Congress": 12,
"AAP": 29
}
print(dict)
print (dict.items())
print(dict.keys())
print(dict.values())
"""
parties = ["BJP", "AAP", "Congress", "BJP","AAP", "BJP", "BJP"]
party_dict = {}
for party in parties:
if party in party_dict:
party_dict[party] += 1
else:
... |
5a6b0d985d1dcbaffc0702939d0fe91aeba778af | irfan-ansari-au28/Python-Pre | /Lectures/lecture8/tuples.py | 179 | 3.859375 | 4 | """
tuple is immutable that
means it can't be change once create
list can be typecast into tuple type
>>> A = list()
>>> B = tuple(A)
to reverse an array
>>> Array[::-1]
""" |
5688123f5e2c4791f8f177a6642df1088138b35f | irfan-ansari-au28/Python-Pre | /Interview/RandomQuestions/binary_search.py | 419 | 3.84375 | 4 |
# for binary search array must be sorted
A = [1,7,23,44,53,63,67,72,87,91,99]
def binary_search(A,target):
low = 0
high = len(A) - 1
while low <= high:
mid = (low + high) // 2
if target < A[mid]:
high = mid - 1
elif target > A[mid]:
low = mid + 1
e... |
594fee53a4e627a3897888522fb425d365b94d56 | irfan-ansari-au28/Python-Pre | /hands_on_python/1.Intro/dictionary.py | 773 | 4.0625 | 4 | """
>>> sorted() -- Does not change the original ordering
but gives a new copy
"""
vowel =['a', 'e', 'i','o' ,'u']
# word = input("provide a word to search for vowels:")
word = "Missippi"
found = []
for letter in word:
if letter in vowel:
if letter not in found:
found.appen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.