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 |
|---|---|---|---|---|---|---|
dcd5df108f3668bfb8e8c2228d1cc86350703500 | KurinchiMalar/DataStructures | /LinkedLists/DoublyLinkedListInsert.py | 1,889 | 4.03125 | 4 | class Node(object):
def __init__(self, data=None, next_node=None, prev_node=None):
self.data = data
self.next = next_node
self.prev = prev_node
def SortedInsert(head, data):
if head == None:
head = Node(data)
return head
p = head
newNode = Node(data)
if p... |
f0a64396e3cd7998f6c982d1b059344d2adfb94d | KurinchiMalar/DataStructures | /Medians/MajorityElement_Copy.py | 4,505 | 3.875 | 4 |
# Sorting Solution
# Time Complexity : O(nlogn) + O(n)
from Sorting.MergeSort import mergesort
from Sorting.Median import getMedian_LinearTime
def find_majorityelem_bruteforce(Ar):
Ar = mergesort(Ar)
print Ar
max_elem = -1
max_count = 0
for i in range(0,len(Ar)):
count = 1
for j i... |
f2640a1412c6ee3414bf47175439aba242d5c81f | KurinchiMalar/DataStructures | /LinkedLists/SqrtNthNode.py | 1,645 | 4.1875 | 4 | '''
Given a singly linked list, write a function to find the sqrt(n) th element, where n is the number of elements in the list.
Assume the value of n is not known in advance.
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
import ListNode
def sqrtNthNode(node):
if node == None:
return None
... |
1133d5be23312ce519c55837cea5880fd729c3f6 | KurinchiMalar/DataStructures | /Medians/PairComparisonMinMax.py | 991 | 4.09375 | 4 |
# Time Complexity : O(n)
# Space Complexity : O(1)
'''
Number of Comparisons:
n is even : (3n/2) - 2
n is odd : (3n/2) - 3/2
'''
def get_MinMax_using_paircomparison(Ar):
start = -1
if len(Ar)% 2 == 0 : # even
min_elem = Ar[0]
max_elem = Ar[1]
start = 2
else: # ... |
ec4a2fc2faea5acfea8a352c16b768c79e679104 | KurinchiMalar/DataStructures | /Hashing/RemoveGivenCharacters.py | 507 | 4.28125 | 4 | '''
Give an algorithm to remove the specified characters from a given string
'''
def remove_chars(inputstring,charstoremove):
hash_table = {}
result = []
for char in charstoremove:
hash_table[char] = 1
#print hash_table
for char in inputstring:
if char not in hash_table:
... |
82ecc3e32e7940422238046cd7aa788979c51f9c | KurinchiMalar/DataStructures | /Stacks/Stack.py | 1,115 | 4.125 | 4 |
from LinkedLists.ListNode import ListNode
class Stack:
def __init__(self,head=None):
self.head = head
self.size = 0
def push(self,data):
newnode = ListNode(data)
newnode.set_next(self.head)
self.head = newnode
self.size = self.size + 1
def pop(self):
... |
0bd2a4006643ef1a0955fa89137bc9dc280efecc | KurinchiMalar/DataStructures | /DynamicProgramming/CountOccurenceOfStringInAnotherString.py | 1,821 | 3.90625 | 4 | '''
Given two strings S and T, give an algorithm to find the number of times S appears in T. It's not compulsory that all the
characters of S should appear contiguous to T.
eg) S = ab and T = abadcb ---> ab is occuring 2 times in abadcb.
'''
'''
Algorithm:
if dest[i-1] == source[j-1]:
T[i][j... |
ace208de8edd92accd7286e73e99b99c89c1eadc | KurinchiMalar/DataStructures | /DynamicProgramming/LongestIncreasingSubsequence.py | 2,826 | 3.90625 | 4 | '''
Given an array find longest increasing subsequence in this array.
https://www.youtube.com/watch?v=CE2b_-XfVDk
'''
# Time Complexity : O(n*n)
# Space Complexity : O(n)
def get_length_of_longest_increasing_subsequence(Ar):
n = len(Ar)
T = [1]*(n)
#print T
for i in range(1,n):
for ... |
bd92e67855f505019f17694631ca04db74aa3fc4 | KurinchiMalar/DataStructures | /lcaBT.py | 1,309 | 3.71875 | 4 | # Time Complexity : O(n)
class BTNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def isNodePresentBT(root, node):
if node == None:
return True
if root == None:
return False
if root == node:
return True
return is... |
61aca3793e81011ff08632c1b110e7fe4a7b7e7d | KurinchiMalar/DataStructures | /LinkedLists/Stack.py | 1,133 | 4.0625 | 4 |
import ListNode
class Stack:
def __init__(self,head=None):
self.head = None
self.size = 0
def print_stack(self):
current = self.head
while current != None:
print current.get_data(),
current = current.get_next()
print
#return self.size
... |
98783f5bfd44ae9259f05242baaac5ff796008e5 | KurinchiMalar/DataStructures | /Searching/SeparateOddAndEven.py | 799 | 4.25 | 4 | '''
Given an array A[], write a function that segregates even and odd numbers.
The functions should put all even numbers first and then odd numbers.
'''
# Time Complexity : O(n)
def separate_even_odd(Ar):
even_ptr = 0
odd_ptr = len(Ar)-1
while even_ptr < odd_ptr:
while even_ptr < odd_ptr... |
c407defd7ab9eef69e27f3ca7134e49d068962b0 | KurinchiMalar/DataStructures | /LinkedLists/PalindromeOrNot.py | 3,930 | 4.1875 | 4 | '''
Give a function to check if linked list is palindrome or not.
'''
import ListNode
import Stack
def reverse_recursive(node):
if node == None:
return
if node.get_next() == None:
head = node
return node
head = reverse_recursive(node.get_next())
node.get_next().set_next(node)
... |
c0a0d05abe2be7af0b67b81d46002b4b8cdcbd40 | KurinchiMalar/DataStructures | /LinkedLists/OddFirstThenEven.py | 2,091 | 4.03125 | 4 | __author__ = 'kurnagar'
import ListNode
'''
Segregate a link list to put odd nodes in the beginning and even behind
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
def swap_values_nodes(node1,node2):
temp = node1.get_data()
node1.set_data(node2.get_data())
node2.set_data(temp)
def segregate_odd_an... |
2661ddc368e29f81cb002a4a5c413580f227d284 | KurinchiMalar/DataStructures | /Searching/CountOccurence.py | 1,957 | 3.953125 | 4 | '''
Given a sorted array of n elements, possibly with duplicates. Find the number of occurrences of a number.
'''
# BruteForce
# Time Complexity - O(n)
from FirstAndLastOccurence import find_first_occurence,find_last_occurence
def count_occurence_bruteforce(Ar,k):
count = 0
for i in range(0,len(Ar)):
... |
30a81157968dcd8771db16cf6ac48e9cd235d713 | KurinchiMalar/DataStructures | /Stacks/InfixToPostfix.py | 2,664 | 4.28125 | 4 | '''
Consider an infix expression : A * B - (C + D) + E
and convert to postfix
the postfix expression : AB * CD + - E +
Algorithm:
1) if operand
just add to result
2) if (
push to stack
3) if )
till a ( is encountered, pop from stack and append to result.
4) if operator
... |
982e3cb81b9a194b629434923943f919b3e36ab8 | KurinchiMalar/DataStructures | /LinkedLists/floyd_LoopLinkList.py | 3,145 | 4.125 | 4 | __author__ = 'kurnagar'
import ListNode
# Time Complexity : O(n)
# Space Complexity : O(n) for hashtable
def check_if_loop_exits_hashtable_method(node):
if node == None:
return -1
hash_table = {}
current = node
while current not in hash_table:
hash_table[current] = current.get_d... |
22f1d817b2d292a4b3fae09a77e3013b9d45bd31 | KurinchiMalar/DataStructures | /Sorting/NearlySorted_MergeSort.py | 1,528 | 4.125 | 4 | #Complexity O(n/k * klogk) = O(nlogk)
# merging k elements using mergesort = klogk
# every n/k elem group is given to mergesort
# Hence totally O(nlogk)
'''
k = 3
4 5 9 | 7 8 3 | 1 2 6
1st merge sort all blocks
4 5 9 | 3 8 9 | 1 2 6
Time Complexity = O(n * (n/k) log k)
i.e to sort k numbers is k * log k
to sort n/... |
6d878bd6ab1e0dbecb0c2a5a2803ee41359b51b8 | KurinchiMalar/DataStructures | /LinkedLists/MergeZigZagTwoLists.py | 2,040 | 4.15625 | 4 | '''
Given two lists
list1 = [A1,A2,.....,An]
list2 = [B1,B2,....,Bn]
merge these two into a third list
result = [A1 B1 A2 B2 A3 ....]
'''
# Time Complexity : O(n)
# Space Complexity : O(1)
import ListNode
import copy
def merge_zigzag(node1,node2,m,n):
if node1 == None or no... |
d1c079ea514b668ac8e2ca32afbaa2aa171754d0 | kwichmann/euler | /pe012.py | 437 | 3.6875 | 4 | def factor_count(n):
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
return count
def triangle(n):
return int(n * (n + 1) / 2)
num = 1
while True:
if num % 2 == 0:
fac = factor_count(int(num / 2)) * factor_count(num + 1)
else:
fac = factor_cou... |
f4726dd533c9efdff032b1e5d3b8589b7469d56f | kwichmann/euler | /pe003.py | 505 | 3.53125 | 4 | num = 600851475143
def divides(n, p):
return n % p == 0
def divides_list(n, l):
for p in l:
if divides(n, p):
return True
return False
def next_prime(l):
counter = max(l) + 1
while divides_list(counter, l):
counter += 1
return counter
cur_prime = 2
prime_list = [2... |
3304d188c15ebea8b0f4f7d4846e90c1dbd9420c | cdpn/htb-challenges | /misc/eternal-loop/unzip-loop.py | 811 | 3.71875 | 4 | #!/usr/bin/env python3
import zipfile
zip_file = "Eternal_Loop.zip"
password = "hackthebox"
# Take care of the first zip file since password won't be the filename inside
with zipfile.ZipFile(zip_file) as zr:
zr.extractall(pwd = bytes(password, 'utf-8'))
# namelist() returns an array, so take the first index ... |
c1bb89404de014f6a188d04c61ba6bc32f68a4f4 | slw2/library-python | /Books.py | 1,710 | 3.734375 | 4 | from Book import Book
import random
class Books:
database = ""
def __init__(self, database):
self.database = database
def books(self):
self.database.cursor.execute('''SELECT title, author, code FROM books''')
allrows = self.database.cursor.fetchall()
list_of_books = []
... |
36e1619c70ac8f322aaa1ac085dc3c9c3e61f099 | slw2/library-python | /LoanController.py | 2,356 | 3.921875 | 4 | class LoanController:
books = ""
users = ""
loans = ""
def __init__(self, books, users, loans):
self.books = books
self.users = users
self.loans = loans
def borrow(self, book_code, user_code):
book = self.books.booksearch_by_code(book_code)
user = self.user... |
228ee138bdc254c9cb229ae19fb4432dadb2e43c | yeyifu/python | /other/set.py | 621 | 4.03125 | 4 | #集合的创建:1.初始化{1,2,3},2.set()函数声明
#特点:无序,无下标,去重
# set = {10, 20, 30, 40, 50, 10}
# print(set)
#增加
# set1 = {10,20}
# set1.add(30) #增加单一数据
# print(set1)
#
# set1.update([5,6,9,5]) #追加数据序列
# print(set1)
#删除
# set2 = {10,20,30,40,50}
# set2.remove(10) #删除不存在的值则报错
# print(set2)
# set2.discard(20)
# print(set2)
#
# set2.po... |
b61a043aedd39dc9120e0b4066327d0095979556 | yeyifu/python | /other/function.py | 602 | 3.90625 | 4 | # 定义函数说明文档
def info_print():
"""函数说明文档"""
print(1+2)
info_print()
# 查看函数文档
help(info_print)
# 一个函数返回多个值
def return_num():
# return 1, 3 #返回的是元组(默认)
# return(10,20) #返回的是元组
# return[10,20] #返回的是列表
return {'name':'python','age':'30'} #返回的是字典
print(return_num())
#函数的参数
# 1.位置参数:传递和定义参数的顺序及个... |
2a5e1828f8e2bc9f46274bd166d3f566f0225d22 | yeyifu/python | /other/test.py | 1,561 | 3.75 | 4 | # import sys
# print(sys.argv)
# num1 = 1
# num2 = 1.1
# print(type(num2))
# name = 'tom'
# age = 18
# weight = 55.5
# stu_id = 2
# print('我叫%s,学号是%.10d,今年%d岁,体重%.2f' % (name, stu_id, age, weight))
# print(f'我叫{name},学号是{stu_id}')
# print('hello\nworld')
# print('hello\tworld')
# print('hello', end='\t')
# print('worl... |
10b994ebf775a1ad965e7522fae132d5bdc1e1ee | colorfulComeMonochrome/data_analysis | /matplotlib/fish.py | 555 | 3.546875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
imdata = plt.imread('fish.png')
# 数据变换
# mydata = np.random.rand(100*100*3).reshape(100,100,3)
# mydata = np.ones(100*100*3).reshape(100,100,3)
mydata = np.zeros(100*100*3).reshape(100,100,3)
# mydata = mydata + np.array([1, 0, 0])
mydata = myda... |
c10b5596458ddc22d97f6dd93968adf9e7766833 | HyunAm0225/Python_Algorithm | /study/programmers/kakao_dart_game.py | 1,163 | 3.625 | 4 | from collections import deque
dartResult = input()
dartque = deque(dartResult)
point = []
def check_dart_point(dartque,point):
index = -1
while dartque:
data = dartque.popleft()
if data.isnumeric():
if data =="0" and index== -1:
point.append(int(data))
... |
ad9b99eef4faff4186c37a26516e4dc085ae9060 | HyunAm0225/Python_Algorithm | /코딩테스트책/7-5.py | 687 | 3.71875 | 4 | # 이진 탐색 실전 문제
# 부품찾기
import sys
input = sys.stdin.readline
def search_binary(array,start,end,target):
while start <= end:
mid = (start + end)//2
if array[mid] == target:
return mid
elif array[mid] > target:
end = mid -1
else:
start = mid + 1
r... |
16e12fbf8289dfb9d62274ccae8196bb06849314 | HyunAm0225/Python_Algorithm | /study/9012.py | 875 | 3.65625 | 4 | # 9012
# 괄호
# 스택문제
# 테스트 케이스의 숫자를 입력받음
t = int(input())
ans = []
data = []
def check_vps(stack_list):
# pop 한 괄호를 담을 list
temp_list = []
temp_list.append(stack_list.pop())
for i in range(len(stack_list)):
# temp_list 비어있을 경우 append
if not temp_list:
temp_list.append(stack_l... |
ca0de2eabb70373eccdefd891484900c21fef0fb | HyunAm0225/Python_Algorithm | /study/1181.py | 203 | 3.5625 | 4 | n = int(input())
data = []
ans = []
for _ in range(n):
data.append(input())
data.sort(key = lambda x:(len(x),x))
for x in data:
if x not in ans:
ans.append(x)
for i in ans:
print(i)
|
65f583ecf0cd952237b9dcd7130cc71a7a519177 | HyunAm0225/Python_Algorithm | /코딩테스트책/10-7.py | 889 | 3.796875 | 4 | # 팀결성 문제
# 서로소 집합 자료구조를 이용하여 구한다
def find_parent(parent,x):
if parent[x] !=x:
return 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:
parent[a] = b
n,m = map(int... |
194086367cacb0dffa9a8e996b35edfe94887754 | HyunAm0225/Python_Algorithm | /hello_coding/chap04/quick_sum.py | 180 | 3.78125 | 4 | def sum(lst):
if lst == []:
return 0
else:
print(f"sum({lst[:]}) = {lst[0]} + sum({lst[1:]})")
return lst[0] + sum(lst[1:])
print(sum([1,2,3,4,5])) |
1b1a4d3bd63310edc10c7e0add62526b041591bb | HyunAm0225/Python_Algorithm | /study/programmers/ternary.py | 443 | 3.9375 | 4 | # 3진법으로 만드는 코드
def ternary(n):
tern_list = []
ans = ''
while n > 0:
# print(f"현재 n값 : {n}")
tern_list.append(n%3)
n //=3
tern_list.reverse()
return tern_list
def solution(n):
tern_list = ternary(n)
ans = 0
for i,num in enumerate(tern_list):
num = num * (... |
83115abfeb4394433aafa7fd291614a826743049 | HyunAm0225/Python_Algorithm | /2292.py | 265 | 3.625 | 4 | # 백준
# 백준 수학 문제
def room_count(number):
six_num = 1
count = 1
while number > six_num and number >1:
six_num+=(6*count)
count +=1
# print(f"six_num : {six_num}")
return count
n = int(input())
print(room_count(n)) |
0e08b45d1f4917cd9d4854344441c635283d683c | hucatherine7/cs362-hw4 | /test_question1.py | 451 | 3.734375 | 4 | #Unit testing question 1
import unittest
import question1
class Question1(unittest.TestCase):
def test_calcVolume(self):
#Normal test case
self.assertEqual(question1.calcVolume(4), 64)
#Negative number test case
self.assertEqual(question1.calcVolume(-1), -1)
#Wrong input ... |
40ef7592544d316ec0fe22e2d0a08e6f95e5611d | lavakin/bioinformatics_tools | /bioinf/distance.py | 1,094 | 3.875 | 4 | #!/usr/bin/env python3
from Bio import pairwise2
def editing_distance(seq1:str, seq2:str):
"""
:param seq1: sequence one
:param seq2: sequence two
:return: editing distance of two sequences along with all alignments with the maximum score
"""
align = list(pairwise2.align.globalms(seq1, seq2, ... |
77990bea69aff99c9201bc80da4e4ede8e2e7f93 | WYHNUS/old-xirvana | /assets/Practice/practice02/skeleton/mile_to_km.py | 317 | 4.0625 | 4 | # mile_to_km.py
# Converts distance in miles to kilometers.
import sys
# main function
def main():
KMS_PER_MILE = 1.609
miles = float(raw_input("Enter distance in miles: "))
kms = KMS_PER_MILE * miles
print "That equals %9.2f km." % kms
# Runs the main method
if __name__ == "__main__":
main()
sys.exit(0)
|
f07201523a286803dafc06c5a4305451f9ea9fd9 | ibbles/HousyBuying | /Stepper.py | 6,811 | 3.859375 | 4 | from datetime import timedelta
import datetime
import calendar
class FastDateNumberList(object):
"""
This may be a bit unnecessary. It is a fixed sized, pre-allocated
DateNumberList used when running the stepper. The purpose is to avoid
reallocations inside the innermost loop, where hundreds of thousands of
... |
276faf09e77e69979004b00a910df2d0ce4c7923 | sumanthreddy07/GOST_Algorithm | /src/main.py | 2,163 | 3.65625 | 4 | #import section
import os
import argparse
from encryption import encrypt,encrypt_cbc
from decryption import decrypt,decrypt_cbc
#locate function returns the path for the txt files in the data folder
def locate(filename):
__location__ = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__f... |
3b91de50d77f86a93f67b9da205573ca8231b874 | Shuguberu/Hello-World | /猜整数.py | 383 | 3.84375 | 4 | import random
secret=random.randint(1,10)
print("=======This is Shuguberu=======")
temp=input("输入数字")
guess=int(temp)
while guess!=secret:
temp=input("wrong,once again:")
guess=int(temp)
if guess==secret:
print("right")
else:
if guess>secret:
print("大了")
... |
f3ab92ce7e915013dc8d62cb87d0dbbc05a16275 | mangrisano/ProjectEuler | /euler17.py | 1,646 | 4.03125 | 4 | # If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19
# letters used in total.
#
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
#
# Result: 21124
def problem():
result = 0
al... |
21a192f8d31f93d63fa60d4b2b19f7e6821a171d | mangrisano/ProjectEuler | /euler6.py | 650 | 3.5625 | 4 | # The sum of the squares of the first ten natural numbers is,
#
# 12 + 22 + ... + 102 = 385
# The square of the sum of the first ten natural numbers is,
#
# (1 + 2 + ... + 10)2 = 552 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum
# is 3025 - 385 =... |
3fd420c5f119f608dda0a1bb30f6014a76a6f82a | mangrisano/ProjectEuler | /euler38.py | 1,318 | 4.03125 | 4 | # Take the number 192 and multiply it by each of 1, 2, and 3:
#
# 192 x 1 = 192
# 192 x 2 = 384
# 192 x 3 = 576
# By concatenating each product we get the 1 to 9 pandigital, 192384576.
# We will call 192384576 the concatenated product of 192 and (1,2,3)
#
# The same can be achieved by starting with 9 and multiplying by... |
0ec6ab37481600c42bb40b7d7560afd1cfa06e67 | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 6&7/studentrecord.py | 2,470 | 3.90625 | 4 | class Student:
def __init__(self,name,classs,section,rollno):
self.name=name
self.classs=classs
self.section=section
self.rollno=rollno
def __str__(self):
string='Student Name:'+str(self.name)+'\nStudent Class:'+\
str(self.classs)+'\nStudent Section:'+str(... |
e818073196e6fabaf47145fab615f345237bf7e3 | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Practical3/binsearch.py | 924 | 4.03125 | 4 | class binsearch:
def __init__(self):
self.n=input('Enter number of elements: ')
self.L=[]
for i in range (self.n):
self.L.append(input('Enter element: '))
itemi=input('Enter element to be searched for : ')
self.L.sort(reverse=True)
self.index=self.binsearc... |
3f1f068d1d557358a42db8bbb9534e5236e2f0f9 | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 4/Question5.py | 1,123 | 3.65625 | 4 | class Bowler:
def __init__(self):
self.fname=''
self.lname=''
self.oversbowled=0
self.noofmaidenovers=0
self.runsgiven=0
self.wicketstaken=0
def inputup(self):
self.fname=raw_input("Player's first name: ")
self.lname=raw_input("Player's last name: ... |
4ad77d79088f85449035804824a12f6beb2e1e7a | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 5/int.py | 503 | 3.515625 | 4 | def compare(listsuper,listsub):
stat=None
for element in listsuper:
if listsuper.count(element)==listsub.count(element):
pass
else:
stat=False
if stat==None:
for element in listsub:
if element in listsub and element in list... |
8147118c98c5d7bf084f405607d3b15c22ea1d3f | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 4/Question10.py | 1,464 | 3.625 | 4 | class HOUSING:
def __init__(self):
self.__REG_NO=0
self.__NAME=''
self.__TYPE=''
self.__COST=0.0
def Read_Data(self):
while not(self.__REG_NO>=10 and self.__REG_No<=1000):
self.__REG_NO=input('Enter registraton number betwee 10-1000: ')
self.__NAME=raw... |
e8cee8af302c88e5e20ff072a466e28c2aa808ae | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 6&7/queue.py | 1,875 | 3.96875 | 4 | class queue:
'''This normal queue'''
def __init__(self,limit):
self.L=[]
self.limit=limit
self.insertstat=True
def insertr(self,element):
if self.insertstat==True:
if len(self.L)==0:
self.L.append(element)
elif len(self.L)... |
4ff55a48679abadf58c65cd9e92f86231c089424 | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 4/Question8.py | 539 | 3.65625 | 4 | class ticbooth:
price=2.50
people=0
totmoney=0.0
def __init__(self):
self.totmoney=float(input('Enter the amount if paid else 0:'))
ticbooth.people+=1
if self.totmoney==2.50:
ticbooth.totmoney+=2.50
@staticmethod
def reset():
ticbooth.people=0
... |
6ad09ceb2ab4a05697fb9673000154dcae6d3e0a | SubrataSarkar32/college3rdsem3035 | /class12pythoncbse-master/Chapter 4/Question11.py | 876 | 3.796875 | 4 | class DATE:
monda=[[1,31],[2,28],[3,31],[4,30],[5,31],[6,30],[7,31],[8,31],[9,30],[10,31],[11,30],[12,31]]
def __init__(self,month,day):
a=len(DATE.monda)
self.month=month
self.day=day
while self.month<1 or self.month>12:
self.month=input('Enter month (1 to 12):')
... |
b31f09ab94e4cbddb88f5180b3d2951c55d4b868 | Kmr-Chetan/python_practice | /Palindrome.py | 907 | 4 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head= None
def isPalindromeUtil(self, string):
return (string == string[:: -1])
def isPalindrome(self):
node = self.head
temp = []
... |
4277a08cf47b4f91712841ef2e3757a49090650f | IStealYourSkill/python | /les3/3_3.py | 579 | 4.28125 | 4 | '''3. Проверить, что хотя бы одно из чисел a или b оканчивается на 0.'''
a = int(input('Введите число A: '))
b = int(input('Введите число B: '))
if ((a >= 10) or (b >= 10)) and (a % 10 == 0 or b % 10 == 0):
print("Одно из чисел оканчивается на 0")
else:
print("Числа {}, {} без нулей".format(a, b))
... |
36c1f3a4606a1e9cc61a363387495cb2f8fdb31d | charlottekosche/compciv-2018-ckosche | /week-05/ezsequences/ezlist.py | 2,581 | 3.546875 | 4 | #################################
# ezsequences/ezlist.py
#
# This skeleton script contains a series of functions that
# return
ez_list = [0, 1, 2, 3, 4, ['a', 'b', 'c'], 5, ['apples', 'oranges'], 42]
def foo_hello():
"""
This function should simply return the `type`
of the `ez_list` object.
This... |
cfdeb5d426d745a6986a5da2c172d9ff4293ab35 | storm2513/Task-manager | /task-manager/library/tmlib/models/notification.py | 755 | 3.640625 | 4 | import enum
class Status(enum.Enum):
"""
Enum that stores values of notification's statuses
CREATED - Notification was created
PENDING - Notification should be shown
SHOWN - Notification was shown
"""
CREATED = 0
PENDING = 1
SHOWN = 2
class Notification:
"""Notification clas... |
ec5f0599d0af4f726978ea37e17c66b4e67da986 | sweetkristas/mercy | /utils/citygen.py | 4,065 | 3.5625 | 4 | from random import randint, random
import noise
# variables: block_vertical block_horizontal road_vertical road_horizontal
# start: block_vertical
# rules: (block_vertical -> block_horizontal road_vertical block_horizontal)
# (block_horizontal -> block_vertical road_horizontal block_vertical)
block_vertical = ... |
31d6a644a8962ddabee4d3d9140d47b131880667 | ivanifp/tresEnRaya | /main.py | 641 | 3.625 | 4 | from utils import numJugadores,getFicha,colocaFicha,imprimirTablero,tableroLibre,victoria
#me creo mi tablero con nueve posiciones
tablero = [' ']*9
numJu = numJugadores()
fichaj1,fichaj2 = getFicha()
while tableroLibre(tablero) or victoria(tablero,fichaj1)== False or victoria(tablero,fichaj2)== False:
... |
264b622be15b275164a1259f3906c9d69fe00819 | stteem/Python | /MyPython/SearchExercise.py | 689 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 20 13:29:27 2017
@author: Uwemuke
"""
print("Please think of a number between 0 and 100!")
high = 100
low = 0
guess = (high - low)//2.0
while guess**2 < high:
print('Is your secret number' + str(guess) + '?')
(input("Enter 'h' to indicate the g... |
fb43e3221791f1b84663b42bb5d3b7e2917270a5 | stteem/Python | /MyPython/Finding biggest value of a key.py | 471 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 26 12:04:30 2017
@author: Uwemuke
"""
def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
result = None
biggestValue = 0
for key... |
25dcce43a2306b81de2040ec215ae16dd77a2136 | stteem/Python | /MyPython/midterm1 unfinished.py | 569 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 1 23:48:44 2017
@author: Uwemuke
"""
def largest_odd_times(L):
L1 = {}
for i in L:
if i in L1:
L1[i] += 1
else:
L1[i] = 1
return L1
def even(k):
k = max(freq)
for ... |
a63221aca27c99efdc063aa6a716b4fa4f6670c0 | stteem/Python | /Pset4/Pset402.py | 797 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 10 00:19:54 2017
@author: Uwemuke
"""
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that let... |
861508bd3e5b4eeeeb8fcfe56fff987e723f4176 | stteem/Python | /MyPython/multiplication_iterative_solution.py | 225 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 21 12:58:11 2017
@author: Uwemuke
"""
def multi_iter(a, b):
result = 0
while b > 0:
result += a
b -= 1
return result
multi_iter(4, 8) |
0f9bc0663d9c38f5e3be9a5051cf0e960736d148 | unbecomingpig/scotchbutter | /scotchbutter/util/database.py | 4,711 | 3.515625 | 4 | """Contains functions to help facilitate reading/writing from a database.
NOTE: Currently only supporting sqlite databases
"""
import logging
import sqlite3
import time
from scotchbutter.util import environment, tables
DB_FILENAME = 'tvshows.sqlite'
logger = logging.getLogger(__name__)
class DBInterface():
""... |
08ef8703147476759e224e66efdc7b5de5addf6e | chaoma1988/Coursera_Python_Program_Essentials | /days_between.py | 1,076 | 4.65625 | 5 | '''
Problem 3: Computing the number of days between two dates
Now that we have a way to check if a given date is valid,
you will write a function called days_between that takes six integers (year1, month1, day1, year2, month2, day2)
and returns the number of days from an earlier date (year1-month1-day1) to a later date... |
d53544648c25cc8d0562cc4cd92ce70341e8d353 | lch172061365/Computational-Physics | /Project3/3e(for jupiter of original mass).py | 3,370 | 3.640625 | 4 | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import math
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.image as img
G = 6.67*10**(-11)
m1 = 6*10**24 #earth
m2 = 2*10**30 #sun
m3 = 1.9*10**27 #jupiter
#m1
x10 = -149597870000
y10 = 0
z10 = 0
p... |
95357539ad5ea90938cb13440a9e419206ba42f3 | moisindustries/Leetcode-practice | /238-product-of-array-except-self.py | 855 | 3.546875 | 4 | """
Problem Link: https://leetcode.com/problems/product-of-array-except-self/description/
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements
of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it... |
b2ead9da892231c4d5e5c610d88797290a1cda29 | ken4815/CP3-Pakkapong-Thonchaisuratkrul | /Lexture 46.py | 87 | 3.546875 | 4 | n = int(input("N:"))
for x in range(24):
x = x+1
print(n ,"*",x,"=",n * (x)) |
562ac5cebcf516d7e40724d3594186209d79c2f4 | Vyara/First-Python-Programs | /quadratic.py | 695 | 4.3125 | 4 | # File: quadratic.py
# A program that uses the quadratic formula to find real roots of a quadratic equation.
def main():
print "This program finds real roots of a quadratic equation ax^2+bx+c=0."
a = input("Type in a value for 'a' and press Enter: ")
b = input("Type in a value for 'b' and press... |
301a8410b1a192e4c0c40b404e0bdaca03005de6 | chilu49/python | /deck-blackjack.py | 321 | 3.6875 | 4 | #from random import shuffle
#ranks = range(2,11) + ['JACK', 'QUEEN', 'KING', 'ACE']
#print ranks
#suits = ['S', 'H', 'D', 'C']
#print suits
#def get_deck():
# """Return new deck of cards"""
# return [[rank,suit] for rank in ranks for suit in suits]
#deck = get_deck()
#shuffle(deck)
#print deck
#print len(deck)
... |
2981b59c33aec6471398075ff81f7757888d68e5 | hurenkam/AoC | /2022/Day02/part2.py | 538 | 3.765625 | 4 | #!/bin/env python
with open('input.txt','r') as file:
lines = [line.strip() for line in file]
lookup = {
"A X": "A C",
"A Y": "A A",
"A Z": "A B",
"B X": "B A",
"B Y": "B B",
"B Z": "B C",
"C X": "C B",
"C Y": "C C",
"C Z": "C A"
}
scores = {
"A A": 4,
"A B": 8,
... |
f8ce648c17349a1b550f4e22d6146a9bffe2509f | hurenkam/AoC | /2022/Day11/part2.py | 2,832 | 3.625 | 4 | #!/bin/env python
with open('input.txt','r') as file:
lines = [line.strip() for line in file]
def parseInput(lines):
while len(lines):
while not lines[0].startswith("Monkey"):
lines.pop(0)
parseMonkey(lines)
monkeys={}
def parseMonkey(lines):
global monkeys
index = parseIn... |
4dcb005342c13a213a78196aab6a4739aa80776a | hurenkam/AoC | /2022/Day08/part2.py | 1,310 | 3.578125 | 4 | #!/bin/env python
with open('input.txt','r') as file:
lines = [line.strip() for line in file]
def buildMatrix():
forrest = []
for line in lines:
treeline = []
for tree in line:
height = int(tree)
treeline.append(height)
forrest.append(treeline)
return f... |
23aeb35a5d118fe8e57e355514ff5bb71652b62b | hurenkam/AoC | /2020/Day13/solve.py | 1,214 | 3.703125 | 4 | #!/usr/bin/env python3
#===================================================================================
def Part1():
departures={}
tmp = [int(bus) for bus in busses if bus !='x']
for bus in tmp:
departs = (int(arrival / bus) +1) * bus
waittime = departs - arrival
departures[wai... |
852cba828e67b97d2ddd91322a827bfdc3c6a849 | ridhamaditi/tops | /Assignments/Module(1)-function&method/b1.py | 287 | 4.3125 | 4 | #Write a Python function to calculate the factorial of a number (a non-negative integer)
def fac(n):
fact=1
for i in range(1,n+1):
fact *= i
print("Fact: ",fact)
try:
n=int(input("Enter non-negative number: "))
if n<0 :
print("Error")
else:
fac(n)
except:
print("Error")
|
287f5f10e5cc7c1e40e545d958c54c8d01586bfb | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a2.py | 252 | 4.15625 | 4 | #write program that will ask the user to enter a number until they guess a stored number correctly
a=10
try:
n=int(input("Enter number: "))
while a!=n :
print("Enter again")
n=int(input("Enter number: "))
print("Yay")
except:
print("Error")
|
4337d05a72684cdfc0bdef255ccfcce72d5f6432 | ridhamaditi/tops | /Assignments/Module(1)-modules/I2.py | 188 | 4.375 | 4 | # Aim: Write a Python program to convert degree to radian.
pi=22/7
try:
degree = float(input("Input degrees: "))
radian = degree*(pi/180)
print(radian)
except:
print("Invalid input.") |
e3eca8bce227d8d6c6b4526189945c2cd79e0c41 | ridhamaditi/tops | /functions/prime.py | 234 | 4.1875 | 4 | def isprime(n,i=2):
if n <= 2:
return True
elif n % i == 0:
return False
elif i*i > n:
return True
else:
return isprime(n,i+1)
n=int(input("Enter No: "))
j=isprime(n)
if j==True:
print("Prime")
else:
print("Not prime") |
bcc1edf1be77b38dff101b8221497dc5baa3f2ec | ridhamaditi/tops | /modules/math_sphere.py | 237 | 4.15625 | 4 | import math
print("Enter radius: ")
try:
r = float(input())
area = math.pi * math.pow(r, 2)
volume = math.pi * (4.0/3.0) * math.pow(r, 3)
print("\nArea:", area)
print("\nVolume:", volume)
except ValueError:
print("Invalid Input.") |
1d2389112a628dbf8891f85d6606ec44543fc81d | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a4.py | 791 | 4.21875 | 4 | #Write program that except Clause with No Exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# user guess... |
ad9be274f3f72de34d1adafccb473bbcb637556b | ridhamaditi/tops | /basics/factorial.py | 149 | 4.15625 | 4 | n= int(input("Enter: "))
fact = 1
# while n > 1:
# fact = fact * n
# n -= 1
for i in range(1, n+1):
fact = fact * i
print("Factorial: ", fact) |
609812d3b68a77f35eb116682df3f844ab3a44c9 | ridhamaditi/tops | /Assignments/Module(1)-Exception Handling/a3.py | 216 | 4.15625 | 4 | #Write function that converts a temperature from degrees Kelvin to degrees Fahrenheit
try:
k=int(input("Enter temp in Kelvin: "))
f=(k - 273.15) * 9/5 + 32
print("Temp in Fahrenheit: ",f)
except:
print("Error")
|
5f9d82659fbfcaac9008b379d82726bcc28b1e96 | pdevezeaud/Python | /range.py | 256 | 3.984375 | 4 | tableau = list(range(10))
print (tableau)
start = 0
stop = 20
x = range(start,stop)
print(x)
print(list(x))
#on peut définir un pas dans la liste
x = range(start,stop,2)
print(list(x))
#on peut boucler sur un range
for num in range(10):
print (num) |
7b8e48108d95aa59aa9cd5af63b5672ee99aa0d1 | pdevezeaud/Python | /tuple.py | 553 | 3.9375 | 4 | t=(4,1,5,2,3,9,7,2,8)
print(t)
print(t[2:3])
t +=(10,) #concenation
print(t)
print(len(t))
ch ='trou du cul'
st = tuple(ch)
print(st)
print("*******************************************")
'''
(!) Tuple : conteneur imuable (dont on ne peut modifier les valeurs)
création de tupe : mon_tuple = () #vide
... |
e5779f5e61468032d5f28b432938c279e9c3af3b | pdevezeaud/Python | /liste_en_comprehension.py | 415 | 3.9375 | 4 |
liste = [x for x in 'exemple']
print (liste)
liste2 = [x**2 for x in range(0,11)]
print(liste2)
# possibilite de mettre des conditions dans la liste
liste2 = [x**2 for x in range(0,11) if x%2 == 0]
print(liste2)
celsius = [0,10,20.1,34.5]
farenheit = [((9/5)*temp + 32) for temp in celsius ]
print(farenheit)
#imbri... |
6940e23dfdfc93a23dab888ead9fe54b8b7baefe | pdevezeaud/Python | /fonction_detaillee.py | 970 | 3.90625 | 4 |
def est_premier (num):
'''
Fonction simple pour determiner si un nombre est premier
parametre : num, le nombre à tester
on par de 2 jusqu'au numero entré (num). Utilisation du range dans ce cas.
'''
for n in range(2,num):
if num % n == 0:
print("Il n'est pas premier")
... |
3ec7e25277951842988d506ed16428575601e0a2 | pdevezeaud/Python | /graven_developpement/boucle_while.py | 88 | 3.640625 | 4 | a = "q"
b = 0
while b = "q":
a = a+1
print ("Vous êtes le client n° 1")
|
144177f8c8d260cbac5c161036564151afe30d1c | pdevezeaud/Python | /gestion_erreur.py | 1,113 | 3.875 | 4 |
# iNSTRUCTION POUR GERER LES EXCEPTIONS (BASE)
'''
Gérer les exceptions : try /except (+ else, finally)
type d'exception : ValueError
NameError
TypeError
ZeroDivisioçnError
OSError
AssertionError
exemple
try:
age = in... |
4d6c8205dee0f10c9ceb4f3e647f5599679e02c1 | MrLanka/algorithm008-class02 | /Week_01/d12_559_N-maxDepth.py | 506 | 3.515625 | 4 | #还是递归,O(N)和O(logN)
#define N-Tree Node
class Node:
def __init__(self,val=None,children=None):
self.val=val
self.childeren=children
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if root is None:
return... |
f56fc3015bdf8de048436f333b1109886768a67a | MrLanka/algorithm008-class02 | /Week_01/homework2_189_rotate.py | 742 | 3.96875 | 4 | #使用三次旋转数组
class Solution:
def rotate(self, nums: List[int], k: int)->None:
"""
Do not return anything, modify nums in-place instead.
"""
n=len(nums)
k=k%n #k对n取余,确定最终旋转的长度
def reverse_nums(list,start,end): #定义一个反转数组的函数
while start<end:
... |
4c69d23e20efafc0e6fa5ac96bd51e5c43fecb2d | annamiklewska/GA | /generate_points.py | 3,852 | 3.609375 | 4 | import numpy as np
import random
import matplotlib.pyplot as plt
import numpy.polynomial.polynomial as p
class Points:
#domain = np.linspace(0, 10, 200) # 100 evenly distributed points in range 0-10
domain = [random.random()*10 for _ in range(100)]
def __init__(self, M):
'''
:param M: de... |
d6f2e7a6ea51d7a7c9d7841349264e77e5b70832 | StechAnurag/python_basics | /33_docstrings.py | 317 | 3.5625 | 4 | # DOCSTRINGS - are used to document the action within a function
def test(a):
'''
Info: this function tests and prints param a
'''
print(a)
# to read documenation there are 3 ways
# 1 - our text editor helps with it
# 2 - help function
# 3 - .__doc__ dundar method
print(help(test))
print(test.__doc__) |
f33e25913c4ad29958ec26a9742055d9a80c5803 | StechAnurag/python_basics | /16_list_patterns.py | 474 | 3.921875 | 4 | # Common List Patterns
basket = ['Apple', 'Guava', 'Banana', 'Lichi']
#1) length
print(len(basket))
#2) sorting
basket.sort()
print(basket)
#3) Reversing
basket.reverse()
print(basket)
#4) copying a list / portion of a list
print(basket[:])
#5) Joining list items
new_sentence = ' '.join(basket)
print(new_sentence... |
927346c7283cb20b708aa151b94679eebb28a330 | StechAnurag/python_basics | /27_is_vs_==.py | 328 | 3.96875 | 4 | # is VS ==
# Implicit type conversion takes place wherever possible
print(True == 1)
print('' == 1)
print(10 == 10.0)
print([] == [])
print('1' == 1)
print([] == 1)
# == checks if the two values are equal
# is - checks the exact reference of the values in memory
print(True is True)
print('1' is 1)
print([1,2,3] is ... |
44952b8458de5ee13c724e4bd172e400c4caa165 | StechAnurag/python_basics | /09_string_immutability.py | 529 | 4.03125 | 4 | # CONCEPT: STRINGS ARE IMMUTABLE in pyhton
fruit = 'Apple'
print(fruit)
# we can reassign a whpole new value to fruit
fruit = 'Orange'
print(fruit)
# but we can't replace any character of the string
# strings are immutable
#fruit[0] = 'U' # ERROR
# print(fruit)
quote = 'To be or Not to be'
# we're just overriding t... |
5426ce922c71f599e2336eea57b9ad0a08458e03 | StechAnurag/python_basics | /03_numbers.py | 405 | 3.71875 | 4 |
print(2+4)
print(type(6))
print(9*9)
print(type(4/2))
print(type(10.56))
# implict type conversion
print(type(20 + 1.1)) #float
# exponentail operator
print(2 ** 3) #equals 8
# divide and round operator
print(2 // 3) #equals 0
print(5 // 4) #equals 1
# modular division
print(5 % 4) #equals 1
#Math Functio... |
bf498bfa0db5373377e0403bbee3bedc259bd9a1 | rahimnathwani/combogrid | /combogrid/plot.py | 2,463 | 3.75 | 4 | import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import datetime
def plot(
df,
x,
y_line,
y_bar,
facet_dimension,
ncols=2,
percent_cols=[],
style="fivethirtyeight",
):
"""Plots a grid of combo charts from a p... |
6419a504a30690b864264b1e013cd4eb7a4f4a9e | mpcalzada/data-science-path | /3-PROGRAMACION-ORIENTADA-OBJETOS/algoritmos_ordenamiento/ordenamiento_burbuja.py | 590 | 3.59375 | 4 | import random
def ordenamiento_burbuja(lista):
n = len(lista)
for i in range(n):
for j in range(0, n - i - 1):
if lista[j] > lista[j + 1]: # O(n) * O(n - i -1) = O(n) * O(n) = O(n ** 2)
lista[j], lista[j + 1] = lista[j + 1], lista[j]
return lista
if __name__ == '__... |
a9e6082aca888bbdbfe81e75e533b49f92ef397e | mpcalzada/data-science-path | /1-CURSO-BASICO-PYTHON/prueba-primalidad.py | 310 | 3.78125 | 4 | def es_primo(numero):
if numero < 2:
return False
for i in range(1, numero):
if (numero % 2) == 0:
return False
return True
if __name__ == '__main__':
n = int(input('Ingrese un numero: '))
print(f'El numero {n} {"es primo" if es_primo(n) else "no es primo"}')
|
ffe4d01767371c73cc5b1e7ab0bb5b30e0046def | drishtim17/supervisedML | /sML_example.py | 386 | 3.515625 | 4 | #!/usr/bin/python3
import sklearn
from sklearn import tree
#features about apple and orange
data=[[100,0],[130,0],[135,1],[150,1]]
output=["apple","apple","orange","orange"]
#decision tree algorithm call
algo=tree.DecisionTreeClassifier()
#train data
trained_algo=algo.fit(data,output)
#now testing phase
predict... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.