blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
df13a154e79b15d5a9b58e510c72513f8f8e2fa0 | dipak-pawar131199/pythonlabAssignment | /Conditional Construct And Looping/SetB/Fibonacci.py | 550 | 4.1875 | 4 | '''4) Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
a. 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
b. By considering the terms in the Fibonacci sequence whose values do not exceed
four hundred, find the sum of the even-valued t... | true |
10e021531d1b56e1375e898e7599422de0ce5c9a | RobStepanyan/OOP | /Random Exercises/ex5.py | 776 | 4.15625 | 4 | '''
An iterator
'''
class Iterator:
def __init__(self, start, end, step=1):
self.index = start
self.start = start
self.end = end
self.step = step
def __iter__(self):
# __iter__ is called before __next__ once
print(self) # <__main__.Iterator object at 0x0000014... | true |
9de5002aa797d635547bb7ca1989a435d4a97256 | altvec/lpthw | /ex32_1.py | 571 | 4.46875 | 4 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count {0}".format(number)
# same as above
for fruit in fruits:
print "A fruit of type: {0... | true |
08087cefea1ebcb767e8cec2e4bcd3f4535b60de | PacktPublishing/Software-Architecture-with-Python | /Chapter04/rotate.py | 417 | 4.1875 | 4 | # Code Listing #6
"""
Example with collections.deque for rotating sequences
"""
from collections import deque
def rotate_seq1(seq1, n):
""" Rotate a sequence left by n """
# E.g: rotate([1,2,3,4,5], 2) => [4,5,1,2,3]
k = len(seq1) - n
return seq1[k:] + seq1[:k]
def rotate_seq2(seq1, n):
""" R... | false |
b8e6af4affac0d2ae50f36296cc55f52c6b44af3 | PacktPublishing/Software-Architecture-with-Python | /Chapter04/defaultdict_example.py | 1,374 | 4.1875 | 4 | # Code Listing #7
"""
Examples of using defaultdict
"""
from collections import defaultdict
counts = {}
text="""Python is an interpreted language. Python is an object-oriented language.
Python is easy to learn. Python is an open source language. """
word="Python"
# Implementations with simple dictionary
for word ... | true |
97b15762af24ba6fb59fc4f11320e99ffcec6cf4 | rxxxxxxb/PracticeOnRepeat | /Python Statement/practice1.py | 540 | 4.125 | 4 |
# Use for, .split(), and if to create a Statement that will print out words that start with 's'
st = 'Print only the words that start with s in this sentence'
for word in st.split():
if word[0] == 's':
print(word)
# even number using range
li = list(range(1,15,2))
print(li)
#List comprehension to ... | true |
70c96ccdda8fec43e4dc2d85ba761bae2c4de876 | heyimbarathy/py_is_easy_assignments | /pirple_functions.py | 978 | 4.15625 | 4 | # -----------------------------------------------------------------------------------
# HOMEWORK #2: FUNCTIONS
# -----------------------------------------------------------------------------------
'''create 3 functions (with the same name as those attributes),
which should return the corresponding value for the attrib... | true |
910185af5c3818d848aa569d6e57de868c9cb790 | heyimbarathy/py_is_easy_assignments | /pirple_lists.py | 1,311 | 4.15625 | 4 | # -----------------------------------------------------------------------------------
# HOMEWORK #4: LISTS
# -----------------------------------------------------------------------------------
'''Create a function that allows you to add things to a list.
Anything that's passed to this function should get added to myUni... | true |
29cc26a015801f4d1fe5e4c5ab103118b98e47bf | Segoka/python_learning | /colacao.py | 650 | 4.125 | 4 | print("*****Preparación de Colacao******")
leche = input("Primero de todo.... tienes leche? [s/n] ")
colacao = input("Y... tienes colacao? [s/n] ")
if leche == "s" and colacao == "s":
print("Perfecto!! Pon la leche en un vaso luego el colacao y a disfrutar :)")
elif leche != "s" and colacao == "s":
... | false |
5045f39041869fd81a8c406159a1bec39e4b7372 | abdelilah-web/games | /Game.py | 2,707 | 4.15625 | 4 |
class Game:
## Constractor for the main game
def __init__(self):
print('Welcome to our Games')
print('choose a game : ')
print('press [1] to play the Even-odd game')
print('Press [2] to play the Average game')
print('Press [3] to play the Multiplication')
self.ch... | true |
b9b5e983017845ef38400a7d8ad8c9e35333d405 | bghoang/coding-challenge-me | /leetcode/Other (not caterogize yet)/maxProductThreeNumbers.py | 1,411 | 4.25 | 4 | '''
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
'''
'''
First solution: O(nlogn) runtime/ O(logn) space caus of sortings
Sort the array,
Find the product of the last 3 numbers
Find the... | true |
17756e03f8022ead554e7ec67add12ea22a45cb5 | lj015625/CodeSnippet | /src/main/python/stack/minMaxStack.py | 1,932 | 4.125 | 4 | """
Write a class for Min Max Stack.
Pushing and Popping value from the stack;
Peeking value at top of the stack;
Getting both minimum and maximum value in the stack at any time.
"""
from collections import deque
class MinMaxStack:
def __init__(self):
# doubly linked list deque is more efficient to imple... | true |
f2e670471bfa9bcac1e5f983ecdb0240eeaaf1f2 | lj015625/CodeSnippet | /src/main/python/array/sumOfTwoNum.py | 1,598 | 4.125 | 4 | """Given an array and a target integer, write a function sum_pair_indices that returns the indices of two integers
in the array that add up to the target integer if not found such just return empty list.
Note: even though there could be many solutions, only one needs to be returned."""
def sum_pair_indices(array, targ... | true |
153468d2ee32d18c1fe7cd6ee705d0f2e38c6ac2 | lj015625/CodeSnippet | /src/main/python/string/anagram.py | 626 | 4.28125 | 4 | """Given two strings, write a function to return True if the strings are anagrams of each other and False if they are not.
A word is not an anagram of itself.
"""
def is_anagram(string1, string2):
if string1 == string2 or len(string1) != len(string2):
return False
string1_list = sorted(string1)
str... | true |
ce33d6bb0f0db42a8a0b28543f1ea6895da0d00c | lj015625/CodeSnippet | /src/main/python/tree/binarySearch.py | 1,055 | 4.1875 | 4 | def binary_search_iterative(array, target):
if not array:
return -1
left = 0
right = len(array)-1
while left <= right:
mid = (left + right) // 2
# found the target
if array[mid] == target:
return mid
# if target is in first half then search from the st... | true |
0ecfc8d40c1d7eba616676d03f04bb9bf187dc09 | xamuel98/The-internship | /aliceAndBob.py | 414 | 4.4375 | 4 | # Prompt user to enter a string
username = str(input("Enter your username, username should be alice or bob: "))
''' Convert the username to lowercase letters and compare
if the what the user entered correlates with accepted string '''
if username.lower() == "alice" or username.lower() == "bob":
pr... | true |
ed4ebe2d41a2da81d843004f32223f0662e59053 | ParulProgrammingHub/assignment-1-kheniparth1998 | /prog10.py | 308 | 4.125 | 4 | principle=input("enter principle amount : ")
time=input("enter time in years : ")
rate=input("enter the interest rate per year in percentage : ")
def simple_interest(principle,time,rate):
s=(principle*rate*time)/100
return s
print "simple interest is : ",simple_interest(principle,rate,time)
| true |
3993689551ceed1cf1878340872846df0863556e | WangDongDong1234/python_code | /高级算法复习/ppt复习/2-2冒泡排序.py | 268 | 4.1875 | 4 | """
冒泡排序
"""
def bubbleSort(array):
for i in range(len(array)-1):
for j in range(0,len(array)-1-i):
if array[j]>array[j+1]:
array[j],array[j+1]=array[j+1],array[j]
array=[2,1,5,6,3,4,9,8,7]
bubbleSort(array)
print(array) | false |
8e73474a9ac03600fee353f5f64259dae9840592 | Sachey-25/TimeMachine | /Python_variables.py | 1,234 | 4.21875 | 4 | #Practice : Python Variables
#Tool : Pycharm Community Edition
#Platform : WINDOWS 10
#Author : Sachin A
#Script starts here
'''Greet'='This is a variable statement'
print(Greet)'''
#Commentning in python
# -- Single line comment
#''' ''' or """ """ multiline comment
print('We are learning python script... | true |
1e8e3b23f03923e87e1910f676cda91e93bc02c8 | skyesyesyo/AllDojo | /python/typelist.py | 929 | 4.25 | 4 | #input
one = ['magical unicorns',19,'hello',98.98,'world']
#output
"The array you entered is of mixed type"
"String: magical unicorns hello world"
"Sum: 117.98"
# input
two = [2,3,1,7,4,12]
#output
"The array you entered is of integer type"
"Sum: 29"
# input
three = ['magical','unicorns']
#output
"The array you enter... | true |
10c76b6c1e3466af784504b55e09bb4580f8303e | linth/learn-python | /function/base/2_closures_fun.py | 1,679 | 4.15625 | 4 | '''
Closure(閉包)
- 寫法特殊請注意
- 在 A 函式中再定義一個 B 函式。
- B 函式使用了 A 函式中的變量。
- A 函式返回 B 函式名。
閉包的使用時機
- 閉包避免了全域變數的使用,並可將資料隱藏起來。
- 當你有一些變數想要定義一個類別封裝起來時,若這個類別內只有一個方法時,使用閉包更為優雅
Reference:
- https://medium.com/@zhoumax/python-%E9%96%89%E5%8C%85-closure-c98c24e52770
- https://www.pythontutorial.net/... | false |
b73586058504c9ac8246fec05a91b091961be353 | linth/learn-python | /data_structure/dict/dict_and_list_example.py | 326 | 4.21875 | 4 | '''
dict + list 範例
Reference:
- https://www.geeksforgeeks.org/python-ways-to-create-a-dictionary-of-lists/?ref=gcse
'''
d = dict((val, range(int(val), int(val) + 2)) for val in ['1', '2', '3'])
print([dict(id=v) for v in range(4)]) # [{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}]
# d2 = dict(a=[1, 2, 3])
# print(d2... | false |
95a0c7d5fd0cf60f7782f94f3dff469b636c519b | linth/learn-python | /async_IO/coroutines/base/1_multiple_process.py | 928 | 4.125 | 4 | '''
使用 multiple-processing 範例
Reference:
- https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb
'''
from multiprocessing import Process
def print_country(country='Asia'):
print('The name of country is: ', country)
# 如果不輸入引數情況下
def not_args():
p ... | false |
886377b8aa15d2883936779974d51aad0e87916e | linth/learn-python | /algorithm/sorting/sort_base.py | 943 | 4.25 | 4 | """
List sorting.
- sorted: 原本的 list 則不受影響
- sort: 改變原本的 list 內容
- sorted(x, revere=True) 反向排序
- itemgetter(), attrgetter()
Reference:
- https://officeguide.cc/python-sort-sorted-tutorial-examples/
"""
from operator import itemgetter, attrgetter
scores = [
('Jane', 'B', 12),
('John', 'A', ... | false |
8750cd8ce01b9521305987bd142f4815f4a0629d | linth/learn-python | /function/lambda/filter/filter.py | 1,070 | 4.125 | 4 | """
References:
- https://www.runoob.com/python/python-func-filter.html
- https://www.liaoxuefeng.com/wiki/1016959663602400/1017323698112640
- https://wiki.jikexueyuan.com/project/explore-python/Advanced-Features/iterator.html
"""
import math
from collections import Iterable
# Iterator 判斷一個object是不是可迭代的
d... | false |
8e018e0b2149ca6dab654c12849004e44761b8ba | linth/learn-python | /class/classAttr_instanceAttr/instance-method/1_InstanceMethod.py | 479 | 4.21875 | 4 | '''
實體方法(Instance Method)
- 至少要有一個self參數
- 實體方法(Instance Method) 透過self參數可以自由的存取物件 (Object)的屬性 (Attribute)及其他方法(Method)
Reference:
- https://www.learncodewithmike.com/2020/01/python-method.html
'''
class Cars:
# 實體方法(Instance Method)
def drive(self):
print('Drive is instance method... | false |
8b4a7475433936941c7f9794ec67783a4be5cadf | linth/learn-python | /function/anonymous_function/anonymous_filter.py | 1,392 | 4.34375 | 4 | """
Anonymous function. (匿名函數)
- map
- filter
- reduce
lambda程式撰寫方式:
- lambda arguments: expression
map程式撰寫方式:
- map(function, iterable(s))
- 抓取符合的元素。
filter程式撰寫方式:
- filter(function, iterable(s))
- 用來過濾序列,過濾掉不符合的元素。
reduce程式撰寫方式:
- reduce(function, sequence[, initial])
- 對序列... | false |
d09451cfc1aae0949562891a2b0d78a385a4eee2 | linth/learn-python | /algorithm/sorting/merge_sort.py | 1,809 | 4.53125 | 5 | """
Merge sorting (合併排序法)
- 把一個 list 開始逐步拆成兩兩一組
- 合併時候再逐步根據大小先後加入到新的 list裡面
- Merge Sort屬於Divide and Conquer演算法
- 把問題先拆解(divide)成子問題,並在逐一處理子問題後,將子問題的結果合併(conquer),如此便解決了原先的問題。
Reference:
- https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm#
- https://www... | false |
139447d3a6786a3fe0312574c48924ab83f7c709 | linth/learn-python | /async_IO/multithreading/base/5_queue_threads.py | 976 | 4.1875 | 4 | '''
學習如何使用 queue + threads
Reference:
- https://blog.gtwang.org/programming/python-threading-multithreaded-programming-tutorial/
'''
from threading import Thread
import time
import queue
class Worker(Thread):
def __init__(self, queue, num):
Thread.__init__(self)
self.queue = queue
se... | false |
584c4e36f9801a63fd17adae4c750647d0afeec8 | linth/learn-python | /class/specificMethod-3.py | 606 | 4.3125 | 4 | '''
specific method
- __str__() and __repr__()
- __repr__() magic method returns a printable representation of the object.
- The __str__() magic method returns the string
Reference:
- https://www.geeksforgeeks.org/python-__repr__-magic-method/?ref=rp
'''
class GFG:
def __init__(self, name):
... | true |
a7ab0d16e3266d89e3119cfe59447d30062a9140 | kelly4strength/intCakes | /intCake3.py | 2,264 | 4.40625 | 4 | # Given a list_of_ints,
# find the highest_product you can get from three of the integers.
# The input list_of_ints will always have at least three integers.
# find max, pop, add popped to a new list_of_ints
# add those ints bam!
# lst = [11,9,4,7,13, 21, 55, 17]
# returns [55, 21, 17]
# 93
# lst = [0, 9, 7]
# retu... | true |
0a3ab7aeeb12e47a41360f067099808b99eeac08 | ChoSooMin/Web_practice | /python_pratice/command.py | 1,230 | 4.1875 | 4 | # list type : [str, int, float, boolean, list] [[1, 2, 3], [1, 2]] list 안의 list가 들어갈 경우, 안에 있는 list의 각 길이가 꼭 같을 필요는 없다.
list_a = [1, 2, 3]
list_b = [4, 5, 6]
print(list_a + list_b, " + 연산 후 list_a : ", list_a) # list_a 값을 변하게 하려면 list_a에 할당을 다시 해줘야 한다.
# 할당했을 경우
# list_a = list_a + list_b
# print("list_a 할당", list_a)... | false |
f4c64fc63ebd9097cc450cc546586f504d385028 | MariaAga/Codewars | /Python/triangle_type.py | 335 | 4.125 | 4 | # Should return triangle type:
# 0 : if triangle cannot be made with given sides
# 1 : acute triangle
# 2 : right triangle
# 3 : obtuse triangle
def triangle_type(a, b, c):
x,y,z = sorted([a,b,c])
if (x+y)<=z:
return 0
if (x*x+y*y==z*z):
return 2
if z*z > (x*x + y*y):
return... | false |
d0434e4c42c139b85ec28c175749bb189d2a19bf | Francisco-LT/trybe-exercices | /bloco36/dia2/reverse.py | 377 | 4.25 | 4 | # def reverse(list):
# reversed_list = []
# for item in list:
# reversed_list.insert(0, item)
# print(reversed_list)
# return reversed_list
def reverse(list):
if len(list) < 2:
return list
else:
print(f"list{list[1:]}, {list[0]}")
return reverse(list[1:]) + ... | true |
d2d8f309a900c4642f0e7c66b3d33e26cabaf4e9 | synaplasticity/py_kata | /ProductOfFibNumbers/product_fib_num.py | 597 | 4.34375 | 4 | def fibonacci(number):
if number == 0 or number == 1:
return number*number
else:
return fibonacci(number - 1) + fibonacci(number - 2)
def product_fib_num(product):
"""
Returns a list of the two consecutive fibonacci numbers
that give the provided product and a boolean indcating if
... | true |
1687b77c4b2d3c44b6871e653a974153db7d3f96 | ntuthukojr/holbertonschool-higher_level_programming-6 | /0x07-python-test_driven_development/0-add_integer.py | 578 | 4.125 | 4 | #!/usr/bin/python3
"""Add integer module."""
def add_integer(a, b=98):
"""
Add integer function.
@a: integer or float to be added.
@b: integer or float to be added (default set to 98).
Returns the result of the sum.
"""
if not isinstance(a, int) and not isinstance(a, float):
raise... | true |
87ee73accac83e33eb0bf032d403ca1fa16c3b63 | evnewlund9/repo-evnewlund | /PythonCode/reverse_string.py | 414 | 4.28125 | 4 | def reverse(string):
list = [character for character in string]
x = 0
n = -1
while x <= ((len(list))/2)-1:
a = list[x]
b = list[n]
list[x] = b
list[n] = a
x = x + 1
n = n - 1
stringFinal = ""
for letter in list:
stringFinal += letter
re... | false |
394bc8e14a370f22d39fc84f176275c58d1ac349 | evnewlund9/repo-evnewlund | /PythonCode/alternating_sum.py | 414 | 4.125 | 4 | def altSum(values):
sum = 0
for i in range(1,(len(values) + 1),2):
sum = sum + (int(values[i]) - int(values[(i - 1)]))
return sum
def main():
values = []
num = "0"
while num != "":
values.append(num)
num = input("Enter a floating point value: ")
answer = str(altSum(v... | false |
7294ac7e6fa9a8e9d9b17cc661f639f7a04c289f | vdubrovskiy/Python | /new.py | 738 | 4.21875 | 4 | # -------------------------------------------------------
# import library
import math
# -------------------------------------------------------
# calculate rect. square
height = 10
width = 20
rectangle_square = height * width
print("Площадь прямоугольника:", rectangle_square)
# --------------------------------------... | false |
b0cd7324e8b0835b40f9c1efbb48ff372ce54386 | adyrmishi/100daysofcode | /rock_paper_scissors.py | 843 | 4.15625 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''... | false |
53bf0300d334909355777fa043e37beb823bd7d2 | NixonRosario/Encryption-and-Decryption | /main.py | 2,772 | 4.1875 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# The Encryption Function
def cipher_encrypt(plain_text, key): # key is used has an swifting value
encrypted... | true |
29d0f0a5b83dbbcee5f053a2455f9c8722b6cb51 | MrYsLab/pseudo-microbit | /neopixel.py | 2,943 | 4.21875 | 4 | """
The neopixel module lets you use Neopixel (WS2812) individually
addressable RGB LED strips with the Microbit.
Note to use the neopixel module, you need to import it separately with:
import neopixel
Note
From our tests, the Microbit Neopixel module can drive up to around 256
Neopixels. Anything above that and yo... | true |
9d7df65d3a7a46a8c762c189d76bdebc04db78a9 | Baude04/Translation-tool-for-Pirates-Gold | /fonctions.py | 299 | 4.1875 | 4 | def without_accent(string):
result = ""
for i in range(0,len(string)):
if string[i] in ["é","è","ê"]:
letter = "e"
elif string[i] in ["à", "â"]:
letter = "a"
else:
letter = string[i]
result += letter
return result
| false |
638715d691110084c104bba50daefd5675aea398 | baif666/ROSALIND_problem | /find_all_substring.py | 501 | 4.25 | 4 | def find_all(string, substr):
'''Find all the indexs of substring in string.'''
#Initialize start index
i = -1
#Creat a empty list to store result
result = []
while True:
i = string.find(substr, i+1)
if i < 0:
break
result.append(i)
return result
... | true |
b0cad0b1e60d45bc598647fa74cb1c584f23eeaa | JGMEYER/py-traffic-sim | /src/physics/pathing.py | 1,939 | 4.1875 | 4 | from abc import ABC, abstractmethod
from typing import Tuple
import numpy as np
class Trajectory(ABC):
@abstractmethod
def move(self, max_move_dist) -> (Tuple[float, float], float):
"""Move the point along the trajectory towards its target by the
specified distance.
If the point woul... | true |
d45df8bc1090aee92d3b02bb4e1d42fc93c402a0 | dheerajkjha/PythonBasics_Udemy | /programmingchallenge_addition_whileloop.py | 285 | 4.25 | 4 | number = int(input("Please enter an Integer number."))
number_sum = 0
print("Entered number by the user is: " + str(number))
while number > 0:
number_sum = number_sum + number
number = number - 1
print("Sum of the numbers from the entered number and 1 is: " + str(number_sum))
| true |
e96f81fc4967ca2dbb9993097f2653632b08a613 | dheerajkjha/PythonBasics_Udemy | /programmingchallenge_numberofcharacters_forloop.py | 258 | 4.34375 | 4 | user_string = input("Please enter a String.")
number_of_characters = 0
for letter in user_string:
number_of_characters = number_of_characters + 1
print(user_string)
print("The number of characters in the input string is: " + str(number_of_characters))
| true |
5e865b5a2ac4f087c4fe118e0423ef05908a4a09 | reedless/dailyinterviewpro_answers | /2019_08/daily_question_20190827.py | 528 | 4.5 | 4 | '''
You are given an array of integers. Return the largest product that
can be made by multiplying any 3 integers in the array.
Example:
[-4, -4, 2, 8] should return 128 as the largest product can be made by multiplying -4 * -4 * 8 = 128.
'''
def maximum_product_of_three(lst):
lst.sort()
cand1 =... | true |
5e9bb62185611666f43897fd2033bae28d91ee18 | reedless/dailyinterviewpro_answers | /2019_08/daily_question_20190830.py | 806 | 4.21875 | 4 | '''
Implement a queue class using two stacks.
A queue is a data structure that supports the FIFO protocol (First in = first out).
Your class should support the enqueue and dequeue methods like a standard queue.
'''
class Queue:
def __init__(self):
self.head = []
self.stack = []
def ... | true |
f1d328556b13e5d99c75d43cd750585184d9d9fa | deltahedge1/decorators | /decorators2.py | 1,008 | 4.28125 | 4 | import functools
#decorator with no arguments
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(*args, **kwargs): #need to add args and kwargs
print("in the decorator")
func(*args, **kwargs) #this is the original function, dont forget to add args and kwargs
pri... | true |
0ac3a65fea58acea5bc8ae4b1bbf9a4fb45b9f87 | Hilamatu/cse210-student-nim | /nim/game/board.py | 1,548 | 4.25 | 4 | import random
class Board:
"""A board is defined as a designated playing surface.
The responsibility of Board is to keep track of the pieces in play.
Stereotype: Information Holder
Attributes:
"""
def __init__(self):
self._piles_list = []
self._prepare()
... | true |
686e53872c553c6dedc03dac6cf19806cc10b19e | NenadPantelic/Cracking-the-coding-Interview | /LinkedList/Partition.py | 1,985 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 16:45:16 2020
@author: nenad
"""
"""
Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
before all nodes greater than or equal to x. If x is contained within the list, the values of x only nee... | true |
886195fb51ac965a88f3ad3c3d505548638cc6bd | JadsyHB/holbertonschool-python | /0x06-python-classes/102-square.py | 2,010 | 4.59375 | 5 | #!/usr/bin/python3
"""
Module 102-square
Defines Square class with private attribute, size validation and area
accessible with setters and getters
comparison with other squares
"""
class Square:
"""
class Square definition
Args:
size: size of side of square, default size is 0
Functions:
... | true |
55ffa8c32622c42f6d3a314018a0adaf0e1c0d18 | JadsyHB/holbertonschool-python | /0x06-python-classes/1-square.py | 373 | 4.125 | 4 | #!/usr/bin/python3
"""
Module 1-square
class Square defined with private attribute size
"""
class Square:
"""
class Square
Args:
size: size of a side in a square
"""
def __init__(self, size):
"""
Initialization of square
Attributes:
size: size of a sid... | true |
4db4720f452b2db358234f9ce50735430fb6a938 | Rouzip/Leetcode | /Search Insert Position.py | 354 | 4.125 | 4 | def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target <= nums[0]:
return 0
for i in range(1, len(nums)):
if nums[i - 1] <= target <= nums[i]:
return i
return len(nu... | false |
4415ba37e475c1650da0d81b32f85b4a4ae7d45c | 23o847519/Python-Crash-Course-2nd-edition | /chapter_02/full_name.py | 492 | 4.125 | 4 | first_name = "ada"
last_name = "lovelace"
# sử dụng f-string format để đổi các biến bên trong {} thành giá trị
# f-string có từ Python 3.6
full_name = f"{first_name} {last_name}"
print(full_name)
# thêm "Hello!," ở phía trước
print(f"Hello, {full_name.title()}!")
# gom lại cho gọn
message = f"Hello, {full_name.title... | false |
7bb73b9cd6ca812395b93b17f116abd8e7033311 | 23o847519/Python-Crash-Course-2nd-edition | /chapter_09/tryityourself913.py | 796 | 4.1875 | 4 | # Import randit function from random library
from random import randint
# Make a class named Die
class Die:
def __init__(self, sides=6):
# default value of 6
self.sides = sides
def describe_die(self):
print(f"\nYour die has: {self.sides} sides")
# Write a method called roll_die() that prints
# a random n... | false |
96384a26d49430e18697d080c49f3341e7b13834 | 23o847519/Python-Crash-Course-2nd-edition | /chapter_08/tryityourself814.py | 874 | 4.4375 | 4 | # 8-14. Cars: Write a function that stores information about
# a car in a dictionary. The function should always receive
# a manufacturer and a model name. It should then accept an
# arbitrary number of keyword arguments. Call the function
# with the required information and two other name-value
# pairs, such as a colo... | true |
e0f7b4c472500360a03266df6e35031cd4534dc4 | 23o847519/Python-Crash-Course-2nd-edition | /chapter_07/tryityourself7.1.py | 334 | 4.15625 | 4 | # Ex 7.1 Rental Car
# Write a program that asks the user what kind of rental car they
# would like. Print a message about that car, such as
# “Let me see if I can find you a Subaru.”
print("\nEx 7.1")
rental_car = input("What kind of rental car would you like?\n")
print(f"\nLet me see if I can find you a {rental_car.t... | true |
9cca96cb78e6ae2772c76f81ccf6a2106ee0ac99 | 23o847519/Python-Crash-Course-2nd-edition | /chapter_03/cars.py | 604 | 4.28125 | 4 | #Sorting
print("\nSorting")
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.sort()
print(cars)
#Reverse sorting
print("\nReverse sorting")
cars.sort(reverse=True)
print(cars)
#Sort tạm thời
print("\n Sorted()")
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Original list:")
print(cars)
print("\nSorted... | true |
44f55bae68ae6fa0fddd6628dea0c92e1f0d81fe | 23o847519/Python-Crash-Course-2nd-edition | /chapter_10/tryityourself106.py | 726 | 4.3125 | 4 | # 10-6. Addition: One common problem when prompting for numerical input
# occurs when people provide text instead of numbers. When you try to
# convert the input to an int, you’ll get a ValueError. Write a program
# that prompts for two numbers. Add them together and print the result.
# Catch the ValueError if either i... | true |
6ba1d02a2025378d11c0cfbf8a11055e0593e3ca | radishmouse/06-2017-cohort-python | /104/n_to_m.py | 629 | 4.375 | 4 | n = int(raw_input("Start from: "))
m = int(raw_input("End on: "))
# Let's use a while loop.
# Every while loop requires three parts:
# - the while keyword
# - the condition that stops the loop
# - a body of code that moves closer to the "stop condition"
# our loop counts up to a value.
# let's declare a counter vari... | true |
50cbb178c40d42e83aed3f936feef223eca8a865 | radishmouse/06-2017-cohort-python | /dictionaries/dictionary1.py | 534 | 4.21875 | 4 | phonebook_dict = {
'Alice': '703-493-1834',
'Bob': '857-384-1234',
'Elizabeth': '484-584-2923'
}
#Print Elizabeth's phone number.
print phonebook_dict['Elizabeth']
#Add a entry to the dictionary: Kareem's number is 938-489-1234.
phonebook_dict['Kareem'] = '938-489-1234'
#Delete Alice's phone entry.
del phoneb... | true |
9858f021c037399c27be321b80a5111b8825e2db | BhushanTayade88/Core-Python | /Feb/day 12/Dynamic/oddeve.py | 756 | 4.3125 | 4 | #1.Program to create odd-even elements list from given list.
l=[]
eve=[]
odd=[]
n=int(input("How many no u wants add in list :"))
for i in range(n):
a=int(input("Enter Numbers :"))
l.append(a)
for i in l:
if i%2==0:
eve.append(i)
else:
odd.append(i)
print("----Statements----\n" \
... | false |
a10c31fc5c15b63e5fd895e1457282eafab1f10f | BhushanTayade88/Core-Python | /March/day 10 filefand/taskfilehand/2perticularline.py | 419 | 4.125 | 4 | '''
2.Program to display particular line taken by user.
'''
f=open("bhushan.txt","r")
##print(f.tell())
##print(f.readline())
##print(f.tell())
##print(f.readline())
##print(f.tell())
##print(f.readline())
##print(f.tell())
##print(f.readline())
b=f.readlines()
print(b)
a=int(input("which line no u want see :"))
pri... | false |
ff01b3080817a8469c3aee2376c6c3abc76ebe8e | BhushanTayade88/Core-Python | /Feb/day 19 const,oper/task/callstudent.py | 2,432 | 4.15625 | 4 | from student import *
print("----Statements----\n" \
"1.Enter details--\n" \
"2.display--\n" \
"3.Exit--\n")
while True:
ch=int(input("Enter Your choice----:"))
if ch<=2:
pass
if ch==1:
l=[]
n=int(input("How many student details u want to insert ... | false |
a14253b6695c8ebbe913a05525d001fe46ddb66c | BhushanTayade88/Core-Python | /March/day 11 decorator/task2/class deco/factorial.py | 271 | 4.21875 | 4 | ##num=int(input("Enter no :"))
##for i in range(num,0,-1):
## fact = 1
## if i==0:
## print("Factorial of 0 is :",'1')
## else:
## for j in range(i,0,-1):
## fact = fact * j
##
## print("Factorial of", i ,"is :",fact)
##
| false |
6ebffaee162c491cc4f2289845a1bf7bbcd33604 | flub78/python-tutorial | /examples/conditions.py | 374 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding:utf8 -*
print ("Basic conditional instructions\n")
def even(a):
if ((a % 2) == 0):
print (a, "is even")
if (a == 0):
print (a, " == 0")
return True
else:
print (a, "is odd")
return False
even(5)
even(6)
even(0)
bln = even(6) ... | true |
0e531d7c0b4da023818f02265ab9e009420eaec6 | flub78/python-tutorial | /examples/test_random.py | 1,395 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding:utf8 -*
"""
How to use unittest
execution:
python test_random.py
or
python -m unittest discover
"""
import random
import unittest
class RandomTest(unittest.TestCase):
""" Test case for random """
def test_choice(self):
"""
given: a list
... | true |
38081fd73316e20f6361d835d710dd379e8c78ea | andremmfaria/exercises-coronapython | /chapter_06/chapter_6_6_4.py | 823 | 4.375 | 4 | # 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102) by replacing your series of print statements with ía loop that runs through the dictionary’s keys and values. When you’re sure that your loop works, add five more Python terms to your glossary. When you... | true |
9634250371f02daea5f2200e7ef401237a660e6f | andremmfaria/exercises-coronapython | /chapter_08/chapter_8_8_10.py | 765 | 4.40625 | 4 | # 8-10. Great Magicians: Start with a copy of your program from Exercise 8-9. Write a function called make_great() that modifies the list of magicians by adding the phrase the Great to each magician’s name. Call show_magicians() to see that the list has actually been modified.
def show_magicians(great_magicians):
... | false |
8c5498b935164c457447729c6de1553b390664e5 | andremmfaria/exercises-coronapython | /chapter_06/chapter_6_6_8.py | 522 | 4.34375 | 4 | # 6-8. Pets: Make several dictionaries, where the name of each dictionary is the name of a pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do print everything you know about each pet.
pet_0 = {
'kind' ... | true |
7bc98b1c9a50acb1e7ff7fe3ce2781ace3a56eb8 | andremmfaria/exercises-coronapython | /chapter_07/chapter_7_7_1.py | 257 | 4.21875 | 4 | # 7-1. Rental Car: Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as “Let me see if I can find you a Subaru.”
message = input("Let me see whether I can find you a Subaru")
print(message) | true |
1647b333db7c0d04a16dc37f794146cb9843561b | Khusniyarovmr/Python | /Lesson_1/4.py | 991 | 4.3125 | 4 | """
4. Написать программу, которая генерирует в указанных пользователем границах
● случайное целое число,
● случайное вещественное число,
● случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f',
то вводятся эти символы. Прог... | false |
5cb4a583ec8a49434d41500e142cb79879070d1a | mkccyro-7/Monday_test | /IF.py | 226 | 4.15625 | 4 | bis = int(input("enter number of biscuits "))
if bis == 3:
print("Not eaten")
elif 0 < bis < 3:
print("partly eaten")
elif bis == 0:
print("fully eaten")
else:
print("Enter 3 or any other number less than 3")
| true |
f029326ea49aaa4f1157fd6da18d6847144c5e26 | Fran0616/beetles | /beatles.py | 821 | 4.1875 | 4 | #The beatles line up
#empty list name beetles
beatles = []
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print("The beatles consist of ", beatles)
print("Both name must be enter as written below\n")
for i in beatles:
i = input("Enter the name \"Stu Sutcliffe\": "... | false |
4ccb729ebdb80510424aa920666f6b4f0acb5a2a | ErenEla/PythonSearchEngine | /Unit_1/Unit1_Hw3.py | 1,060 | 4.1875 | 4 | # IMPORTANT BEFORE SUBMITTING:
# You should only have one print command in your function
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to ... | true |
4ed0dc77c6784f2006ca437568f80a73a8d51438 | ErenEla/PythonSearchEngine | /Unit_3/Unit3_Quiz1.py | 504 | 4.15625 | 4 | # Define a procedure, replace_spy,
# that takes as its input a list of
# three numbers, and modifies the
# value of the third element in the
# input list to be one more than its
# previous value.
spy = [1,2,2]
def replace_spy(x):
x[0] = x[0]
x[1] = x[1]
x[2] = x[2]+1
return x
# In the test below, ... | true |
c2d3e85a587c11b9bae19348149545584de22a49 | Bower312/Tasks | /task4/4.py | 791 | 4.28125 | 4 | # 4) Напишите калькулятор с возможностью находить сумму, разницу, так
# же делить и умножать. (используйте функции).А так же добавьте
# проверку не собирается ли пользователь делить на ноль, если так, то
# укажите на ошибку.
def calc(a,b,z):
if z == "+":
print(a+b)
elif z == "-":
print(a-b)
... | false |
66c4d00e9ce49d8570cd7a703d04aef1b6b4d3f6 | iSabbuGiri/Control-Structures-Python- | /qs_17.py | 962 | 4.21875 | 4 | #Python program that serves as a basic calculator
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
choice = input... | true |
8bd69d5c6077386a9e79557a3d1ff83ffe464c1b | iSabbuGiri/Control-Structures-Python- | /qs_2.py | 341 | 4.15625 | 4 | #Leap year is defined as year which is exactly divisible by 4 except for century year i.e years ending with 00.
#Century year is a year which is divisible by 400
year = int(input("Enter a leap year:"))
if (year%4 == 0 and year%100 !=0 or year%400==0 ):
print("The year is a leap year")
else:
print("The year ... | false |
3ba2ea80dcc916bf8e245a2ab518042b9ee55e3e | richardrcw/python | /guess.py | 270 | 4.1875 | 4 | import random
highest = 10
num = random.randint(1, highest)
guess = -1
while guess != num:
guess = int(input("Guess number between 1 and {}: ".format(highest)))
if guess > num:
print("Lower...")
elif guess < num:
print("Higher....")
else:
print("Got it!")
| true |
4c33a43d27dede9366a759d3a40bccffcba92d3a | justhonor/Data-Structures | /Sort/BubbleSort.py | 532 | 4.15625 | 4 | #!/usr/bin/python
# coding:utf-8
##
# Filename: BubbleSort.py
# Author : aiapple
# Date : 2017-07-05
# Describe:
##
#############################################
def BubbleSort(a):
length = len(a)
while(length):
for j in range(length-1):
if a[j] > a[j+1]:
temp = a[j]
... | false |
4d737f3cdff3065f1c11c03ed8ce14c8c70b9f74 | CeciliaTPSCosta/atv-construdelas | /lista1/temperatura.py | 220 | 4.15625 | 4 | # Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius.
fahrenheit = float(input('Diga-me uma temperatura em F \n'))
print(f'{5 * ((fahrenheit-32) / 9)}°C')
| false |
efabcf8f6f413c833a75c8cc5e57e556c2d12823 | prathamarora10/guessingNumber | /GuessingNumber.py | 561 | 4.21875 | 4 | print('Number Guessing Game')
print('Guess a Number (between 1 and 9):')
import random
number = random.randint(1,9)
print(number)
for i in range(0,5,1):
userInput = int(input('Enter your Guess :- '))
if userInput < 3:
print('Your guess was too low: Guess a number higher than 3')
elif userInput < 5... | true |
39cebe0780b8532517dadf4fd04517b9ba79f207 | Carterhuang/sql-transpiler | /util.py | 922 | 4.375 | 4 | def standardize_keyword(token):
""" In returned result, all keywords are in upper case."""
return token.upper()
def join_tokens(lst, token):
"""
While joining each element in 'lst' with token,
we want to make sure each word is separated
with space.
"""
_token = token.strip(' ')
if ... | true |
8c9890c843a63d8b2fa90098b28594ba1e012d99 | justinhohner/python_basics | /datatypes.py | 1,042 | 4.34375 | 4 | #!/usr/local/bin/python3
# https://www.tutorialsteacher.com/python/python-data-types
#
"""
Numeric
Integer: Positive or negative whole numbers (without a fractional part)
Float: Any real number with a floating point representation in which a fractional component is denoted by a decimal symbol or scientifi... | true |
9acddfa9dc609fbb3aad91d19c4348dda1aee239 | jsanon01/100-days-of-python | /resources/day4/area_circumference_circle.py | 427 | 4.59375 | 5 | """
Fill out the functions to calculate the area and circumference of a circle.
Print the result to the user.
"""
import math
def area(r):
return math.pi * r ** 2
def circumference(r):
return math.pi * 2 * r
radius = float(input("Circle radius: "))
circle_area = area(radius)
circle_circumference = circu... | true |
e2ca488af3efc7e4d8f5bc72be4ac0a3f139edd9 | saumyatiwari/Algorithm-of-the-day | /api/FirstAPI.py | 790 | 4.125 | 4 | import flask
app=flask.Flask(__name__) #function name is app
# use to create the flask app and intilize it
@app.route("/", methods =['GET']) #Defining route and calling methods. GET will be in caps intalized as an arrya
# if giving the giving any configuration then function name will proceed with @ else it will use n... | true |
1544a910a16011cc302ba6bcb449c0c8887c05ee | msvrk/frequency_dict | /build/lib/frequency_dict/frequency_dict_from_collection.py | 557 | 4.53125 | 5 | def frequency_dict_from_collection(collection):
"""
This is a useful function to convert a collection of items into a dictionary depicting the frequency of each of
the items. :param collection: Takes a collection of items as input :return: dict
"""
assert len(collection) > 0, "Cannot perform the ope... | true |
660a467f0428f2564fdeec4da7f5dc171b7a2e65 | DivijeshVarma/CoreySchafer | /Decorators2.py | 2,922 | 4.46875 | 4 | # first class functions allow us to treat functions like any other
# object, for example we can pass functions as arguments to another
# function, we can return functions and we can assign functions to
# variable. Closures-- it will take advantage of first class functions
# and return inner function that remembers and ... | true |
b1ebc3eeeceebdf1eb6760c88d00be6b40d9e5cd | DivijeshVarma/CoreySchafer | /generators.py | 809 | 4.28125 | 4 | def square_nums(nums):
result = []
for i in nums:
result.append(i * i)
return result
sq_nums = square_nums([1, 2, 3, 4, 5])
print(sq_nums)
# square_nums function returns list , we could convert
# this to generator, we no longer get list
# Generators don't hold entire result in memory
# it yield ... | true |
e328a29edf17fdeed4d8e6c620fc258d9ad28890 | DivijeshVarma/CoreySchafer | /FirstclassFunctions.py | 1,438 | 4.34375 | 4 | # First class functions allow us to treat functions like
# any other object, i.e we can pass functions as argument
# to another function and returns functions, assign functions
# to variables.
def square(x):
return x * x
f1 = square(5)
# we assigned function to variable
f = square
print(f)
print(f(5))
print(f1)
... | true |
560043e5d1c9d6e31f9b9f6d4b86c02ac5bff325 | Kyeongrok/python_crawler | /lecture/lecture_gn5/week2/01_function.py | 859 | 4.21875 | 4 | # plus라는 이름의 함수를 만들어 보세요
# 파라메터는 val1, val2
# 두개의 입력받은 값을 더한 결과를 리턴하는 함수를 만들어서
# 10 + 20을 콘솔에 출력 해보세요.
def plus(val1, val2):
result = val1 + val2
return result
def minus(val1, val2):
return val1 - val2
def multiple(val1, val2):
return val1 * val2
def divide(val1, val2):
return val1 / val2
resul... | false |
4f9c1ddb562de274a644e6d41e73d70195929274 | sairamprogramming/learn_python | /book4/chapter_1/display_output.py | 279 | 4.125 | 4 | # Program demonstrates print statement in python to display output.
print("Learning Python is fun and enjoy it.")
a = 2
print("The value of a is", a)
# Using keyword arguments in python.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='+')
print(1, 2, 3, 4, sep='+', end='%')
print()
| true |
64c62c53556f38d9783de543225b11be87304daf | sairamprogramming/learn_python | /pluralsight/core_python_getting_started/modularity/words.py | 1,204 | 4.5625 | 5 | # Program to read a txt file from internet and put the words in string format
# into a list.
# Getting the url from the command line.
"""Retrive and print words from a URL.
Usage:
python3 words.py <url>
"""
import sys
def fetch_words(url):
"""Fetch a list of words from a URL.
Args:
url: The... | true |
99bd7e715f504ce64452c252ac93a026f426554d | gotdang/edabit-exercises | /python/factorial_iterative.py | 414 | 4.375 | 4 | """
Return the Factorial
Create a function that takes an integer and returns
the factorial of that integer. That is, the integer
multiplied by all positive lower integers.
Examples:
factorial(3) ➞ 6
factorial(5) ➞ 120
factorial(13) ➞ 6227020800
Notes:
Assume all inputs are greater than or equal to 0.
"""
def facto... | true |
30d9fe50769150b3efcaa2a1628ef9c7c05984fa | gotdang/edabit-exercises | /python/index_multiplier.py | 428 | 4.125 | 4 | """
Index Multiplier
Return the sum of all items in a list, where each
item is multiplied by its index (zero-based).
For empty lists, return 0.
Examples:
index_multiplier([1, 2, 3, 4, 5]) ➞ 40
# (1*0 + 2*1 + 3*2 + 4*3 + 5*4)
index_multiplier([-3, 0, 8, -6]) ➞ -2
# (-3*0 + 0*1 + 8*2 + -6*3)
Notes
All items in the lis... | true |
36f7db179bcc0339c7969dfa9f588dcd51c6d904 | adarshsree11/basic_algorithms | /sorting algorithms/heap_sort.py | 1,200 | 4.21875 | 4 | def heapify(the_list, length, i):
largest = i # considering as root
left = 2*i+1 # index of left child
right = 2*i+2 # index of right child
#see if left child exist and greater than root
if left<length and the_list[i]<the_list[left]:
largest = left
#see if right child exist and greater than root
if rig... | true |
88bf240c30c8373b3779a459698223ec3cb74e24 | mliu31/codeinplace | /assn2/khansole_academy.py | 836 | 4.1875 | 4 | """
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
def main():
num_correct = 0
while num_correct != 3:
num1 = random.randint(10,99)
num2 = random.randint(10,99)
sum = num1 + num2
answer = int(input("what is " + str(num1) + " + " +... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.