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 |
|---|---|---|---|---|---|---|
8146a0a68782bf0745c250965e9440689dd3d957 | Litao439420999/LeetCodeAlgorithm | /Python/candy.py | 3,342 | 3.640625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: candy.py
@Function: 分发糖果 贪心策略
@Link: https://leetcode-cn.com/problems/candy/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-04
"""
# --------------------------------------------------------------
class Solution2:
"""0、只需要简单的两次遍历即可:把所有孩子的糖果数初始化为 1;
1、... |
268b790641e7a522cc7d2431dcdb28b9a30126c8 | Litao439420999/LeetCodeAlgorithm | /Python/MinStack.py | 754 | 3.65625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: MinStack.py
@Function: 最小栈
@Link: https://leetcode-cn.com/problems/min-stack/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-25
"""
import math
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = [math.inf]
def pu... |
03a7ff048927334379e9758f3d2e7b43d2ceee43 | Litao439420999/LeetCodeAlgorithm | /Python/hammingDistance.py | 636 | 3.78125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: hammingDistance.py
@Function: 两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目
@Link: https://leetcode-cn.com/problems/hamming-distance/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-21
"""
class Solution:
def hammingDistance(self, x, y):
return bin(x ^ y).... |
f04df87810d13395100540e524f48db20db18d52 | Litao439420999/LeetCodeAlgorithm | /Python/calculate.py | 1,149 | 3.875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: calculate.py
@Function: 基本计算器 II
@Link: https://leetcode-cn.com/problems/basic-calculator-ii/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-28
"""
class Solution:
def calculate(self, s: str) -> int:
n = len(s)
stack = []
preSign... |
a39d90db4f8ca2489ce1c157bc075f59aba7c24d | Litao439420999/LeetCodeAlgorithm | /Python/reconstructQueue.py | 1,015 | 3.859375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: reconstructQueue.py
@Function: 根据身高重建队列 贪心策略
@Link: https://leetcode-cn.com/problems/queue-reconstruction-by-height/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-06
"""
# ---------------------------
class Solution:
def reconstructQueue(self, people):
... |
0334614a346b0a1dcddf4da9b585a997ab561dad | Litao439420999/LeetCodeAlgorithm | /Python/matrixReshape.py | 850 | 4.0625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: matrixReshape.py
@Function: 重塑矩阵
@Link: https://leetcode-cn.com/problems/reshape-the-matrix/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-26
"""
from typing import List
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) ->... |
7b22af2549e23620e764bfe31cf5fbddf2a6b6bd | Litao439420999/LeetCodeAlgorithm | /Python/dailyTemperatures.py | 956 | 3.96875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: dailyTemperatures.py
@Function: 每日温度
@Link: https://leetcode-cn.com/problems/daily-temperatures/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-25
"""
from typing import List
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[... |
2c3bdd46d4cd3975dfb4cadb5f4f29af6bbd7872 | Litao439420999/LeetCodeAlgorithm | /Python/wiggleMaxLength.py | 1,074 | 3.71875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: wiggleMaxLength.py
@Function: 摆动序列 动态规划
@Link:https://leetcode-cn.com/problems/wiggle-subsequence/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-16
"""
class Solution:
def wiggleMaxLength(self, nums) -> int:
n = len(nums)
if n < 2:
... |
adb7c6349316892da5414d10a589f891e97bb1e5 | Litao439420999/LeetCodeAlgorithm | /Python/constructFromPrePost.py | 1,101 | 3.875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: constructFromPrePost.py
@Function: 根据前序和后序遍历构造二叉树
@Link : https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-08-02
"""
# Definition for a binary tree node.
class TreeNode... |
97427f841b2215fda35a0110c3323725acace837 | Litao439420999/LeetCodeAlgorithm | /Python/findKthLargest.py | 1,315 | 3.953125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: findKthLargest.py
@Function: 数组中的第K个最大元素 快速选择
@Link: https: // leetcode-cn.com/problems/kth-largest-element-in-an-array/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-10
"""
import random
class Solution:
def findKthLargest(self, nums, k):
def... |
b944a375a96ced5824239689a7e7b5f26dc854c4 | Litao439420999/LeetCodeAlgorithm | /Python/binaryTreePaths.py | 2,102 | 3.96875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: binaryTreePaths.py
@Function: 二叉树的所有路径
@Link: https://leetcode-cn.com/problems/binary-tree-paths/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-12
"""
import collections
from typing import List
import string
# Definition for a binary tree node.
class TreeN... |
6bc5f504ef16bea225cae8f52e818fb96687b002 | Litao439420999/LeetCodeAlgorithm | /Python/sumOfLeftLeaves.py | 1,006 | 3.78125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: sumOfLeftLeaves.py
@Function: 左叶子之和
@Link: https://leetcode-cn.com/problems/sum-of-left-leaves/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-08-01
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
... |
8b39bba2440821071ad46e65071a642da9ce5434 | Litao439420999/LeetCodeAlgorithm | /Python/lowestCommonAncestor2.py | 962 | 3.65625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: lowestCommonAncestor2.py
@Function: 二叉树的最近公共祖先
@Link : https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-08-02
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self... |
fbc71fc9cb47523ce6a7b1aed3f1c24b3723846b | Litao439420999/LeetCodeAlgorithm | /Python/numSquares.py | 1,301 | 3.671875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: numSquares.py
@Function: 完全平方数 动态规划
@Link: https://leetcode-cn.com/problems/perfect-squares/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-14
"""
class Solution:
def numSquares(self, n: int) -> int:
'''版本一'''
# 初始化
nums = [i**2 ... |
3bb8a813d915675a1aec37019e157674a162dfef | renatovvjr/candidatosDoacaoPython | /main.py | 1,269 | 3.796875 | 4 | #O programa receberá informações de 10 candidatos à doação de sangue. O programa deverá ler a idade e informar a seguinte condição:
#- Se menor de 16 ou acima de 69 anos, não poderá doar;
#- Se tiver entre 16 e 17 anos, somente poderá doar se estiver acompanhado dos pais ou responsáveis (neste caso criar uma condição:... |
ef1db11ab060501a5f23c772da2e3467889b3fb3 | Zetinator/just_code | /python/leetcode/jumping_clouds.py | 655 | 3.84375 | 4 | """
Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads.
"""
def deep(x, jumps):
i... |
dd146b10d8b6c0900a77754d93b0c9231e2737a8 | Zetinator/just_code | /python/leetcode/sorting_bubble_sort.py | 1,012 | 4.09375 | 4 | """https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting
Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following three lines:
Arr... |
2dcdbed4df8b0608780c4d3a226c4f25d0de2b38 | Zetinator/just_code | /python/leetcode/binary_distance.py | 872 | 4.1875 | 4 | """
The distance between 2 binary strings is the sum of their lengths after removing the common prefix. For example: the common prefix of 1011000 and 1011110 is 1011 so the distance is len("000") + len("110") = 3 + 3 = 6.
Given a list of binary strings, pick a pair that gives you maximum distance among all possible pa... |
2b9f81e6106ebe23353158a2b4b3f12d034003e7 | Zetinator/just_code | /python/leetcode/simple_text_editor.py | 1,697 | 4 | 4 | """https://www.hackerrank.com/challenges/simple-text-editor/problem
In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, . You must perform operations of the following types:
append - Append string to the end of .
delete - Delete the last characters of .
prin... |
18b95ddca9704d64627cde69375e30a880efaa95 | Zetinator/just_code | /python/leetcode/poisonous_plants.py | 3,076 | 3.921875 | 4 | """https://www.hackerrank.com/challenges/poisonous-plants/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=stacks-queues
There are a number of plants in a garden. Each of these plants has been treated with some amount of pesticide. After each day, if any plant has more pesticid... |
246928be6fa574268809d7291343ff2e7d099234 | Zetinator/just_code | /python/classics/max_change.py | 654 | 3.8125 | 4 | """
Coin Change problem: Given a list of coin values in a1, what is the minimum number of coins needed to get the value v?
"""
from functools import lru_cache
@lru_cache(maxsize=1000)
def r(x, coins, coins_used):
"""recursive implementation
"""
if x <=0: return coins_used
return min(r(x-coin, coins, co... |
319781d2b8b2a6bb1fdbb3070ac71057b4e949a0 | Zetinator/just_code | /python/data_structures/radix_trie.py | 5,142 | 3.53125 | 4 | """custom implementation of a radix trie with the purpose of practice
the ADT contains the following methods:
- insert
- search
- delete
"""
class RTrie():
class Node():
"""Node basic chainable storage unit
"""
def __init__(self, x=None):
self.data = x
sel... |
27db300075e7661296ee4d494f378aac89b21c83 | Zetinator/just_code | /python/algorithms/dinic.py | 2,041 | 4 | 4 | """implementation of the dinic's algorithm
computes the max flow possible within a given network gaph
https://visualgo.net/en/maxflow
https://en.wikipedia.org/wiki/Dinic%27s_algorithm
"""
from data_structures import network_graph
def dinic(graph: network_graph.NGraph) -> int:
"""computes the maximum flow value of... |
6fc20cea6cd490bd44af17299584ee0be51356e4 | Zetinator/just_code | /python/leetcode/min_swaps_2.py | 1,795 | 3.796875 | 4 | """https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=arrays
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. ... |
c1d4def8281d064203472299ab75b786a9261ae2 | Zetinator/just_code | /python/leetcode/find_maximum_index_product.py | 1,328 | 3.9375 | 4 | """https://www.hackerrank.com/challenges/find-maximum-index-product/problem
You are given a list of numbers . For each element at position (), we define and as:
Sample Input
5
5 4 3 4 5
Sample Output
8
Explanation
We can compute the following:
The largest of these is 8, so it is the answer.
"""
def solve(arr):
... |
308f485babf73eec8c433821951390b8c2414750 | Zetinator/just_code | /python/leetcode/pairs.py | 966 | 4.1875 | 4 | """https://www.hackerrank.com/challenges/pairs/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=search
You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value.
Complete... |
671ea3e72e4ff94b20aed867eb3c4075b2be4d92 | Zetinator/just_code | /python/classics/longest_common_substring.py | 828 | 3.9375 | 4 | """In computer science, the longest common substring problem is to find the longest string (or strings) that is a substring (or are substrings) of two or more strings.
https://en.wikipedia.org/wiki/Longest_common_substring_problem
"""
from functools import lru_cache
@lru_cache(maxsize=1000)
def r(x, y, record=0):
... |
d7927eb47f552113d335a0e1b04f608e852a8c3a | Zetinator/just_code | /python/leetcode/string_comparator.py | 910 | 4.0625 | 4 | """https://www.hackerrank.com/challenges/ctci-comparator-sorting/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
Comparators are used to compare two objects. In this challenge, you'll create a comparator... |
e823b273ed44482d8c05499f66bf76e78b06d842 | Zetinator/just_code | /python/leetcode/special_string_again.py | 2,477 | 4.21875 | 4 | """https://www.hackerrank.com/challenges/special-palindrome-again/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=strings
A string is said to be a special string if either of two conditions is met:
All of the characters are the same, e.g. aaa.
All characters excep... |
768f200cbdbbbd4808c4eea18004f7e4ff7c912c | Zetinator/just_code | /python/data_structures/double_linked_list.py | 3,017 | 3.96875 | 4 | """custom implementation of a double linked list with the purpose of practice
the ADT contains the following methods:
- append
- insert
- search
- delete
- traverse
"""
class DoubleLinkedList():
class Node():
"""Node basic chainable storage unit
"""
def __init__(self, x=N... |
51e43263d84055e470d62d41a870972357ab30f2 | Zetinator/just_code | /python/leetcode/give_change.py | 472 | 3.671875 | 4 | def give_change(quantity):
coins = [25, 10, 5, 1]
def go_deep(quantity, coins, change):
print('STATUS: quantity: {}, coins:{}, change:{}'.format(quantity, coins, change))
if quantity <= 0: return change
n = quantity // coins[0]
change[coins[0]] = n
quantity -= n*coins[0]
... |
6ee354648d87ca74e3a5c3776c70741bed442799 | Zetinator/just_code | /python/leetcode/candies.py | 3,186 | 3.984375 | 4 | """https://www.hackerrank.com/challenges/candies/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=dynamic-programming
Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a... |
7353020b0f9f4e876ad39334bad7953aa1096b44 | Zetinator/just_code | /python/leetcode/max_min.py | 965 | 3.953125 | 4 | """https://www.hackerrank.com/challenges/angry-children/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=greedy-algorithms
Complete the maxMin function in the editor below. It must return an integer that denotes the minimum possible value of unfairness.
maxMin has ... |
44b2c2a5ef7e890d3f38b6ccb1e990ed668930d2 | Zetinator/just_code | /python/data_structures/max_heap.py | 3,645 | 3.875 | 4 | """custom implementation of a max heap tree with the purpose of practice
the ADT contains the following methods:
- push
- peek
- pop
"""
class Heap():
def __init__(self, x=[]):
self.v = []
for e in x:
self.push(e)
def __len__(self):
return len(self.v)
def __... |
e2b8fe6ba7d4d000b5ef8578aae3caf1847efc9d | Zetinator/just_code | /python/leetcode/unique_email.py | 1,391 | 4.375 | 4 | """
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name p... |
c80ef444ca25f5a4a263ef68b3dfdab39aa85c89 | santiagoahc/coderbyte-solutions | /medium/swapII.py | 513 | 3.5 | 4 | def SwapII(str):
new_str = []
last_digit = (None, -1)
for i, s in enumerate(str):
if s.isalpha():
s = s.lower() if s.isupper() else s.upper()
elif s.isdigit():
if last_digit[0]:
new_str[last_digit[1]] = s
s = last_digit[0]
last_digit = (None, -1)
elif i+1 < len(st... |
b1310efca71f5bf0d3daa2d0ae9135a0edc70382 | santiagoahc/coderbyte-solutions | /medium/bracket_matcher.py | 711 | 3.96875 | 4 | def BracketMatcher(str):
round_brackets = 0
square_brackets = 0
total_pairs = 0
for s in str:
if s == '(':
round_brackets += 1
total_pairs += 1
elif s == ')':
if round_brackets < 1:
return 0
round_brackets -= 1
elif s == '[':
squa... |
a8b5da625783c4dc555005d83ebb04dbea1b4e50 | santiagoahc/coderbyte-solutions | /medium/most_free_time.py | 1,603 | 4.09375 | 4 | """
Using the Python language, have the function MostFreeTime(strArr) read the strArr parameter being passed which will represent a full day and will be filled with events that span from time X to time Y in the day. The format of each event will be hh:mmAM/PM-hh:mmAM/PM. For example, strArr may be ["10:00AM-12:30PM","0... |
91f2f7d0ab659ac5454438737642142c3c18af15 | santiagoahc/coderbyte-solutions | /hard/bitch.py | 2,860 | 3.625 | 4 | def gcd(a, b):
while a % b:
a, b = b, a % b
return b
def frac_reduce(num, den):
g = gcd(num, den)
return (num/g, den/g)
class Fraction:
def __init__(self, num, den=1):
self.num, self.den = frac_reduce(num, den)
def __neg__(self):
return Fraction(-self.num, self.den)
... |
70d7c7e63e2c431192dafc2df18f86ef0551541d | santiagoahc/coderbyte-solutions | /members/kaprekars.py | 1,338 | 3.671875 | 4 | """
Using the Python language,
have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits.
Your program should perform the following routine on the number:
Arrange the digits in descending order and in ascending order (adding zeroes to... |
c685e5a1b88a50e5206e108c18453cd8206aa855 | santiagoahc/coderbyte-solutions | /medium/polish notation.py | 633 | 3.984375 | 4 | """
"+ + 1 2 3"
expr is a polish notation list
"""
def solve(expr):
"""Solve the polish notation expression in the list `expr` using a stack.
"""
operands = []
# Scan the given prefix expression from right to left
for op in reversed(expr):
if op == "+":
operands.append(operand... |
0bca43812f3d8fcf893ca985c8f5f7db76335a25 | santiagoahc/coderbyte-solutions | /medium/arith_geo.py | 810 | 3.609375 | 4 | __author__ = 'osharabi'
def ArithGeoII(arr):
if len(arr) <= 1:
return -1
diff = arr[1] - arr[0]
mult = arr[1] / arr[0]
i = 1
while (i+1) < len(arr) and not (diff is None and mult is None):
cur_diff = arr[i+1] - arr[i]
curr_mult = arr[i+1] / arr[i]
if cur_diff != di... |
292d7fcf6be00f2e22950fc9af2abc9f6493bf0d | santiagoahc/coderbyte-solutions | /medium/three_five_mult.py | 130 | 3.875 | 4 | def ThreeFiveMultiples(num):
return sum([n for n in range(3, num) if (n % 3 == 0 or n % 5 == 0)])
print ThreeFiveMultiples(16)
|
2a2acbc1e8bf446dd7b8ac5582d9faa5f4f7f51b | nbonfils/fixed-probe | /sensor-server.py | 6,956 | 3.5625 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""Server that reads values from differents sensors.
This script is a server that is supposed to run on a RPi with the
adequate sensors hooked to it via GPIO.
It reads the value of the sensors then store them on disk or on
the usb drive if one is plugged, it also always expo... |
ca54ebba62347e2c3a4107872889e4746c51a922 | malbt/PythonFundamentals.Exercises.Part5 | /anagram.py | 497 | 4.375 | 4 | def is_anagram(first_string: str, second_string: str) -> bool:
"""
Given two strings, this functions determines if they are an anagram of one another.
"""
pass # remove pass statement and implement me
first_string = sorted(first_string)
second_string = sorted(second_string)
if first_string... |
c093ea69bbcc1a304b3d9d65580f3930ac9aeefc | jpages/twopy | /tests/quick_sort.py | 987 | 3.96875 | 4 | import random
# Very inefficient bubble sort
def bubble_sort(array):
for i in range(len(array)):
for j in range(i, len(array)):
if array[i] > array[j]:
# Swap these elements
temp = array[i]
array[i] = array[j]
array[j] = temp
... |
e7e5c25404dcbd2c211d1ac67d59909bc48c81f7 | jpages/twopy | /tests/sum35.py | 917 | 3.75 | 4 | def sum35a(n):
'Direct count'
# note: ranges go to n-1
return sum(x for x in range(n) if x%3==0 or x%5==0)
def sum35b(n):
"Count all the 3's; all the 5's; minus double-counted 3*5's"
# note: ranges go to n-1
return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))
def sum35c(n)... |
7530cd3094d1a69ac8a8ec7f8aff2555875167ba | Fashgubben/TicTacToe | /test_program.py | 12,276 | 3.578125 | 4 | import unittest
import check_input
import check_for_winner
import game_functions
from class_statistics import Statistics, Player
from random import randint
class TestCases(unittest.TestCase):
"""Test "check_input" functions"""
def test_strip_spaces(self):
test_value1 = '1 1 '
... |
a3ee45b658838526491e85141bc219b4e8a8d31e | Vipulhere/Python-practice-Code | /Module 10/3.1 insertinto.py | 322 | 3.796875 | 4 | import sqlite3
conn=sqlite3.connect("database.db")
query="INSERT into STD(name,age,dept)values ('bob',20,'CS');"
try:
cursor=conn.cursor()
cursor.execute(query)
conn.commit()
print("Our record is inserted into database")
except:
print("Error in database insert record")
conn.rollback()
conn.close... |
cc779c69d84dc9ea2afc1249646caef9f589c15e | Vipulhere/Python-practice-Code | /Module 3/12.1 loops with else block of code.py | 254 | 4.0625 | 4 | for a in range(5):
print(a)
else:
print("The loop has completed execution")
print("_______________________")
t=0
n=10
while (n<=10):
t=t+n
n=n+1
print("Value of total while loop is",t)
else:
print("You have value is equal to 10") |
e777115b8048caa29617b9b0e99d6fbac3beef99 | Vipulhere/Python-practice-Code | /Module 8/11.1 inheritance.py | 643 | 4.3125 | 4 | #parent class
class parent:
parentname=""
childname=""
def show_parent(self):
print(self.parentname)
#this is child class which is inherites from parent
class Child(parent):
def show_child(self):
print(self.childname)
#this object of child class
c=Child()
c.parentname="BOB"
c.childname=... |
3db13f56cd5cac39e2e32ba3a5aa460d3cd957c4 | Vipulhere/Python-practice-Code | /Module 8/7.1 object method.py | 237 | 3.84375 | 4 | class car:
def __init__(self,name,color):
self.name=name
self.color=color
def car_detail(self):
print("Name of car",self.name)
print("Color of car",self.color)
c=car("ford","white")
c.car_detail() |
e549aca0a2c1b27dcde960f56b65da2eb6632fbd | Vipulhere/Python-practice-Code | /Module 6/6.1 tuple.py | 169 | 3.75 | 4 | tuple=()
tuple2=(1,2,3,4,5,6)
tuple3=("python","java","php")
tuple4=(10,20,"java","php")
print(tuple)
print(tuple2)
print(tuple3)
del tuple3
print(tuple3)
print(tuple4)
|
bcabbb2b0ed927d608c3bd8a832aded14e53738f | Vipulhere/Python-practice-Code | /Module 7/2.1 exception handling.py | 209 | 3.796875 | 4 | try:
text=input("Enter a value or something you like")
except EOFError:
print("EOF Error")
except KeyboardInterrupt:
print("You cancelled the operation")
else:
print("you enterd".format(text))
|
5e9af0fd6c370d21c0ce17a5d6ccffad245abaf2 | Vipulhere/Python-practice-Code | /Module 8/16.1 encapsulation.py | 609 | 3.890625 | 4 | class encapsulation:
__name=None
def __init__(self,name):
self.__name=name
def getname(self):
return self.__name
e=encapsulation("Encapsulation")
print(e.getname())
print("________________")
class car(object):
def __init__(self,name="BMw",year=2020,mileage="250",color="white"):
... |
f37f6cfbbe1ca3542992c7a6673284d9b59666a1 | Vipulhere/Python-practice-Code | /Module 6/17.1 sort a dict.py | 172 | 3.921875 | 4 | dict={
"BMW":"2020",
"Ford":"2019",
"Toyota":"2018",
"BMW": "2012",
"Honda": "2015"
}
for key1 in sorted(dict,key=dict.get):
print(key1,dict[key1]) |
391625ce1ccb63a4471ba41a184c346114168c46 | Vipulhere/Python-practice-Code | /Module 2/5.1 Short Hand of operator.py | 83 | 3.71875 | 4 | var=2
var+=10
print(var)
var*=10
print(var)
var/=10
print(var)
var-=10
print(var) |
7b49801dcfbc7feeadb92bf9a9c8de86a7a90d48 | Vipulhere/Python-practice-Code | /Module 3/5.1 nested if else.py | 137 | 3.6875 | 4 | var=-10
if var>0:
print("Postive Number")
else:
print("Negative Number")
if -10<=var:
print("Two Digit are Negative") |
3c2b47f35531074d47b6e3022ae94d8c30d5e99d | Vipulhere/Python-practice-Code | /Module 8/2.1 Classes and Object.py | 170 | 3.921875 | 4 | class car:
model=2020
name="ford"
c=car()
print(c.model,c.name)
class animal:
age=20
name="dog"
color="Black"
a=animal()
print(a.name,a.age,a.color) |
3e49fd765e0672df380c18249f1b1cada092b1d9 | pivacik/leetcode-algorithms | /plan_calc.py | 272 | 3.71875 | 4 | import sys
def calculate_plan(a, b, c, d):
if d > b:
return a + c * (d - b)
else:
return a
string = ''
for line in sys.stdin:
string += line
lst = list(string.split())
a, b, c, d = lst
print(a, b, c, d)
print(calculate_plan(a, b, c, d))
|
aae533ba404018f1c31e8fb949d44741fc54c792 | frigusgulo/F4_Architecture | /VM_Control_Only.py | 1,540 | 3.71875 | 4 |
def Main():
pass
# VM Control
def goto(labelname):
return "@" + str(labelname) + "\n0;JMP\n"
def if_goto(labelname):
return pop_D() + "D=D+1\n@" + str(labelname) + "\nD;JGT\n"
# my understanding is if-goto jumps if top of stack is -1 (true) i.e. pop_D() + D=D+1 + D;JEQ
def label(labelname):
retu... |
78f055ae60f4eaa45424f8f9dea223ff1d5c667c | yukimiii/competitive-programming | /typical90/solved/75.py | 378 | 3.703125 | 4 | def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
n = int(input())
a=prime_factorize(n)
b=len(a)... |
b8585391d0425578a059c18ccd8399eaa4db1581 | Bullsquid/gitTask-1 | /halves.py | 693 | 3.8125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def min_halves(f, a, b, eps):
if b < a:
tmp = a
a = b
b = tmp
t = np.arange(a-1.0, b+1.0, 0.02)
right = []
left = []
plt.plot(t, f(t))
while b-a >= eps:
center = (a + b) / 2.0
delta = (b-a) / 4.0
... |
b0032fa5aa5281354ec4cd92162dc9ac2e1e2e78 | lohe987/ECE366Group4Project3 | /simulator_z.py | 5,921 | 3.640625 | 4 | import sys
import collections
# Class CPU will hold the information of the CPU
class CPU:
PC = 0 # Program Counter
DIC = 0 # Insturction Counter
R = [0] * 4 # Register Values
instructions = [] # instructions in array
memory = [] # memory in array
def check_parity_bit(machine_line):
# Count the... |
1dd2bc4d81e2f09a5dec71127ac5eade13be3dd8 | mayanksingh2233/ML-algo | /ML Algorithms/linear regression.py | 899 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # linear regression
# In[17]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# In[115]:
df=pd.read_csv('E:\\python\\datasets\\cars.csv',delimiter=';',skiprows=[1])
df.head()
# In[118]:
x=df[['Displacement']]
x
# In[120]:
y=df[['Acceleration... |
b59bb752bfdc1b3fdd2c2f2c961b79b27dcc9188 | 935375572/python_study | /1基础/13成员运算符in_notin.py | 146 | 3.65625 | 4 | # in 判断数据是否在序列之中
# not in 判断数据是否不再序列中
numbers = ["A", "B", "C"]
if "B" in numbers:
print("对的") |
3a40e487e84bdd009f31a2606a1261bf8d81ebaf | 935375572/python_study | /1基础/4在字符串上使用乘法.py | 563 | 3.78125 | 4 | info = "msg" * 5 # 重复5遍
print(info)
"""使用与逻辑运算符 and"""
name = "张三"
age = 13
result = name == "张三" and age == 13
print(result)
"""使用或逻辑运算符 or"""
name = "张三"
age = 13
result = name == "张三" or age == 13
print(result)
"""使用非逻辑运算符 and"""
name = "张三"
age = 13
result = not age == 13
print(result)
"""身份运算符:通过一个id()函数以获取数... |
883c2914bec7eb100a9d1eb5be239b04793af6d9 | 935375572/python_study | /1基础/3定义布尔型变量.py | 610 | 3.828125 | 4 | flag = True
print(type(flag)) # 获取变量的类型
if flag:
print("你好啊老哥") # 条件满足时执行
"""字符串的连接操作"""
info = "hello"
info = info + "world"
info += "python"
info = "优拓软件学院\"www.yootk.com\"\n\t极限IT程序员:\'www.jixianit.com\'"
print(info)
"""input()函数 获取键盘输入的数据"""
msg = input("请输入你的内容:")
wc = int(msg) # 将字符串转为int类型
if wc > 12:
... |
13398c4ff7dad957ac14f32791f942f9c9ed4b58 | AlSakharoB/easy_list_v1 | /ft_even_index_list.py | 265 | 3.640625 | 4 | def ft_len_mass(mass):
count = 0
for i in mass:
count += 1
return count
def ft_even_index_list(mass):
mass1 = []
for i in range(ft_len_mass(mass)):
if i % 2 == 0:
mass1.append(mass[i])
return mass1
|
13e0b3ecf515c7e7f35e947e6ae523eb40320e5e | sraghus/Python_examples | /triangle.py | 440 | 3.625 | 4 | #!usr/bin/env python
#import modules used here - sys is a very standard one
import sys
def area(base, height):
return (base * height) / 2
if __name__ == '__main__':
print('Area :', area(12,23))
def perimeter(side1, side2, side3):
return (side1 + side2 + side3)
if __name__ == '__main__':
print ('Perimet... |
979fb7ce2ecbf9672d9674f8da264b6e3d870e50 | chelseasenter/custom-dice-roller | /dice.py | 6,846 | 3.515625 | 4 | import random
run='y'
while run == 'y':
## introduction for user --------------------------------------------------------------------------------------------
# print(".")
# print(".")
# print(".")
# print(".")
# print(".")
# print(".")
# print(".--------------------------------------------... |
854bb5826a378627b9041b230607e51da2905cd8 | tberhanu/green_book | /ch2_LinkedLists/check_llist_palindrome.py | 772 | 3.984375 | 4 | # from LinkedList import LinkedList
def check_llist_palindrome(llist):
curr = llist
runner = llist
stack = [] #In python we use 'lists' as 'stacks'
while runner and runner.next:
stack.append(curr.data)
curr = curr.next
runner = runner.next.next
if runner:
curr = curr.next
while curr:
top = stack.pop()
... |
b1858530c96c0ff053d78237695ac3764ccc5362 | tberhanu/green_book | /ch1_Arrays&Strings/check_permutation3_counter.py | 690 | 3.859375 | 4 | from collections import Counter
def check_permutation3_counter(str1, str2):
if len(str1) != len(str2):
return False
cntr1 = Counter(str1) #gives a dictionary of each CHAR:FREQUENCY
cntr2 = Counter(str2)
for key1 in cntr1:
for key2 in cntr2:
if key1 == key2 and cntr1[key1] != cntr2[key2]:
return False
... |
4380cb3cb4bbdace75f27ff7059a0505e17687b7 | ToxaRyd/WebCase-Python-course- | /7.py | 1,757 | 4.3125 | 4 | """
Данный класс создан для хранения персональной (смею предположить, корпоративной) информации.
Ниже приведены doc тесты/примеры работы с классом.
>>> Employee = Person('James', 'Holt', '19.09.1989', 'surgeon', '3', '5000', 'Germany', 'Berlin', 'male')
>>> Employee.name
James Holt
>>> Employee.age
29 years ... |
eb44d31501175cf09d4eac5bfc3ab2e8784168f9 | jasonfhill/cronwatch | /app/utils.py | 1,391 | 3.953125 | 4 | import os
import re
import sys
_filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]')
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode
else:
text_type = str
def secure_filename(filename):
r"""Pass it a filename and it will return a secure version of it. This
filename can then safely be... |
d5532a8bf440890fd844ee1f0cdd02f06ea4dc55 | ckfChao/My-First-git-Repository | /main.py | 451 | 3.953125 | 4 | from op import op
#input
a = int(input("Enter value of a:"))
input_op = input("Enter operater:")
b = int(input("Enter value of b:"))
calc = op(a, b)
if (input_op == "+"):
print("%d + %d = %d"%(a, b, calc.add()))
elif (input_op == "-"):
print("%d - %d = %d"%(a, b, calc.sub()))
elif (input_op == "*"):
prin... |
9efdeb16d054511cf515531db3eb805fc690f4a5 | logchi/scrach_zone | /python/data_structure_algorithms/breath_first_serach.py | 1,055 | 3.78125 | 4 | from collections import deque
def search_queue(graph, dq, right, searched=[]):
def addnextlevel(dq, node):
next_level = graph.get(node)
if next_level:
dq += next_level
if dq:
node = dq.popleft()
if node in searched:
return search_queue(graph, dq, right,... |
0147ba4f123a05170e4ed99fea9f2741974301e4 | akashzcoder/coding_discipline | /CoderPro/day3/solution.py | 413 | 3.53125 | 4 | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return self._permute_helper(nums, [])
def _permute_helper(self, nums: list, values: list = []) -> list:
if len(nums) == 0:
return [values]
result = []
for i in range(len(nums)):
result... |
4fe543b01436500dd6ca7b3d2ff27746fc2508a5 | Wibbo/voting | /main.py | 240 | 3.515625 | 4 | from election import election
choices = ['Salad', 'Burger', 'Pizza', 'Curry', 'Pasta', 'BLT']
campaign = election(300, choices)
print('NEW ELECTION')
print(f'Number of voters is {campaign.voter_count}')
print(campaign.vote_counts)
|
9ae6c4d2f37119e7f90db29b3db050b40d5dff8b | nnicexplsz/python | /Work/test4.py | 606 | 3.578125 | 4 | a = input('enter number 1 \n')
b = input('enter number 2 \n')
c = input('enter number 3 \n')
d = input('enter number 4 \n')
c = input('enter number 5 \n')
a1 = float(a)
a2 = complex(a)
a3 = float(b)
a4 = complex(b)
a5 = float(c)
a6 = complex(c)
a7 = float(d)
a8 = complex(d)
a9 = float(c)
a10 = complex(c)
print('float o... |
fcedb2e85cb1283c77421a2f9aed8fd1b77af591 | nnicexplsz/python | /Work/4_2.py | 2,336 | 3.8125 | 4 | t = 5
vocadulary = {
"rose apple":" n.คำนาม ชมพู่ ",
"keyboard":" n.คำนาม คีย์บอร์ด",
"drink":" v.คำกริยา ดื่ม ",
"speak":" v.คำกริยา พูด",
"These":" adj.ขยายคำนาม พวกนี้",
}
while(True):
print("พจนานุกรม\n 1)เพิ่มคำศัพท์\n 2)แสดงคำศัพท์\n 3)ลบคำ... |
f46ef7a473eaa019a376c7312864168d63e06ef5 | nnicexplsz/python | /week3/week3_2.py | 896 | 3.703125 | 4 | value = int(input("กรุณากรอกจำนวนครั้งการรับค่า")) # แบบฝึกหัด 3.2
i = 1
a = 0
while(i <= value) :
number = int(input("กรอกตัวเลข :"))
i=i+1
a=a+number
print("ผลรวมที่รับค่ามาทั้งหมด = %d"%a)
print("ป้อนชื่ออาหารโปรดของคุณ หรือ exit เพื่อออกจากโปรแกรม")
foodlist[]
i = 0
while(True):
i = i +1
prin... |
b3f0da91062c2cef4b18f75077bacb5b9b555d02 | JFincher42/RandomStuff | /sairam-test.py | 493 | 3.53125 | 4 | import pygame
pygame.init()
window = pygame.display.set_mode([500,500])
x_speed = 7
y_speed = 3
b_x = 15
b_y = 15
frames = 0
while frames < 750:
frames += 1
b_x += x_speed
b_y += y_speed
if b_x >= 485:
b_x = 15
elif b_x <= 15:
b_x = 485
if b_y >= 485:
b_y = 15
e... |
e66d6267baedca2ed407055dec553fc524811e0c | abhinavgairola/PowerSimData | /powersimdata/utility/helpers.py | 3,071 | 3.59375 | 4 | import copy
import importlib
import os
import sys
class MemoryCache:
"""Wrapper around a dict object that exposes a cache interface. Users should
create a separate instance for each distinct use case.
"""
def __init__(self):
"""Constructor"""
self._cache = {}
def put(self, key, o... |
68f964fde72113fea68ff42de7cb33db2e7f4e86 | abhinavgairola/PowerSimData | /powersimdata/utility/distance.py | 2,790 | 3.703125 | 4 | from math import acos, asin, cos, degrees, radians, sin, sqrt
def haversine(point1, point2):
"""Given two lat/long pairs, return distance in miles.
:param tuple point1: first point, (lat, long) in degrees.
:param tuple point2: second point, (lat, long) in degrees.
:return: (*float*) -- distance in mi... |
c210c723687f3b80583ad336bcdbc0b9f737af0d | mytbk/xgboost-learning | /convert_data.py | 895 | 3.5625 | 4 | #!/usr/bin/env python2
import pandas
import sys
from types import *
def getDataFromCSV(csv):
table = pandas.read_csv(csv)
column_names = table.columns
working = pandas.DataFrame()
for col in column_names:
print(col)
if type(table[col][0]) is not StringType:
... |
308f36d76762dfc539ff391c11c3464963ac7e4c | mattbaumann1/contractors | /main.py | 1,173 | 3.96875 | 4 | #!/usr/bin/python3
# main.py authored by Matt Baumann for COMP 412 Loyola University
#The following video was very helpful for this assignment: https://www.youtube.com/watch?v=mlt7MrwU4hY
import csv
#Creation of list objects.
contractorList = []
lobbyistList = []
#Reading in the contractorList with contracts for ... |
f7269f85dbc1ec9a43880f49efa09b193e080aee | bopopescu/PycharmProjects | /shashi/7) Mebership & indentity operators.py | 1,117 | 4.0625 | 4 | # Membership Operators 15/05/2018
#a = '1'
#if (a === 1):
# print(a)
#if(a == '1'):
# print(a)
'''l1 = [1,2,3,4]
if 1 in l1:
print(1 in l1)
d1 = {'a': 1 , 'b': 2}
print('a' in d1)
print('aa' in d1)
print('a' not in d1)
print('aa' not in d1)'''
# Indentity operators
'''a = 1
print(a is 1)
print(a is not... |
347460f3edf3af4e5601a45b287d1a086e1a3bc3 | bopopescu/PycharmProjects | /Class_topic/7) single_inheritance_ex2.py | 1,601 | 4.53125 | 5 | # Using Super in Child class we can alter Parent class attributes like Pincode
# super is like update version of parent class in child class
'''class UserProfile(Profile): # Child Class
def __init__(self,name,email,address,pincode): # constructor of child Class
super(UserProfile, self).__init__(name,email... |
55f9eb36b8d77e7adfa28e1d27a5922dfddf1206 | bopopescu/PycharmProjects | /shashi/17) ExceptionHandling_try& _except.py | 840 | 4 | 4 | '''try:
int("sds")
print(name)
name = "aaaa"
open('dddddd')
import asdfg
print("went good...")
except (NameError, ValueError, ImportError):
print("something went Wrong")
except NameError:
print("NameError")
#except:
except ValueError:
print("exception")
except ImportError:
pr... |
2329f20248f4ab62b23828caae234b23dad10ab8 | bopopescu/PycharmProjects | /shashi/14) import_3_methods & packages .py | 552 | 3.515625 | 4 | # import 3 methods
# 1) import PackageName
'''import test
print(test.email)
test.name()'''
# 2) from PackageName import VarName ,functions ,Classes
'''from test import name,email
name()
print((email))'''
# 3) from PackageName import *
'''from test import *
name()
print(email)'''
# 4) from PackageName import VarN... |
6a6b1394a960ba09ff2c97fa71e61b78a1c45858 | bopopescu/PycharmProjects | /shashi/10) functions_1( lambda) .py | 1,902 | 4.25 | 4 | #Nested function
'''def func1():
def func2():
return "hello"
return func2
data = func1()
print(data())'''
#global function
'''a = 100
def test():
global a # ti use a value in function
a = a + 1
print(a)
#print(a)
test()'''
'''a = 100
def test():
global a # ti use a value in function... |
ee3776a9a10899adb7ca4e6979145114c979dabf | bopopescu/PycharmProjects | /Class_topic/class_assigment.py | 351 | 3.75 | 4 | '''class A:
def __init__(self,file):
self.file = open("Demo")
data = self.file.read()
print(data)
def f1(self,f):
m = input("enter a string")
self.f = open("demo")as w:
self.f = m.writeable()
def __del__(self):
print("i am here")
a = A("file2")
te... |
2001b07997daf96893b9885f14bff85c97f59d2d | danniekot/programming | /Practice/21/Python/21.py | 281 | 3.875 | 4 | def BMI(weight: float, height: float):
return weight/(height*height/10000)
def printBMI(bmi: float):
if BMI < 18.5 print('Underweight')
elif BMI < 25 print('Normal')
elif BMI < 30 print('Overweight')
else print('Obesity')
w,h=map(float,input().split())
printBMI(BMI(w,h)) |
1f6a9e033c3a3b8c5c278cb4a96d5900ef8a994e | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/optional-labs/roadtrip/roadtrip-v1.py | 1,130 | 4.15625 | 4 | city_dict = {
'Boston': {'New York', 'Albany', 'Portland'},
'New York': {'Boston', 'Albany', 'Philadelphia'},
'Albany': {'Boston', 'New York', 'Portland'},
'Portland': {'Boston', 'Albany'},
'Philadelphia': {'New York'}
}
city_dict2 = {
'Boston': {'New York': 4, 'Albany': 6, 'Portland': 3},
'New York': {'... |
0f6a5f4930f4a7ef9ce28e4fe790d79b1e77561b | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/lab15/lab15-number-to-phrase-v2.py | 1,819 | 3.984375 | 4 | '''
lab15-number-to-phrase-v2
Version2:
Handle numbers from 100-999
'''
print("Welcome to Number to Phrase v2.0. We'll convert your number between 0-999 to easily readable letters.")
while True:
n = int(input("Please enter an integer between 0 and 999: "))
if n not in range(0, 1000):
print("Please e... |
7c693a0fe73b2fe3cbeeddf1551bf3d2f0250ab2 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/lab12/lab12-guess_the_number-v3.py | 694 | 4.34375 | 4 | '''
lab12-guess_the_number-v3.py
Guess a random number between 1 and 10.
V3
Tell the user whether their guess is above ('too high!') or below ('too low!') the target value.'''
import random
x = random.randint(1, 10)
guess = int(input("Welcome to Guess the Number v3. The computer is thinking of a number between 1 and ... |
ffa71514a68193fcebd2c4939dfeaa28529d5f75 | pjz987/2019-10-28-fullstack-night | /Assignments/dj/lab10-v1.py | 390 | 4.09375 | 4 | """
Name: DJ Thomas
Lab: 11 version 1
Filename: lab10-v1.py
Date: 10-31-2019
Lab covers the following:
- input()
- float()
- for/in loop
- fstring
- range
"""
num = int(input("how many numbers?: "))
total_sum = 0
for i in range(num):
numbers = float(input('Enter number: '))
total_sum +=... |
f4da5503cbbf47772f9bcccdbfc7487c6efdc13f | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab14-gambling_pick6v2.py | 2,237 | 4.09375 | 4 | '''
lab14-pick6-v1.py
v2
The ROI (return on investment) is defined as (earnings - expenses)/expenses. Calculate your ROI, print it out along with your earnings and expenses.
'''
#1.Generate a list of 6 random numbers representing the winning tickets...so define a pick6() function here.
import random
def pick6():
ti... |
82ef1519965203526bf480fc9b989e73fb955f54 | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab17-palidrome_anagramv2.py | 312 | 4.5625 | 5 | # Python Program to Check a Given String is Palindrome or Not
string = input("Please enter enter a word : ")
str1 = ""
for i in string:
str1 = i + str1
print("Your word backwards is : ", str1)
if(string == str1):
print("This is a Palindrome String")
else:
print("This is Not a Palindrome String") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.