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 |
|---|---|---|---|---|---|---|
0aca792ff94330e304c5ebfa836d88a53e00b0d5 | jke-zq/my_lintcode | /Sort Colors II.py | 2,813 | 3.546875 | 4 | class Solution:
"""
@param colors: A list of integer
@param k: An integer
@return: nothing
"""
def sortColors2(self, colors, k):
# write your code here
# def helper(start, end, kstart, kend, colors):
# if kstart >= kend or start >= end:
# return
... |
e7deb4de032c109bfc552e93888ce0e74da6147d | jke-zq/my_lintcode | /Tweaked Identical Binary Tree.py | 779 | 4 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param a, b, the root of binary trees.
@return true if they are tweaked identical, or false.
"""
def isTweakedIdentical(self, a, b):
... |
10a51c8544b7dd713b7d107a59c56ca1342a7f3d | jke-zq/my_lintcode | /Insertion Sort List.py | 1,263 | 3.953125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of linked list.
"""
def insertionSortList(self, head):
# write yo... |
6bf431880aa9181b7b4db9bec2b98c633be6977b | jke-zq/my_lintcode | /Ugly Number II.py | 687 | 3.5625 | 4 | import heapq
class Solution:
"""
@param {int} n an integer.
@return {int} the nth prime number as description.
"""
def nthUglyNumber(self, n):
# write your code here
ans = [1]
factors = [2, 3, 5]
times = [0] * len(factors)
values = []
for i in... |
a26f915fbc8f1239d40f56c382a64079798a848b | jke-zq/my_lintcode | /Number of Airplanes in the Sky.py | 727 | 3.734375 | 4 | """
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
# @param airplanes, a list of Interval
# @return an integer
def countOfAirplanes(self, airplanes):
# write your code here
airs = []
... |
986002310e86fe8863f0bf202682e0bb1a45a2d0 | jke-zq/my_lintcode | /Nuts & Bolts Problem.py | 2,019 | 4.03125 | 4 | # class Comparator:
# def cmp(self, a, b)
# You can use Compare.cmp(a, b) to compare nuts "a" and bolts "b",
# if "a" is bigger than "b", it will return 1, else if they are equal,
# it will return 0, else if "a" is smaller than "b", it will return -1.
# When "a" is not a nut or "b" is not a bolt, it will return 2, ... |
db2243fb1c78847358a9e6602fe3e714b987b2b4 | jke-zq/my_lintcode | /Sqrt(x).py | 664 | 4.0625 | 4 | class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# write your code here
left, right = 0, x
while left + 1 < right:
mid = left + (right - left) / 2
if mid * mid <= x:
left = mid
... |
ae96a2e0c735c36a8e9556bb5458c83169151728 | jke-zq/my_lintcode | /Search in Rotated Sorted Array II.py | 2,059 | 3.625 | 4 | class Solution:
"""
@param A : an integer ratated sorted array and duplicates are allowed
@param target : an integer to be searched
@return : a boolean
"""
def search(self, A, target):
# write your code here
if not A:
return False
left, right = 0, len(A) - 1
... |
610166915f6cf184fba95786259e143c548217fa | jke-zq/my_lintcode | /Rehashing.py | 1,204 | 3.796875 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param hashTable: A list of The first node of linked list
@return: A list of The first node of linked list which have twice size
"""
def... |
eeab506beb08c5689d60f046aa721edaa0a295a0 | jke-zq/my_lintcode | /Binary Tree Preorder Traversal.py | 1,575 | 3.828125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Preorder in ArrayList which contains node values.
"""
def preorderTraversal(self, root):... |
5d0260047d4f389d9d78c518c11e2ee83085db9e | jke-zq/my_lintcode | /Construct Binary Tree from Inorder and Postorder Traversal.py | 1,022 | 3.96875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param inorder : A list of integers that inorder traversal of a tree
@param postorder : A list of integers that postorder traversal of a tree
... |
ad310e83dc738c9318e78c685549c3735f52723a | ddxygq/PyCode | /Python基础语法/算法/SortAlgo.py | 2,268 | 3.9375 | 4 | # -*- coding:utf-8 -*-
# 冒泡排序
def bubbleSort(arr):
for i in range(len(arr) - 1):
for j in range(i+1, len(arr)):
if arr[i] > arr[j]:
arr[i],arr[j] = arr[j],arr[i]
# 选择排序
def selectSort(arr):
for i in range(len(arr) - 1):
# 使用变量存储最小元素的index
minIndex = i
for j in range(i+1, len(arr)):
if arr[minInd... |
652fe49d11f5fb18e15cbad5085f680d3aed13a0 | ddxygq/PyCode | /Python基础语法/面向对象/senior_object.py | 579 | 3.875 | 4 | # 面向对象高级
class Teacher(object):
# 限制该类能动态添加的属性
__slots__ = ('name', 'age')
pass
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
if __name__ == '__main__':
teacher = Teacher()
# 给实例绑定方法
from types import MethodType
teacher.set_name = MethodTy... |
a21e2a40f49e48372fbeb400a24219b7ae657fb1 | DrydenHenriques/50-coding-interview-questions | /bit/33_Bit-Int-Modulus.py | 476 | 3.578125 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/27'
Given a list of bytes a, each representing one byte of a larger integer (ie. {0x12, 0x34, 0x56, 0x78} represents the integer 0x12345678), and an integer b, find a % b.
mod({0x03, 0xED}, 10) = 5
'''
def mod(bits, num):
res = 0
fo... |
5749bc33bc6565336b29598ef3ec651190a7346f | DrydenHenriques/50-coding-interview-questions | /recursion/24_Balanced-Binary-Tree.py | 704 | 4.09375 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/2/17'
Given a binary tree, write a function to determine whether the tree is balanced.
- all branches are same height(±1).
- all subtrees are balanced.
'''
class TreeNode(object):
def __init__(self, val, left=None, right=None):
se... |
0685929c6aefd5016521602eded7981f46d9e19f | DrydenHenriques/50-coding-interview-questions | /stack/28_Sort-Stacks.py | 772 | 3.96875 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/26'
Given a stack, sort the elements in the stack using one additional stack.
'''
def sort1(stack):
# two additional stacks
buf1, buf2 = [], []
while stack:
top = stack.pop()
while buf1 and buf1[-1] > top:
... |
8fa7b4b95e0fd65016df733a187f1794bab79367 | DrydenHenriques/50-coding-interview-questions | /array/06_Zero-Matrix.py | 1,154 | 3.890625 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/24'
Given a boolean matrix, update it so that if any cell is true, all the cells in that row and column are true.
[true, false, false] [true, true, true ]
[false, false, false] -> [true, false, false]
[false, false, false] [tr... |
86e16a7c1ea92437fcbaceec30dae0f4558ddf56 | DrydenHenriques/50-coding-interview-questions | /bit/34_Swap-Variables.py | 506 | 4.09375 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/27'
Given two integers, write a function that swaps them without using any temporary variables.
'''
def swap1(num1, num2):
num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2
return num1, num2
def swap2(num1, num2):
... |
df88a89721806474b5792478f2209806defbd69c | DrydenHenriques/50-coding-interview-questions | /array/07_Square-Submatrix.py | 1,721 | 3.609375 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/24'
Given a 2D array of 1s and 0s, find the largest square subarray of all 1s.
subarray([1, 1, 1, 0]
[1, 1, 1, 1]
[1, 1, 0, 0]) = 2
'''
def subarray1(matrix):
# brute
if not matrix or not matrix[0]:
return ... |
261769794d54cf67e348842dd778fb8fda97abe2 | tau49/Lommeregner | /Lommeregner.py | 1,067 | 4.0625 | 4 | import Divider
import Gange
import Plus
import Minus
while(True):
print("[1] Divider")
print("[2] Gange")
print("[3] Plus")
print("[4] Minus")
Choice = input("Please choose an option")
if Choice == "1":
number1 = int(input("Choose the first number"))
number2 = int(input("Choose t... |
7fb3399b4a0a07395ce5be57e062dca4b4fdaf90 | MakDon/toy_calculator | /toy_calculator_python/test.py | 2,511 | 3.875 | 4 | import unittest
from calculator import Calculator
calculator = Calculator()
class TestCalculator(unittest.TestCase):
def test_calculate0(self):
question = "1+2+3+5+7"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate01(self):
question = "11.5+12.5+3... |
b2ca6afbd9940a891d59ed0164ce7cb3d13921a0 | sebastianrmirz/collaborative-filterting | /collab.py | 731 | 3.53125 | 4 | import math
def pearsons(r, i, j, num_items):
""" Computes pearsons similarity coefficient
parameters
r -- vector of ratings, where r[i][k] represents the rating user i gave to item k
i -- user i
j -- user j
num_items -- number of items
"""
... |
36987ff25b32b7f90e4fdcddbb0e8067acdbd4ec | saubhagyav/100_Days_Code_Challenge | /DAYS/Day61/Collatz_Sequence.py | 315 | 4.34375 | 4 | def Collatz_Sequence(num):
Result = [num]
while num != 1:
if num % 2 == 0:
num = num/2
else:
num = 3*num+1
Result.append(num)
return Result
if __name__ == "__main__":
num = int(input("Enter a Number: "))
print(Collatz_Sequence(num)) |
a9edafde6f0d863850db43754b465bae1fb20537 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day28/Remove_Tuple_of_length_k.py | 233 | 3.96875 | 4 | def Remove_Tuple(Test_list, K):
return [elements for elements in Test_list if len(elements) != K]
Test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
K = int(input("Enter K: "))
print(Remove_Tuple(Test_list, K))
|
36f35dd3437b55bd7f7ca44373cf578309d23a01 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day29/Leap_Year.py | 325 | 3.9375 | 4 | import calendar
def Leap_Year(Test_input):
count = 0
Result = []
while count < 15:
if calendar.isleap(Test_input):
Result.append(Test_input)
count += 1
Test_input += 1
return Result
Test_input = int(input("Enter Year: "))
print(Leap_Year(Test_inpu... |
e3302797c8258c01afea690eca6bd70cba19fc4d | saubhagyav/100_Days_Code_Challenge | /DAYS/Day48/String_start_with_substring.py | 357 | 3.828125 | 4 | import re
def String_start_with_Substring(Test_string, Test_sample):
Result = "^"+Test_sample
if re.search(Result, Test_string):
return "True"
else:
return "False"
Test_string = "100 Days of Code Challenge makes your basic clear"
Test_sample = "100"
print(String_start_with_S... |
461493440fce1408696e7acc596556c6622232c5 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day22/Size_of_Largest_Subset_in_Anagram.py | 385 | 3.984375 | 4 | from collections import Counter
def Max_Anagram(Test_string):
for i in range(0, len(Test_string.split(" "))):
Test_string[i] = ''.join(sorted(Test_string[i]))
Dict_Frequency = Counter(Test_string)
return max(Dict_Frequency.values())
if __name__ == "__main__":
Test_string = 'ant ma... |
b36a4f25c517fde8bd57a573ec089b41f1bf6839 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day1/Number_is_Fibonacci_or_not.py | 443 | 3.765625 | 4 | import math
def check_Perfect_Square(m):
semifinal = int(math.sqrt(m))
if pow(semifinal, 2) == m:
return True
return False
def fibo(n):
t1 = 5*n*n+4
t2 = 5*n*n-4
if check_Perfect_Square(t1) or check_Perfect_Square(t2):
return True
else:
return False
a = int(input... |
7d05b911c7a34e6f39829c6ed7a7befa7f472829 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day9/Product_of_All_Elements_in_Matrix.py | 354 | 3.546875 | 4 | def Final_Product(Check_list):
Prod = 1
for ele in Check_list:
Prod *= ele
return Prod
def Product_Matrix(Test_list):
Semi_Result = Final_Product(
[element for ele in Test_list for element in ele])
return Semi_Result
Test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
... |
5491efb3841bc753f8de6fff6b0f5233c132a805 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day22/Remove_Duplicates_in_Dictionary.py | 364 | 4.21875 | 4 | def Remove_Duplicates(Test_string):
Test_list = []
for elements in Test_string.split(" "):
if ((Test_string.count(elements) > 1 or Test_string.count(elements) == 1) and elements not in Test_list):
Test_list.append(elements)
return Test_list
Test_string = input("Enter a String: ... |
d2a637895e2db739ff8fa2a691a6fcd0ff3da411 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day69/Triangular_Number.py | 461 | 3.828125 | 4 | def divisor(num):
Result = []
for i in range(1, int(num)):
if num % i == 0:
Result.append(i)
return Result
def triangular_number(num):
count = True
natural = 1
while count:
ctr = (natural*(natural+1))/2
if len(divisor(ctr)) >= num:
... |
da3594bcfad1473e9cb47e5ee182638695d023d3 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day45/Starts_End_with_same_Character.py | 298 | 3.625 | 4 | import re
def Starts_End(Pattern, Test_string):
if re.search(Pattern, Test_string):
print("Valid...")
else:
print("Invalid...")
if __name__ == "__main__":
Pattern = r'^[a-z]$|^([a-z]).*\1$'
Test_string = "abba"
Starts_End(Pattern, Test_string)
|
dc9da0a4798e250e060a08117a204a9bed31c13f | saubhagyav/100_Days_Code_Challenge | /DAYS/Day48/String_Starting_with_Vowel.py | 311 | 3.796875 | 4 | import re
def Vowel_String(Test_string):
pattern = "^[aeiouAEIOU][a-zA-Z0-9]*"
if re.search(pattern, Test_string):
print("Accepted")
else:
print("Discarded")
Test_string1 = "code"
Test_string2 = "expression20"
Vowel_String(Test_string1)
Vowel_String(Test_string2)
|
6233668a16cfacdc34604fd06b72c9310ce10326 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day29/Rabbits_Chicken_Heads_and_Legs.py | 334 | 3.671875 | 4 | def solve(heads, legs):
error_msg = "No solution"
chicken_count = 0
rabbit_count = 0
if legs % 2 != 0:
print("No Solution")
else:
rabbit_count = (legs-2*heads)/2
chicken_count = (4*heads-legs)/2
print(int(chicken_count))
print(int(rabbit_count))
... |
8d88ed7cb958f7e8a9ad0efb1611afdc6142188c | saubhagyav/100_Days_Code_Challenge | /DAYS/Day21/Binary_Representation_of_Two_Numbers_is_Anagram_or_not.py | 562 | 3.96875 | 4 | from collections import Counter
def Check_Binary_Representation(Num_1, Num_2):
Bin_1 = bin(Num_1)[2:]
Bin_2 = bin(Num_2)[2:]
Zeroes = abs(len(Bin_1)-len(Bin_2))
if len(Bin_2) > len(Bin_1):
Bin_1 = Zeroes*'0'+Bin_1
else:
Bin_2 = Zeroes*'0'+Bin_2
Dict_1 = Counter(Bin_1... |
4bd416b64aebef2483ac3d4faeecfc319e80a651 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day27/Size_of_Tuple.py | 384 | 3.640625 | 4 | import sys
Tuple_1 = ("A", 1, "B", 2, "C", 3)
Tuple_2 = ("Geek1", "Satyam", "hey you yeah you", "Tushar", "Geek3", "Aditya")
Tuple_3 = ((1, "Lion"), (2, "Tiger"), (3, "Fox"), (4, "Wolf"))
print(f"Size of Tuple_1: {str(sys.getsizeof(Tuple_1))} bytes")
print(f"Size of Tuple_2: {str(sys.getsizeof(Tuple_2))} bytes")
... |
d6e99faeff373c8ab030181c665115375da3ef2d | saubhagyav/100_Days_Code_Challenge | /DAYS/Day22/Counting_the_Frequency.py | 319 | 4.0625 | 4 | def Counting_the_frequency(Test_list):
Test_dict = {}
for items in Test_list:
Test_dict[items] = Test_list.count(items)
for key, value in Test_dict.items():
print(f"{key} : {value}")
Test_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
Counting_the_frequency(Test_list) |
4f5300f78579e7a9f6025cf18cc39a61c0d629a9 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day28/Occurrences_of_Characters.py | 344 | 3.828125 | 4 | def encode(Test_string):
count = 1
Result = ""
for i in range(len(Test_string)):
if (i+1) < len(Test_string) and (Test_string[i] == Test_string[i+1]):
count += 1
else:
Result += str(count)+Test_string[i]
count = 1
return Result
print(enco... |
7de91698b3caac78d74d5c09c8e338c414db5d51 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day18/Sorting_Dictionary_Using_Itemgetter.py | 509 | 3.625 | 4 | from operator import itemgetter
def Sort_list_Name_and_Age(Test_list):
Test_list.sort(key=itemgetter("Age", "Name"))
return Test_list
def Sort_list_Age(Test_list):
Test_list.sort(key=itemgetter('Age'))
return Test_list
Test_list = [{"Name": "Tushar", "Age": 20},
{"Name":... |
5f8a8d0431696f22ca84bc4a73cf97b39a091507 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day32/Sort_tuple_by_Maximum_Values.py | 209 | 3.625 | 4 | def Sort_Tuple(Test_list):
Test_list.sort(key=lambda Sub: max(Sub), reverse=True)
return Test_list
Test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
print(Sort_Tuple(Test_list))
|
f78a0db46b8f87c58f5b99517121ec59a6eb4c96 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day27/Join_Tuples_if_Similar_initial_elements.py | 323 | 3.75 | 4 | from collections import defaultdict
def Join_Tuples(Test_list):
Result = defaultdict(list)
for key, value in Test_list:
Result[key].append(value)
return [(key, *value) for key, value in Result.items()]
Test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print(Join_Tuples(Test_list)... |
65fe822aaedb3fb8aa89d11c919e7db3ba321474 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day6/Maximum_of_Each_key_in_List.py | 486 | 3.765625 | 4 | def Maximum_Key(Test_list):
Result = {}
for dictionary in Test_list:
for key, value in dictionary.items():
if key in Result:
Result[key] = max(Result[key], value)
else:
Result[key] = value
return Result
Test_list = [{"Days": 8, "Co... |
f2f47ab9d8e116d43c619e88b3db0807b4d658f9 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day10/String_Palindrome.py | 203 | 4.1875 | 4 | def Palindrome(Test_String):
if Test_String == Test_String[::-1]:
return True
else:
return False
Test_String = input("Enter a String: ")
print(Palindrome(Test_String))
|
816b1917aa477d70f2ce4c30323d811ae7896bde | saubhagyav/100_Days_Code_Challenge | /DAYS/Day18/Remove_Keys_from_Dictionary.py | 387 | 4.1875 | 4 | def Remove_Keys(Test_dict, Remove_Value):
return {key: value for key, value in Test_dict.items() if key != Remove_Value}
N_value = int(input("Enter n: "))
Test_dict = {}
for i in range(N_value):
key = input("Key: ")
Value = int(input("Value: "))
Test_dict[key] = Value
Remove_Value = input("W... |
c2ccff1ef8bb8cd4089a941333a125e934139ff1 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day18/Extract_Unique_Dictionary_Values.py | 325 | 3.515625 | 4 | def Extract_Dictionary_Values(Test_dict):
return [sorted({numbers for ele in Test_dict.values() for numbers in ele})]
Test_dict = {'Challenges': [5, 6, 7, 8],
'are': [10, 11, 7, 5],
'best': [6, 12, 10, 8],
'for': [1, 2, 5]}
print(*(Extract_Dictionary_Values(Test_dict... |
52d46272af760df140aa8e4ba0bdaf87e587ed94 | fjsaca2001/proyectosPersonales | /python/funciones.py | 269 | 3.859375 | 4 | def insertar():
lista = []
b = True
while b:
dato = input("Ingrese un dato para agregar a la lista: ")
cond = input("Desea ingresar otro valor y/n: ")
lista.append(dato)
b = True if cond == "y" else print(lista)
insertar()
|
de68e76d6f9ec522b48bd55f48e1c42f2dcd0356 | phully/PythonHomeWork | /day05/Calculator/calculator.py | 4,381 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
该计算器思路:
1、递归寻找表达式中只含有 数字和运算符的表达式,并计算结果
2、由于整数计算会忽略小数,所有的数字都认为是浮点型操作,以此来保留小数
使用技术:
1、正则表达式
2、递归
请计算表达式: 1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
"""
import re
def jj_ys(new_str):
'''加减运算函数'''
... |
9866933ef4f88513e71df0a966ccb7af00eb1e4e | Gkish/Fundamentals-of-data-science | /Assignment 3.py | 8,913 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Assignment 3
#
# Welcome to Assignment 3. This will be even more fun. Now we will calculate statistical measures.
#
# ## You only have to pass 4 out of 7 functions
#
# Just make sure you hit the play button on each cell from top to down. There are seven functions you have ... |
114547be0035b90ea6f8e47883f3d1e62a7e9906 | victonpp/Algoritmos-ADS20171 | /ALGORITMOS/Faça um Programa que leia 20 números inteiros e armazene-os num vetor. Armazene os números pares no vetor PAR e os números IMPARES no vetor impar. Imprima os três vetores.py | 242 | 3.671875 | 4 | numero=[]
par=[]
impar=[]
for i in range (4):
digito=int(input("Digite um número: "))
numero.append(digito)
if (digito%2)==0:
par.append(digito)
else:
impar.append(digito)
print(numero)
print(par)
print(impar) |
9869989a61b358b5372aa0205063cffc47c27842 | victonpp/Algoritmos-ADS20171 | /ALGORITMOS/DESAFIOFaça um algoritmo que leia um número inteiro calcule o seu número de Fibonacci.py | 278 | 3.9375 | 4 | nfinal = 0
while (nfinal <= 0):
nfinal = int(input('Você quer que a série de Fibonacci vá até qual número '))
if (nfinal <= 0):
print('O número deve ser positivo!')
f1 = 1
print (f1)
f2 = 1
for i in range(1, nfinal):
print(f2)
f3 = f1 + f2
f1 = f2
f2 = f3
|
08ff60fcb166b3f5158a437e70015b7929ce61a3 | victonpp/Algoritmos-ADS20171 | /ALGORITMOS/sistema deve perguntar quantos cigarros a pessoa fuma por dia e por quantos anos ela já fuma.py | 154 | 3.71875 | 4 | C=int(input("Quantos cigarros você fuma por dia?"))
D=int(input("Faz quantos anos que você fuma?"))
print("Dias perdidos: %2.0f" %((C*10*365*D)/1440))
|
718d4999826a00c394434ca15ac7a28d8061f0ae | victonpp/Algoritmos-ADS20171 | /ALGORITMOS/O sistema deve informar a o consumo médio (kml).py | 229 | 3.8125 | 4 | k1=int(input("Digite os km no momento em que o tanque é cheio: "))
k2=int(input("Digite os km percorridos: "))
g=int(input("Digite a quantidade necessária para completar o tanque: "))
m=(k2-k1)/g
print("Média de:",m, "km/l ")
|
adfb29dc678d620373b3902a661c9c9148f2c799 | japablaza/DevOps | /Python/101/game02.py | 513 | 3.671875 | 4 | #/usr/bin/python
# Este es el juego de los datos
from random import randint as ri
computador = ri(1,6)
usuario = int(input('Dame un numero entre el 1 y el 6:\n'))
print(f'El computador saco: {computador}')
if computador == usuario:
print('\n**********')
print('Hay un empate')
print('**********')
... |
d0558531a0a1e78eceda6f22bb2eca1f4588691a | vergi1iu5/CodeForce-Solutions | /Young_Physicist.py | 1,095 | 3.5625 | 4 | ################################################
#algorith:
#
#open input file
#read first line and asses:
# if interger <= 0
# print yes, end program
#
#for i in range(first line - 1)
# read next line
# divide into xi, yi, and zi (function)
# if i is 0
# if x + xi or y + yi or z + zi is not 0
# break
# else... |
2c3195375addf50e0de113f0d5a131c6da7ec6fc | offscript/python_practice | /company_manager/company.py | 592 | 3.515625 | 4 | import employee
class Company():
def __init__(self, revenue, employees):
self.revenue = revenue
def generate_wages(revenue):
executive_wages = revenue * .01
manager_wages = revenue .001
human_resources_wages = revenue * .0005
sales_associate_wages = revenue * .0003
'''
def generate_employees(employ... |
59542f43766de71953f8dd4d9af74dbe89096558 | cormacdoyle/BattleShips | /PycharmProjects/Computer science/new.py | 44,378 | 3.984375 | 4 | import pygame, random
print("The user is given a start screen, from here they choose to start, go to high score screen, or quit.")
print("When the user chooses start they will be presented with the game board.")
print("If the user looks in the top right they will see a ‘status’ bar this bar provides basic instructions... |
21439a41943032771b39965644296b90d59effe5 | arun-siv/tutor_pyclass | /tableExtend1.py | 1,704 | 3.5625 | 4 | #what if the Parent class initialized some value. How to deal with it for child classes
import sys
def print_tables(objects, colnames, formatter):
#emits some table header
formatter.headings(colnames)
for obj in objects:
rowdata = [str(getattr(obj, colname)) for colname in colnames]
forma... |
a95dcf4d629f3f43bdd94778206f1474a42ee02c | jackchauvin/Python | /Vector/test-vec.py | 765 | 3.671875 | 4 | from Vector import Vector
#Test for __init__
vec=Vector(1.356,2.434)
#Test for __str__
print("vec:",vec)
#Test for __repr__
print('vec.__repr__():',vec.__repr__())
vec2=Vector(3.65576,1.4785)
#Test for __add__
vec3 = vec + vec2
print(vec,'+',vec2,'=',vec3)
#Tests for __sub__
vec3 = ... |
075cae912cdbce6709803c00b4e289070ecd6a89 | aamp19/Poisson-Regression | /Poisson Regression.py | 5,383 | 3.640625 | 4 | import numpy as np
import util
import pandas as pd
import matplotlib.pyplot as plt
def main(lr, train_path, eval_path, save_path):
"""Problem: Poisson regression with gradient ascent.
Args:
lr: Learning rate for gradient ascent.
train_path: Path to CSV file containing dataset for tra... |
b895438fc8c05bb23d27ea21433387cb5b955a64 | at-vo/HackWestern7 | /tests/test.py | 2,557 | 3.53125 | 4 | from nltk.corpus import wordnet as wn
import string
import numpy
import matplotlib.pyplot as plt
### Synonym checker using nltk package
# def check_synonym(word, sent):
# word_synonyms = []
# for synset in wn.synsets(word):
# for lemma in synset.lemma_names():
# if lemma in sent and lemma !... |
59796135369dd236a8a209931f937640ae117926 | TriCot-Game-Studio/bullets | /bullets/enemy.py | 1,361 | 3.515625 | 4 | from .actor import Actor
class Enemy(Actor):
def __init__(self, pos, radius, color, max_health, pcb1, pcb2, pcb3, img=None):
super().__init__(pos=pos, radius=radius, color=color, img=img)
self.health = max_health
self.max_health = max_health
self.phase = 0
self.damage = 0
... |
a6bc5c5f70191259ccbf727497a4c8f0c7dd8b18 | malay190/quiz_assignments | /Hangman/hangman_game.py | 3,409 | 3.953125 | 4 | import random
#library for hangman
movi = ["baghi","ddlj","raazi","parmanu","newton"]
actor = ["hritik","varun","sidharth","arjun"]
profession = ["student","teacher","enterpreneur","farmer","pilote"]
fastfood = ["choumin","springroll","sandwich","noodles","burger"]
list_of_list = [movi,actor,profession,fastfood]
#s... |
ab24f06d7a40626bf37222236b0ad610637171bb | yuttana76/python_study | /py_dictionary.py | 563 | 4.125 | 4 | phonebook = {
'John':999,
'Jack':888,
'Jill':777
}
print(phonebook)
#Interating
for name,tel in phonebook.items():
print('%s has phone number is %s' %(name,tel))
#Delete item
print('Delete item')
del phonebook['Jill']
print(phonebook)
#Update and Add item
print('Update and Add item')
phonebook.update... |
df5550b64ecc4b55d5fa441990258debad0f1414 | nzh1992/pydesign | /create_mode/factory_method/creator.py | 969 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python3
"""
@Author : ziheng.ni
@Time : 2021/2/7 16:57
@Contact : nzh199266@163.com
@Desc :
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from create_mode.factory_method.product import Product, Truck, Ship
class Creator(ABC):
"""
构造... |
7ec071d5462baac29552f523f3793b8d1ab96a3c | alexei-alexov/compilation | /lab3.py | 1,880 | 3.796875 | 4 |
SUPPORTED = set('/*-+')
OPERATORS = {
'/': lambda a, b: a / b,
'*': lambda a, b: a * b,
'-': lambda a, b: a - b,
'+': lambda a, b: a + b,
}
class Node(object):
"""Tree node"""
def __init__(self, data):
self.l = None
self.r = None
self.data = data
... |
86c20902e76e3869adb32bf478fddd39f156c6aa | Ekozmaster/python-experiments | /lil_math.py | 1,491 | 3.671875 | 4 | import math
class Vector3:
x = y = z = 0.0
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
# Algebra Operators
def __add__(self, other):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
... |
37ef42e9a772c3eabb06e9e6a7f62eb7dcc383e1 | britannica/euler-club | /Week31/euler31_smccullars.py | 1,000 | 3.5625 | 4 | desired_total = 200
denominations = (1,2,5,10,20,50,100,200)
def resolve(solutions):
additions = set()
deletions = set()
for solution in solutions:
current_total = sum(solution)
if current_total < desired_total:
deletions.add(solution)
for coin in denominations:
... |
73d106223ed6a7d1b8435d731bf0ac076927484e | britannica/euler-club | /Week33/euler33_smccullars.py | 2,818 | 4.125 | 4 | class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __eq__(self, other):
return self.numerator == other.numerator and self.denominator == other.denominator
def __str__(self):
return '{}/{}'.format(self.nu... |
0d5b66817cd3395f69eb8ac4b5522becd7a7d867 | britannica/euler-club | /Week6/euler6_smccullars.py | 226 | 3.78125 | 4 | sum_of_squares = 0
sum_to_be_squared = 0
for i in range(1, 101):
sum_of_squares += i ** 2
sum_to_be_squared += i
difference = (sum_to_be_squared ** 2) - sum_of_squares
print("sum square difference is: ", difference)
|
bb94b387948467639dcca67d43407db437c9ab1d | britannica/euler-club | /Week16/euler16_mwieche.py | 244 | 3.5625 | 4 | from functools import reduce
def sum_digits(n):
i = [int(d) for d in str(n)]
result = reduce(lambda x, y: x+y, i)
return result
if __name__ == '__main__':
num = 2**1000
answer = sum_digits(num)
print(answer) # 1366
|
22cda89eae84abdda5716d9f74a8e20d238e95f5 | britannica/euler-club | /Week14/euler14_mwiechec.py | 1,587 | 3.765625 | 4 | import time
import functools
def memoize(func):
"""Wrapper function to cache function results"""
memo = {}
@functools.wraps(func)
def wrapper(key):
if key in memo:
return memo[key]
else:
memo[key] = func(key)
return memo[key]
return wrapper
de... |
3ab90e3010619636be2f1bb71b35001846d6b635 | britannica/euler-club | /Week37/euler37_smccullars.py | 1,107 | 3.75 | 4 | ####### begin sieve generation of primes #######
MAX_PRIME = 1000000
# initialize sieve
sieve = [None] * MAX_PRIME
# zero and one are not primes
sieve[0] = False
sieve[1] = False
# populate the sieve
for x in range(2,MAX_PRIME):
if sieve[x] is None:
sieve[x] = True
for y in range(x*2, MAX_PRIME, x):
... |
8d1104d588f6fed18dad78923939984efcd18ea9 | britannica/euler-club | /Week2/euler2-mwiechec.py | 316 | 3.5625 | 4 | import time
def fibsumeven(x):
res1 = 1
res2 = 1
evens = 0
sum = 0
while sum < 4000000:
sum = res1 + res2
res1, res2 = res2, sum
if (sum % 2 == 0):
evens += sum
return evens
start = time.time()
print (fibsumeven(35))
end = time.time()
print(end - start)
|
fb9eff4ed31a3a1cb47286a3639461233966d189 | scudan/TestPython | /com/liaoxuefeng/OO/classAndInstance1.py | 624 | 3.875 | 4 | class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' %(self.__name, self.__score))
def get_name(self):
return self.__name;
def get_score(self):
return self.__score;
def set_na... |
01273d79f5a771eeb48a3b357afdddb7e1d2a2c5 | scudan/TestPython | /com/python/sundan/controlor.py | 107 | 3.84375 | 4 | a = 10;
b = 10;
if a > b :
print("a > b")
elif (a == b):
print ("a = b")
else:
print ("a < b") |
b12f7071fdcb5ccd38cff72b70c7aaf189ac75b1 | scudan/TestPython | /com/python/sundan/basic/yieldTest.py | 194 | 4 | 4 | #生成器:结果生成一个序列,而不仅仅是一个值
def countdown(n):
print("Count down!");
while n > 0:
yield (n)
n -= 1;
for i in countdown(10):
print(i);
|
1e85e424aca7ac12163b3385ae89891a57c3ef09 | scudan/TestPython | /com/liaoxuefeng/highFeture/Iteration.py | 743 | 3.765625 | 4 | from collections import Iterable
d= {'a':1,'b':2,'c':3,'d':4}
for key in d:
print(key, d.get(key))
for k,v in d.items():
print("key:"+k,v);
for ch in 'ABCD':
print(ch)
print(isinstance('abc',Iterable))
print(isinstance([1,2,3],Iterable))
for i, va in enumerate(['A','b','d']):
print(i, va)
print("... |
d386360920ee5b5e08654d3e2c781148839fbdc9 | scudan/TestPython | /com/refrencePython/function/FunctionT1.py | 468 | 4.375 | 4 | #可变参数函数
def concat(*args , sep ='/'):
return sep.join(args);
result = concat("earth","mars","venus");
print(result);
result1 = concat("earth","mars","venus",sep =".");
print(result1);
# 参数分拆
# *args 分拆 元祖
# **args 分拆 字典
list1 = list(range(3,6))
print(list1);
args = [3,6]
list2 = list(range(*args))
print(list2);
... |
c7cc071afaa110c71ea0bb98d5ce7307a5f84b08 | scudan/TestPython | /com/refrencePython/exception/test.py | 281 | 3.875 | 4 | while True:
try:
x = int(input(("please enter a num:")))
break
# 有异常,且匹配则走异常分支,完了继续转到try.
# 如果未匹配到,则直接退出
except ValueError:
print("Oops! That was no valud num. try again...") |
2cd0932519e63d2cd2d93c78150f371d58838f56 | scudan/TestPython | /com/python/sundan/third/referenceAndcopy.py | 352 | 3.984375 | 4 | import copy
a = [1,2,3,4]
b = a # b引用a
print(b is a )
b [2] = 10 # a 也改变
print(a)
d = [1,2,[3,4]]
c = list(d) # 浅复制
print(c is d )
c.append(100)
print(d)
c[2][0] = -1000 # c 和 d 共享浅复制的内容,当c改变,d对应改变
print(d)
e = [1,2,[3,4]]
f = copy.deepcopy(e)
f[2][0] = -1000
print("e:") # e 不会有变化
print(e)
|
889a98204abf5681a27085284c75c120ab1acff9 | scudan/TestPython | /com/refrencePython/APITest/Tdecimal/Tdecimal1.py | 293 | 3.703125 | 4 | from decimal import *
#十进制
print(round(Decimal('0.70')*Decimal('1.05'),2))
#二进制
print(round(.70*1.05,2))
print(Decimal('1.00') % Decimal('.10'))
print(1.00 % 0.10)
print("-----",sum([Decimal(0.1)]*10))
print(sum([Decimal(0.1)]*10) == Decimal('1.0'))
print(sum([0.1]*10) == 1.0) |
c2676d58846f6d041a3fcbf4a95fad9fa30753fa | HemangShimpi/To-Do-App | /Source Code/Main.py | 1,487 | 3.828125 | 4 | '''
File Name: Main.py
Author: Hemang Shimpi
Date Created: 12/19/20
Date last modified: 12/25/20
Language: Python
Gui: Tkinter
'''
# importing all the necessary tkinter gui modules here
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
# importing class here
from Lo... |
3b691f146cf9a241b242506b38be69a919aa5443 | lurium-ruri/python_automate | /chapter9/renameDates.py | 726 | 3.515625 | 4 | #! python3
# renameDates.py - 米国式日付を欧州式に書き換える
import shutil
import os
import re
def main():
date_pattern = re.compile(r"""~(.*?)
((0|1)?\d)-
((0|1|2|3)?\d)-
(.*?)$
""", re.VERBOSE)
for amer_filename in os.listdir('.'):
mo = date_pattern.search(amer_filename)
if mo == None:
... |
f5b84d9f58c607b5c21dbc564ea13efbc9eabaee | lurium-ruri/python_automate | /chapter9/backupToZip.py | 1,016 | 4.03125 | 4 | #! python3
# backupToZip.py フォルダ全体を連番付きZIPファイルにコピーする
import os
import zipfile
from pathlib import Path
def backup_to_zip(folder):
folder = Path(folder).absolute
number = 1
while True:
zip_filename = Path(f'{folder}_{str(number)}.zip')
if not Path(zip_filename).exists:
break
... |
1b7784bc087a5a12ea6e4bca861f623ba2277b2d | youirong/PracticePython | /src/chapter1.py | 703 | 3.8125 | 4 | '''
Created on 2015年4月11日
@author: Rong
'''
# movies = ["a", "b", "c"]
# print (movies[1])
#
# movies.insert(1, 1)
# movies.insert(3, 2)
# movies.append(3)
# for movie in movies:
# print(movie)
#
# a = 0
# print (isinstance(movies, list))
# print (isinstance(a, list))
movies = ["a", "b", ["c", ["d"... |
ece97500c6445bd645e0f0d84c2f2dab9a4ddbca | PeterCassell92/Slither-pygame | /slither.py | 6,962 | 3.59375 | 4 | import pygame
import random
pygame.init()
white= (255,255,255)
black= (0,0,0)
red = (255,0,0)
green = (0,155,0)
display_width = 800
display_height = 600
block_size =20
appleThickness = 30
img = pygame.image.load('Snakehead.png')
appleimg= pygame.image.load('Apple.png')
FPS = 10
gameDisplay = pygame.display.set_mode... |
471899721408786f171a4d48c329c4b56e775bcf | saintlyzero/Interview-Coding-Problems | /CheekySolutions/MigratoryBirds.py | 473 | 3.796875 | 4 | """
Problem Link: https://www.hackerrank.com/challenges/migratory-birds
Time Complexity : O(N)
Space Complexity: O(M) ; M : Distinct Numbers
"""
def migratoryBirds(arr):
count = [0]*6
for i in arr:
count[i] += 1
return count.index(max(count))
# index() considers index of fir... |
bb1a8090d3fc97546339037bbc0e9b06ff43b438 | 3point14guy/Interactive-Python | /strings/count_e.py | 1,153 | 4.34375 | 4 | # Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text - perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.
#
# Write a function that counts the number of alphabetic characters (a through z, or A through Z) in your text and then k... |
f4f2cb69d567572b77f784f50d6c7c06633898a6 | 3point14guy/Interactive-Python | /turtles/preso/sierpinski_recursive_colored.py | 1,442 | 3.515625 | 4 | import turtle
import time
def draw_triangle(points,color,t):
t.fillcolor(color)
t.up()
t.goto(points[0][0],points[0][1])
t.down()
t.begin_fill()
t.goto(points[1][0],points[1][1])
t.goto(points[2][0],points[2][1])
t.goto(points[0][0],points[0][1])
t.end_fill()
def get_mid(p1, p2):
... |
11992691b92d6d74aa41fe6797f70f810ea3bfb9 | 3point14guy/Interactive-Python | /tkinter/hello_world_tkinter.py | 1,249 | 4.15625 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import simpledialog
window = tk.Tk()
# my_label = ttk.Label(window, text="Hello World!")
# my_label.grid(row=1, column=1)
# messagebox.showinfo("Information", "Information Message")
# messagebox.showerror("Error", "My error mess... |
28ee083d251af397d591971df533d3a22f696ce0 | 3point14guy/Interactive-Python | /alice.py | 1,772 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import string
book = open("alice_in_wonderland.txt", "r")
# dict = {}
#
# for lines in book:
# words = lines.split()
# for word in words:
# word = list(word.lower())
# for letter in word:
# if letter in string.punctuation:
# word = word.replac... |
3390cf0821cb88815d9dbf7ad72bcde2ab971932 | 3point14guy/Interactive-Python | /turtles/fractals/fractal_tree.py | 2,260 | 3.796875 | 4 | # import turtle
#
# def tree(branchLen,t, i):
#
# if branchLen > 5:
# t.forward(branchLen)
# t.right(20)
# tree(branchLen-15,t, i)
# t.left(40)
# tree(branchLen-15,t, i)
# t.right(20)
# t.backward(branchLen)
#
#
# def main():
# t = turtle.Turtle()
# my... |
fe393e270b76b8816201dc34faa287205f5e5825 | george-git-dev/CursoemVideo | /PYTHON/ex007.py | 153 | 3.5 | 4 |
# Média aritimética
n1 = float(input("Primeira nota: "))
n2 = float(input("Segunda nota: "))
conta = (n1 + n2)/2
print("Média {}".format(conta))
|
4c561fa0bc9be90dce570c79417005b2502e5b95 | george-git-dev/CursoemVideo | /PYTHON/ex074.py | 239 | 3.515625 | 4 | from random import randint
n = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10))
print(f"Eu sorteei os valores {n}")
print(f"O maior valor sorteado foi {max(n)}")
print(f"O menor valor sorteado foi {min(n)}") |
e7954829da25b91dc96ae66347e5ea50a47402c2 | george-git-dev/CursoemVideo | /PYTHON/ex049.py | 129 | 3.703125 | 4 | tabuada = int(input("Tabuada do numero: "))
for c in range(1, 11):
print("{} X {} = {}".format(tabuada, c, tabuada*(c)))
|
ed68079ef6d98818c687a28667436620442e7196 | mh453Uol/PythonLearning | /learning/lamda_functions.py | 181 | 3.921875 | 4 | double = lambda x: x * 2
triple = lambda x: x * 3
square_root = lambda x: x * x
print(double(10) == 20)
print(double(5) == 10)
print(triple(10) == 30)
print(square_root(10) == 100) |
9987ad5ff9385a13234a4ee808b7236384495d80 | mh453Uol/PythonLearning | /learning/student_manager.py | 1,631 | 3.765625 | 4 | students = []
def titlecase(element: str) -> str:
to_return = []
words = element.split(" ")
for word in words:
titlecased = word[0].upper() + word[1:].lower()
to_return.append(titlecased)
return " ".join(to_return)
def add_student(name:str, student_id:int = -1):
student = {
... |
3142444064cdc70471f4878bc431a51b6a8bb22c | mh453Uol/PythonLearning | /pythonbo-course/pyStudentManager/functions.py | 1,465 | 3.984375 | 4 | students = [
{"name":"majid hussain khattak","id":1},
{"name":"majid","id":2},
{"name":"h","id":3},
{"name":"MAJID HUSSAIN KHATTAK","id":4}
]
countIndex = 0 # this variable is in the main scope
def get_student_titlecase(students):
titledcased = []
for student in students:
print(student)... |
1aa991d0a31100b8fddb5eb00fdabc146f221d14 | smile0304/py_asyncio | /chapter01/type_object_class.py | 361 | 3.765625 | 4 | a=1
b="abc"
print(type(1))
print(type(int))
#type->int->1
print(type(b))
print(type(str))
#type->str->abc
class Student:
pass
print(type(Student))
a=[1,2]
print(type(a))
print(type(list))
print(Student.__bases__)
class My_Student(Student):
pass
print(My_Student.__bases__)
print(type(object))
print(type(int... |
3c600900972e76cf65fc068e2612e12dd976e720 | smile0304/py_asyncio | /chapter04/abc_test.py | 1,223 | 3.5625 | 4 | class Company(object):
def __init__(self,employee_list):
self.employee = employee_list
def __len__(self):
return len(self.employee)
com = Company(["TT1","TT2","TT3"])
#我们在某些情况下,判定某些对象的类型
#from collections.abc import Sized
from collections.abc import *
#print(hasattr(com,"__len__"))
print(isin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.