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 |
|---|---|---|---|---|---|---|
7aee7be6944d071d042370f4b92f23bbd85469e3 | earvin0/pythonKurs | /zestaw7/Circle.py | 1,277 | 3.859375 | 4 | from Point import Point
import math
class Circle:
def __init__(self, x=0, y=0, radius=1):
if isinstance(radius, (int, float, complex)):
if radius < 0:
raise ValueError("Promień ujemny")
self.pt = Point(x, y)
self.radius = radius
else:
... |
a85137114a12dd0bbc72e8ce0a14cff08b72f792 | earvin0/pythonKurs | /zestaw7/zad75.py | 1,210 | 3.65625 | 4 | import unittest
import Circle as circ
from math import pi
f1 = circ.Circle(1, 1, 5)
f2 = circ.Circle(0, 0, 1)
f3 = circ.Circle(-4, 2, 7)
f4 = circ.Circle(5, 7, 2)
class TestCircle(unittest.TestCase):
def test_repr_circle(self):
self.assertEqual(repr(f1), 'Circle(1,1,5)')
def test_eq_circle(self):
... |
38787946591e464b730afa096dda72fd042408c6 | oneyuan/CodeforFun | /PythonCode/src/116.populating-next-right-pointers-in-each-node.py | 1,489 | 3.796875 | 4 | #
# @lc app=leetcode id=116 lang=python3
#
# [116] Populating Next Right Pointers in Each Node
#
"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connec... |
06806d8af095dea34d79abf39fec6312acc06129 | oneyuan/CodeforFun | /PythonCode/src/0009_Palindrome_Number.py | 443 | 3.546875 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s = str(x)
l = [s[i] for i in range(len(s))]
l.reverse()
t = "".join(l)
if s == t:
return True
else:
return False
def isPa... |
f34db46d9a3cae823e53a5f0a68705d2546e425c | oneyuan/CodeforFun | /PythonCode/src/0044_Wildcard_Matching.py | 1,536 | 3.515625 | 4 | class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
i = 0
j = 0
starIndex = -1
while j < len(s):
if i < len(p) and (p[i] == "?" or s[j] == p[i]):
i += 1
... |
e31b38478eeaa124b93cf7078e530ffe1552f6c2 | oneyuan/CodeforFun | /PythonCode/src/0014_Longest_Common_Prefix.py | 849 | 3.515625 | 4 | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
tmp = [strs[0][i] for i in range(len(strs[0]))]
res = []
j = 0
while j < len(tmp):
for i in strs... |
c12e97fa709e576988aba35039c9bfc49b149e58 | oneyuan/CodeforFun | /PythonCode/src/125.valid-palindrome.py | 1,380 | 3.984375 | 4 | #
# @lc app=leetcode id=125 lang=python3
#
# [125] Valid Palindrome
#
# https://leetcode.com/problems/valid-palindrome/description/
#
# algorithms
# Easy (30.97%)
# Likes: 582
# Dislikes: 1707
# Total Accepted: 354.8K
# Total Submissions: 1.1M
# Testcase Example: '"A man, a plan, a canal: Panama"'
#
# Given a st... |
a43ffed5c98d3586b909b53385c4dda12995e978 | oneyuan/CodeforFun | /PythonCode/src/0097_Interleaving_String.py | 1,947 | 3.734375 | 4 | class Solution:
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
m = len(s1)
n = len(s2)
l = len(s3)
if m + n != l:
return False
dp = [[False for _ in range(n+1)] for... |
9fe2b8f2b914f492dfda1b19f5745a3f83bab5a5 | oneyuan/CodeforFun | /PythonCode/src/210.course-schedule-ii.py | 3,013 | 3.765625 | 4 | #
# @lc app=leetcode id=210 lang=python3
#
# [210] Course Schedule II
#
# https://leetcode.com/problems/course-schedule-ii/description/
#
# algorithms
# Medium (35.11%)
# Likes: 1209
# Dislikes: 86
# Total Accepted: 173.3K
# Total Submissions: 477.5K
# Testcase Example: '2\n[[1,0]]'
#
# There are a total of n co... |
a13c9611b9cfffb9477deb515076100ae4ed462a | oneyuan/CodeforFun | /PythonCode/src/0045_Jump_Game_II.py | 1,808 | 3.53125 | 4 | class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
sadly time limit exceeded
"""
def iteration(nums, i, count, res):
if i >= len(nums)-1:
if count < res:
res = count
re... |
77330e76f7492912f4e068a8f56d99444ee5fd3b | oneyuan/CodeforFun | /PythonCode/src/647.palindromic-substrings.py | 2,264 | 3.84375 | 4 | #
# @lc app=leetcode id=647 lang=python3
#
# [647] Palindromic Substrings
#
# https://leetcode.com/problems/palindromic-substrings/description/
#
# algorithms
# Medium (55.59%)
# Total Accepted: 88.7K
# Total Submissions: 157.8K
# Testcase Example: '"abc"'
#
# Given a string, your task is to count how many palindro... |
764b3f2f44fd7a0182673df496a7576142cbb4dd | oneyuan/CodeforFun | /PythonCode/src/0148_Sort_List.py | 1,510 | 3.921875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def merge(l1, l2):
dummy = ListNode(0)
... |
36a4a6abbe87362a4d1e1b835fcb2dd7d15c1fe4 | matt-lourenco/unit-3-02 | /code/num_guesser.py | 561 | 4.09375 | 4 | # Created by: Matthew Lourenco
# Created on: 3 Oct 2016
# This is a program that lets you guess what number it has chosen
import ui
from numpy import random
#choose random number
number_to_guess = random.randint(1, 10)
print(number_to_guess)
def guess_touch_up_inside(sender):
guess = int(view['guess_textfield'].... |
5c74f6abde2052330ae7b8b1ece26c0a6da68436 | galemos/ZNC | /Tutoriais de Python/Estudos Python/tstes2.py | 554 | 3.984375 | 4 | from datetime import datetime
now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day
print current_day,"/",current_month,"/",current_year
#
print"----------------------------------------------------------------------"
#
from datetime import datetime
now = datetime.now()
print... |
8b465b3fdf3469496da0838e70ed8af071025c9e | Lily-j17-source/Python_Scripts | /clase11.py | 2,286 | 3.984375 | 4 | ##crear la clase lista
#crear metodo append()
#crear metodo extend()
#crear metodo pop()
class lista(object):
def __init__(self,*valores):
self.lista_interna = []
for i in valores:
self.lista_interna.append(i)
def __str__(self):
aux = "["
for i in sel.lista_interna
... |
13ae06928edeed47f4615485ebacd51036ba43da | NataliiaBidak/py-training-hw | /Homework5/Task15/Task15.py | 2,709 | 3.71875 | 4 | """
Write a python program that takes a list of file extensions and prints all the files from the current
directory matching the extension given. The following extensions and meaning should be supported:
c should find and print all .c and .h file names
py should find and print all .py and .pyc file names
pl should find... |
670bf62089dcaf9d40d47733fc2ee595e9e66558 | NataliiaBidak/py-training-hw | /Homework6/Test_task7.py | 635 | 3.5 | 4 | import unittest
from contacts import Contacts
class TestContacts(unittest.TestCase):
def setUp(self):
self.home_book = Contacts()
self.work_book = Contacts()
def test_create_and_search(self):
self.home_book.add('Tom', {'lives_in': 'USA', 'email': 'tomthecat@gmail.com'})
self.h... |
a28ba945ae2271b62f9d8c6ae5ccf13ea75d01ab | NataliiaBidak/py-training-hw | /Homework6/inherit.py | 421 | 3.71875 | 4 | class A:
attr_a = 123
def __init__(self, a):
self.a = a
def m1(self):
print(f"class A m1 called")
class AA:
def m1(self):
print(f"class AA m1 called")
class B(A):
def __init__(self, a, b):
self.b = b
super().__init__(a)
class C(AA, A):
def m3(self):
... |
aa82cfb605e7cec0fff586fa9e24b9e8bf0df80e | NataliiaBidak/py-training-hw | /decorators.py | 1,667 | 4.1875 | 4 | """Write a Decorator named after5 that will ignore the decorated function in the first 5 times it is called. Example Usage:
@after5
def doit(): print("Yo!")
# ignore the first 5 calls
doit()
doit()
doit()
doit()
doit()
# so only print yo once
doit()
please make a similar one, but that acceps times to skip as param (... |
9016a00e80b1ef07874d6ab852433602b192baa3 | NataliiaBidak/py-training-hw | /Homework6/Task4.py | 1,891 | 3.78125 | 4 | """
Implement a class named Color.
It should construct color from hex value (e.g. #ffffff) and have optional name: ‘color’.
Add possibility to set and get name (property).
Add property rgb that returns rgb tuple of color
Add method to convert hex value to rgb tuple.
Add possibility to construct object from rgb value (c... |
ee1d4507e09662c998be51b8634cfc983af5ed81 | NataliiaBidak/py-training-hw | /Homework4/dict_task5.py | 671 | 4.03125 | 4 | """
Write a Python program to get the depth of a dictionary
"""
import math
d1 = {}
d2 = {1: {}}
d3 = {1: {2: {}}}
d4 = {1: {2: {3: {6}}}}
def depth_of_dictionary(dictionary: dict):
length = 0
list_of_curly_braces = []
for x in str(dictionary):
if x == "}":
length += 1
lis... |
335dde38438c68d0ac53af06f1955adf1bba1d3b | NataliiaBidak/py-training-hw | /Homework6/Task2.py | 312 | 4.0625 | 4 | """
Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle.
"""
from circle import Circle
print(Circle.generic_square(3))
print(Circle.generic_perimetr(7))
new_circle = Circle(6)
print(new_circle.square())
print(new_circle.perimetr()) |
dffee0fcf80a8f8aa5f2e161a8a071479b4b99ac | NataliiaBidak/py-training-hw | /Homework4/dict_task7.py | 228 | 4.03125 | 4 | """
Write a Python program to find all the values in a list are greater than a specified number
"""
def greater_than(lst:list, number:int):
return [x for x in lst if x > number]
print(greater_than([34,56,23,1,45,2,3,87],25)) |
41971505f826f1f56f2860f732cf111caa4d3e94 | shakeel99/guvi | /Sha10.py | 99 | 3.671875 | 4 | num10 = int(input())
count2 = 0
while(num10 > 0):
count2=count2+1
num10=num10/10
print(count2)
|
ee14e5a6918d198251c92c97fccb994665543607 | JavaJava911/Variable-1st-Assignment- | /Variable Package.py | 341 | 3.78125 | 4 | print ("My First Program")
# Variables are fun but the Borg is better!
hourly_rate = 12.0
overtime = hourly_rate * 1.5
standard_hours = 40
hours_worked = 60
income = ((hours_worked - standard_hours)*overtime) + (standard_hours * hourly_rate)
print("This week I worked")
print(hours_worked)
print("I made")
print(income... |
aad258ee72f85b15b203ccbc18916a7748943038 | Alejandro32/ejecicios-python | /Problemas/Arreglos/pro1.py | 277 | 3.5625 | 4 |
promedio=[10,9,9,10,7,10,9]
cal=0
print("\n\n\n 1. Joel ya recibió sus calificaciones 10, 8, 9, 10, 7 , 10, 9. "
" ¿podrías sacar su promedio usando menos de 5 variables?\n")
for i in range(0,7):
cal=promedio[i]+cal
print("El Promediode Joel es___",round(cal/7),2)
|
08bd4c0d6beecd131b8a88116f52c85ce3d20ecc | Alejandro32/ejecicios-python | /Problemas/Condicionales/pro6.py | 601 | 3.984375 | 4 |
print("\n\n\n 6. Paco está haciendo un videojuego y necesita"
" hacer un programa que determine la jerarquía de usuario"
" de acuerdo a su nivel, las jerarquías son paladin : nivel"
" 0 -10, caballero dorado : nivel 11 - 30, dios destructor: "
" 31 - 50.\n")
numero = int(input("\n Escribe un... |
c0df2d04776c45425208091afe069eafc5f83bde | Alejandro32/ejecicios-python | /Problemas/Arreglos/pro2.py | 433 | 3.59375 | 4 | import random
Empleado=[]
print("\n\n\n 2. Antonio es el encargado de hacer la rifa de la compañía, cada empleado participa usando su clave de empleado y necesita determinar a un ganador. "
" ¿Puedes hacer un programa que le ayude a elegir al ganador de la rifa?\n")
numero=int(input("Ingresa numero de empleados___... |
34b404276601227ab7d713cd2ee6cfa1839e7969 | ddjaell/algorithm | /Stack.py | 524 | 4.15625 | 4 | """
스택은 LIFO, FILO의 형태가 있다
"""
"""
python의 list는 기본적으로 스택의 구조를 가지고 있음
"""
stack_list = list()
stack_list.append(1)
stack_list.append(2)
stack_list.append(3)
print(stack_list)
print(stack_list.pop())
print("after pop() once = ", stack_list)
"""
pop(), push() 함수 만들어보기
"""
stack_self = list()
def push(data):
sta... |
0fe6cc127e69fd0d6cb6ed6284acfac44deafd1b | Waweru007/PythonBasics | /Inheritance.py | 1,529 | 4.0625 | 4 | class Account: ##This is the parent class which will be inherited by the child classes
def __init__(self, names, account_no, balance):
self.names=names
self.account_no=account_no
self.balance=balance
def check(self):
print(self.names,self.balance)
def deposit(self,amount):
... |
cf8c6d0f645999802ef7904d42503c0a1c19a907 | Waweru007/PythonBasics | /ClassExample.py | 340 | 3.953125 | 4 | ###A classes stores functions and data(A class start with a capital letter)
class Person:
def greet(self):
print("hi")
def calculate(self):
print(88*10)
def add(self,x,y):
print(x+y)
###Before accessing functions in a class we must create variables
x=Person()
x.greet()
x.ca... |
7498e0e3d6658736c53c800a929fa12472bd36f6 | kura123/language_processing100 | /chapter1/03.py | 497 | 4.125 | 4 | # 03. 円周率Permalink
# “Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”という文を単語に分解し,
# 各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
string = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.'
string = string.replace(',','').replace('.... |
bbedd7067062272a12acac80dab4d488b412de64 | MJHowatCreations/python-programs | /dictionary_list_by_greatest_value.py | 357 | 4 | 4 | temporary = list()
for key, value in dictionary.items():
temporary.append( (value, key) ) #reorders the values and key
print temporary
temporary.sort(reverse=True) #sorts list largest to smallest
for value, key in temporary[:10]: #prints top 10 values sorted largest to smallest
print key, value
#print sor... |
22b428d3d78181ea591cbe4d6c1fcc85fe3c8d85 | mlttanaka/tangokaunto | /tangokaunto.py | 2,587 | 3.953125 | 4 | #!/usr/bin/env python
"""
Tangokaunto, "word count" in Japanese, reads Japanese text from an input file,
splits the text into words (as defined by TinySegmenter), and prints out a
word count as well as all the word it segmented from the text.
author: mochipuff
"""
import sys
import codecs
import tinysegmenter as ts
... |
e6a84fdea6cbd3ceb275c45d47bb0f3c6f0d6d5d | WweiL/LeetCode | /125-valid_palindrome.py | 639 | 3.546875 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
start = 0
end = len(s)-1
while start < end:
while start < len(s) and not (s[start].isalpha() or s[start].isdigit()):
start += 1
... |
a4afe75b937ff7803e25d21c089f447e6e63a7da | WweiL/LeetCode | /708-insert_into__cyclic_linked_list.py | 1,046 | 3.96875 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val, next):
self.val = val
self.next = next
"""
class Solution:
def insert(self, head, insertVal):
"""
:type head: Node
:type insertVal: int
:rtype: Node
"""
node = Node(insertVal, None)
... |
0c3c6a498fdd92067fa6d92f6a01761a6b89758b | WweiL/LeetCode | /53-maximun_subarr.py | 247 | 3.546875 | 4 | class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)-2, -1, -1):
nums[i] = max(nums[i]+nums[i+1], nums[i])
return max(nums)
|
22b1fcf5c7c7c2a5190b1a32e861626d3788dd87 | WweiL/LeetCode | /865-smallest_subtree_with_all_deepest_nodes.py | 829 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:... |
1c8d3c909159769332f053f51cd8e5d04531518c | WweiL/LeetCode | /212-word_search_ii.py | 2,102 | 3.640625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.children = {}
self.word = ''
class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
if not board or ... |
ed4e22a3b8755e570be14435bba6b55387b18fe4 | WweiL/LeetCode | /21-merge_two_sorted_lists.py | 1,372 | 4.03125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
... |
b295d75782593be2da4de11309ce6bcf5810010d | WweiL/LeetCode | /9-pal_number.py | 410 | 3.765625 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
def isPal(x):
if len(x) == 1 or len(x) == 0:
return True
elif x[0] != x[-1]:
return False
else:
return isPal(x[1:-1... |
efca76ef9fa64ee9471989d9f69dd904cab14201 | WweiL/LeetCode | /554-brick_wall.py | 475 | 3.515625 | 4 | class Solution:
def leastBricks(self, wall):
"""
:type wall: List[List[int]]
:rtype: int
"""
from collections import defaultdict
line = defaultdict(int)
max_blank = 0
for l in wall:
length = 0
for i in l[:-1]:
le... |
3b45314adb268e6ebcb70b2b3d9fef0a6ab9f915 | WweiL/LeetCode | /42-trapping_water.py | 3,578 | 3.859375 | 4 | # # more easy to be thought of stack:
import collections
class Solution:
def trap(self, height):
stack = collections.deque()
index = 0
water = 0
while index < len(height):
# decreasing order, find bottom
if len(stack) == 0 or height[index] <= height[stack[-1]]... |
9eef23e36dfb8f63e7e74c953ef7a089727603d8 | WweiL/LeetCode | /314-BST_vertical_order_traversal.py | 2,449 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
l = {}
... |
b01b15af5f255218f57ad5e2893bb0d1fd7b0922 | WweiL/LeetCode | /98-validate_bst.py | 1,057 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
... |
c5f0f77d42644f95af81e3dedafcd768b4dfbaba | WweiL/LeetCode | /bin_search.py | 1,529 | 3.8125 | 4 | def search(arr, target):
# binary search with duplicated values and non-existing target, find the first value smaller than or equal to target
# return index and value
# [1, 2, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10] 2.5
# [2, 2, 2, 2,2,2 ] 2.5
# [1, 2, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10] 12.5
l = 0
r = le... |
8df7b137572f71daf2a8e040937fc11f736558c2 | WweiL/LeetCode | /75-sort_colors.py | 708 | 3.84375 | 4 | class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# three pointers
zero, one = 0, 0
for two in range(len(nums)):
n = nums[two]
nums[two] = 2
... |
5658ad41242d5564ce3629ff9327dbe76b4b6015 | shubhrajps/SimplyPython | /Pandas_Jupyter.py | 470 | 3.5 | 4 | import pandas
df1 = pandas.read_excel("expenses.xlsx")
# df1 = df1.set_index("DATE")
# df2 = df1.loc["23-07-2018":"26-07-2018", "EXPENSES":"REASON"]
# print(list(df1.loc[:, "DATE"]))
# df2 = df1.iloc[1, 3]
# df2 = df1.ix[1,2]
# df2 = df1.drop("DATE", 1)
# df2 = df1.drop(df1.index[0:3], 0)
# d... |
35ba640038c268bcb35561d5cef24d3088b82d37 | yash-sinha-850/Personal | /bfs.py | 724 | 3.640625 | 4 | class Node:
def __init__(self,name):
self.name=name
self.adj_list=[]
self.visited=False
class Breath_search_first:
def bfs(self,startnode):
queue=[]
queue.append(startnode)
startnode=True
while queue:
actualnode= queue.pop(0)
print(actualnode.name)
for i in ac... |
795189e1fd7e81e3af846919df888a2350470067 | foriduzzaaman-zihad/URI-Solution-in-Python | /1074.py | 340 | 4 | 4 | x = input()
for i in range(x):
y = input()
t = ""
if y == 0:
print("NULL")
else:
if y % 2 == 0:
t += "EVEN "
else:
t += "ODD "
if y > 0:
t += "POSITIVE"
else:
t += "NEGATIVE"
print(t)
... |
2788c7bf35f0a906c592a804afd1579080015a90 | foriduzzaaman-zihad/URI-Solution-in-Python | /1073.py | 120 | 3.828125 | 4 | x = int(input()) + 1
for i in range(x):
if i % 2 == 0 and i != 0:
print(str(i) + "^2 = " + str(i**2))
|
491f83fd8faed22959a8989ba18b827b5707a17f | foriduzzaaman-zihad/URI-Solution-in-Python | /1117.py | 192 | 3.828125 | 4 | x = 0
s = 0.0
while x != 2:
y = float(input())
if y > 10 or y < 0:
print("nota invalida")
else:
x+=1
s+=y
print("media = {:.2f}").format(s/2)
|
572de7396488d43a1af6ebffd8b8416ada57a55b | snowcloak/PYTHON | /map1.py | 1,965 | 3.671875 | 4 | import folium
import pandas as pd
#read data/csv
data = pd.read_csv("Files/Volcanoes.txt")
#create lists from dataframe
lat = list(data["LAT"])
lon = list(data["LON"])
elev = list(data["ELEV"])
name = list(data["NAME"])
#stylizing with HTML (know HTML)
html = """
<b><br>
<a href="https://www.google.com/search?q=%%22... |
9755f9ccf007059a1f076513a9a2afa01545d848 | xkfz007/python_scripts | /py_cook_book.py | 779 | 3.9375 | 4 | #!/bin/python
__author__ = 'hfz2597'
import string
# Checking Whether a String Is Text or Binary
def istext(s, threshold=0.30):
text_characters = "".join(map(chr, range(32, 127))) + "\n\r\t\b"
_null_trans = string.maketrans("", "")
# if s contains any null, it's not text:
if "\0" in s:
... |
7a11d863a7957eefd6d8c7f8f02a9ceb5b5bdfdc | ivogeorg/python-prog-asst01 | /data_structures.py | 497 | 3.6875 | 4 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
numbers = [0, 1, 2, 3, 4, 5, 6, 7]
floats = [1.2, 3.4, 6.7, 1.01, 4.9, 12.8, 5.45]
strings = [a + str(b) for (a, b) in zip(letters, numbers)]
print(strings)
# strings = []
# for (a, b, c) in zip(letters, numbers, floats):
# strings.append(a + str(b) + str(c))
#
# pri... |
86f78a9371de633abb9779bab12a1f4bb70c4b34 | Sherlocked21B/Python | /pattern.py | 195 | 3.671875 | 4 | n=int(input("Enter the dimension of tree:"))
m=n
j=1
for i in range(0,n):
print(f"{(m-1)*' '} {(i+j)*'*'}")
m=m-1
j=j+1
for i in range(0,n):
print((n-1)*' ',end="")
print('*') |
ba1c24a87d5b61a4981ffbf32c086cf0efd87cae | Sherlocked21B/Python | /check.py | 286 | 3.515625 | 4 | count=0
capital=""
mydict={}
f = open("/home/bijaya/Downloads/countrycapitals.csv","r")
a=f.readlines()
b=input("Enter the name of the country::")
c=b.lower().title()
for i in a:
count=count+1
for i in range(count):
con=a[i].split(",")
mydict[con[0]]=con[1]
print(mydict[c]) |
a34d391fe51ea92d12ff3b3c42fa6b77f797b7fa | rahul-relekar/professional-internship-practise | /Sem-A/MainQuestions/Q1-Qsort.py | 1,741 | 4.09375 | 4 | """
Write a function by Quick Sort algorithm to sort the following array.
data = 3, 4, 9, 0, 2, 2, 3, 5, 11, 1
Type: Divide-and-Conquer Algorithm
"""
# function to sort the integer array in ascending order
def QuickSort(arr):
# saves the length of the given array arr
elements = len(arr)
... |
2d9d5b72d3c087ee59b61d0bcedfd91ba03003ff | MarshallMicuit/pendu | /pendu/pendu.py | 1,625 | 3.734375 | 4 | import donnees
import fonctions
# On demande d'abord son nom à l'utilisateur afin d'enregistrer son score dans un fichier.
# Avec la fonction verifier_utilisateur on vérifie si le pseudo est déjà rentré et on met son score à jour
# En plus de récupérer la liste des scores du jeu
nom_utilisateur = input("Entrez... |
b309163a54cb56b9f9c3b21795388a74658910fb | 99zraymond/Daily-Lesson-Exercises | /Daily Exercise 02082018.py | 770 | 4.34375 | 4 | #Your Name - Python Daily Exercise - date of learning
# Instructions - create a file for each of the daily exercises, answer each question seperately
# 1. Write a statement that concatenates at least two variables (you can have more than 2 for this practice).
# 2. Create a program that asks the user to enter t... |
bfadcf4caaff8fa8631a02786936d9ecfc18ba69 | Gomathi-Janakiram/greyatom-python-for-data-science | /Loan-Approval-analysis/code.py | 3,110 | 3.984375 | 4 | # --------------
# Importing header files
import numpy as np
import pandas as pd
from scipy.stats import mode
import warnings
warnings.filterwarnings('ignore')
#Reading file
bank_data = pd.read_csv(path)
print(bank_data.head())
#Code starts here
#step 1
"""Let's check which variable is categorical ... |
ff69b994ddf9b8b03d6f0fe5ccd9bb8179271b59 | Al3x-BB/Unidad3-Ejercicio2 | /Helado.py | 501 | 3.65625 | 4 | class claseHelado:
__gr = 0 #gramos
__sabores = []
def addSabores(self, sabores):
self.__sabores = sabores.copy()
def __str__(self):
return "Helado de {}gr".format(self.__gr)
def addGr(self, gramos):
self.__gr += gramos
def mostrar(self):
for i in ran... |
52b0aac6d8ea924fd839914e0421f4a270f6bbbf | khanhbaovu/Monte-Carlo-Simulation | /monteCarlo.py | 735 | 3.703125 | 4 | # Khanh Vu
# [Monte Carlo simulation of the value of e]
import numpy as np
import math
N = int(input("Enter number of sub-intervals to simulate: "))
print()
array = np.zeros(N)
Z = 0
for i in range(0, N):
num = np.random.random()
location = int(N*num)
array[location] += 1
for i in range(0, N):
... |
cd3f9a8024752d033278ad1748f4c853072fffc7 | RMaturin/GB_python | /Les02/004.py | 545 | 3.953125 | 4 | # 4. Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
s1 = input('Введите нескольких слов, разделённых пробелами: ')
for ind, el in enumerate(s1.split()):
pri... |
6b656fb2352d88edf3ecf14d24dcc87f92dbefe3 | RMaturin/GB_python | /Les04/001.py | 710 | 3.8125 | 4 | # 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
# В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия.
# Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
from sys import argv
def emp_... |
3150a4bfae3d062c0194c5b80799a1e6ac7545eb | RMaturin/GB_python | /Les01/004.py | 459 | 3.953125 | 4 | # 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
n = int(input('Введите число: '))
res = 0
while (n > 0):
if res < (n % 10):
res = n % 10
n = n // 10
print(f'Самая большая цифра - {res}') |
089be5f072f0301f74b9e2cc962a2abe89fdea1f | RMaturin/GB_python | /Les04/006.py | 1,437 | 3.84375 | 4 | # 6. Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
# Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание,
# что создаваемый цикл не должен быть бесконечным... |
c17429816d6ed538202ab6c12b568f88fa011f89 | LiangFei90/PythonDataAnalysis | /Study/sort.py | 1,366 | 3.984375 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue May 16 16:25:14 2017
@author: frank
"""
def buble_sort(l):
print 'buble_sort:'
for i in range(len(l)):
for j in range(len(l)-1):
if (l[j]>l[j+1]):
temp=l[j]
l[j]=l[j+1]
l[j+1]=... |
d09df18ffdb0f804057f8b9413dd03b91cdc7fe2 | coreycrosby/collections_and_iterations_part1 | /exercises.py | 3,484 | 3.6875 | 4 | #Exercise 0
fav_colours = ["red", "yellow", "orange", "black", "green"]
ages = [22, 20, 29, 22, 30]
coin_flip = ["heads", "tails", "heads", "heads", "tails"]
fav_artist = ["Drake", "Kendrick Lamar", "Big Sean"]
words_defs = {
"semantic": "related to meaning in language or logic",
"successful": "accomplishing a... |
c9498cbc6f9469f5f6b4294d6d80ccc91d144f8d | eatabay/LeetCode | /007_Reverse_Integer/main.py | 1,215 | 4.0625 | 4 | # Given a 32-bit signed integer, reverse digits of an integer.
#
# Example 1:
#
# Input: 123
# Output: 321
#
# Example 2:
#
# Input: -123
# Output: -321
#
# Example 3:
#
# Input: 120
# Output: 21
#
# Note:
# Assume we are dealing with an environment which could only store
# integers within the 32-bit signed int... |
d543d8c766e6e4ae4b87271abba64c949f6ce43c | eatabay/LeetCode | /001_Two_Sum/main.py | 536 | 3.5625 | 4 | import timeit
def twoSumNaive(nums, target):
pairs = []
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if (nums[i] + nums[j]) == target:
pairs.append((i,j))
return pairs
def twoSumBest(nums, target):
ht = {}
for i, num in enumerate(nums):
... |
fad49c621416ab69fd34d55b3ba32d89257cb1be | jinwuxia/pyunit | /progressbar.py | 1,521 | 3.515625 | 4 | import Tkinter
tk = Tkinter # Alternative to the messy 'from Tkinter import *' often seen
class ProgressBar(tk.Frame):
"""A simple progress bar that shows a percentage progress in
the given colour."""
def __init__(self, *args, **kwargs):
apply(tk.Frame.__init__, (self,) + args, kwargs)
... |
b73055e0f0a5071ed2eaf3eabcd662ee2e2a454b | patorres61/prg105-CreatingAndDrawingObjects | /creating_and_drawingObjects.py | 3,252 | 4.15625 | 4 | # Phyllis Torres
# Create and Draw Objects
# Due Date: November 3, 2016
# import swampy
from swampy.World import World
# create a world object from World class
world = World()
# define classes for point, circle, and rectangel
# noinspection PyPep8
class Point:
"""defines a point in 2 dimensional spa... |
d0e5bfc547bdc9d64901979a13619ecf9a7982cd | TheSiggs/Python-Exercises | /Exercises/Sum and Rest the Number with its Reversed and See What Happens.py | 771 | 3.546875 | 4 | def group_check(s):
openings = ["{","[","("]
closings = ["}","]",")"]
openCount = 0
closeCount = 0
start = s[0]
end = s[-1]
check1 = False
check2 = False
for i in range(len(openings)):
if start == openings[i] and end == closings[i]:
check1 = True
for i in s:
if i in openings:
openCount += 1
... |
780960e6a03ce194be8466ef87fb173a59d7df9f | TheSiggs/Python-Exercises | /Digital Root Finding.py | 183 | 3.671875 | 4 | def digital_root(n):
n = str(n)
strnum = [int(num) for num in n]
num = sum(strnum)
if len(str(num)) > 1:
digital_root(num)
else:
print(num)
return num
digital_root(493193) |
1016205d73bf3440943ba7053f7b23f7ecddea1b | YigitKeser/Navigation-Task | /navi.py | 1,862 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 16:12:49 2020
@author: yigitkeser
"""
import numpy as np
import pandas as pd
import random
from matplotlib import pyplot as plt
cities = pd.read_csv('cities.txt', sep = ';', skiprows = 1 , names = ['name','latitude','longitude','admin','city_or... |
209d16d6c3c729004d22e83ce041b72a7b09ad85 | rosstripi/2038 | /intro.py | 3,422 | 3.90625 | 4 | """
Author: rossbot
intro sequence for 2038
"""
import pygame, sys, time, random
# import constants from pygame
from pygame.locals import *
# set up the colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
GRAY = (150, 150, 150)
def intro_sequence(windowSurface=p... |
94a530c7b6b638e8c510231c0e61e43ac92277ee | huynhhoc/FaceIDProject | /LogFile.py | 945 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__="hthoc@..."
__date__ ="$02-01-2019$"
import datetime
class LogFile:
def __init__(self, fileLogName):
self.fileLogName = fileLogName
def showLog(self, logMessage):
try:
f = open(self.fileLogName, "ab")
message = '[... |
ec19745c90f31884dfb661792e2d2505370e76da | nsidnev/mirea | /term3/dsa/labs/lab2/main.py | 436 | 3.96875 | 4 | def is_prime(n):
if n == 2:
return True
if n % 2 == 0 or n <= 1:
return False
for i in range(3, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def main():
n = 0
while n < 1:
n = int(input("n: "))
a = [int(number.strip()) for numbe... |
c271b4e93740739d52bf9f552a37d9ffbca34418 | MortadelaXD/cop4530-linked-stack | /main.py | 5,315 | 3.890625 | 4 | #!/usr/bin/env python3
# A linked stack data structure for COP 4530 by Team Nevada
# Thomas Hall (Requirements)
# Grant Gurvis (Developer)
# Austin Hadsock (Tester)
# Brian Guenzatti (Tester)
# Imports python standard libraries
import ast
import os
import pprint
import sys
from typing import Optional, Any
class Lin... |
0a3a33a28fda37d94aae01bc44978d3bf4f7db7c | wayfair/pylift | /pylift/explore/base.py | 11,834 | 3.6875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from ..style import _plot_defaults
def _add_bins(df, feats, n_bins=10):
"""Finds n_bins bins of equal size for each feature in dataframe and outputs the result as a dataframe.
Parameters
----------
df : pandas.DataFrame
dat... |
e32cc13a2f419735c933d0aeb2daa4f7f82d0543 | nobodyn0se/Python_Web_Data | /Week3_Sockets.py | 661 | 3.578125 | 4 | ''' Week 3 assignment - encodes a given webpage into Unicode, sends GET request
for header and content, receives relevant data and displays all
parameters such as Content Type, Content Length from the headers, etc. '''
import socket
def soc():
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysoc... |
1f2577f7efcc4d45e17a8534a0e0c08b587c6272 | ankerbachryhl/Owels-and-Mice | /slot.py | 3,087 | 3.5625 | 4 | class Slot(object):
def __init__(self, cordI, cordJ):
self.cordI = cordI
self.cordJ = cordJ
self.num_mice = 0;
self.num_owels = 0;
self.has_rock = False;
self.hideUnderRock = False;
self.all_animals = self.num_mice + self.num_owels
self.state = 0
... |
2c8180c8ae8b480a098ce3560a119afc22364a26 | zc78520/python-learn | /11_function.py | 630 | 3.546875 | 4 | #filename:function.py
print(abs(100))
print(abs(-100))
print(abs(12.34))
print(max(1,2))
print(max(1,2,3,-4))
print(int('123'))
print(int(12.34))
print(str(1.23))
print(str(100))
print(bool(1))
print(bool(''))
def myabs(x):
if x>=0:
return x
else:
return -x
print(myabs(-4))
def nop():
pa... |
c369e3f3f82c69ea99710e8d5cfe31a10c5b3c72 | manjunath2019/Python_7am_May_2019 | /OOPS/inherit_multiple.py | 350 | 3.640625 | 4 | class Animal:
def __init__(self, name=''):
self.name = name
def talk1(self):
#pass # Empty
print(self.name,"Welcome to Animal World")
class Cat(Animal):
def talk2(self):
print (self.name,"Meow!")
class Dog(Cat,Animal):
def talk(self):
print (self.name, "Woof!")
a = Dog()... |
76c8f045cfe417b890bcd02aad54cd7184feb88d | manjunath2019/Python_7am_May_2019 | /OOPS/Overview.py | 214 | 3.5 | 4 | class MyFirstClass:
variable = "Welcome to Python World"
def abc(self):
print("This is a Message inside the Class MyFirstClass")
myObject = MyFirstClass()
print(myObject.variable)
myObject.abc() |
b669b0d200e99212d05f3c31f0fd69f787389227 | manjunath2019/Python_7am_May_2019 | /DataTypes/Dictionaries/Basics.py | 264 | 3.6875 | 4 |
# dict()
# {}
# Key & Value
# Element is seperated with ,
# Mutable DataType
# Creating Dict Variable
aDict = {'Sno':0,'FirstName':'Guido','MiddleName':'Van','LastName':"Rossum"}
print(aDict)
print(type(aDict))
print(id(aDict))
print(dict(enumerate(aDict))) |
5906f241dd31462703c199c049a475251cb3bba1 | manjunath2019/Python_7am_May_2019 | /DataTypes/Sets/Basics.py | 384 | 3.96875 | 4 | """
A set is an unorderd collection without duplicates
when printed, iterated upon, or converted into a sequence, it's elements will appear in an arbitrary, implementation-dependent order.
"""
a = set()
print(a, type(a), id(a))
#abc = set(('a','b','a','b'))
abc = set(['a','b','a','b'])
print(abc,type(abc),id(abc... |
0905f469a7ec21316af166112277cd2579d1fabf | manjunath2019/Python_7am_May_2019 | /Exception_Handling/ExceptionHandling_Recap.py | 2,736 | 4.09375 | 4 | """
try:
statement(s)
except:
statement(s)
else:
statement(s)
finally:
statement(s)
>>> 4 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
raise ----> exception
x = 10
if x > 5:
#print(f"{x} Its True")
raise Exception(f"X Shoul... |
505c59d5b7161eab01c637f144f7f3bf790f2bfb | manjunath2019/Python_7am_May_2019 | /Operators/Membership.py | 452 | 4.15625 | 4 |
"""
in and not in are the membership operators in python
Are used to test whether a value or variable is found in a sequence
(String, List, Tuple, & Dictrionary)
"""
x_value = 'Guido Van Rossum'
y_value = {1:'a',2:'b'}
print(x_value)
print(y_value)
#a = input('Enter a Value : ')
#print(a in x_value.lower())
pr... |
a4a49bca0df997991c5409f9a72b2012a92338c0 | juliamosk/my_python | /call_tel.py | 270 | 3.84375 | 4 | n=int(input("Введите число минут:"))
code=int(input("Введите код города:"))
if code==343:
print(15*n);
elif code==381:
print(18*n);
elif code==473:
print(13*n);
elif code==485:
print(11*n);
else:
print('wrong code')
|
863b6ae019910da7173557127ec0cff7aa1974da | R-second/number_theory | /ch05/collatz_problem.py | 1,146 | 3.875 | 4 | ### 「3n+1」アルゴリズム
# 入力nから、「3n+1」アルゴリズムに従う次の数字を返す
def collatz_next(n):
if n % 2 == 0:
return n / 2
else:
return 3 * n + 1
# アルゴリズムの長さL(n)と、最後の値T(n)を返す
def collatz(n):
# 生成された数列を格納
sequence = [n]
next_num = collatz_next(n)
while next_num not in sequence:
sequence.append... |
40a780a1b86997f87f560f5a5fd6694a8bc61535 | R-second/number_theory | /ch16/power_mod.py | 559 | 3.75 | 4 | # 練習問題16.2
# 繰り返し二乗法で, a^k (mod m) を求める.
def power_mod(a, k, m):
b = 1
while k >= 1:
if k % 2 == 1:
b = (a * b) % m
a = ( a * a ) % m
k = int(k / 2)
return b
# (c) 計算
print(power_mod(2, 1000, 2379))
print(power_mod(567, 1234, 4321))
print(power_mod(47, 258008, 1315171)... |
a5efe67130f6ac5bc3b438f3468466882936bcaa | Sirikonss/unittesting-Sirikonss | /practice_unittest.py | 841 | 3.9375 | 4 | import math
import time
import unittest
from fraction import Fraction
class FractionTest(unittest.TestCase) :
"""Test the methods and constructor of the Fraction class. """
def test_str(self) :
f = Fraction(3,10)
self.assertEqual("3/10",f.__str__())
f = Fraction(-3,1)
self.asser... |
fe772bb99d73d91ec7557c483374e4e60e8db83a | martirosyanrafi/python-course | /part1/homework4/problem2.py | 491 | 4 | 4 | class MyTime:
def __init__(self, t):
self.t = t
def print_time(self):
print("The current time is", self.t)
class MyDate:
def __init__(self, d):
self.d = d
def print_date(self):
print("The current date is", self.d)
class DaTeTime(MyTime, MyDate):
def __init__(... |
021d17237d11ce4094ecc6cfddcccf2441aac66a | tinahuang5X/prescribe-api-python | /code/create_table.py | 1,309 | 3.921875 | 4 | import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
# MUST BE INTEGER
# This is the only place where int vs INTEGER matters—in auto-incrementing columns
create_table = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text, password text)"
cursor.execute(create_table... |
5d3d6a91634084521936c01408a4c5b6e63de0ee | FlameFractal/CSD302-342-Algorithms-DataMining | /progress-pie.py | 1,042 | 3.78125 | 4 | import math
class circle:
def __init__ (self, radius, center_x, center_y):
self.radius = radius
self.center_x = center_x
self.center_y = center_y
def isInCircle(c, point_x, point_y):
return ((point_x-c.center_x)*(point_x-c.center_x) + (point_y-c.center_y)*(point_y-c.center_y) <= c.radius*c.radius)
def isInSe... |
d19fc73afcea4b9a9b438985eb8ae64d1caabe06 | hoklavat/beginner-data-science | /13-ScalarVectorMatrice/13-ScalarVectorMatrice.py | 1,123 | 3.625 | 4 | #13-ScalarVectorMatrice
import numpy as np
#SCALAR
s = 5
s
#VECTOR
v = np.array([5, -2, 4]) #column vector
v
v = v.reshape(3, 1) #row vector
v
#MATRICE
m = np.array([[5, 12, 6], [-3, 0, 14]])
m
#DATA TYPES
type(s) #integer
type(v) #1-dimensional array
type(m) #2-dimensional array
s_array = np.array(5) #1-dimensi... |
7d81fff0678e42eb172110b98c000581f4fcaf7d | cshintov/sicp | /chapter_1_building_abstractions_with_functions/fib.py | 733 | 3.6875 | 4 | from pprint import pprint
def ifib(n):
""" Compute the nth fibonacci number where n >= 2 """
if n < 2:
return n
curr, pred = 0, 1
k = 0
while k < n:
pred, curr = curr, pred + curr
k = k + 1
return curr
def rfib(n, mem={}):
""" Compute the nth fibonacci number whe... |
16370d5f6b441b75a0c8dbcbe61563ad32d40aea | JoaoCastro84/aulas-de-python | /lista com while aula 3.py | 241 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 16:51:35 2018
@author: joaoc
"""
lista=[]
x=1
while x>0:
x=int(input("Digite um número"))
if x!=0:
lista.append(x)
print(lista)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.