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 |
|---|---|---|---|---|---|---|
83d1b386046c5aecd8c66f49fa08d4e4638bd5dd | MayuriTambe/Programs | /Programs/DataStructures/Tuples/ConvertListTuple.py | 127 | 3.703125 | 4 | Data=[44,33,66,44,87,34]
print("The list is:",Data)
tuple_list=tuple(Data)
print("After convert list into tuple:",tuple_list)
|
b78e7680525cf662961359a93bae05bbb72b9630 | MayuriTambe/Programs | /Programs/Numpy/OneOnBorder.py | 155 | 3.75 | 4 | import numpy as np
Ones_Array=np.ones((5,5))
print("The Array is :",Ones_Array)
Ones_Array[1:-1]=0
print("Adding Zeros in middle of matrix:\n",Ones_Array) |
b28c8017483878a4051bdf39e05d090f63639bad | MayuriTambe/Programs | /Programs/BasicPython/BinaryFormat.py | 175 | 4.09375 | 4 | value=int(input("Enter the number"))
binary=(format(value,'08b'))
print("The binary format is:",binary)
AddZeros=(format(value, '010b'))
print("Leads to zero is:",AddZeros)
|
1b35e0f18f0127e576a99c2cd524f715328b2256 | MayuriTambe/Programs | /Programs/DataStructures/Tuples/RepeatedElements.py | 188 | 3.65625 | 4 | Data=(22,54,11,66,4,8,55,22,54,8,4)
print("The tuple is:",Data)
for i in range(0,len(Data)):
for j in range(i+1,len(Data)):
if Data[i]==Data[j]:
print(Data[i])
|
91e4955a5ae2e20c6073d181e145c52f2031dd47 | MayuriTambe/Programs | /Programs/DataStructures/List/6.RemoveDuplicates.py | 173 | 4.3125 | 4 | values=[1,3,5,4,6,7,8,5,3]
print("The list is:",values)
dup=[]
for i in values:
if i not in dup:
dup.append(i)
print("After removing duplicates list is:",dup)
|
df1920f69ffd2cab63280aa8140c7cade46d6289 | bhavyanshu/PythonCodeSnippets | /src/input.py | 1,297 | 4.59375 | 5 | # Now let us look at examples on how to ask the end user for inputs.
print "How many cats were there?",
numberofcats = int(raw_input())
print numberofcats
# Now basically what we have here is that we take user input as a string and not as a proper integer value as
# it is supposed to be. So this is a major problem be... |
23076b5f678e5410dbe339231119b8b42e5a7914 | ClaudiuCreanga/DataScienceSchool | /solutions/gapminder.py | 2,508 | 4 | 4 | import statistics as stats
import csv
def gdp_stats_by_continent_and_year(gapminder_filepath, continent='Europe', year='1952'):
"""
Returns a dictionary of the average, median and standard deviation of GDP per capita
for all countries of the selected continent for a given year.
gapminder_filepath ---... |
a4c368b133a8eb5816f0e9cbf5fb83803c8b6612 | liufeinuaa/raspberrypi4b_someproj | /opencv_test/IThresh.py | 3,519 | 3.59375 | 4 | '''
from opencv.org tutorials
https://docs.opencv.org/4.5.2/d7/d4d/tutorial_py_thresholding.html
Image Thresholding
'''
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread('../foo1.jpg',0)
# Simple Thresholding
# ret, thresh1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
# ret, t... |
e8ccd80555e168fb819b7c29c2073a45b3a7ccb0 | skhaksari/code-challenge | /find_store.py | 3,217 | 3.53125 | 4 | """Find Store.
Usage:
find_store.py --address="<address>"
find_store.py --address="<address>" [--units=(mi|km)] [--output=text|json]
find_store.py --zip=<zip>
find_store.py --zip=<zip> [--units=(mi|km)] [--output=text|json]
Options:
--zip=<zip> Find nearest store to this zip code. If there are mu... |
d61859bd56ff667e6ee48cda3f27422b0f22130d | njbultman/pyxlsxfunctions | /pyxlsxfunctions/text/core.py | 6,504 | 4.4375 | 4 | import numpy as np
def UPPER(text):
"""Convert all text to uppercase.
Parameters
----------
text : list or string
string(s) to be converted to uppercase.
Returns
-------
list or string
A list of converted strings or converted string to uppercase.
"""
if type(text) ... |
b3d7b0db6da6ea4d30b76995b4d78618585132ff | alenkran/ANES212_Seizure | /scripts/LMS.py | 6,797 | 3.546875 | 4 | ################################################################################
# Description: Classes for linear filters
# Mu and Alpha LMS filter is implemented
# *adapted from Wilson Wilson's lecture in EE 368
################################################################################
import numpy as np
# L... |
8a59dcfea3b1d0c8bdf63c2fbecfd83181fa4c09 | jlassi1/holbertonschool-higher_level_programming | /0x03-python-data_structures/0-print_list_integer.py | 170 | 3.859375 | 4 | #!/usr/bin/python3
def print_list_integer(my_list=[]):
x = len(my_list)
i = 0
while x:
print("{:d}".format(my_list[i]))
x -= 1
i += 1
|
c0c986476ddb5849c3eb093487047acb2a8cadec | jlassi1/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 413 | 4.34375 | 4 | #!/usr/bin/python3
"""module"""
def append_write(filename="", text=""):
"""function that appends a string at the end of a text file (UTF8)
and returns the number of characters added:"""
with open(filename, mode="a", encoding="UTF8") as myfile:
myfile.write(text)
num_char = 0
for w... |
d61e39c5801324a5e8e1558a6a315c8a16afbec6 | jlassi1/holbertonschool-higher_level_programming | /0x0B-python-input_output/5-to_json_string.py | 287 | 3.578125 | 4 | #!/usr/bin/python3
"""module"""
import json
def to_json_string(my_obj):
"""unction that returns the JSON representation of an object (string)"""
if not json.dumps(my_obj):
raise Exception("{} is not JSON serializable".format(str(my_obj)))
return json.dumps(my_obj)
|
9db38a3e854e2184d7a1b2301dabf1bc5df931b7 | Sisyphus235/tech_lab | /algorithm/sort/quick_sort.py | 1,224 | 3.828125 | 4 | # -*- coding: utf8 -*-
"""
apply to large scale
best scenario: O(nlogn)
worst scenario: O(n^2)
"""
import time
import random
def partition(array: list, left: int, right: int) -> int:
pivot_value, j = array[left], left
for i in range(left + 1, right + 1):
if array[i] <= pivot_value:
j +=... |
8583fccda88b05dd25b0822e1e403de2ad64af11 | Sisyphus235/tech_lab | /algorithm/tree/lc110_balanced_binary_tree.py | 2,283 | 4.40625 | 4 | # -*- coding: utf8 -*-
"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/... |
07f15ebebf89a100cdb3cb5172f782c93d4691c5 | Sisyphus235/tech_lab | /algorithm/tree/my_linked_binary_tree.py | 2,521 | 3.703125 | 4 | # -*- coding: utf8 -*-
class LinkedNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class LinkedBinaryTree:
def __init__(self):
self.root = None
@property
def is_empty(self):
return self.root is None
def _level(self,... |
3c7c978a4d753e09e2b12245b559960347972b37 | Sisyphus235/tech_lab | /algorithm/tree/lc572_subtree_of_another_tree.py | 1,623 | 4.3125 | 4 | # -*- coding: utf8 -*-
"""
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure
and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
Example 1:
Give... |
8e47d0058a83584b8fefd4bd68c61bba15ed59a2 | Sisyphus235/tech_lab | /algorithm/dynamic_programming/lc70_climbing_stairs.py | 1,239 | 4 | 4 | # -*- coding: utf8 -*-
"""
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the to... |
1651e397c9fb56f6c6b56933babc60f97e830aac | Sisyphus235/tech_lab | /algorithm/array/find_number_occuring_odd_times.py | 1,177 | 4.25 | 4 | # -*- coding: utf8 -*-
"""
Given an array of positive integers.
All numbers occur even number of times except one number which occurs odd number of times.
Find the number in O(n) time & constant space.
Examples :
Input : arr = {1, 2, 3, 2, 3, 1, 3}
Output : 3
Input : arr = {5, 7, 2, 7, 5, 2, 5}
Output : 5
"""
def... |
3cc965eda451b01a9c0f8eee2f80f64ea1d902a3 | Sisyphus235/tech_lab | /algorithm/tree/lc145_post_order_traversal.py | 1,363 | 4.15625 | 4 | # -*- coding: utf8 -*-
"""
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
from typing import List
class TreeNode:
def __init__(self, ... |
0ce435487392cc29b24a7489992a5983bcde05df | Sisyphus235/tech_lab | /algorithm/dynamic_programming/climbing_stairs_user_defined.py | 917 | 3.625 | 4 | # -*- coding: utf8 -*-
"""
一次爬 2/3 阶,多少种不同方案上 n 阶?n 是非负整数
"""
def two_three_climb(n: int) -> int:
"""
状态方程:dp_array[n] = dp_array[n-2] + dp_array[n-3]
:param n:
:return:
"""
if n < 2:
return 0
if n < 4:
return 1
dp_array = [0] * (n + 1)
dp_array[2], dp_array[3] = 1... |
236c86f092704ebcb9f4d68f370031b0a83df716 | Sisyphus235/tech_lab | /algorithm/math/last_num_in_circle.py | 1,325 | 3.515625 | 4 | # -*- coding: utf8 -*-
"""
0,1,...,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。
例如:
0-4 一个圈,每次删除第 3 个数字
0, 1, 2, 3, 4
第一次删除 2
3, 4, 0, 1
第二次删除 0
1, 3, 4
第三次删除 4
1, 3
第四次删除 1
3
最后返回 3
剑指 offer 62
"""
from algorithm.linked_list.my_singly_linked_list import SinglyNode
def last_num_in_circle_recursive(n: in... |
6cd89185251ef3d7f5f17a1862d2a09ddb0a9074 | Sisyphus235/tech_lab | /python/csv_file.py | 904 | 3.8125 | 4 | # -*- coding: utf8 -*-
import csv
import os
from io import StringIO
def write_csv(filename):
csv_io = StringIO()
writer = csv.DictWriter(csv_io, fieldnames=['a', '人', 'c'])
writer.writeheader()
row = {'a': 1, '人': 2, 'c': 3}
writer.writerow(row)
with open(filename, 'w', encoding='utf8') as ... |
3e28c30413921dd2703cb9c5fa0d433604bfdc6b | omarfq/CSGDSA | /Chapter12/Exercise1.py | 624 | 3.84375 | 4 | # Fix the following code to eliminate unnecesary recursive code with Dynamic Programming
'''
def add_until_100(array):
if len(array):
return 0
if array[0] + add_until_100(array[1:]) > 100:
return add_until_100(array[1:])
else:
return array[0] + add_until_100(array[1:])
'''
def add_... |
d7eda822fb84cd5abd4e7a66fa76eec506b09599 | omarfq/CSGDSA | /Chapter14/Exercise2.py | 960 | 4.25 | 4 | # Add a method to the DoublyLinkedList class that prints all the elements in reverse order
class Node:
def __init__(self, data):
self.data = data
self.next_element = None
self.previous_element = None
class DoublyLinkedList:
def __init__(self, head_node, last_node):
self.head_n... |
3f13fa57a9d0e51fd4702c7c7814e0e277cb8f36 | omarfq/CSGDSA | /Chapter13/Exercise2.py | 277 | 4.125 | 4 | # Write a function that returns the missing number from an array of integers.
def find_number(array):
array.sort()
for i in range(len(array)):
if i not in array:
return i
return None
arr = [7, 1, 3, 4, 5, 8, 6, 9, 0]
print(find_number(arr))
|
322c0fbb3ee4ac1e80855fba5a14ee74d4f4f971 | hazelclement/python-programs | /test1.py | 91 | 3.734375 | 4 | def power(x,y=2):
r=1
for i in range(y):
r=r*x
return r
power(3,3) |
194c0cafc643a7b15caa229bb7bce89c4ee5b019 | hazelclement/python-programs | /returnQ9.py | 161 | 3.71875 | 4 |
def series(x,y):
a=(x+y)//4
l =
for i in range(3):
x=x+a
l+=[x]
return l
x=int(input(":"))
y=int(input(":"))
print(series(x,y)) |
b598ca463ad9beaab6835696c8d9a8a0ebe79f79 | hazelclement/python-programs | /returnQ7.py | 256 | 3.53125 | 4 | import random as r
def len_no(n):
x = ""
y = "1"
for i in range(n):
x += "9"
v = int(x)
for p in range(n - 1):
y += "0"
w = int(y)
number=r.randrange(w,v)
return number
n = int(input(":"))
print(len_no(n)) |
60fa6633a36b82327a6e2a9e5203ffcc326f9a30 | hazelclement/python-programs | /recordfile3/working with lines and words.py | 244 | 4.03125 | 4 | def separator():
file=open("text.txt")
for i in range(5):
file_data=file.readline()
for word in file_data:
if word==" ":
print("#",end="")
else:
print(word,end="")
separator() |
36683784f8869b2102223476008fa9251d38df4d | hazelclement/python-programs | /f.py | 319 | 3.53125 | 4 | def readfile():
f = open("recordfile3/reports.txt")
f1 = open("cons.txt","w+")
for line in f:
for char in line:
print(char,end="")
if char not in "aeiou1234567890":
f1.write(char)
for k in f1:
print(k,end="")
f.close()
f1.close()
readfile() |
7bd6c02aaf292bc8e6b5407a9cacf77d415e057a | jameykim112/COMP9021 | /Assignments/Assignment1/test2.py | 1,645 | 3.78125 | 4 |
def perfect_ride(input_values):
increment = input_values[1] - input_values[0]
print("Increment required for perfect ride is:", increment)
perfect_ride_count = 1
for i in range(0, len(input_values) - 1):
if input_values[i+1] - input_values[i] == increment:
perfect_ride_count += 1
... |
cd851f3e7089f637fe747906625df3a90ca636c2 | superhiro220/dice-roller | /dice roller 3.1 beta.py | 347 | 3.921875 | 4 | from random import randint
while True :
try :
stat = int(input("What stat are you rolling? "))
except NameError :
print("Not a number.")
continue
try :
dice = int(input("What die shall you cast? "))
except NameError :
print("Not a number.")
continue
roll = randint(1,dice)
print("roll", ... |
06c5592c2a463067baa78a1040115386bd91a017 | vegarsti/image-to-table-web | /sanitize.py | 1,148 | 3.609375 | 4 | import re
def is_numerical(cell):
N = len(cell)
digits = "\d"
N_numerical = len(re.findall(digits, cell))
percentage_numerical = N_numerical / N
return percentage_numerical > 0.5
def make_cell_numerical(cell, full_dictionary):
regex_replace = dict((re.escape(k), v) for k, v in full_dictionar... |
63226638939260126c5d1ee013b0f76e9d5f5812 | Temujin18/trader_code_test | /programming_test1/solution_to_C.py | 506 | 4.3125 | 4 | """
C. Write a rotate(A, k) function which returns a rotated array A, k times; that is, each
element of A will be shifted to the right k times
○
rotate([3, 8, 9, 7, 6], 3) returns [9, 7, 6, 3, 8]
○
rotate([0, 0, 0], 1) returns [0, 0, 0]
○
rotate([1, 2, 3, 4], 4) returns [1, 2, 3, 4]
"""
from typing import List
def ... |
03b94b0bcd11116d7b2d707754d9dd943dafdceb | BrendanArthurRing/algorithms | /div_by_two.py | 270 | 3.875 | 4 | from stack import Stack
def convert_int_to_bin(dec_num):
s = Stack()
while dec_num > 0:
s.push(str(dec_num % 2))
dec_num = dec_num // 2
bits = ""
while not s.is_empty():
bits += s.pop()
print(bits)
convert_int_to_bin(242) |
297722a2b47e4a306bd0b56c64d81f89b59c10f5 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_106_divide_file_path.py | 302 | 3.875 | 4 | """Write a Python program to divide a path on the extension separator."""
import os
def divide_from_extension(path):
basename = os.path.basename(path)
only_name = basename.split(".")
return print(only_name[0])
path = 'Basic_Part_I/ex_92_special_character.py'
divide_from_extension(path) |
ce09c0ea453cc0dd1b7126516b7f4ffa60418eca | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_141_decimal_to_hexidecimal.py | 92 | 3.796875 | 4 | """Write a python program to convert decimal to hexadecimal. """
a = 12
b = hex(a)
print(b) |
b4a8b1868d1d2926d9c2d1788ec766d8f454449a | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_33_if_two_sum_zero.py | 241 | 4.03125 | 4 | """Write a Python program to sum of three given integers. However, if two values are equal sum will be zero"""
def Sumujemy(a,b,c):
if a == b or b == c or c == a:
return 0
else:
return a+b+c
print(Sumujemy(3,2,3))
|
a62af29bd84e26323bb7fc0442e602b894ce422e | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_110_divide_by_15.py | 200 | 3.890625 | 4 | """Write a Python program to get numbers divisible by fifteen from a list using an anonymous function."""
new_list = list(filter(lambda x: (x % 15 == 0) and (x != 0) , range(150)))
print(new_list)
|
76ad592892c5354801aab5f9c250c8fa6ca167a2 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_25_check_if_special.py | 280 | 4 | 4 | """Write a Python program to check whether a specified value is contained in a group of values."""
def check_if(number,list):
return [print("There is {} in {}".format(number, i)) for i in list if number in i]
list = [[1,3,5,6],[1,7,9,10]]
number = 7
check_if(number,list)
|
80ecf5852fb3b79a7d3d8e3a8459ef02743e3851 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_61_feets_to_inches_miles_etc.py | 295 | 3.96875 | 4 | """Write a Python program to convert the distance (in feet) to inches, yards, and miles."""
def converts_me(distance):
return print("{} feets equal to {} inches or {} yards or {} miles".format(
distance, 12*distance, 0.333333*distance, 0.000189394*distance)
)
converts_me(150) |
caa8b047d3bcbb580e9dfc657a9f3ae1f59c0273 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_111_wildcard_usage.py | 395 | 3.96875 | 4 | """Write a Python program to make file lists from current directory using a wildcard."""
import os
import glob
import fnmatch
pattern = "*file*"
for x in glob.glob("Basic_Part_I/*"):
if fnmatch.fnmatch(x,pattern):
print(os.path.basename(x))
print(40*"*")
ina = [print(os.path.basename(x)) for x in glob.... |
6f0692ee1c0b21fa26148ed20d377c6fe1a2ffff | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_113_number_or_error.py | 506 | 3.921875 | 4 | """Write a Python program to input a number, if it is not a number generates an error message."""
def give_me_number(number:int):
if type(number) == int:
return print(number)
else:
raise TypeError("This is not a number")
# give_me_number("xdd")
def give_me_number_2():
while True:
... |
1d9c572a57b05b6a0bc2720fc20b2f6d1d5c5e8f | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_128_is_lowercase_here.py | 594 | 4 | 4 | """ Write a Python program to check whether lowercase letters exist in a string."""
def check_if_lower(string:str):
if len([x for x in string if x.islower()]) > 1:
return print("String contains lowercase letter")
else:
return print("String without lowercase letter")
def check_if_lower_v2(... |
5f7af6066aea6ad6e7a5dfc11103eb961a42e717 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_66_BMI.py | 160 | 3.578125 | 4 | """Write a Python program to calculate body mass index."""
def BMI(height, weight):
return (weight/(height * height)).__round__(2)
print(BMI(1.80, 70)) |
ea13ba0ca0babd500a0b701db9693587830a4546 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_21_even_or_odd.py | 380 | 4.28125 | 4 | """Write a Python program to find whether a given number (accept from the user) is even or odd,
print out an appropriate message to the user."""
def even_or_odd(number):
if (number % 2 == 0) and (number > 0):
print("The number is even")
elif number == 0:
print("This is zero")
else:
... |
b592d71885a98d77bbbf654135690b6776056b53 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_36_add_if_integers.py | 261 | 4.09375 | 4 | """ Write a Python program to add two objects if both objects are an integer type."""
def both_integers(a,b):
if isinstance(a, int) and isinstance(b, int):
return a+b
return "One or both values are not integer type"
print(both_integers(1,"a")) |
a4ef6aa445bf96433c73b13d6d1d87cae610c7c7 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_83_greater_than.py | 346 | 3.921875 | 4 | """Write a Python program to test whether all numbers of a list is greater than a certain number. """
def greater_than(lista:list, number:int):
for x in lista:
if number > x:
yield print("Yes".format(x))
break
print("No")
break
przyklad = greater_than([6,7,6,6], 5)... |
5a6b53fcda4175ed119def2bc56ff9f263fb993d | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_82_sum_of_all_objects.py | 197 | 3.84375 | 4 | """ Write a Python program to calculate the sum of all items of a container (tuple, list, set, dictionary)."""
def sum_me(iterable_object):
return print(sum(iterable_object))
sum_me({1,2,3}) |
18349f75f9e46fe477d3a2e0e591050d62df963a | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_145_list_set_or_tuple.py | 270 | 3.984375 | 4 | """Write a Python program to test if a variable is a list or tuple or a set."""
obj = (0,)
if isinstance(obj, list):
print("List")
elif isinstance(obj, tuple):
print("Tuple")
elif isinstance(obj, dict):
print("Dict")
else:
print("Something went wrong") |
874d7f0e701db35a7c6a7fc4c8e1b796bb29499f | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_102_system_command_output.py | 234 | 3.546875 | 4 | """Write a Python program to get system command output."""
import subprocess
subprocess = subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE)
subprocess_return = subprocess.stdout.read()
print(subprocess_return) |
cf3681f0b083e64b88f0741ac330415e364b6c9b | ElectronicMakerSpace/Scraping | /listComprehension.py | 777 | 3.765625 | 4 | """ h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
"""
#[expression for item in list]
"""
h_letters = [ letter for letter in 'human' ]
print( h_letters)
number_list = [x for x in range(20) if x % 2 == 0 ]
print(number_list)
num_list1 = [y for y in range(100) if y % 5 == 0 if ... |
caf800249196b2a6e7c09ab352897e19ca8fb902 | coool0230/smallTurtle | /p14/p9_8.py | 422 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : p9_8.py
# @Author: huyn
# @Date : 2018/4/29
# @Desc :
def showMaxFactor(num):
count = num // 2
while count > 1:
if num % count == 0:
print("{}的最大公约数是{}".format(num,count))
break
count -=1
else:
print... |
87c562cd513aeab621ebb0cb3911cb0b5bc99957 | coool0230/smallTurtle | /p14/p9_6.py | 1,375 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : p9_6.py
# @Author: huyn
# @Date : 2018/4/28
# @Desc :
origin = (0, 0) # 原点
legal_x = [-100, 100] # x轴的移动范围
legal_y = [-100, 100] # y轴的移动范围
def create(pos_x=0, pos_y=0):
# 初始化位于原点为主
def moving(direction, *step):
# direction参数设置方向,1为向右(向上),-... |
38671dacd7dbf295ac3f0cefbe3b77c144db2e60 | lakshmiprasanth-siddavaram-au19/cc-week1-day1 | /day1cc.py | 610 | 3.71875 | 4 | x=("CREATING USER PROFILE")
print(x)
name=str(input("user name:"))
age=int(input("age:"))
mobile=int(input("mobile number:"))
email=str(input("mail ID:"))
address=input("Address:")
pincode=int(input("pin code:"))
a=("congratulations you successfully created your profile😇")
#outputs and their data t... |
b08f7c6b9133c9ce89b131ff9a0e70c8651deb77 | minhee0327/Algorithm | /python/SWEC/02_Stack1/SWEA4869_종이붙이기.py | 788 | 3.5625 | 4 | def paperCount(n):
if n == 1:
return 1
elif n == 2:
return 3
else:
return paperCount(n-1) + paperCount(n-2) * 2
for t in range(1, 1+int(input())):
print("#{} {}".format(t, paperCount(int(input())//10)))
'''
[code review]
- 아...........
- 점화식을 못찾아서 한시간 내내 뻘뻘댄 문제..
- 왜못찾았냐하면 N=... |
609cbe9ca8ba5e9eed4909f8f98375cdb5cc0055 | minhee0327/Algorithm | /python/BOJ/01_기본/2_예외/17413_단어뒤집기2.py | 485 | 3.75 | 4 | string = input()
temp, ans, ck = "", "", False
for i in string:
if i == ' ':
if not ck:
ans += temp[::-1] + ' '
temp = ''
else:
ans += ' '
elif i == '>':
ck = False
ans += '>'
elif i == '<':
if not ck:
ck = True
... |
ddd35bc20266174bee29727db4ec9d6ca6d8d785 | minhee0327/Algorithm | /python/BOJ/01_기본/2_예외/17413_단어뒤집기2_3.py | 508 | 3.90625 | 4 | string = input()
temp, ck = "", False
for i in string:
if i == ' ':
if not ck:
print(temp[::-1], end=" ")
temp = ''
else:
print(" ", end="")
elif i == '>':
ck = False
print('>', end="")
elif i == '<':
if not ck:
ck = T... |
91a2f7d8891b4b1f5ef1cf1e6fa3d317dee248f5 | minhee0327/Algorithm | /python/BOJ/01_기본/2_예외/16675_두개의손_2.py | 590 | 3.671875 | 4 | # 모듈러 형식으로 0 < 1, 1 < 2, 2 < 0
# 가위, 바위, 보를 숫자(index)로 표현
# find 내장함수를 사용하는 것도 좋다.
# S: 0, R: 1, P: 2
ml, mr, tl, tr = ('SRP'.index(i) for i in input().split())
#print(ml, mr, tl, tr)
# 태경이가 이기려면 민성이가 낸 것보다 1을 더한 값을 가지고 있을 때 이긴다
if ml == mr and (ml+1) % 3 in [tl, tr]:
print("TK")
# 민성이가 이기려면 태경이가 낸것보다 1을 더한값을 가지고... |
51fbe9373e6ba8aeca874fbdd570436ce443b22c | minhee0327/Algorithm | /python/BOJ/01_정렬/BOJ2750_수정렬하기.py | 148 | 3.625 | 4 | N = int(input())
input_value = []
for _ in range(N):
input_value.append(int(input()))
input_value.sort()
for i in input_value:
print(i)
|
2413eb58c843fcf1a3368cfcacfb5d80339f3579 | minhee0327/Algorithm | /python/BOJ/01_정렬/BOJ2751_수정렬하기2_1.py | 799 | 3.859375 | 4 | import sys
def merge(left, right):
lp, rp = 0, 0
sorted_arr = []
while lp < len(left) and rp < len(right):
if left[lp] < right[rp]:
sorted_arr.append(left[lp])
lp += 1
else:
sorted_arr.append(right[rp])
rp += 1
while lp < len(left):
... |
932a3366752aee42a42ee2fb0ca9fb8c4ef6a8cf | minhee0327/Algorithm | /python/BOJ/10_DFS_BFS/BOJ2644_촌수계산.py | 984 | 3.71875 | 4 | from queue import deque
def bfs(p1, p2):
cnt = 0
need_visit = deque([[p1, cnt]])
while need_visit:
current = need_visit.popleft()
p = current[0]
cnt = current[1]
if p == p2:
return cnt
if not visited[p]:
cnt += 1
visited[p] = 1
... |
81f1d9c3f5e40c55c6cc7e2e4edee58fbd65993c | jerryhanhuan/leetcode | /python/reverse_int.py | 952 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#File Name:reverse_int.py
#Created Time:2019-08-05 04:25:00
# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转
# 例如, 输入 123 => 输出 321,输入 123, 输出 -321, 输入 120 ,输出 21
class Solution:
# def reverse(self, x:int) -> int:
def reverse(self, x):
postive = 0
if x >... |
ac87bd8f764b70ef0bf5f5484a4ff8167148876c | momentum-team-3/examples | /python/oo-examples/animal.py | 3,919 | 4.5 | 4 | """ Python OO examples.
"""
# This is the simplest kind of class - it stores named data attributes and provides a basic
# interface to Python with the __str__ method (provides a printable string representation)
# and the __repr__ method (provides a more detailed string representation for debugging/working
# in the co... |
4bb88de5f9de506d24fe0ff4acf2c43bb4bc7bca | momentum-team-3/examples | /python/oo-examples/color.py | 1,888 | 4.3125 | 4 | def avg(a, b):
""" This simple helper gets the average of two numbers.
It will be used when adding two Colors.
"""
return (a + b) // 2 # // will divide and round all in one.
def favg(a, b):
""" This simple helper gets the average of two numbers.
It will be used when adding two Colors.... |
9b95c60537292b97103a9bc2277a99fe64c24231 | Cqyreall/week_02_homework | /tests/song_test.py | 326 | 3.5 | 4 | import unittest
from src.song import Song
class TestSong(unittest.TestCase):
def setUp(self):
self.song = Song("New man", "Ed sheeran")
def test_song_name(self):
self.assertEqual("New man", self.song.name)
def test_song_has_verse(self):
self.assertEqual("Ed sheeran", sel... |
83956da5cb73095691f6bc6448fcad669730bc7f | shubham01309/Stone-paper-scissor | /main.py | 1,218 | 3.953125 | 4 | import random
attempts = 0
while (attempts<=10):
lst = ["Stone","Paper","Sessior"]
x = random.choice(lst)
print("enter your choice Stone or Paper or Sessior")
your_choice = input()
print(your_choice + "=" + x)
if your_choice == "Sessior" and x =="Stone":
print("computer wins")
... |
8420db695b5cd49488918e2a47c79d7888dc7ad5 | nicomessina/frro-soporte-2019-22 | /practico_01/ejercicio-10.py | 961 | 3.859375 | 4 | # Implementar las funciones superposicion_x(), que tomen dos listas y devuelva un booleano en base a
# si tienen al menos 1 elemento en común.
# se debe implementar utilizando bucles anidados 2 for.
def superposicion_loop(lista_1, lista_2):
resultado=False
for valor_lista1 in lista_1:
for valor_lista2... |
9da1606478954cc07181d1fa0a0658f8630631ae | baixing002/laugh | /106-1.py | 1,180 | 3.890625 | 4 | # coding:utf-8
def add_function(a,b):
c= a+b
print(c)
if __name__ == "__main__":
add_function(2,0)
# 分别写出三个变量为int类型,float类型,str类型,例如int类型:a = 1
# 查看定义三个变量的类型(type)并计算数值类型总值
a = 1
b = '25'
c = 3.14
print(type(a),type(b),type(c))
print(a+int(b)+int(c))
a = "如果给这份爱加上⼀个期限我希望是"
b = "9999.00"
c = "1"
d = "年... |
5a24f829dfe4f7587481b7f0ccbf4753c9ec7ec3 | fauziakbar101/Labpy03 | /latihan1.py | 283 | 3.578125 | 4 | print('Nama : Fauziakbar')
print('Nim : 311810855')
print('PROGRAM MENAMPILKAN N BILANGAN ACAK LEBIH < 0.5')
print('')
import random
n = int(input("Masukan nilai N : "))
for i in range(n) :
a=random.uniform(0.0,0.5)
print ("Data ke : ", i, "=> ", a)
print("Selesai")
|
e41cce0a725809085d3a417e3192cb4d98717d7e | ink-water/ink | /git_test/mysql_test.py | 2,304 | 3.671875 | 4 | """
pymysql操作流程
"""
import pymysql
# 连接本地数据库,仅有端口号port是数字形式
db = pymysql.connect( # 关键字传参
host="127.0.0.1", # 默认localhost,可以省略
port=3306, # 默认3306,可以省略
user="root",
password="123456",
database="stu",
charset="utf8"
)
# 生成游标对象(用于操作数据库数据,获取SQL执行结果的对象),执行SQL命令
cur = db.cursor()
# 执行各种数据库SQ... |
cb1dfbd6aaecc7a433a18463ae97e89af4fad417 | curtiscook/xivapi-py | /pyxivapi/decorators.py | 459 | 3.625 | 4 | import logging
from functools import wraps
from time import time
__log__ = logging.getLogger(__name__)
def timed(func):
"""This decorator prints the execution time for the decorated function."""
@wraps(func)
async def wrapper(*args, **kwargs):
start = time()
result = await func(*args, **k... |
75efa92986cef3e85bf44dc6fbcf437cc96d430a | ZhangDepeng/SinaSpider | /distance.py | 553 | 3.953125 | 4 | # -*- coding: utf-8 -*-
#根据地球上任意两点的经纬度计算两点的距离
import math
def rad(d):
return d * math.pi / 180.0
def distance(lat1,lng1,lat2,lng2):
radlat1=rad(lat1)
radlat2=rad(lat2)
a=radlat1-radlat2
b=rad(lng1)-rad(lng2)
s=2*math.asin(math.sqrt(math.pow(math.sin(a/2),2)+math.cos(radlat1)*math.cos(radlat2)*ma... |
c20d16b102e1e408648cf055eb2b37a6d5198987 | VSpasojevic/PA | /vezba05/stablo/stablo/stablo.py | 2,136 | 4.21875 | 4 | class Node:
"""
Tree node: left child, right child and data
"""
def __init__(self, p = None, l = None, r = None, d = None):
"""
Node constructor
@param A node data object
"""
self.parent = p
self.left = l
self.right = r
self.data = d
clas... |
4b95c62f0357a8604e9c7927c72bdac5a5cc5027 | VSpasojevic/PA | /vezba09/grafovi/grafovi/grafovi.py | 2,611 | 3.65625 | 4 | from enum import Enum
import sys
import math
class Vertex:
"""
Graph vertex: A graph vertex (node) with data
"""
def __init__(self, c = None, p = None, d1 = None, d2 = None, i = None):
"""
Vertex constructor
@param color, parent, auxilary data1, auxilary data2
"""
... |
ccd4abd6b2cb0de659650b6687e9015a0a5d66f4 | CiSigep/bookstore | /database.py | 1,413 | 4.0625 | 4 | import sqlite3
class Database:
def __init__(self, db):
self.connection = sqlite3.connect(db)
self.cursor = self.connection.cursor()
self.cursor.execute(
"CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, "
"isbn INTEGE... |
2584a4f783fe31e0d5ecaf7853082cb15e22b487 | pk00749/Example_Python | /meks-pygame-samples/eight_dir_movement_adjusted.py | 3,939 | 3.5 | 4 | """
Script is identical to eight_dir_move with an adjustment so that the player
moves at the correct speed when travelling at an angle. The script is also
changed to use a time step to update the player. This means that speed is now
in pixels per second, rather than pixels per frame. The advantage of this is
that the g... |
c2b822b0059103bceb7d8c2acf628ae3505bfffb | pk00749/Example_Python | /Test_Static&ClassMethod (2).py | 1,289 | 3.515625 | 4 | # class A:
# bar = 1
# def foo(self):
# print('foo')
#
# @staticmethod
# def static_foo():
# print('static_foo')
# print(A.bar)
#
# @classmethod
# def class_foo(cls):
# print('class_foo')
# # print(cls.bar)
# # cls().foo()
# cls().foo()
# ... |
d27ba554db88205e48977f3fe891373f26095ce6 | gaoshang1999/Python | /leetcod/p295.py | 1,380 | 3.765625 | 4 | class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.list = []
def addNum(self, num):
"""
:type num: int
:rtype: void
"""
i = self._bsearch(num)
self.list.insert(i, num ... |
26f77ff9d2e26fe9e711f5b72a4d09aed7f45b16 | gaoshang1999/Python | /leetcod/dp/p121.py | 1,421 | 4.125 | 4 | # 121. Best Time to Buy and Sell Stock
# DescriptionHintsSubmissionsDiscussSolution
# Discuss Pick One
# Say you have an array for which the ith element is the price of a given stock on day i.
#
# If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design ... |
0a6136f5966398beb22bcc95c952e4dafd984003 | gaoshang1999/Python | /leetcod/array/p216.py | 1,760 | 3.71875 | 4 | # 216. Combination Sum III
# DescriptionHintsSubmissionsDiscussSolution
# Discuss Pick One
# Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
#
#
# Example 1:
#
# Input: k = 3, n = 7
... |
80e6b3945be9e20320f80801fea0517296fd2961 | gaoshang1999/Python | /leetcod/dp/p375.py | 1,825 | 3.78125 | 4 | import copy
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
s = ""
if self.left != None:
s += self.left.__str__()
s += " "+str... |
e5e3ce3fc50c1f1495cd62fe6cbdb15aa87e2f92 | gaoshang1999/Python | /merge_csv_2_excel.py | 765 | 3.5 | 4 | from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd
import os
path = "C:/Work/test/"
xls_file = "merged.xlsx"
workbook = Workbook()
sheet = workbook.active
workbook.remove(sheet)
for dirpath, dirs, files in os.walk(path):
for filename in files:
if filen... |
017fea93032ca7134cc940f781f1d2fdf0fa6900 | MartinGalvanCastro/UDP-Server | /src/logger.py | 2,061 | 3.84375 | 4 | import logging
from datetime import datetime
class logger:
def __init__(self,handler:str):
"""Create a logger
Args:
handler (str): Handler for the logger
"""
now = datetime.now()
time = now.strftime("%Y-%m-%d-%H-%M-%S")
logs_filename = f"logs/{... |
9e1f39f38cfb01d98dece9ef85cd12537c8b6377 | debeshmandal/starpolymers | /starpolymers/io/colvars.py | 2,336 | 3.609375 | 4 | """
Script to generate Colvars files
"""
def _create(star, dna, lower, upper, k, steps, start, stop):
"""
Create a string to be written to a Colvars file.
Parameters
----------
star : int
number of atoms in star polymer
dna : int
number of atoms in dna molecule
lower : floa... |
40a656582586a941945de4d2e62dd1aeed82236b | gokarna14/Facebook-Friend-based-on-ethinicity-NEPALI | /DDA.py | 611 | 3.8125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
p = [
[int(input("ENTER X1: ")), int(input("ENTER Y1:"))],
[int(input("ENTER X2: ")), int(input("ENTER Y2:"))]
]
dx = -(p[0][0]-p[1][0])
dy = -(p[0][1]-p[1][1])
step = 0
x = [p[0][0]]
y = [p[0][1]]
x_ = x[0]
y_ = y[0]
if abs(dx) > abs(dy):
... |
a4622371d83ba767750aedbc575e2d7f8a046e5b | SWABHIMAN8400/Robotics-Learning-Series | /python_task1.py | 1,701 | 3.5 | 4 | import random
num =random.randrange(1000,10000)
copy1=num
n=int(input("guess the 4digit number:"))
points =20
#storing digits of random number
nu4=int(num%10)
nu3=int((num/10)%10)
nu2=int((num/100)%10)
nu1=int((num/1000)%10)
#function for working of program
def checkdigitmatch(c,points,n,num,t):
while (n != num):
... |
57d514a145018a271cdfbe941b720a82a951d6b8 | cb1521/freestyle-project | /app/weather_service.py | 8,595 | 3.609375 | 4 | import os
import json
from pprint import pprint
from dateutil.parser import parse as parse_datetime
import requests
from app import APP_ENV
from dotenv import load_dotenv
from pgeocode import Nominatim as Geocoder
from pandas import isnull
load_dotenv()
COUNTRY_CODE = os.getenv("COUNTRY_CODE", default="US")
ZIP_CODE... |
fe82dce52d79df152dc57e93ae6e97e9efa722e5 | keerthiballa/PyPart4 | /fibonacci_linear.py | 856 | 4.3125 | 4 | """
Exercise 3
Create a program called fibonacci_linear.py
Requirements
Given a term (n), determine the value of x(n).
In the fibonacci_linear.py program, create a function called fibonnaci. The function should take in an integer and return the value of x(n).
This problem must be solved WITHOUT the use of recursion.... |
7f020bc8300e05d3cd2b9abbc424b978f1c29745 | joaquindev/redis-first-steps | /examples/course/python/redistransaction.py | 1,490 | 3.734375 | 4 | """
This example shows the differences betweet pipeline and transaction.
The main difference is that transactions are atomic. In this example we will
launch a pipeline with a number of incr in a counter. also in another thread
there will be a loop sending continous request fo se the state of the counter.
In a transac... |
fedaeb5fdd5c929563ba0892cef53acb354f81a9 | kuzichkin2001/MachineLearning | /MachineLearningPractice/contest1/task10.py | 106 | 3.515625 | 4 | a = int(input())
b = int(input())
x = int((a + b) / 2)
y = int((a - b) / 2)
print(str(x) + ' ' + str(y)) |
37043bf898cac972ecd19dcaa90ab93eb5cf27e7 | kuzichkin2001/MachineLearning | /MachineLearningPractice/contest2/task11.py | 247 | 3.875 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
if (a ** 2 + b ** 2) ** 0.5 <= d:
print('Yes')
elif (a ** 2 + c ** 2) ** 0.5 <= d:
print('Yes')
elif (b ** 2 + c ** 2) ** 0.5 <= d:
print('Yes')
else:
print('No') |
a35e62aeae798a6e4c80812fec93bc8dfd0fc86b | sudarshansanjeev/Python | /varDemo.py | 180 | 3.625 | 4 |
y=1;
def abc() :
x = 1;
print("x value : ",x);
x+=1;
def xyz() :
global y;
print("y value : ",y);
y+=1;
abc();
abc();
xyz();
xyz();
|
9856acbe7977805896a68085db9e69bdc726a610 | sudarshansanjeev/Python | /employeePandas.py | 1,247 | 3.5625 | 4 | import numpy as py;
import pandas as pd;
df = pd.read_csv(r'C:\Users\768936\Desktop\CTS\Python\employeeDetails.csv',names=["id","name","age","salary","designation","department","project_id","project_name","manager","city","state"]);
#print(df);
# eldest
mx = df['age'].max();
#print(df[df.age==mx]);
# you... |
5c72e6f97103091273550c256d44b3a01640076e | zhaoxuyan/raspberry_code | /10_caculator.py | 5,315 | 3.84375 | 4 | # -*- coding: utf-8 -*
import Tkinter
import tkFont
# 计算
def calculate():
try:
# eval()是python的内置函数, 用来执行一个字符串表达式,并返回表达式的值。
# display_str.get()获取此时display_str内容
result = eval(display_str.get())
# 拼接
display_str.set(display_str.get() + "=\n" + str(result))
except:
... |
b82ffe9426c6a5d5f9d2b4824b5b59018b83a0ee | SergeyOreshkin1/TestTask | /testTask/main.py | 2,150 | 3.8125 | 4 | import random
def task():
# Итоговый массив
a = []
# Вспомогательный массив для проверки, что все массивы имеют разную длину. Его элементы - длины массивов.
b = []
print("Количество массивов - натуральное число, (n > 0)")
for n in range(int(input("Введите количество массивов: "))+1):
#... |
38367ab9a4c7cc52c393e9c22b1752dd27e0f0f4 | eugenejazz/python2 | /task02-2.py | 625 | 4.25 | 4 | # coding: utf-8
# 2. Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560, то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
def checkeven(x):
if (int(x) % 2) == 0:
return 1
else:
return 0
def checkodd(x):
if (int(x) % 2) == 0:
return 0
else:
retu... |
4e480a91ec51f5a2b8bf4802c3bd40d134cac839 | eugenejazz/python2 | /task02-3.py | 412 | 4.4375 | 4 | # coding: utf-8
# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
# Например, если введено число 3486, то надо вывести число 6843.
def reversestring(x):
return(print(x[::-1]))
a = str(input("Введите число: "))
reversestring(a) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.