blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8f4667338e761fca8b77a813d4f5ee957e0cbaa0 | Akansha0211/Basics-of-try-except-revision | /Basics of try-except.py | 1,461 | 4.1875 | 4 | '''num1=input("Enter the first number \n")
num2=input("Enter the second number \n")
try:
print("the sum of twoi numbers is", int(num1) + int(num2))
except Exception as e:
print(e)
print("This line is very important")'''
#Will never come in except block
'''a=[1,2,3]
try:
print("second element",... | true |
9c511a9a74f9eccbed868ed190d3f58392157bed | asouzajr/algoritmosLogicaProgramacao | /lingProgPython/programasPython/testesCondicionais.py | 479 | 4.375 | 4 | x = -2
y = -3
if x == y:
print("números iguais")
elif x < y:
print ("x menor que y")
elif y > x:
print("y maior que x")
else:
print ("algo deu errado")
if x > y:
if x > 0:
print("x é maior que y e é positivo")
else:
print ("x é maior que y e é negativo")
else:
print ("y é menor que x")
if x == y:
prin... | false |
8c4d57da1267b058b76250618f25893a4114949f | jonesy212/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,277 | 4.15625 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
def selection_sort(arr):
for i in range(0, len(arr)-1):
cur__index = i
smallest_index = cur_index
#find the next smallest element q
for x in range(cur_index, len(arr)):
if arr[x] < arr[small... | true |
be344fd136945a81eb038d99bbda7372fdba3c0b | anihakobyan98/group-2 | /Exceptions/task4.py | 274 | 4.5 | 4 | ''' Number that type is integer and it can be divided to 3 '''
try:
a = int(input("Enter a number: "))
except ValueError:
print("Entered value must be an integer type")
else:
if a % 3 != 0:
raise TypeError("Number must be divisible to 3")
else:
print("Excellent")
| true |
b1119e6cb30d4b4a20dcc6a0f7065150fc080b32 | ayushthesmarty/Simple-python-car-game | /main.py | 1,336 | 4.25 | 4 | help_ = """
The are the commands of the game
help - show the commands
start - start the car
stop - stop the car
exit - exit the game
"""
print(help_)
running = True
car_run = False
while running:
command = input("Your command: ").lower()
if command == "help":
print(help_)
eli... | true |
1ff020d024ad2dd9d2e238125f6ec7402acac880 | chanzer/leetcode | /575_distributeCandies.py | 1,205 | 4.625 | 5 | """
Distribute Candies
题目描述:
Given an integer array with even length, where
different numbers in this array represent different kinds of
candies. Each number means one candy of the corresponding
kind. You need to distribute these candies equally in number
to brother and sister. Return the maximum number of kinds of
c... | true |
25b3275a82d546d5f17f9232ec4c363e2e85c402 | chanzer/leetcode | /867_transpose.py | 862 | 4.21875 | 4 | """
Transpose Matrix
题目描述:
Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over
it's main diagonal, switching the row and column indices of
the matrix.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2,3],[4,5,6]]... | true |
6d801ce1b4951d9b4b7fa1c7e39aa2d1dd69a1b4 | chanzer/leetcode | /697_findShortestSubArray.py | 1,269 | 4.21875 | 4 | """
Degree of an Array
题目描述:
Given a non-empty array of non-negative integers
nums, the degree of this array is defined as the maximum
frequency of any one of its elements.
Your task is to find the smallest possible length of a
(contiguous) subarray of nums, that has the same degree
as nums.
Example 1:
Input: [1, ... | true |
4eef3b2411dd7eaa18cd6ceb5224098379d4672c | chanzer/leetcode | /628_maximumProduct.py | 669 | 4.5 | 4 | """
Maximum Product of Three Numbers
题目描述:
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
Note:
1.The length of the given array will be in range
[3,104] and all elements are in the range... | true |
0f8c88f4a60a4c9f26553c9903e7d6d111ca8ed1 | chanzer/leetcode | /453_minMoves.py | 842 | 4.15625 | 4 | """
Minimum Moves to Equal Array Elements
题目描述:
Given a non-empty integer array of size n, find the
minimum number of moves required to make all array elements
equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:[1,2,3]
Output:3
Explanation:Only three moves are needed (remember each
move increm... | true |
6947cc6a019c3b232b432788a8ce9ed5729e8551 | MichelGeorgesNajarian/randomscripts | /Python/recursive_rename.py | 907 | 4.28125 | 4 | # Python3 code to rename multiple
# files in a directory or folder
#give root directory as argument when executing program and all the file in root directory and subsequent folders will be renamed
#renaming parameter are to remove any '[xyz123]', '(xyz123)' and to replace '_' by ' '
# importing os module
import os... | true |
0d1564abb38b41d58ce025ee1353e90e62d084be | wrgsRay/playground | /amz_label.py | 2,181 | 4.21875 | 4 | """
Python 3.6
@Author: wrgsRay
"""
import time
class Shipment:
def __init__(self, last_page, total_pallet, pallet_list=[], current_pallet):
self.last_page = last_page
self.total_pallet = total_pallet
self.pallet_list = pallet_list
self.current_pallet = current_pallet
def get_... | true |
d603602255347b138dfb7b6685222b2b03501986 | SaraKenig/codewars-solutions | /python/7kyu/Unique string characters.py | 598 | 4.34375 | 4 | # In this Kata, you will be given two strings a and b and your task will be to return the characters that are not common in the two strings.
# For example:
# solve("xyab","xzca") = "ybzc"
# --The first string has 'yb' which is not in the second string.
# --The second string has 'zc' which is not in the first string.
... | true |
acbf417955c0e14618b09ab10a0952fc6e63d79a | SaraKenig/codewars-solutions | /python/7kyu/sort array by last character.py | 539 | 4.34375 | 4 | # Sort array by last character
# Write a function sortMe or sort_me to sort a given array or list by last character of elements.
# Element can be an integer or a string.
# Example:
# sortMe(['acvd','bcc']) => ['bcc','acvd']
# The last characters of the strings are d and c. As c comes before d, sorting by last chara... | true |
32b1fdce0553b30a13993a7f2d487af7187b4500 | FrancoisCzarny/HackerRank | /Python/Python_weirdFunction.py | 565 | 4.46875 | 4 | #!/usr/bin/env python
#-*- coding : utf-8 -*-
"""
Given an integer, n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weir... | false |
b7f7a1ec2ec63e46c1162b3e5e6967048f222569 | vidyakov/geek | /2lesson/2_task.py | 572 | 4.28125 | 4 | # Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
a = input('Введите натуральное число: ')
even = 0
odd = 0
for i in a:
if int(i) % 2 == 0 or i == '0':
even += 1
else:
odd += 1
print(f... | false |
77637b2eaef358ad308de773a915caddab871f12 | begogineni/cs-guided-project-python-basics | /src/demonstration_03.py | 566 | 4.40625 | 4 | """
Challenge #3:
Create a function that takes a string and returns it as an integer.
Examples:
- string_int("6") ➞ 6
- string_int("1000") ➞ 1000
- string_int("12") ➞ 12
"""
import re
def string_int(txt):
'''
input: str
output: int
'''
# Your code here
#what to do if there is a letter in the... | true |
2bea7f84ca43f1bfde89b3590f7212edf469a5d9 | tarushsinha/WireframePrograms | /3fizz5buzz.py | 452 | 4.125 | 4 | ## program that returns multiples of 3 as fizz, multiples of 5 as buzz, and multiples of both as fizzbuzz within a range
def fizzBuzz(rng):
retList = []
for i in range(rng):
if i % 3 == 0 and i % 5 == 0:
retList.append("fizzbuzz")
elif i%3 == 0:
retList.append("fizz")
... | true |
52f36317552e8eb0e533b61c0f4947b653e7d52d | saikirandulla/HW06 | /HW06_ex09_04.py | 1,337 | 4.40625 | 4 | #!/usr/bin/env python
# HW06_ex09_04.py
# (1)
# Write a function named uses_only that takes a word and a string of letters,
# and that returns True if the word contains only letters in the list.
# - write uses_only
# (2)
# Can you make a sentence using only the letters acefhlo? Other than "Hoe
# alfalfa?"
# - writ... | true |
31f3c7d5da418e3abbf4c44fced349ab7aac1fab | yotroz/white-blue-belt-modules | /17-exceptions/blue_belt.py | 488 | 4.53125 | 5 | #%%
#Create a function that reads through a file
#and prints all the lines in uppercase.
#
#
#
#be sure to control exceptions that may occur here,
#such as the file not existing
def print_file_uppercase(filename):
try:
file = open(filename)
for line in file:
print(line... | true |
147ebca997008e894bd6b5f6f74d63c658643188 | Umesh8Joshi/My-Python-Programs | /numbers/PItoNth.py | 274 | 4.21875 | 4 | '''
Enter a number to find the value of PI till that digit
'''
def nthPI(num):
'''
function to return nth digit value of PU
:param num: number provided by user
:return : PI value till that digit
'''
num = input('Enter the digit')
return "%.{num}f"(22/7).format(num) | true |
d05ea438611f9a1af279a4935c1c966047ae41d5 | Chener-Zhang/HighSchoolProject | /Assembly/hw6pr5.py | 2,447 | 4.15625 | 4 | # hw6 problem 5
#
# date:
#
# Hmmm...
#
#
# For cs5gold, this is the Ex. Cr. recursive "Power" (Problem4)
# and recursive Fibonacci" (Problem5) program
# Here is the starter for gold's Problem4 (recursive power):
# This is the recursive factorial from class, to be changed to a recursive _po... | true |
f8c33c98dc671fd597a5b40848d72e42f504fbc5 | tsakallioglu/Random-Python-Challenges | /Weak_numbers.py | 1,324 | 4.25 | 4 | #We define the weakness of number x as the number of positive integers smaller than x that have more divisors than x.
#It follows that the weaker the number, the greater overall weakness it has. For the given integer n, you need to answer two questions:
#what is the weakness of the weakest numbers in the range [1, n]?
... | true |
3edca50ac0faee8c95d27f19232bd03202ab814c | shenlinli3/python_learn | /second_stage/day_11/demo_05_面向对象-多态和鸭子类型.py | 1,449 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/5/22 16:08
@Author : zero
"""
# 多态:在面向对象中,一个类的实例可以是多种形态(向上转型)
# 鸭子类型:在python中,只要一个对象长的像鸭子,走路和鸭子差不多,我就认为它是一只鸭子
class Person: # 会默认继承自object类
def eat(self):
print("eat eat eat")
class Student(Person):
pass
class LowLevelStudent(Student):
... | false |
24ac42452a2c8d4a84d52447187451ea079d4b1d | shenlinli3/python_learn | /second_stage/day_03/demo_03_for循环.py | 1,090 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/5/12 16:06
@Author : zero
"""
# for循环
"""
for 变量名 in 可迭代对象:
print(变量名)
...
"""
# 遍历字符串
# str01 = "hello world!" # 12
# for i in str01:
# print(i)
# 遍历列表
# list01 = [1, 2, 3, 4, 5]
# for j in list01:
# print(j)
# 遍历元组
# tuple01... | false |
7af6a875e8789ca9846521d0df9be2bd5eb2fa22 | KhushiRana2003/Hacktoberfest2021-1 | /Python/bubble_sort.py | 319 | 4.21875 | 4 | def bubbleSort(array):
for i in range(len(array)):
for j in range(len(array) - i - 1):
if array[j] > array[j + 1]:
swap(j, j + 1, array)
return array
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
# Time Complexity: O(n^2)
# Space Complexity: O(1) | false |
71417cb49cb8704d54aa0f6f923e92bd37da5bd9 | Niteshyadav0331/Zip-File-Extractor | /main.py | 248 | 4.15625 | 4 | from zipfile import ZipFile
file_name = input("Enter the name of file you want to file in .zip: ")
with ZipFile(file_name, 'r') as zip:
zip.printdir()
print('Extracting all the files...')
zip.extractall()
print("Done!") | true |
74d174d8878c2604daf720d755e6b156a6ec4881 | netor27/codefights-solutions | /arcade/python/arcade-theCore/07_BookMarket/053_IsTandemRepeat.py | 643 | 4.3125 | 4 | def isTandemRepeat(inputString):
'''
Determine whether the given string can be obtained by one concatenation of some string to itself.
Example
For inputString = "tandemtandem", the output should be
isTandemRepeat(inputString) = true;
For inputString = "qqq", the output should b... | true |
e082ba713c0a0001a3c47dfb5b1e31719534600d | netor27/codefights-solutions | /arcade/python/arcade-theCore/07_BookMarket/054_IsCaseInsensitivePalindrome.py | 339 | 4.1875 | 4 | def isCaseInsensitivePalindrome(inputString):
'''
Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters.
'''
lowerCase = inputString.lower()
return lowerCase == lowerCase[::-1]
print(isCaseInsensitivePalindrome("AaBaa"))
print(isCaseInsensitiveP... | true |
c32f3501b32a4141e575abe2f57b9b8eb712b6e1 | netor27/codefights-solutions | /arcade/python/arcade-intro/02_Edge of the Ocean/004_adjacentElementsProduct.py | 522 | 4.15625 | 4 | def adjacentElementsProduct(inputArray):
'''Given an array of integers, find the pair of adjacent elements
that has the largest product and return that product.
'''
n = len(inputArray)
if n < 2:
raise "inputArray must have at least 2 elements"
maxValue = inputArray[0] * inputArray[1]
... | true |
62bbb74e43256f78b67050821d847af478d4669c | netor27/codefights-solutions | /arcade/python/arcade-intro/12_Land of Logic/052_longestWord.py | 637 | 4.21875 | 4 | def longestWord(text):
'''
Define a word as a sequence of consecutive English letters. Find the longest word from the given string.
'''
maxLen, maxStart, currStart, currLen = 0, 0, 0, 0
for i in range(len(text)):
if text[i].isalpha():
if currLen == 0:
currSta... | true |
6cc342813a5cf0ab9e54f0ebb7bf05911b66e9b0 | netor27/codefights-solutions | /arcade/python/arcade-theCore/05_ListForestEdge/040_IsSmooth.py | 996 | 4.125 | 4 | def isSmooth(arr):
'''
We define the middle of the array arr as follows:
if arr contains an odd number of elements, its middle is the element whose index number
is the same when counting from the beginning of the array and from its end;
if arr contains an even number of elements, its midd... | true |
df112813c067411853941f8455d31fed51a2c1fa | netor27/codefights-solutions | /arcade/python/arcade-theCore/01_IntroGates/005_MaxMultiple.py | 349 | 4.21875 | 4 | def maxMultiple(divisor, bound):
'''
Given a divisor and a bound, find the largest integer N such that:
N is divisible by divisor.
N is less than or equal to bound.
N is greater than 0.
It is guaranteed that such a number exists.
'''
num = bound - (bound % divisor)
return max(0, nu... | true |
4360bfb5399e8fc6a7d7453b8582063d04704139 | netor27/codefights-solutions | /arcade/python/arcade-intro/02_Edge of the Ocean/008_matrixElementsSum.py | 1,100 | 4.1875 | 4 | def matrixElementsSum(matrix):
'''
After they became famous, the CodeBots all decided to move to a new building
and live together. The building is represented by a rectangular matrix of rooms.
Each cell in the matrix contains an integer that represents the price of the room.
Some rooms are free (... | true |
9ab6e5d04bdd7d278e9f6c1188160ff8ae892e14 | netor27/codefights-solutions | /arcade/python/arcade-theCore/04_LoopTunnel/029_AdditionWithoutCarrying.py | 763 | 4.375 | 4 | def additionWithoutCarrying(param1, param2):
'''
A little boy is studying arithmetics.
He has just learned how to add two integers, written one below another, column by column.
But he always forgets about the important part - carrying.
Given two integers, find the result which the little boy ... | true |
cb03a35c7e74fc7ca73545dadc59c16bce5c6f7a | netor27/codefights-solutions | /arcade/python/arcade-theCore/08_MirrorLake/059_StringsConstruction.py | 634 | 4.1875 | 4 | def stringsConstruction(a, b):
'''
How many strings equal to a can be constructed using letters from the string b? Each letter can be used only once and in one string only.
Example
For a = "abc" and b = "abccba", the output should be
stringsConstruction(a, b) = 2.
We can construct 2 strings a with letters fr... | true |
5cf96612d1c9bdb7f2fd851e8a00b424c2da2b6f | mixelpixel/CS1-Code-Challenges | /cc69strings/strings.py | 2,486 | 4.28125 | 4 | # cc69 strings
# https://repl.it/student/submissions/1855286
# https://developers.google.com/edu/python/
# http://pythoncentral.io/cutting-and-slicing-strings-in-python/
'''
For this challenge, you'll be writing some basic string functions.
Simply follow along with each exercise's prompt.
You may find the following a... | true |
c2bad1043e0499dfcd0fed9d617d9200ebede882 | lijerryjr/MONIAC | /textFunctions.py | 1,637 | 4.21875 | 4 | ###################
# rightJustifyText
# This contains the text justifier code from HW3
###################
import string
def replaceWhiteSpace(text):
#replace white space in text with normal spaces
#inspired by recitation 3 video
inWhiteSpace=False
result=''
for c in text:
if not inWhiteSp... | true |
4c92c735e5966ba9de1cd9c0538c82040271139a | cloudsecuritylabs/pythonProject_1 | /ch_01/19.comparisonoperators..py | 812 | 4.125 | 4 | '''
Let's learn about comparison operators
'''
age = 0
if age <= 100:
print("You are too young")
elif age >100:
print("You are a strong kid")
else:
print("We need to talk")
if True:
print("hey there")
# this does not print anything
if False:
print("Oh No!")
string = "he he"
if string:
prin... | true |
c9e05c41ee43bd41fc57f5da76649fad20c261be | KingTom1/StudyBySelf | /视频学习练习/视频第二周学习_数据类型/列表类型.py | 1,426 | 4.21875 | 4 | # 列表(list)是有序的元素集合
# 列表元素可以通过索引访问单个元素
# 列表与元组不同的是: 列表的大小没有限制,可以随时修改
'''
<seq> + <seq> 连接两个序列
<seq> * <整数类型> 对序列进行整数次重复
<seq> [<整数类型>] 索引序列中的元素
Len(<seq>) 序列中元素个数
<seq>[<整数类型>:<整数类型>] 取序列的一个子序列
For<var> in <seq>: 对序列进行循环列举
<expr> in <seq> ... | false |
75775de1bd44da7021fa2bcc7e2d9ebb9124e2e8 | ahmad-atmeh/my_project | /CA07/Problem 3/triangle.py | 2,036 | 4.1875 | 4 | # Class Triangle
class Triangle():
# TODO: Implement __init__ for this class use a,b,c and for the length of the sides
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def __str__(self):
tri = """
*
***
*****
******
... | false |
da2004b72fdf6dc722bd025c1c6580a9e9aaed8e | ahmad-atmeh/my_project | /CA10/3.py | 592 | 4.34375 | 4 |
# 3.You are given a list of words. Write a function called find_frequencies(words) which returns a dictionary of the words along with their frequency.
# Input: find_frequencies(['cat', 'bat', 'cat'])
# Return: {'cat': 2, 'bat': 1}
# Creating an empty dictionary
def find_frequencies(word):
freq ={}
fo... | true |
36cda705b3d2e83c671be0582bbaf1cb45b7484d | ahmad-atmeh/my_project | /CA10/4.py | 384 | 4.125 | 4 |
#4. You are given a list of integers. Write a function cumulative_sum(numbers) which calculates the cumulative sum of the list. The cumulative sum of a list numbers = [a, b, c, ...] can be defined as [a, a+b, a+b+c, ...].
# Input: numbers = [1, 2, 3, 4]
# Return: cumulative_sum_list = [1, 3, 6, 10]
lis = [1, 2, 3, 4]... | true |
2e2eccaa840f0fbf6bde633cf87834b7b4b62173 | ahmad-atmeh/my_project | /CA07/Problem 3/circle.py | 2,002 | 4.46875 | 4 | # Class Circle
import math
class Circle:
# TODO: Define an instance attribute for PI
def __init__(self, radius=1.0):
# TODO: Define an instance attribute for the radius
self.PI=3.14
self.radius=radius
# TODO: Define the string represent... | true |
eb954e96ab4f8a34e70891920d417a2d93822b44 | Dipin-Adhikari/Python-From-Scratch | /Dictionary/dictionary.py | 1,398 | 4.125 | 4 | """Dictionaries is collection of keyvalue pairs.it is ordered and changeable but it doesnot allow duplicates values.."""
dictionary = {
"python": "Python is an interpreted high-level general-purpose programming language.",
"django": "Django is a Python-based free and open-source web framework that follows the ... | true |
07604d6d6910ff0efa994121dd13f8784568634e | Aadit017/code_sharing | /type of triangle.py | 411 | 4.28125 | 4 | while True:
f= float(input("Enter first side: "))
s= float(input("Enter second side: "))
t= float(input("Enter third side: "))
if(f==s and f==t):
print("THE TRIANGLE IS AN EQUILATERAL TRIANGLE")
elif(f==s or f==t or s==t):
print("THE TRIANGLE IS AN ISOSCELES TRIANG... | false |
b578a4a9a57922b7b6a13472a074c1ad883b0421 | Aadit017/code_sharing | /month to days.py | 756 | 4.1875 | 4 | while True:
name=input("Enter name of month: ")
name=name.lower()
if(name=="january"):
print("days=31")
elif(name=="february"):
print("days=28")
elif(name=="march"):
print("days=31")
elif(name=="april"):
print("days=30")
elif(name=="may"):
... | true |
a6759a0d5fb17142435d89d87ccbd4ce64629a39 | Abhilash11Addanki/cspp1-assignments | /Module 22 Week Exam/Check Sudoku/check_sudoku.py | 1,741 | 4.28125 | 4 | '''
Sudoku is a logic-based, combinatorial number-placement puzzle.
The objective is to fill a 9×9 grid with digits so that
each column, each row, and each of the nine 3×3 subgrids that compose the grid
contains all of the digits from 1 to 9.
Complete the check_sudoku function to check if the given... | true |
174ca0fb814021e716969bcd6b681fca98d5fbb9 | Abhilash11Addanki/cspp1-assignments | /Practice Problems/Code Camp matrix/matrix_operations.py | 2,042 | 4.125 | 4 | '''Matrix operations.'''
def mult_matrix(m_1, m_2):
'''
check if the matrix1 columns = matrix2 rows
mult the matrices and return the result matrix
print an error message if the matrix shapes are not valid for mult
and return None
error message should be "Error: Matrix shapes ... | true |
6485a65aaf4ecbcdbf3e86c954a792aeaa5c8948 | BabaYaga007/Second-1 | /stone_paper_scissor.py | 1,198 | 4.1875 | 4 | from random import randint
def print_menu():
print('1 for Stone')
print('2 for Paper')
print('3 for Scissor')
print('Enter your choice')
def print_score(a,b):
print('---Score---')
print('Player =',a)
print('Computer =',b)
choice = ['stone','paper','scissor']
a=0
b=0
while(... | true |
238f30f035a54ede9b8a3cae148c074bbd806ec3 | ralsouza/python_data_structures | /section7_arrays/searching_an_element.py | 440 | 4.1875 | 4 | from array import *
arr1 = array("i", [1,2,3,4,5,6])
def search_array(array, value):
for i in array: # --------------------------------------> O(n)
if i == value:# ------------------------------------> O(1)
return array.index(value) # --------------------> O(1)
return "The element does no... | true |
3f9c04833a87be9b112078e462c08aa7369dc9bc | ralsouza/python_data_structures | /section8_lists/chal6_pairs.py | 550 | 4.21875 | 4 | # Pairs
# Write a function to find all pairs of an integer array whose sum is equal to a given number.
# Example: pair_sum([2,4,3,5,6,-2,4,7,8,9], 7)
# Output: ['2+5', '4+3', '3+4', '-2+9']
my_list = [2,4,3,5,6,-2,4,7,8,9]
def pair_sum(list, num_sum):
output = []
for i in range(len(list)):
for j in r... | true |
49ab45268ba1099af5637316d5584e075a601dab | ralsouza/python_data_structures | /section28_sorting_algorithms/293_bubbles_sort.py | 490 | 4.25 | 4 | # Bubble Sort
# - Bubble sort is also referred as Sinking sort
# - We repeatedly compare each pair of adjacent items and swap them if
# they are in the wrong order
def bubble_sort(custom_list):
for i in range(len(custom_list)-1):
for j in range(len(custom_list)-i-1):
if custom_list[j] > custo... | true |
6adcebfeff79bf2c97bf0587a49e658e71b7b503 | ralsouza/python_data_structures | /section8_lists/proj3_finding_numer_in_array.py | 399 | 4.15625 | 4 | # Project 3 - Finding a number in a array
# Question 3 - How to check if an array contains a number in Python
import numpy as np
my_list = list(range(1,21))
my_array = np.array(my_list)
def find_number(array, number):
for i in range(len(array)):
if array[i] == number:
print(f"The number {numb... | true |
c22fbab5afe23a79783eeaa86b6d0041c5c01b7d | viratalbu1/Python- | /AccesingInstanceVariable.py | 513 | 4.25 | 4 | #This Example is used for understanding what is instance variable
class test:
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
def info(self):
print(self.name)
print(self.rollno)
#In Above Example state creation of constructor and object method
# For Accessing it just create Obje... | true |
78e9924735898785f3963c59531b866f1f44138b | viratalbu1/Python- | /IteratorAndGeneratorExample.py | 695 | 4.875 | 5 | # Iterator is used for creating object for iteratable object such as string, list , tuple
itr_list=iter([1,2,3,4])
itr_tuple=iter((1,2,3,4))
itr_string=iter('String')
print('--------List ------')
for val in itr_list:
print(val)
print('-----Tuple----------')
for val in itr_tuple:
print(val)
print('--... | true |
ad96b449267f2c830b6ebc0f6f0d8f13a1300f0a | bongjour/effective_python | /part1/zip.py | 672 | 4.15625 | 4 | from itertools import zip_longest
names = ['dante', 'beerang', 'sonic']
letters = [len(each) for each in names]
longest_name = None
max_letter = 0
# for i, name in enumerate(names):
# count = letters[i]
#
# if count > max_letter:
# longest_name = name
# max_letter = count
for name, count i... | true |
4f1ee7021d8707fcf351345b18d164ecc0ccd3db | aFuzzyBear/Python | /python/mystuff/ex24.py | 1,953 | 4.28125 | 4 | # Ex24- More Python Practicing
#Here we are using the escape \\ commands int eh print statement.
print "Let's practice everything."
print "You\'d need to know \'bout dealing with \\escape statements\\ that do \n newlines and \t tabs"
#Here we have made the poem a multilined print statement
poem = """
\tThe lovely wor... | true |
09f90dc3135c90b4e3a62d3ef3553f160c621f4a | aFuzzyBear/Python | /python/mystuff/ex33.py | 1,228 | 4.375 | 4 | #While Loops
"""A While loop will keep executing code if the boolean expression is True. It is a simple If-Statement but instead of running a block of code once if True, it would keep running through the block untill it reaches the first False expression.
The issue with while-loops is that they sometimes dont stop. Th... | true |
1766f40560f8a404a0c964a89198d185304c20c7 | aFuzzyBear/Python | /python/mystuff/ex20.py | 606 | 4.15625 | 4 | #Functions and Files
from sys import argv
scrit, input_file = argv
def print_all(f):
print f.read()
def rewind (f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file: \n"
print_all(current_file)
print "Now let's ... | true |
d37e27a702a74af02dce7b41c3a6a368f714ba2e | szhongren/leetcode | /129/main.py | 1,697 | 4.15625 | 4 | """
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents t... | true |
1a1a9e775108be74c02d4e90c42bf1928f94ca4f | szhongren/leetcode | /337/main.py | 2,378 | 4.15625 | 4 | """
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the p... | true |
522b1b01a64b08202f162b7fae780dbf2219066e | szhongren/leetcode | /473/main.py | 1,692 | 4.3125 | 4 | """
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input w... | true |
10c13ace9bc8e87cf08e9f5a4947808deb630506 | AI-System/ai-learning-material-old | /Basic-Python/code/test_oop/2.py | 814 | 4.125 | 4 | ### 类的构造方法 __init__
class A:
def __init__(self):
# 实例化时自动调用,一般用于初始化
print('init ...')
def fun(self):
print('class A...')
a = A() # 实例化 A 时, 如果内部有 __init__ 方法, 那么会调用该方法
print('✨' * 20)
class Person:
name=""
age=0
def __init__(self):
pass
def getInfo(self):
print(self.name, " : ", s... | false |
4671c9f8d366e45e97a92920d6190e1d7c65d894 | tdongsi/effective_python | /ep/item13b.py | 1,973 | 4.15625 | 4 |
NUMBERS = [8, 3, 1, 2, 5, 4, 7, 6]
GROUP = {2, 3, 5, 7}
def sort_priority(numbers, group):
""" Sort the input numbers but put those in "group" first.
:param numbers: list of input numbers.
:param group: set of numbers in priority group.
:return: True if any number in priority is found.
"""
f... | true |
6c73b0dade33e1a6dfbd3bfc1bb9e43ec21dabbf | tdongsi/effective_python | /ep/item13.py | 924 | 4.46875 | 4 |
meep = 23
def enclosing():
""" Variable reference in different scopes.
When referring to a variable not existing in the inner scope,
Python will try to look up in the outer scope.
"""
foo = 15
def my_func():
bar = 10
print(bar) # local scope
print(foo) # e... | true |
3d8fa1d96a89e06299f099b1f4ccc88cf33b5d97 | oigwe/learning_data_analyzing | /python/Step 1/2.Python Data Analysis Basics: Takeaways.py | 1,229 | 4.1875 | 4 | #Python Data Analysis Basics: Takeaways
#by Dataquest Labs, Inc. - All rights reserved © 2020
#Syntax
#STRING FORMATTING AND FORMAT SPECIFICATIONS
#Insert values into a string in order:
continents = "France is in {} and China is in {}".format("Europe", "Asia")
#Insert values into a string by position:
squares = "{0}... | true |
0a4042a5c22e529574bc1ccb8f1f6bbfad9c7894 | oigwe/learning_data_analyzing | /python/Step 1/Lists and For Loops: Takeaways.py | 1,567 | 4.375 | 4 | #Lists and For Loops: Takeaways
#by Dataquest Labs, Inc. - All rights reserved © 2020
#Syntax
#Creating a list of data points:
row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5]
#Creating a list of lists:
data = [row_1, row_2]
#Retrieving an element of a list:
first_row ... | true |
28d231a0a4e9f1a42c968643e77bd1598e0da992 | jonag-code/python | /dictionary_list_tuples.py | 1,675 | 4.25 | 4 | List =[x**2 for x in range(5)]
Dictionary = {0:'zero', 1:'one', 2:'four', 3:'nine', 4:'sixteen'}
Tuple = tuple(List)
#The following doesn't work as with lists: Tuple2 =(x**2 for x in range(10)).
#Also the entries of tuples cannot be modified like in lists or dictionaries.
#This is useful when storing import... | true |
b831921bf3f540ef6e9a6a8957720757feda3e46 | theparadogs/Python | /Calculator.py | 780 | 4.125 | 4 | print("===============================================")
#masukan input dari user
print("Selamat Datang di Program Kalkulator sederhana")
enter = input("klik enter untuk lanjut : ")
print("Program ini dibuat oleh Felix Rizky Lesmana")
enter = input("klik enter untuk lanjut : ")
print("================================... | false |
4e5a34a5a570d67a33a414124f62dd3b498e06a2 | Robin-Andrews/Serious-Fun-with-Python-Turtle-Graphics | /Chapter 8 - The Classic Snake Game with Python Turtle Graphics/2. basic_snake_movement.py | 1,362 | 4.25 | 4 | # Import the Turtle Graphics module
import turtle
# Define program constants
WIDTH = 500
HEIGHT = 500
DELAY = 400 # Milliseconds between screen updates
def move_snake():
stamper.clearstamps() # Remove existing stamps made by stamper.
# Next position for head of snake.
new_head = snake[-1].copy()
... | true |
ec0af5bcde099c9a9695d6ec4d8f4f231b13ce7e | rizqo46/refactory-assignment | /logic_test/leapyear.py | 695 | 4.15625 | 4 | # In the Gregorian calendar, three conditions are used to identify leap years:
# - The year can be evenly divided by 4, is a leap year, unless:
# - * The year can be evenly divided by 100, it is NOT a leap year, unless:
# - - # The year is also evenly divisible by 400. Then it is a leap year.
def leapyear(a, b):
i... | false |
501ca8c5a71b67cd7db14e7577be41fcd6646fd7 | shantanusharma95/LearningPython | /DataStructures/priority_queue.py | 2,988 | 4.25 | 4 | import sys
class node:
def __init__(self,data,priority):
self.data=data
self.priority=priority
self.next=None
class queue:
def __init__(self):
self.Head=self.Tail=None
self.queueSize=0
#adds a new value to queue, based on priority of data
#this will make enqueu... | true |
08951c8a90dc3bffde4ce992e89a15ff0ba31acf | adudjandaniel/Fractions | /lib/fraction/fraction.py | 2,313 | 4.1875 | 4 | class Fraction():
'''A basic fraction data type in python'''
def __init__(self, a=0, b=1):
self.a = a
self.b = b if b else 1
def __str__(self):
'''Converts the instance to a string'''
return "{}/{}".format(self.a, self.b)
def __repr__(self):
'''View of the inst... | true |
41f9eaee34956ebf3e6688ebca4d55b095552448 | yafiimo/python-practice | /lessons/11_ranges.py | 992 | 4.21875 | 4 | print('\nloops from n=0 to n=4, ie up to 5 non-inclusive of 5')
for n in range(5):
print(n)
print('\nloops from 1 to 6 non-inclusive of 6')
for n in range(1,6):
print(n)
print('\nloop from 0 to 20 in steps of 4')
for n in range(0, 21, 4):
print(n)
print('\nloop through list like a for loop')
food = ['cha... | true |
842079f591bef1485312dad98a8d44ad0cbace44 | yafiimo/python-practice | /lessons/27_writing_files.py | 941 | 4.125 | 4 | # must use 'w' as 2nd argument to write to a file, and file_name as first argument
with open('text_files/write_file.txt', 'w') as write_file:
text1 = 'Hello, I am writing my first line to a file using Python!'
print('Writing first line to file...')
write_file.write(text1)
# if you want to ammend a file, yo... | true |
a40506eaf66ec0af19289816a30e8ff2039e5868 | zerodayz/dailycoding | /Examples/Recursion.py | 350 | 4.1875 | 4 | def recursive(input):
print("recursive(%s)" %input)
if input <= 0:
print("returning 0 into output")
return input
else:
print("entering recursive(%s)" %( input -1 ))
output = recursive(input -1)
print("output = %s from recursive(%s)" %(output, input - 1))
retur... | true |
fd0494ab43d057e55d61d3a0b0c2797406da3e47 | arpitsingh17/DataStructures | /binarysearch.py | 697 | 4.125 | 4 | # Binary Search
# Input list must be sorted in this search method.
def bin(alist,item):
aalist = alist
midterm = alist[(len(alist)//2)]
found = False
while True:
try:
if item < midterm:
#print (alist[:((alist.index(midterm)))])
return(bin(alist[:((alist.index(midte... | true |
68bb058fda2c703036d8bd76c1c57171db1608a0 | ericwebsite/ericwebsite.github.io | /src/python/TheTemple(2).py | 1,376 | 4.125 | 4 | import random
print("Importable +")
import time
time.sleep(3)
print("You went in a temple. I dare you. ")
print(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,")
time.sleep(3)
print("You saw...")
print("()()()()()()()()()()()()")
time.sleep(3)
power = input("Choose a power. waterBreathing(w),fireProtection(fp),Blas... | false |
d5b0e6cae118c886d8ac206b3af3e16ca0b4edf5 | j-thepac/Python_snippets | /SmallHighPow/smallhighpow.py | 896 | 4.21875 | 4 | """
We have the number 12385. We want to know the value of the closest cube but higher than 12385. The answer will be 13824.
Now, another case. We have the number 1245678. We want to know the 5th power, closest and higher than that number. The value will be 1419857.
We need a function find_next_power ( findNextPower ... | true |
08f2d5e5f13dcb98a8e419568b391b56439ae6cf | j-thepac/Python_snippets | /IntSeq/python/intseq.py | 1,626 | 4.21875 | 4 | """
Description:
Complete function findSequences. It accepts a positive integer n. Your task is to find such integer sequences:
Continuous positive integer and their sum value equals to n
For example, n = 15
valid integer sequences:
[1,2,3,4,5] (1+2+3+4+5==15)
[4,5,6] (4+5+6==15)
[7,8] (7+8==1... | true |
c7dfc6b9bbf3f103a6c4a127119edc8f0e0df1bd | j-thepac/Python_snippets | /Brackets/brackets.py | 1,423 | 4.21875 | 4 | """
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket ... | true |
ebf04b862009e61e6993d8216c0ffdb3db6cf5a2 | j-thepac/Python_snippets | /SameCase/samecase.py | 1,069 | 4.1875 | 4 | """
Write a function that will check if two given characters are the same case.
'a' and 'g' returns 1
'A' and 'C' returns 1
'b' and 'G' returns 0
'B' and 'g' returns 0
'0' and '?' returns -1
If any of characters is not a letter, return -1.
If both characters are the same case, return 1.
If both characters are l... | true |
14c7bf781e52c8f4eaa62b0d30dab3939d452180 | j-thepac/Python_snippets | /Phoneno/phoneno.py | 1,032 | 4.21875 | 4 | """
Write a function that accepts an array of 10 integers (between 0 and 9)== that returns a string of those numbers in the form of a phone number.
Example
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
The returned format must be correct in order to complete this challenge.
Don't fo... | true |
e362ff3a5d949f03cceb6f8de2602b06d1d2cac4 | barthelemyleveque/Piscine_Python | /D00/ex06/recipe.py | 2,559 | 4.125 | 4 | import sys
import time
cookbook= {
'sandwich': {
'ingredients':['ham', 'bread', 'cheese', 'tomatoes'],
'meal':'lunch',
'prep_time':10,
},
'cake' : {
'ingredients':['flour', 'sugar', 'eggs'],
'meal':'dessert',
'prep_time':60
},
'salad':{
'ingre... | true |
ce499afe3bf4323bc35f81eda9cb02bbeb866f2b | anand13sethi/Data-Structures-with-Python | /Queue/QueueReverse.py | 963 | 4.15625 | 4 | # Reversing a Queue implemented using singly link list using stack.
from QueueUsingLinkList import Queue
class Stack:
def __init__(self):
self.stack = []
self.size = 0
def is_empty(self):
return self.size <= 0
def push(self, data):
self.stack.append(data)
self.s... | true |
1b6bc1d29ff40669e1d3f47d92f5675934c4c8c8 | joeybtfsplk/projecteuler | /10.py | 1,353 | 4.125 | 4 | #!/usr/bin/env python
"""
file: 10.py
date: Thu Jul 31 09:25:11 EDT 2014
from: Project Euler: http://projecteuler.net
auth: tls
purp: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of
all the primes below two million.
Ans: 142913828922 on Fri Aug 1 22:34:07 EDT 2014
"""
def prime_list(... | true |
0cd3f80f80bed75176e9ca50eb0f928d73df4cc6 | zw-999/learngit | /study_script/find_the_largest.py | 481 | 4.21875 | 4 | #!/usr/bin/env python
# coding=utf-8
import sys
def find_largest(file):
fi = open(file,"r")
for line in fi:
line = line.split()
print line
#fi.close()
#line = fi.readline()
largest = -1
for value in line.split():
v = int(value[:-1])
if v > largest:
... | true |
1a2f875189437c1c09d34ece099de1858cdaa880 | Kavitajagtap/Python3 | /Day14.py | 1,792 | 4.375 | 4 | """
1.Write a program to sort a list alphabetically in a dictionary
Enter dictionary = {1: ['B', 'C', 'A'], 2: ['D', 'B', 'A'], 3: ['V', 'A', 'K']}
Sorted list of dictionary = {1: ['A', 'B', 'C'], 2: ['A', 'B', 'D'], 3: ['A', 'K', 'V']}
"""
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = int(i... | false |
87424e37b3e029ddd8fcc1ccd752b23fc5864b33 | Kavitajagtap/Python3 | /Day8.py | 1,852 | 4.59375 | 5 |
# 1.Write a program to create dictionary and access all elements with keys and values
dict = eval(input("Enter dictionary = "))
print("Accessing Elements from dictionary -->")
for key in dict:
print(key,dict[key])
'''
Output :
Enter dictionary = {'Apple':2017,'Microsoft':1985,'Facebook':2012,'Amazon':1997}
Acces... | true |
71432b142344cfa33686bf7bdcaeafb4f2d4b372 | Kavitajagtap/Python3 | /Day16.py | 1,528 | 4.3125 | 4 |
"""
1. Write program to sort Counter by value.
Sample data : {'Math':81, 'Physics':83, 'Chemistry':87}
Expected data: [('Chemistry', 87), ('Physics', 83), ('Math', 81)]
"""
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = (input("key: "))
v = int(input("value: "))
dict[k] = v
print("di... | true |
b369a56787f0a1d15519d7e228ac7ef2ef6b849a | VolodymyrMeda/Twittmap | /json_navigator.py | 1,646 | 4.1875 | 4 | import json
def reading_json(file):
'''
str -> dict
Function reads json file
and returns dictionary
'''
with open(file, mode='r', encoding='utf-8') as rd:
json_read = json.load(rd)
return json_read
def json_navigation(json_read):
'''
Function navigates user in
json d... | true |
a75fa80c8412141fd7e8b28978b5a7f92643fbed | annmag/Student-manager | /generator_function.py | 985 | 4.21875 | 4 | # Generator function - a way of crating iterators (objects which you can iterate over)
# Creating generator - defining function with at least one yield statement (or more) instead of return statement
# Difference: return terminates a function entirely
# yield pauses the function saving all it's states and continues ... | true |
0bd27accb7021db31fbfd540a9318d768adb366c | gokullogu/pylearn | /tutorial/list/add.py | 550 | 4.25 | 4 | #to add the the value to end of list use append
cars=["audi","bens","rolls royce"]
cars.append("bmw")
print(cars)
#['audi', 'bens', 'rolls royce', 'bmw']
#to append the list to the list use extend
fruit=["apple","mango","banana"]
veg=["carrot","beetroot","brinjal"]
fruit.extend(veg)
print(fruit)
#['apple', 'mango', 'b... | true |
28080c6a55b1fc92494501d470c314beb176f11e | gokullogu/pylearn | /tutorial/tuple/access.py | 1,044 | 4.4375 | 4 |
cars=("bmw","rolls royce","MG hector","tata tigor","audi","creta")
print(cars)
#('bmw', 'rolls royce', 'MG hector', 'tata tigor', 'audi', 'creta')
#second item
print(cars[1])
#rolls royce
#last item index -1
print(cars[-1])
#creta
print(cars[2:4])
#('MG hector', 'tata tigor')
print(cars[-5:-1])
#('rolls royce', 'M... | false |
39f45bae07f632c715928a8237750ac70edafdef | gokullogu/pylearn | /tutorial/functions.py | 1,287 | 4.21875 | 4 | #creating functions
def my_fun():
print("hello world")
my_fun()
#hello world
#function with argument
def namefun(fname,lname):
print(fname+" "+lname)
namefun("gokul","L")
#gokul L
#namefun("gokul") will cause to error
#using argument tuple to get values
def namefun(*name):
print(name[2])
namefun("emil",... | false |
50e3a4dbe8af7537d416e830a6882fcacf7fce1e | gokullogu/pylearn | /tutorial/list/remove.py | 778 | 4.28125 | 4 | #remove() removes item sepecified
fruit=["mango","orange","papaya"]
fruit.remove("mango")
print(fruit)
#['orange', 'papaya']
#pop() removes the list item at specified index
this_list=["john","19","poland"]
this_list.pop(1)
print(this_list)
#['john', 'poland']
#pop() removes the last item if unspecified
this_list1 =... | true |
33de33e1b694522a1ce35baf5777cab2ba132560 | gokullogu/pylearn | /tutorial/tuple/loop.py | 531 | 4.375 | 4 | #loop through the tuple using for
fruit=("apple","banana","carrot","beetroot")
for x in fruit:
print(x)
#apple
#banana
#carrot
#beetroot
#loop through tuple using index numbers
print("for loop by index number:")
for i in range(len(fruit)):
print(i,"",fruit[i])
#for loop by index number:
#0 apple
#1 banana
#... | false |
bff509e7057885d4a0c7e480c09a4605db36bcb8 | ChadevPython/WeeklyChallenge | /2017/02-06-2017/EthanWalker/main.py | 240 | 4.3125 | 4 | #!/usr/bin/env python3
from reverse_str import reverse_line
import sys
#open file and get lines
with open(sys.argv[1], 'r') as in_file:
file = in_file.readlines()
# print reversed lines
for line in file:
print(reverse_line(line)) | true |
9a63728319bc7a007e3edcc2acf916c0e32b988a | Arunken/PythonScripts | /2_Python Advanced/8_Pandas/10_Sorting.py | 1,643 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 14:30:07 2018
@author: SilverDoe
"""
'''
There are two kinds of sorting available in Pandas :
1. By Label
2. By Actual Value
'''
'''================== Sorting By Label ========================================'''
import pandas as pd
import numpy as n... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.