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 |
|---|---|---|---|---|---|---|
6ccc09c89f9516d5e9278a7ebda9588e67cff79c | ravisjoshi/python_snippets | /Concepts/binaryTree-DS.py | 2,377 | 4.03125 | 4 | class Node:
def __init__(self, value=None):
self.value = value
self.right = None
self.left = None
class binary_search_tree:
def __init__(self):
self.root = None
def insert(self, value):
if not self.root:
self.root = Node(value)
else:
... |
7243a437893be6023fc909bd2af8804a7b2e1944 | ravisjoshi/python_snippets | /Basics-3/BackspaceStringCompare.py | 1,212 | 3.953125 | 4 | """
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Input: S = "ab#c", T = "ad#c" / Output: true
Explanation: Both S and T become "ac".
Input: S = "ab##", T = "c#d... |
7821546f9e04bf912f7810421996157e790b589d | ravisjoshi/python_snippets | /Array/TwoSum.py | 720 | 3.921875 | 4 | """
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
cl... |
f95eb88f8b5ae743155b8d3b55389c6d8686cfe2 | ravisjoshi/python_snippets | /Array/SearchInsertPosition.py | 801 | 4.15625 | 4 | """
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Input: [1,3,5,6], 5 / Output: 2
Input: [1,3,5,6], 2 / Output: 1
Input: [1,3,5,6], 7 / Output: 4
Input: [1,3,5,6]... |
e723e122f4582bbb268941198bd46688e2cae020 | ravisjoshi/python_snippets | /DataStructure/linkedLists/RemoveLinkedListElements.py | 1,687 | 3.71875 | 4 | """
Remove all elements from a linked list of integers that have value val.
Input: 1->2->6->3->4->5->6, val = 6 / Output: 1->2->3->4->5
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def __init__(self):
self.head = None
... |
0334ea3d2d970823df4f5b66f1cfc5855d972206 | ravisjoshi/python_snippets | /Basics-3/ConstructTheRectangle.py | 2,118 | 4.15625 | 4 | """
For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
1. The area of the rectangular web page you designed must equal to ... |
272a9925a7e7c9fa671779a87354cac682c8e379 | ravisjoshi/python_snippets | /Strings/validateParenthesis.py | 1,217 | 4.40625 | 4 | """
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a correspondin... |
d1ecbd69e0c6be56a224939bb7c110019239b18d | ravisjoshi/python_snippets | /Basics-2/reverseInteger.py | 731 | 3.921875 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Input: 123 / Output: 321
Input: -123 / Output: -321
Input: 120 / Output: 21
"""
class Solution:
def reverse(self, num):
if num >= 2 ** 31 - 1 or num <= -2 ** 31:
return 0
result = 0
flag = 1 if num > 0 else -1... |
1d64714d534a4f798ffed51a21674fdfa0de87d0 | ravisjoshi/python_snippets | /HashTable/CountPrimes.py | 567 | 3.90625 | 4 | """
Count the number of prime numbers less than a non-negative number, n.
Input: 10 / Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
"""
class Solution:
def countPrimes(self, num):
if num == 1:
return 0
count = 1
for index in range(3, num+1... |
eca9d62bfa72def990e37f698784958f692e6917 | ravisjoshi/python_snippets | /Basics-2/KidsWithTheGreatestNumberOfCandies.py | 1,834 | 4.03125 | 4 | """
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.
For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the ... |
3a2ab445be28e3da8491cc57473ba43252435d4a | ravisjoshi/python_snippets | /Strings/LongestUncommonSubsequenceI.py | 1,496 | 4.21875 | 4 | """
Given two strings, you need to find the longest uncommon subsequence of this two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other string.
A subsequence is a sequence that can be derived from one se... |
dc52061454014fea26d67bd88c9c4a34f5bdd17c | ravisjoshi/python_snippets | /DataStructure/sorting/quickSort.py | 854 | 4.1875 | 4 | """
Quick Sort: https://en.wikipedia.org/wiki/Quicksort
Ref:
https://www.youtube.com/watch?v=1Mx5pEeTp3A
https://www.youtube.com/watch?v=RFyLsF9y83c
"""
from random import randint
def quick_sort(arr):
if len(arr) <= 1: return arr
left, equal, right = [], [], []
pivot = arr[randint(0, len(arr)-1)]
fo... |
0ff711409fb7b5384c7a28ed33bfa704db87fb0b | ravisjoshi/python_snippets | /Basics-1/ConvertIntegertoTheSumOfTwoNo-ZeroIntegers.py | 1,038 | 3.796875 | 4 | """
Given an integer n. No-Zero integer is a positive integer which doesn't contain any 0 in its decimal representation.
Return a list of two integers [A, B] where:
A and B are No-Zero integers.
A + B = n
It's guarateed that there is at least one valid solution. If there are many valid solutions you can return any of ... |
9d4e6b030ca3445700a4b02726d619227384b234 | ravisjoshi/python_snippets | /Basics-4/Play with Chips.py | 1,148 | 3.96875 | 4 | """
There are some chips, and the i-th chip is at position chips[i].
You can perform any of the two following types of moves any number of times (possibly zero) on any chip:
Move the i-th chip by 2 units to the left or to the right with a cost of 0.
Move the i-th chip by 1 unit to the left or to the right with ... |
e23aa12f21080505ddc87557ed152c9886edb6d7 | ravisjoshi/python_snippets | /Statistics/001-Mean-Median-Mode.py | 1,354 | 4 | 4 | """
Mean: The "average" number; found by adding all data points and dividing by the number of data points.
Median: The middle number; found by ordering all data points and picking out the one in the middle (or if there are two middle numbers, taking the mean of those two numbers).
Mode: The most frequent number—that is... |
afb730476d85a9f2a28581c990e225e3298b0820 | ravisjoshi/python_snippets | /Basics-1/largestUniqueNumber.py | 306 | 3.65625 | 4 | class Solution:
def largestUnique(self, numList):
newList = sorted(list(set(numList)))
return max([i for i in newList[::-1] if numList.count(i) == 1])
if __name__ == '__main__':
s = Solution()
numList = [2, 8, 1, 9, 100, 23, 18, 100, 1, 8]
print(s.largestUnique(numList))
|
03670d974ef18610084e94c1e19573c55e060cdc | ravisjoshi/python_snippets | /DataStructure/StackAndQueue/MaximumElement.py | 1,417 | 4.3125 | 4 | """
You have an empty sequence, and you will be given N queries. Each query is one of these three types:
1 -Push the element x into the stack.
2 -Delete the element present at the top of the stack.
3 -Print the maximum element in the stack.
Input Format: The first line of input contains an integer N. The next line... |
848696aadc4c2889406f5b2f1c61c47adb09f41d | ravisjoshi/python_snippets | /ProjectEuler/Basics-0/009-SpecialPythagoreanTriplet.py | 540 | 4.46875 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def pythagoreanTriplet(num):
for a in range(1, num//2):
for b in ... |
4e5c5c5378e4d08594e5a2c13265c18a52427dc2 | ravisjoshi/python_snippets | /Basics-2/mergeTwoSortedLists.py | 1,014 | 4 | 4 | """
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
... |
24b03adda55bc74c4365e93ecf529f3cc1c4453d | ravisjoshi/python_snippets | /Permutation-Combination/PermutationAndCombination.py | 879 | 4.3125 | 4 | """
"My fruit salad is a combination of apples, grapes and bananas" We don't care what order the fruits are in, they could also be "bananas, grapes and apples" or "grapes, apples and bananas", its the same fruit salad.
"The combination to the safe is 472". Now we do care about the order. "724" won't work, nor will "247... |
c90e7d6f56a990f373775438722f91d821f1ff1f | ravisjoshi/python_snippets | /Basics-2/NumberOfDaysBetweenTwoDates.py | 815 | 4.21875 | 4 | """
Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Input: date1 = "2019-06-29", date2 = "2019-06-30" / Output: 1
Input: date1 = "2020-01-15", date2 = "2019-12-31" / Output: 15
Constraints: The given dates are ... |
8ad1855fc54a64425106d19023d4dd2175fefbcd | ravisjoshi/python_snippets | /Basics-1/ConsecutiveCharacters.py | 1,795 | 4 | 4 | """
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Input: s = "leetcode" / Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Input: s = "abbcccddddeeeeedcba" / Outpu... |
272616f7c0360942fb032e220b9c025dca02f868 | anashikkar/pycode | /factorial.py | 198 | 3.953125 | 4 | import math
def factorial(x):
f = 1
while x > 1:
print x
y = x
sum = f * y
x = x - 1
f = sum
print (y,sum)
return sum
print factorial(6)
|
228e9868f9142aec935642cae53376452d296029 | monreyes/SelWebDriver | /PythonProj1/Sec3-UnderstandingVariablesAndDataTypes/319-StringMethods-Part2/string-methods2.py | 404 | 4.3125 | 4 | """
Examples to show available string methods in python
"""
# Replace Method
a = "1abc2abc3abc4abc"
print(a.replace('abc', 'ABC'))
#print(a.upper()) # another way to convert if all is need to upper case (or a.lower if all needed to be in lower case)
# Sub-Strings
# starting index is inclusive
# Ending index is exclus... |
902b77933c6d369a13fa8963737cde0a22c0d01b | monreyes/SelWebDriver | /PythonProj1/Sec3-UnderstandingVariablesAndDataTypes/314-Numbers-ExponentiationAndModulo/numbers_operations.py | 427 | 4.28125 | 4 | # This is a one line comment
# Exponentiation
exponents = 10**2
print(exponents)
"""
this is a multi line comment
modulo - returns the remainder
"""
a=100
b=3
remainder = a % b
print("Getting the modulo of " + str(a)+ " % "+ str(b) + " is just like getting the remainder integer when " + str(a) +"... |
e0e58817c9c9c0f193702530713de5bdc9755ec9 | monreyes/SelWebDriver | /PythonProj1/Sec3-UnderstandingVariablesAndDataTypes/321-StringsFormating/strings_formatting.py | 314 | 4.25 | 4 | """
Examples to show how string formatting works in python
"""
city = "nyc"
dine = "alingdosya"
event = "show"
#dine = "alingdosya"
print("Welcome to "+city+" and enjoy the "+event+", dont forget to eat at "+dine )
print("Welcome to %s and enjoy the %s, dont forget to eat at %s" % (city,event,dine))
|
8f5279bb0cd201fd8d2401a667a00f5759a1bd4a | monreyes/SelWebDriver | /PythonProj1/Sec6-ProgramControlFlow/634-ForLoopDemo/forloop1.py | 121 | 3.96875 | 4 | my_string = 'abanaku'
for k in my_string:
if k == 'a':
print(k.upper(), end=' ')
#print(k, end='')
|
c5406cf19d5bcfefb0e0c959db38fe245f2b31f9 | yangbinnnn/leetcode_easy | /Strings/valid_palindrome.py | 1,249 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# Author: yangbin
# Created: 02/25/2018
"""
Given a string, determine if it is a palindrome, considering only alphanumeric characters and
ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string mi... |
bb284e58282018535397cba828cb90f8cd101fac | yangbinnnn/leetcode_easy | /Strings/str_str.py | 1,153 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# Author: yangbin
# Created: 02/27/2018
"""
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: ... |
3fe219c7a4291ce67742d7a33fcca82d44c22c6d | yangbinnnn/leetcode_easy | /Array/rm_dup_from_sorted_array.py | 910 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# Author: yangbin
# Created: 01/23/2018
"""
Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Exam... |
e34f2093a9cc86aaf0e94891bef8b4f3355d254e | yangbinnnn/leetcode_easy | /Dynamic_Programming/best_time_to_buy_and_sell_stock.py | 1,947 | 3.9375 | 4 | # -*- coding:utf-8 -*-
# Author: yangbin
# Created: 02/13/2018
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Exa... |
ddb4a47288b73951542d6c1aa3854b7c3846cf9c | DysphoricUnicorn/CodingChallenges | /extra_char_finder.py | 1,630 | 4.3125 | 4 | """
This is my solution to the interview question at https://www.careercup.com/question?id=5101712088498176
The exercise was to write a script that, when given two strings that are the same except that one string has an extra
character, prints out that character.
"""
import sys
def find_extra_char(longer_string, shor... |
bd8509526fa1c27f6bcdb473439b73c7636483f0 | Soulreaper23781/pygame-2d-jrpg-demo | /main.py | 1,191 | 3.953125 | 4 | import pygame
import player
import time
#Initiate pygame
pygame.init()
#Create our screen, set caption, initiate clock
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Python/Pygame Animation")
clock = pygame.time.Clock()
'''Here we create our player object. The (200, 200) values are passed ... |
50e2269b947db8c0f626fa8b8b044daf825138d7 | rabelais88/pyscrape-mac | /src/legacy/save_sqlite3.py | 940 | 3.6875 | 4 | # sqlite3 is basic python package(only on windows)
# on Ubuntu, sudo apt-get install -y sqlite3
import sqlite3
import random
conn = sqlite3.connect('top_cities.db')
c = conn.cursor()
c.execute('DROP TABLE IF EXISTS cities')
c.execute('''
CREATE TABLE cities (
rank integer,
city text,
population integer
)
''')... |
c29f30dff81a2557b2ad5222f64727eaee2b6f84 | NicolasDS88/Phyton_Course_01 | /Lesson_1.py | 865 | 3.921875 | 4 | '''
Created on Mar 27, 2017
'''
# First lesson how to use:
# Multiple choices - List, Array and Dictionary
# Flow control - For loop
# Conditional sentences
def main():
print('This is how a Dictionary is use it')
choices=dict(
alex="A",
jane="B",
john="C"
)
print(cho... |
a1e56b841ee689b9096b28447200e4deaf112f8f | shoriwe/sololearn-challenges | /sololearn/voodo_prime.py | 482 | 3.953125 | 4 | def is_prime(number):
basic_primes = [2, 3, 5, 7, 11]
if number in basic_primes:
return True
for prime in basic_primes:
if number % prime == 0:
return False
return True
def voodo_prime(prime: int):
decimal = str(1 / prime).split('.')[1]
return str(prime) in decimal
number = int(input('prime:'))
if is_p... |
8e61101e083dc208b322a74581530303de955477 | pratikmallya/interview_questions | /misc/text-format.py | 5,181 | 3.71875 | 4 | """
Format the characters in the stdin by the given number of spaces
Python 3
Assumptions:
============
* if a word is greater than width, it will NOT be split across the
lines. Instead, the entire word will be printed out
* the line to be read is not larger than available main memory
* input is formatted correctly ... |
6a563dbae7b8cf7a46621ba9013275c2856ffc95 | pratikmallya/interview_questions | /sorting/insertion_sort.py | 1,011 | 4.34375 | 4 | """
Insertion Sort
Pick lowest element, push it to the front of the list
This will be an in-place sort. Why? Because that's a little
more complicated.
"""
import unittest
from random import sample
from copy import deepcopy
class TestAlg(unittest.TestCase):
def test_case_1(self):
v = [10, 9, 8, 7, 6, 5, ... |
3ccb62662a0dd7b60cdf29d0cf1164dc308ac68d | pratikmallya/interview_questions | /search/cycle_search.py | 1,875 | 3.515625 | 4 | """
Find all cycles in the given input digraph
* one node points at 1 or less other node
* N not large enough to overflow set(range(N))
"""
import sys
import unittest
class TestNumCycles(unittest.TestCase):
def test_sanity(self):
N = 7
nodes = [2, 3, 4, 5, 6, -1, 0]
graph = {}
f... |
d9f84ba769a8bf20820bc90e72d3270443f2e82f | 4workspace/Python-calisma-notlari | /32_selenium_instagram_giris.py | 1,860 | 3.703125 | 4 | # İnstagramda oturum açma
# email = input("Kullanıcı adı veya email girin: ")
# password = input("Şifrenizi girin: ")
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
username = "username"
password = "password"
class Instagram:
def __init__(self, username, ... |
630e1f44c1d6d298de515180ba5f74b0422f8e03 | 4workspace/Python-calisma-notlari | /12_list_tuple_set_dic_farklari.py | 977 | 3.703125 | 4 | # list: [] ile gösterilir.
# tuple: () ile gösterilir.
# set: ([]) ile gösterilir.
# dictionary: {} ile gösterilir.
list1 = ["Python","C/C++","C#"]
list1[0] = "Artifical" # eleman değiştirilebilir.
print(list1)
tuple1 = ("Python","C/C++","C#")
# tuple1[0] = "Artificial" # tuple da ... |
c5492e8f03bae372141991a54ab2c6e3b452254a | ChristophTempelhoff/DatabaseCommands | /src/DeleteData.py | 467 | 3.59375 | 4 | import sqlite3
from sqlite3 import Error
def deleteData(connection, sqlCommand):
"""
Deletes data from the sqlCommand statement
###Arguments###
connection: Connection object created with conn
sqlCommand: SQL-Statement to delete data from
###Returns###
none
"""
try:
cursor = connection.cursor()
cursor... |
8c7c90d16ca1386270427abca222325d36d09f70 | chikii/Projects | /pdf_formatting_A4.py | 1,508 | 3.703125 | 4 | """
A very long pdf page will be formate to small pages to get print.
prerequist libraries -> PyPDF2
usage ->
===> To change all the files present in folder
1) change dirctory_path
2) run main
3) change output location
===> To change single file
1) change file_path
2) change ... |
94a7c4c1400e047a2b422e3b4398e22e67839320 | BoredPotatoDev/PLD-40-Programs | /Exercise_1_Value_of_a_Quadratic.py | 192 | 4.15625 | 4 | from fractions import Fraction
print("Given 3x^2 - 8x + 4")
x = str(input("Assign a value for X: "))
y = Fraction(x)
ans = 3*(y**2) - 8*(y) + 4
print(f"At 2 = {x} the value is {ans}") |
c154c37ff28336d0bc095af314f08471ad7e9967 | BoredPotatoDev/PLD-40-Programs | /Exercise_8_Correct_Change.py | 1,008 | 3.8125 | 4 | x = int(input("Input your change due (in cents): "))
print("Your change is: ", end= "")
if x == 0:
print("no change")
if x//100 >= 1:
if x//100 == 1:
print(f"{x//100} dollar", end= " ")
x = x % 100
elif x//100 > 1:
print(f"{x//100} dollars", end= " ")
x = x % 100
... |
2e744069e0f464e2a34bc10f4a31f078663b6614 | BoredPotatoDev/PLD-40-Programs | /Exercise_2_Re-assigning_values_to_Variables.py | 118 | 3.765625 | 4 | x = 0
for i in range (0, 3):
x += 2
ans = 3*(x**2) - 8*(x) + 4
print(f"At x = {x} the value is {ans}") |
ffa6463d352aa14be9e098a14702ad8dd7afc531 | BoredPotatoDev/PLD-40-Programs | /Exercise_9_Ohm's_Law.py | 145 | 3.828125 | 4 | v = int(input("Input the number of Volts: "))
r = int(input("input the number of Ohms: "))
i = (v + 0.0)/r
print(f"The current is {i} amps") |
04c50f1b9bb1b308817dcc3f304f7eb04b922ef2 | SasidharRA/qwerty | /servoTest.py | 608 | 3.703125 | 4 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# Declaring Servo Pin
servoPin = 3
# Setting mode for servo pin
GPIO.setup(servoPin , GPIO.OUT)
# function for setting angle of the servo motor using PWM
# for this initial frequency of PWM must be set to 50Hz
# Servos will set to 0 degrees if given a sig... |
4206e176b23841534c80170b24ca94ee87170c1a | navnathsatre/Python-pyCharm | /BasicOprations.py | 580 | 4.25 | 4 | num1=int(input("Enter the value for num1 "))
num2=int(input("Enter the value for num2 "))
#num1=568
#num2=64
add=num1+num2
multi=num1*num2
sub=num1-num2
div=num1/num2
pow=num1**num2
"""print("addition of num1 and num2 is:-",add)
print("multiplication of num1 and num2 is:-",multi)
print("substraction of num1 ... |
a1a4ba97f6954549f8503a2936e458257b9fe215 | navnathsatre/Python-pyCharm | /16mar21.py | 2,650 | 3.6875 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> i = 10
>>> print(i)
10
>>> type(i)
<class 'int'>
>>> i = 'WELCOME'
>>> PRINT(i)
Traceback (most recent call last):
File "<pyshell#4>", l... |
2cf1cad023f38750af54b1842e9335e3284e8250 | navnathsatre/Python-pyCharm | /pyComp_7.py | 273 | 3.546875 | 4 | s = "Welcome to the world of Python Programming. the world is full of programmers"
# [(0, "Welcome", 7), (1, "to", 2), (2, "the", 3) ...]
lstWords = s.split(" ")
# enumerate
result = [(index, item, len(item)) for index, item in enumerate(lstWords)]
print(result) |
147560dd844918b281b381aedec10aac292711e6 | navnathsatre/Python-pyCharm | /pyFunc_3.py | 301 | 4.1875 | 4 | # Factorial of number
# 5! = 5*4*3*2*1
#1! = 0
#0! = 0
def iterFactorial(num):
result = 1
for item in range(1, num+1):
result = result*item
return result
n = int(input("Enter the number: "))
out = iterFactorial(n)
print("Factorial of {} is {} ".format(n, out)) |
38468a4291af8d02b2151e2a6e16ec0238568185 | navnathsatre/Python-pyCharm | /pyClass_13.py | 311 | 3.546875 | 4 | class Student:
def __init__(self, name):
self.name = name
# def __del__(self):
# print("I am in __del__")
s1 = Student("Virat")
s2 = Student("Dhoni")
s2.age = 37
print("s1 dict : ", s1.__dict__)
print("s2 dict : ", s2.__dict__)
# Monkey Patching
|
97327926348bc6d884df255463b3d86f6696fe1d | navnathsatre/Python-pyCharm | /InfoOfEmploye.py | 466 | 4.03125 | 4 | employee_name=input("Enter the name of employee")
employee_no=int(input("Enter the no of employee"))
sallary=float(input("Enter the sallary "))
job=input("Enter the job")
commition=int(input("Write commition "))
dep_no=int(input("Enter department no "))
print("Employee name is",employee_name)
print("Employee_n... |
6a4a51eb4b506b8447ed5d0cb0d829d62c62203b | duamkr/Python_Lecture | /1.Python_Dojang/Unit 8.py | 210 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 00:49:47 2019
@author: OH
"""
korean, english, math, science = map(int, input().split())
print(korean >= 90 and english > 80 and math > 85 and science >= 80) |
01e08f514b5984bc606b464d98b5e9336bd544c9 | s-sliwinski/SortingAlgorithmsVisualized | /BubbleSortViz.py | 1,594 | 3.828125 | 4 | import pygame
import random
def bubble_sort(reclist):
for i in range(0, len(reclist) - 1):
for j in range(0, len(reclist) - 1 - i):
if reclist[j][3] > reclist[j+1][3]:
reclist[j][3], reclist[j+1][3] = reclist[j+1][3], reclist[j][3]
redraw_screen(screen, reclist, j)
... |
ecb593594e042ae7a4970b48547ed966792f1c73 | subash54/my-algorithm | /practising.py | 189 | 3.859375 | 4 | #returning index of thelargest element
a=[1,2,3,4,5]
max=0
for i in range(len(a)):
if a[i]>a[max]:
max=i
for j in a:
if (2*j==a[max]):
print(max)
else:
print(-1) |
dc8d1e68476d077ab36ca4aece654e6ac5ef63bb | RyanLongRoad/Records | /Test scores.py | 745 | 4.15625 | 4 | #Ryan Cox
#29/01/15
#Store and display students test scores
#Blue print
class studentMarks:
def __init__(self):
self.testScore = "-"
self.studentName = "-"
#main program
def create_record():
new_studentMarks = studentMarks
def enter_enformation():
studentMarks... |
a95c72f1bd491be8f8c8e6fc18bb0f4f9dffaa2e | cypriluc/PyLadies-Praha-Barclays-2020 | /02_turtle_draw_a_house.py | 394 | 3.640625 | 4 | from turtle import shape, speed, forward, left, right, penup, pendown, exitonclick
from math import sqrt
shape("turtle")
speed(1)
forward(60)
left(90)
forward(60)
left(90)
forward(60)
right(135)
forward((sqrt(2 * (60 ** 2))) / 2)
right(90)
forward((sqrt(2 * (60 ** 2))) / 2)
right(90)
forward(sqrt(2 * (60 ** 2)))
rig... |
34dfc453ed3eefd583f6326d4b21822938367a7f | dazza-codes/gene_expression | /myHTML.py | 756 | 3.875 | 4 | #!/usr/bin/env python
"""
My module for HTML constructs
print_header(title="")
print_footer()
print_para(value)
"""
def print_header(title=""):
"""
Print the HTML header, including body.
print_header(title="")
The title string is used in both the
header title and a H1 title.
"""
print "Con... |
8da5655d4c8beb7a7c1d3fe44c779963b84eb6b6 | lpc359175324/myPython | /HelloWord.py | 3,383 | 3.671875 | 4 | print('helloWorld')
# u 前缀字符串 统一编码
print(u'''静夜思
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。''')
# 倒序索引 从 -1开始
L = [95.5, 85, 59]
print(L[-1])
print(L[-2])
print(L[-3])
# list 添加到末尾 append()
L.append('李四')
print(L)
# list 添加到指定位置 -1 倒叙第二位
L.insert(0, '张三')
print(L)
# list删除元素 第二次删除时 数组变化 下标不能越界
L.pop(2)
L.pop(3)
print('删除', L)
# li... |
8d365eaae0672fa53e82d35158d0cc4a261f9da8 | ahupe01/PYTHON | /myClient1.py | 1,152 | 3.890625 | 4 | #!/usr/bin/env python
'''
Client: client program should take two arguments
the first is the port number of the listening server
and the second is the file path to a data file.
client should read from the input file and send the contents
of the file to the server.
The se... |
23a64cbed28d0c8e4e2126ba88f0ffa31ca0f94b | vksbhandary/python-programming | /problems/regular expression/re-substitute.py | 733 | 3.734375 | 4 | # This is solution to problem stated in link https://www.hackerrank.com/challenges/re-sub-regex-substitution/problem
# Points - 20
# Difficulty- Medium
# Concept usage - Regular expressions
## added multiple lines for both cases because
## it didnt replace all " && " by " and " in case two && are joint together
## m... |
5e286568315e6aad2fdcb5e2be893fa57adc1f66 | vksbhandary/python-programming | /problems/sets/union.py | 402 | 3.96875 | 4 | # Name of problem: "Set .union() Operation"
# This is solution to problem stated in link https://www.hackerrank.com/challenges/py-set-union/problem
# Points - 10
# Difficulty- Easy
# Concept usage - Sets
if __name__ == '__main__':
a_count =int(input())
a = set(map(int, input().split()))
b_count = int(inp... |
7c3da3c2b106d83f64fd6412708ada033334fcf6 | Hilary02/atcoder | /ABC/174/a.py | 65 | 3.71875 | 4 | x = int(input())
cond = x >= 30
print("Yes" if cond else "No")
|
2356d52ff7ef738058605dfa46e351dcee530095 | Hilary02/atcoder | /Seisen_100/02_abc106_b.py | 298 | 3.578125 | 4 | n = int(input())
ans = 0
def divisors(n):
set_div = set()
for i in range(1, int(n**0.5)+1):
if n % i == 0:
set_div.add(i)
set_div.add(n//i)
return set_div
for i in range(1, n+1, 2):
t = len(divisors(i))
if t == 8:
ans += 1
print(ans)
|
da5169d7cde49d9b37621b723b35bdeb365d2842 | kuangyu1997/Python | /100sample/kuang/ky009.py | 185 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
myD = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
for key, value in dict.itens(myD):
print key, value
time.sleep(1) #暂停一秒
|
50aaddc79b3eb43902a4ebf6c26b602bde090a76 | tamkevindo97/Runestone-Academy-Exercises | /sum_even_list.py | 476 | 3.71875 | 4 | def sumEven(lst):
sum = 0
for i in range(len(lst)):
if lst[i] % 2 == 0:
sum = sum + lst[i]
return sum
lst = []
moreInputs = True
count = 0
while moreInputs:
lst.append(int(input("Add integer (999 to end): ")))
if lst[count] == 999:
lst.pop()
mor... |
3cdcc8c5f51e8b0813fad7ad93b09331af801b9a | tamkevindo97/Runestone-Academy-Exercises | /longest_word_dict.py | 456 | 4.28125 | 4 | import string
def longest_word(text):
text.translate(str.maketrans('', '', string.punctuation))
list_text = list(text.split())
dictionary = {}
for aChar in list_text:
dictionary.update({aChar: len(aChar)})
max_key = max(dictionary, key=dictionary.get)
print(dictionary)
r... |
b5d45cedae5734b38da8e2d7463e864e9d22391a | chaintuts/coinstack | /src/core/interpreter.py | 1,807 | 3.796875 | 4 | # This file contains code that handles the execution of simple, stack-based scripts
# The code starts with a string format script, tokenizes, and executes each op it encounters
#
# Author: Josh McIntyre
#
import op
from op import OPS
# This function tokenizes a string format script
def tokenize(script_string):
# Spl... |
f71eafc4df47902962b4485af7ccf1f5590d8034 | Rajat986/Python-Learning | /sss.py | 253 | 4.03125 | 4 | a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=int(input("Enter c: "))
def min():
if a>=b and a>=c:
print(a,"is the largest")
elif b>=a and b>=c:
print(b,"is the largest")
elif c>=a and c>=b:
print(c,"is the largest")
min()
|
cf714d1796d56fe211f62161b158821164121c43 | Rajat986/Python-Learning | /nnum.py | 232 | 4.125 | 4 | a=[]
n=int(input("Enter number of elements:"))
for i in range(n):
b=int(input("Enter element:"))
a.append(b)
l=a[0]
#print(a[0])
for i in range(n):
if (l<a[i]):
l=a[i]
print("Largest element is:",l)
|
ab9e2b113a318f6bfab391424eab7901cc28752e | Rajat986/Python-Learning | /Sudoku.py | 794 | 3.53125 | 4 | class board:
def __init__(self):
self.a=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]
def compute(self):
for i in range(9):
r=getrow(i)
... |
25d99ef11187909657ea93e10f291281ea024716 | sun04303/python | /5086-배수와 약수.py | 188 | 3.84375 | 4 | while 1:
a, b = map(int, input().split())
if a+b == 0:break
if a < b and b % a == 0:print("factor")
elif a > b and a % b == 0:print("multiple")
else : print("neither") |
a705a0ea8f1dc0051034fc8e22333d54e658fc64 | sun04303/python | /4999-아!.py | 79 | 3.53125 | 4 | s = input()
s1 = input()
if len(s) >= len(s1) : print("go")
else : print("no") |
75a091a9d094dc035ca5e14f809db36e46239bb7 | sun04303/python | /8958-OX퀴즈.py | 210 | 3.546875 | 4 | num = int(input())
for i in range(num):
sum = 0
s = input().split("X")
while '' in s:
s.remove('')
for j in s:
for k in range(1, len(j) + 1):
sum += k
print(sum) |
8cf935707b7cd6aebb75a686c16e534f24afce6f | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter02/ch2/dicts.py | 2,531 | 3.59375 | 4 | # dicts.py
>>> a = dict(A=1, Z=-1)
>>> b = {'A': 1, 'Z': -1}
>>> c = dict(zip(['A', 'Z'], [1, -1]))
>>> d = dict([('A', 1), ('Z', -1)])
>>> e = dict({'Z': -1, 'A': 1})
>>> a == b == c == d == e # are they all the same?
True # They are indeed
# zip
>>> list(zip(['h', 'e', 'l', 'l', 'o'], [1, 2, 3, 4, 5]))
[('h', 1... |
4e7a68aff29331a4581a94cd9306910f198569bb | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter05/ch5/set.comprehensions.py | 169 | 4.0625 | 4 | word = 'Hello'
letters1 = set(c for c in word)
letters2 = {c for c in word}
print(letters1) # prints: {'H', 'o', 'e', 'l'}
print(letters1 == letters2) # prints: True
|
08f8761330af9c9dccb0ed64557e1b45516b2bc4 | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter01/ch1/scopes3.py | 450 | 4.21875 | 4 | # Local, Enclosing and Global
def enclosing_func():
m = 13
def local():
# m doesn't belong to the scope defined by the local
# function so Python will keep looking into the next
# enclosing scope. This time m is found in the enclosing
# scope
print(m, 'printing from th... |
c5f406af4631e63e1fa90c79277f0d52b70ff0d3 | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter07/ch7/persistence/shelf.py | 972 | 3.5 | 4 | import shelve
class Person:
def __init__(self, name, id):
self.name = name
self.id = id
with shelve.open('shelf1.shelve') as db:
db['obi1'] = Person('Obi-Wan', 123)
db['ani'] = Person('Anakin', 456)
db['a_list'] = [2, 3, 5]
db['delete_me'] = 'we will have to delete this one...'
... |
bc05819329eaf1e8acf574652dbac4a2b1a32891 | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter10/ch10/local.py | 702 | 3.71875 | 4 | import threading
from random import randint
local = threading.local()
def run(local, barrier):
local.my_value = randint(0, 10**2)
t = threading.current_thread()
print(f'Thread {t.name} has value {local.my_value}')
barrier.wait()
print(f'Thread {t.name} still has value {local.my_value}')
count ... |
820ef74bfa13580a4fea759dd0e1edbc25538a11 | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter06/ch6/oop/class.init.py | 304 | 3.859375 | 4 | class Rectangle:
def __init__(self, side_a, side_b):
self.side_a = side_a
self.side_b = side_b
def area(self):
return self.side_a * self.side_b
r1 = Rectangle(10, 4)
print(r1.side_a, r1.side_b) # 10 4
print(r1.area()) # 40
r2 = Rectangle(7, 3)
print(r2.area()) # 21
|
57d70215873d3eea2447729cabac8aab032871b4 | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter05/ch5/dictionary.comprehensions.duplicates.py | 122 | 4.03125 | 4 | word = 'Hello'
swaps = {c: c.swapcase() for c in word}
print(swaps) # prints: {'H': 'h', 'e': 'E', 'l': 'L', 'o': 'O'}
|
09af477ce1604409f5e20f6078c4b71a856b96f0 | LancersDevTeam/nas | /tests/test_gacha.py | 1,009 | 3.703125 | 4 | # -*- coding: utf-8 -*-
from src.gacha import select_prize, roll_a_gacha
def test_select_prize():
"""Functions for determining gacha prizes
If you win the gacha, one of the prizes will be selected at random from the set prizes.
The giveaway is defined in the function.
I'd really like to cut it out som... |
1fa6b14737a8f22af6338f21e73fe898d568bf86 | sjmoon715/cs207_stephen_moon | /lectures/L21/L21-E1.py | 913 | 3.828125 | 4 | import sqlite3
db = sqlite3.connect('E1_db.sqlite')
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS candidates")
cursor.execute("DROP TABLE IF EXISTS contributors")
cursor.execute("PRAGMA foreign_keys=1")
cursor.execute('''CREATE TABLE candidates (
id INTEGER PRIMARY KEY NOT NULL,
... |
d58b805047207bca1d69bed64348634ad7994c3b | sjmoon715/cs207_stephen_moon | /homeworks/HW5/HW5-final/longest_sentence.py | 1,091 | 3.671875 | 4 | import sys
from linked_list import LinkedList, Nil
sys.setrecursionlimit(2000)
def get_list_of_sentences(chapter1='swansway-chapter1.txt'):
def to_sentences(p):
for delimiter in '.?!': p = p.replace(delimiter, '|')
return [s.strip('\" ') for s in p.split('|')]
with open(chapter1, 'r', e... |
d3e3be8397917b3f96313ddc6e9a154ccf4bcca9 | sjmoon715/cs207_stephen_moon | /lectures/L11/L11E2.py | 154 | 3.890625 | 4 | # Defining variables
a = 3
r = 4
x = [a,1]
f = [0.0,0.0]
# Evaluating function
f[0] = x[0]**r
# Evaluating derivative
f[1] = r*x[0]**(r-1)*x[0]
print (f) |
e6f838c346925040a868063435027e4b93c15bfa | DIY-Z/Python_Study_Basis | /ex10.py | 790 | 3.59375 | 4 | a = "I am 6'2\" tall." # 将字符串中的双引号转义
b = 'I am 6\'2" tall.' # 将字符串中的单引号转义
print (a)
print (b)
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
#三个双引号起到转义的效果
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
x = """
哈哈哈
... |
1e13288842cb3b7dc52ad0aaf18f81d5f9c3aaed | NekoGaHoshiyi/Python_Advance | /test.py | 719 | 3.71875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def IsContinuous(self, numbers):
# write code here
if not numbers:
return False
king,check = 0,0
numbers.sort()
L = []
for card in numbers:
if card == 0:
king+=1
else:
... |
39f0cc2512522103fe03d7420a3cf3586fbf48fb | NekoGaHoshiyi/Python_Advance | /usewith.py | 848 | 3.796875 | 4 | class MyOpen():
def __init__(self,filename):
'''初始化方法'''
self.filename = filename
self.filehandler = None
return
def __enter__(self):
'''enter,返回文件操作对象'''
print("enter:", self.filename)
self.filehandler = open(self.filename, "r")
return self.fileha... |
db67fb19a6a852603638ace223f148c5ae316889 | eric-czech/portfolio | /functional/cs_problems/python/most_frequent_item/lib.py | 4,734 | 3.78125 | 4 | '''
Created on May 29, 2014
Solution functions for the following problem:
"Write a function where the input is an array of integers and the output is the value that
appears most frequently. Ex: [1, 2, 2, 5, 5, 5, 2, 2] => 2"
There are two solutions contained, one "practical" solution (i.e. one that
you'd likely use... |
ab3c317a01d233e8d00ddff6b0470540632a568e | eric-czech/portfolio | /functional/cs_problems/python/most_frequent_item/test.py | 1,595 | 3.53125 | 4 | '''
Created on May 29, 2014
Unit tests for 'most_frequent_item' library, defining methods for determining
the most frequently occurring element in a list
@author: Eric Czech
'''
import unittest
from lib import *
class Test(unittest.TestCase):
def validate(self, arr, expected):
# Get results f... |
d63ec38d3d682b65d461bece33de285e72dae4ce | eric-czech/portfolio | /functional/ml/python/py_utils/collection_utils.py | 4,873 | 3.546875 | 4 |
def to_batches(sequence, batch_size):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(sequence), batch_size):
yield sequence[i:i+batch_size]
def subset(d, subset_func, subset_op=None, log=True):
"""
Applies a filter/subset function to a data structure and summarizes reduc... |
fd98d89d2f530385f399b9b509444565b8918b4d | Emszszsz/Restaurant-Simulation | /simulation/group.py | 1,637 | 3.703125 | 4 | import numpy as np
import random as random
class Group:
""" Group of clients that is interpreted by system as one
unseparable client
p - private
Attributes:
>p id - identification number of the group, must be
greater than 0
> probs - probabilities of the ... |
84fbf6428bf6c73f757cd5b4f6ffb180f7dcf554 | Emszszsz/Restaurant-Simulation | /simulation/stats.py | 1,818 | 3.765625 | 4 | import matplotlib.pyplot as plt
import statistics
class Stats:
"""description of class"""
def __init__(self):
self.wait_time_headwaiter = []
self.queue_tables = []
self.wait_time_waiter = []
self.queue_cashiers = []
self.groups_appearance_time = []
self.headwaite... |
124ec13f563e467e99991ab9a1b1631e58330b80 | BRUMUSE/Python | /tag.py | 3,105 | 3.921875 | 4 | from math import fabs
n = int(input("Введите размер пятнашек(3 или 4): "))
pole = [[] for i in range(n)]
pole_win = [[] for k in range(n)]
if n == 3:
pole_numb = 9
empty_value = [2, 2]
else:
pole_numb = 16
empty_value = [3, 3]
def init():
active_line = 0
for k in reversed(ran... |
e78efae6366f67686cc7ed6d3a687d257e51b6b9 | joni2good/PyExam | /OOP/PrivateAndPublic.py | 731 | 3.5625 | 4 | # Encapsulation, @Propeties
class Person:
def __init__(self, name, nickname):
self.__name = name
self.__nickname = nickname
test = 'test'
@property
def name(self):
return self.__name
@property
def nickname(self):
return self.__nickname
@name.setter
... |
68cfe091a054509268f9cda9768a783b3fd0fa65 | hyuglim/interviewpractice | /Raymond/linked_list/partition.py | 612 | 3.59375 | 4 | #in place partition where given value k
#all elements of linked list less than k have index less than
#all elements greater or equal to k
#runtime O(n)
import Node as node_file
def partition(start_node, k):
pivot_node = start_node
iter_node = start_node
while iter_node != None:
if iter_node.value < k:
temp = ... |
3802e9a08d6080de1dab62e76b5155d48d993d56 | hyuglim/interviewpractice | /Jonathan/LinkedList/remove_middle_node.py | 1,545 | 3.953125 | 4 | # remove node in the middle given only access to that node
# Runtime analysis: remove middle node O(n)
class Node:
def __init__(self, data):
self.next_node = None
self.data = data
def add_to_tail(self, data):
current = self
while current.next_node is not None:
curr... |
f4ffc5b29e28d546d8b970dd354b51ad9565cb74 | syth3/Miscellaneous-Python-Scripts | /rename-files-recursively.py | 1,827 | 3.546875 | 4 | import os
import sys
from pathlib import Path
WINDOWS_DISALLOWED_FILENAME_CHARACTERS = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
class Input:
def __init__(self, target_dir, remove_text, replace_text):
"""
Init method for Input class
:param target_dir: Directory to start searching in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.