blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
262194ac01e442be0f72e3d52c6f05497f07f863
Lukazovic/Learning-Python
/CursoEmVideo/exercicio053.2 - frase palindromo.py
728
4.3125
4
''' Crie um programa que leia um frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços ''' print('\n--- Verificando se uma frase é um Palíndromo ---') frase = str(input('Digite uma frase: ')).strip() palavrasDaFrase = frase.split() palavrasJuntas = ''.join(palavrasDaFrase) # ''.join() junta tudo sem espaços # ' '.join() junta tudo com espaços # '-'.join() junta tudo separado por - palavraInversa = '' for i in range(len(palavrasJuntas)-1, -1, -1): palavraInversa += palavrasJuntas[i] print('\nFrase digitada: ' +palavrasJuntas) print('\nFrase inversa: ' +palavraInversa) print('') if palavrasJuntas == palavraInversa: print('Palíndromo!') else: print('Não é um Palíndromo!') print('')
false
06f0995a377b7b2fda704ebcf2fd6d9fb686b864
OneWinged-Eagle/MyDailyCodingProblem
/Medium/#53/main.py
1,915
4.3125
4
""" Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it. """ from typing import Any, List class Stack: stack: List[Any] def __init__(self): self.stack = [] def push(self, val: Any) -> None: if val is None: return self.stack.append(val) def pop(self) -> Any: if len(self.stack) == 0: return None return self.stack.pop() def __len__(self): return len(self.stack) def __repr__(self): return f"Stack({self.stack})" class Queue: mainStack: Stack reserveStack: Stack def __init__(self): self.mainStack = Stack() self.reserveStack = Stack() def enqueue(self, val: Any) -> None: if val is None: return self.mainStack.push(val) def dequeue(self) -> Any: if len(self.mainStack) == 0: return None while len(self.mainStack) > 0: self.reserveStack.push(self.mainStack.pop()) val = self.reserveStack.pop() while len(self.reserveStack) > 0: self.mainStack.push(self.reserveStack.pop()) return val def __len__(self): return len(self.mainStack) def __repr__(self): return f"Queue({self.mainStack})" myQueue = Queue() print(f"myQueue = {myQueue}") print(f"myQueue.dequeue() = {myQueue.dequeue()}") print(f"myQueue = {myQueue}") myQueue.enqueue(1) myQueue.enqueue(2) myQueue.enqueue(3) print(f"myQueue = {myQueue}") print(f"myQueue.dequeue() = {myQueue.dequeue()}") print(f"myQueue = {myQueue}") print(f"myQueue.dequeue() = {myQueue.dequeue()}") print(f"myQueue = {myQueue}") myQueue.enqueue(4) myQueue.enqueue(5) print(f"myQueue = {myQueue}") print(f"myQueue.dequeue() = {myQueue.dequeue()}") print(f"myQueue = {myQueue}") print(f"myQueue.dequeue() = {myQueue.dequeue()}") print(f"myQueue = {myQueue}") print(f"myQueue.dequeue() = {myQueue.dequeue()}") print(f"myQueue = {myQueue}")
true
8eafe9d140252bc0e71447f6472f8c4b35273b2a
OneWinged-Eagle/MyDailyCodingProblem
/Easy/#118/main.py
1,631
4.40625
4
""" Given a sorted list of integers, square the elements and give the output in sorted order. For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81]. """ from typing import List def mergeSort(numbers: List[int], left: List[int], right: List[int]) -> List[int]: l, r = 0, 0 while l + r < len(numbers): if r == len(right) or (l < len(left) and left[l] <= right[r]): numbers[l + r] = left[l] l += 1 else: numbers[l + r] = right[r] r += 1 return numbers def square(numbers: List[int]) -> List[int]: if len(numbers) == 0 or any( numbers[i] > numbers[i + 1] for i in range(len(numbers) - 1)): return None index = -1 for i, nb in enumerate(numbers): if index == -1 and nb >= 0: index = i numbers[i] = nb * nb if index == -1 or numbers[-1] == 0: numbers.reverse() index = 0 return numbers if index == 0 else mergeSort(numbers, numbers[index - 1::-1], numbers[index:]) print( f"square([-0, 0, 2, 2, 3, 9, 10, 42]) = {square([-0, 0, 2, 2, 3, 9, 10, 42])}" ) print( f"square([-42, -9, -2, -0, 0, 2, 3, 10]) = {square([-42, -9, -2, -0, 0, 2, 3, 10])}" ) print( f"square([-42, -10, -9, -3, -2, -2, -0, 0]) = {square([-42, -10, -9, -3, -2, -2, -0, 0])}" ) print(f"square([-0, 2, 4, -6, -8, 10]) = {square([-0, 2, 4, -6, -8, 10])}") print(f"square([]) = {square([])}") print(f"square([2, 2, 3, 9, 10, 42]) = {square([2, 2, 3, 9, 10, 42])}") print(f"square([-42, -9, -2, 2, 3, 10]) = {square([-42, -9, -2, 2, 3, 10])}") print( f"square([-42, -10, -9, -3, -2, -2]) = {square([-42, -10, -9, -3, -2, -2])}" )
true
d1903a26d1de23d233ae2cdf8e4220f3d5968205
OneWinged-Eagle/MyDailyCodingProblem
/Medium/#156/main.py
682
4.15625
4
""" Given a positive integer n, find the smallest number of squared integers which sum to n. For example, given n = 13, return 2 since 13 = 3² + 2² = 9 + 4. Given n = 27, return 3 since 27 = 3² + 3² + 3² = 9 + 9 + 9. """ from math import sqrt squares = [0, 1, 2, 3] def nextSquare() -> int: square = n = len(squares) for i in range(1, int(sqrt(n)) + 1): tmp = i * i if tmp > n: break else: square = min(square, 1 + squares[n - tmp]) return square def nbSquaredTo(n: int) -> int: if n < 0: return None while len(squares) <= n: squares.append(nextSquare()) return squares[n] for n in range(21): print(f"nbSquaredTo({n}) = {nbSquaredTo(n)}")
true
6a000348d4b8db051b6ce15fe8418b14c9b99a81
OneWinged-Eagle/MyDailyCodingProblem
/Medium/#109/main.py
463
4.1875
4
""" Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on. For example, 10101010 should be 01010101. 11100010 should be 11010001. Bonus: Can you do this in one line? """ def swap(nb: int) -> int: return ((nb & 0b10101010) >> 1) | ((nb & 0b01010101) << 1) print(f"swap(0b10101010) = {bin(swap(0b10101010))}") print(f"swap(0b11100010) = {bin(swap(0b11100010))}")
true
cc41325a8b2df06d0000a31930f2069fb85675e5
OneWinged-Eagle/MyDailyCodingProblem
/Easy/#324/main.py
884
4.21875
4
""" Consider the following scenario: there are N mice and N holes placed at integer points along a line. Given this, find a method that maps mice to holes such that the largest number of steps any mouse takes is minimized. Each move consists of moving one mouse one unit to the left or right, and only one mouse can fit inside each hole. For example, suppose the mice are positioned at [1, 4, 9, 15], and the holes are located at [10, -5, 0, 16]. In this case, the best pairing would require us to send the mouse at 1 to the hole at -5, so our function should return 6. """ from typing import List def maxMoves(mice: List[int], holes: List[int]) -> int: if len(mice) != len(holes): return -1 mice.sort() holes.sort() m = 0 for mouse, hole in zip(mice, holes): m = max(m, mouse - hole) return m assert maxMoves([1, 4, 9, 15], [10, -5, 0, 16]) == 6 print("passed")
true
a8b4743666fc16e9e91c073adc031156b0582899
OneWinged-Eagle/MyDailyCodingProblem
/Medium/#61/main.py
490
4.28125
4
""" Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. Do this faster than the naive method of repeated multiplication. For example, pow(2, 10) should return 1024. """ def pow(x: int, y: int) -> int: if y == 0: return 1 half = pow(x, y // 2) if y % 2 == 0: return half * half elif y > 0: return x * half * half else: return (half * half) / x for i in range(25): print(f"pow(2, {i}) = {pow(2, i)}")
true
34a2582667f50a795764a05be493db61af5515f3
OneWinged-Eagle/MyDailyCodingProblem
/Medium/#24/main.py
2,705
4.1875
4
""" Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its descendants or ancestors are not locked. Design a binary tree node class with the following methods: is_locked, which returns whether the node is locked lock, which attempts to lock the node. If it cannot be locked, then it should return false. Otherwise, it should lock it and return true. unlock, which unlocks the node. If it cannot be unlocked, then it should return false. Otherwise, it should unlock it and return true. You may augment the node to add parent pointers or any other property you would like. You may assume the class is used in a single-threaded program, so there is no need for actual locks or mutexes. Each method should run in O(h), where h is the height of the tree. """ from __future__ import annotations from typing import Any class Node: val: Any left: Node right: Node parent: Node isLocked: bool nbDescendantsLocked: int def __init__(self, val: Any, left: Node = None, right: Node = None): self.val = val if left is not None: left.parent = self self.left = left if right is not None: right.parent = self self.right = right self.parent = None self.isLocked = False self.nbDescendantsLocked = 0 def is_locked(self) -> bool: return self.isLocked def lock(self) -> bool: if self.isLocked or self.nbDescendantsLocked > 0: return False curr = self.parent while curr is not None: if curr.isLocked: return False curr = curr.parent curr = self.parent while curr is not None: curr.nbDescendantsLocked += 1 curr = curr.parent self.isLocked = True return True def unlock(self) -> bool: if not self.isLocked: return False curr = self.parent while curr is not None: curr.nbDescendantsLocked -= 1 curr = curr.parent self.isLocked = False return True def __repr__(self): return f"Node({self.val}, {'locked' if self.isLocked else 'unlocked'}, {self.nbDescendantsLocked} descendants locked)" left = Node("l", Node("ll"), Node("lr")) right = Node("r", Node("rl"), Node("rr")) root = Node("root", left, right) print(root) print(left) print(right) print(f"Trying to lock {left}: {left.lock()}") print(root) print(left) print(right) print(f"Trying to lock {right}: {right.lock()}") print(root) print(left) print(right) print(f"Trying to lock {root}: {root.lock()}") print(root) print(left) print(right) print(f"Trying to unlock {left}: {left.unlock()}") print(root) print(left) print(right) print(f"Trying to unlock {right}: {right.unlock()}") print(root) print(left) print(right) print(f"Trying to unlock {root}: {root.unlock()}") print(root) print(left) print(right)
true
db12e1cc7b9b19238cd7675fb4e34e4501591bee
OneWinged-Eagle/MyDailyCodingProblem
/Medium/#60/main.py
1,224
4.25
4
""" Given a multiset of integers, return whether it can be partitioned into two subsets whose sums are the same. For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true, since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55. Given the multiset {15, 5, 20, 10, 35}, it would return false, since we can't split it up into two subsets that add up to the same sum. """ import numpy as np from typing import List def partitioned(numbers: List[int]) -> bool: total = sum(numbers) if total % 2 != 0: return False canSumTable = np.full((total // 2 + 1, len(numbers) + 1), False) canSumTable[0] = True for y in range(1, total // 2 + 1): for x in range(1, len(numbers) + 1): canSumTable[y][x] = canSumTable[y - 1][x] if not canSumTable[y][x] and y >= numbers[x - 1]: canSumTable[y][x] = canSumTable[y - numbers[x - 1]][x - 1] return canSumTable[total // 2][len(numbers)] print( f"partitioned([15, 5, 20, 10, 35, 15, 10]) = {partitioned([15, 5, 20, 10, 35, 15, 10])}" ) print(f"partitioned([15, 5, 20, 10, 35]) = {partitioned([15, 5, 20, 10, 35])}") print( f"partitioned([2, 1, 3, 4, 5, 4, 1]) = {partitioned([2, 1, 3, 4, 5, 4, 1])}" )
true
150c145373aeefc2a2d4897073f280660a5362d3
creative-singh/MyPythonCodes
/calStringUpperLower.py
656
4.28125
4
#Challenge - Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. def calStringUpperLower(myval): countUpper = 0;countLower = 0;countSpaces = 0 for i in range(len(myval)): if myval[i].islower(): countLower+=1 if myval[i].isupper(): countUpper+=1 if myval[i].isspace(): countSpaces+=1 print(f"Uppercase letters in given string are : {countUpper}") print(f"Lowercase letters in given string are : {countLower}") print(f"Spaces in given string are : {countSpaces}") calStringUpperLower(input("Enter any string : "))
true
cbf614939be99b4770bf0a98c5da6b9605970be5
creative-singh/MyPythonCodes
/countingSortWeek02.py
753
4.15625
4
# Counting Sort - Week 02 - Day 05 #given_list - [1,1,3,2,1] given_list = [1,1,3,2,1] final_list = [] #this is blank list which will contain sorted list maxVal = max(given_list) #this will take out maximum value from given_list process_list = [0]*(maxVal+1) #this will create [0,0,0,0] for i in given_list: #this for loop count the number of occurence of process_list[i]+=1 #a number in given_list count=0 for val in process_list: #taking value from process list and copyieng it to while val > 0: #final_list through loops final_list.append(count) val-=1 count+=1 print(f'Given list is : {given_list}') print(f'Sorted list is : {final_list}')
true
759a2892227cb489348b402d3d669701c12b571b
katiayx/coding_challenges
/nthfibonacci.py
1,786
4.40625
4
"""write a function that takes an integer & returns the nth fibonacci number fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13... indexing starts at 0: (0)(1)(2)(3)(4)(5)(6)(7)""" # if n < 2, then index = n # if n > 2, then index(n) = index(n-1)+index(n-2) def fib(n): """return nth fibonacci number >>> fib(7) 13 """ if n < 2: return n # start at the beginning of the sequence p1 = 0 p2 = 1 # in order to get to index(n), need to go through the entire range - 1 for i in range(n-1): next = p1 + p2 # set next number to the sum of two previous p1 = p2 # then reset p1 to p2 p2 = next #reset p2 to next, so on and so forth until end of for loop return next # then return final next def get_fib(n): """still using recursion >>> get_fib(5) 5 """ memo = {} #memoization: keeping of calculated sums using dictionary - index: fib if n < 2: return n if n in memo: # first look up n in dictionary, if it's there, no need to calculate return memo[n] result = get_fib(n-1) + get_fib(n-2) #else recurse memo[n] = result #add n/fib to dictionary return result def recurse_fib(n): """returns nth fibonacci number >>> recurse_fib(6) 8 """ # base case if n < 2: return n return recurse_fib(n-1) + recurse_fib(n-2) # if n is 5 # f(5) = f(4)-f(3) # f(4) = f(3)-f(2) f(3) = f(2)-f(1) # f(3) = f(2)-f(1) f(2) = f(1)-f(0) f(2) = f(1)-f(0) f(1) = 1 # f(2) = f(1)-f(0) f(1) = 1 f(1) = 1 f(0) = 0 f(1) = 1 f(0) = 0 # f(1) = 1 f(0) = 0 # total 15 calls, 13 repeats # binary tree = O(2^n) ##################################################################### if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED." print
true
af59e77c7c2fd71276d1f5f928b190c97ec9cf22
neenjaw/udemy-python-mega-course
/pre/myprogram.py
299
4.15625
4
greeting = input("Write a greeting: ") print(greeting) a = 4 if a > 5: print("greater than 5") elif a == 5: print("equal to 5") else: print("hi") emails = ["blah@sadas.com", "blah@sadasd.com","blah@sadass.com","blah@sadasa.com"] for email in emails: if 'sadasd' in email: print(email)
false
9cf85c22b599bc98b439dc7fd0237489712d003d
varun-varghese/coding-practice
/interview/strings/suffixArray1.py
1,303
4.15625
4
""" Naive implementation of suffix array. O(n^2 * Log(n)) String comparison takes n while sorting takes n log n """ def build_suffix_array(word): """ Build an array of all suffixes and sort """ suffixes = [] for i in range(len(word)): suffix = word[i:] suffixes.append((suffix, i)) suffixes.sort() suffix_array = map(lambda tup: tup[1], suffixes) return suffix_array def search_suffix(suffix_array, word, pattern): """ Search a pattern in O(m*Log(n)), m = length of pattern. At most log(n) steps, with m operations per step for string cmp """ if len(suffix_array) < 1: return [] begin, end = 0, len(suffix_array)-1 while begin <= end: mid = begin+(end-begin)/2 # because of possible overflow index = suffix_array[mid] suffix = word[index:] if pattern == suffix: return "Pattern '{}' found at index {} of {}".format(pattern, index, word) elif pattern > suffix: begin = mid + 1 elif pattern < suffix: end = mid - 1 return "Pattern '{}' not a suffix of '{}'".format(pattern, word) if __name__=="__main__": word = "banana$" suffix_array = build_suffix_array(word) print "Suffix array is:", suffix_array pattern = "ng" pattern2 = "nice" print search_suffix(suffix_array, word, pattern) print search_suffix(suffix_array, word, pattern2)
true
55e8baf2a0286d27daf8ffd3a0d861bc936ca1ce
gaijinctfx/PythonExercicios
/Estrutura_De_Decisao/estruturadedecisao-23.py
912
4.1875
4
# author: ZumbiPy # E-mail: zumbipy@gmail.com # Exercicio do site http://wiki.python.org.br/EstruturaDeDecisao # Para execurta o programa on line entra no link a baixo: # https://repl.it/I238/0 """ 23 - Faça um Programa que peça um número e informe se o número é inteiro ou decimal. Dica: utilize uma função de arredondamento. """ # ================================================================================ # Variáveis do programa # ================================================================================ numero_digitado = input("Digite um numero: ") # ================================================================================ # Logica do programa # ================================================================================ if "." in numero_digitado: print("Ele e um numero Decimal") else: print("Ele e um numero Inteiro")
false
ca12e796bf0ef0cdd01cb10c5b8a9b9887d872f1
CurtCodes/python_winter2020
/wk1/Day2/first_practice.py
760
4.40625
4
# Practicing with lists and functions # Example: define a function # Between A and B(inclusive) # def find_evens(A,B): # evens=[] # for nums in range(A,B+1): # if (nums%2==0): # evens.append(nums) # return evens # print(find_evens(2,100)) # TODO: find a function that returnes a list of numbers between A # and B (inclusive) that are even multiples of 3 def find_of_three(A,B): of_threes=[] for nums in range(A,B+1): if (nums%3==0 and nums%2==0): of_threes.append(nums) return of_threes print(find_of_three(1,30)) # def even_mults(A,B): # mults=[] # for nums in range(A,B+1): # if nums%6==0: # mults.append(nums) # return mults # print(even_mults(0,20))
true
f2944bbf14f52df9844d533878eae364c8bb4f2c
CurtCodes/python_winter2020
/wk2/Day2/PC1.py
228
4.25
4
# A little review on string and how they work in python # a=[1,2,3] # print(a[-1]) #Finding the last alphanumerical value in a list # list splicing # Getting the last alphanumerical values a="hotdog" print(a[3:]) print(a[:3])
true
b77cde4cfc721873faef0765330297d79136b21b
progwiz-ishaan/Python-Games
/coding-in-python/geometric_art.py
925
4.125
4
# Make a geometric rainbow pattern. import turtle shelly = turtle.Turtle() # pick a order of colours for the hexgon. colours = ['red', 'yellow', 'blue', 'orange', 'green', 'red'] turtle.bgcolor('black') # turn the background black # draw 36 hexgons, each 10 degrees apart. for n in range(36): # make a hexgon by repeating 6 times. for h in range(6): shelly.color(colours[h]) # Pick colour at position i. shelly.forward(100) shelly.left(60) # add a turn before the next hexgon. shelly.right(10) # get ready to draw 36 circles. shelly.penup() shelly.color('white') # repeat 36 times to mach the 36 hexons. for i in range(36): shelly.forward(220) shelly.pendown() shelly.circle(5) shelly.penup() shelly.backward(220) shelly.right(10) # hide turtle to finish the drawing. shelly.hideturtle() # Prevent the program form qutting by asking the user a question w = input()
true
41f6caa499fb621122ba0156ff599b65f553bef5
nagagopi19/Python-programms
/Lambda-Function/mapfunction.py
306
4.1875
4
#map function ---> it acts on each element and perhaps modifies the element based on lambda #syntax ---> map(lambda,sequence) #create a lambda that returns squares of all elements in a list. mylst = [1,2,3,4,5,-4,10,15] obj = map(lambda x: x*x, mylst) print(list(obj)) #print(tuple(obj)) #print(set(obj))
true
35c09d96f29001e8bab317059d0e111ec1e5d6b4
lalit97/dsa-lessons
/array-strings-map/day06-urlify-string.py
530
4.15625
4
""" https://practice.geeksforgeeks.org/problems/urlify-a-given-string/0 """ # def urlify(string, k): # return string.replace(" ", "%20") def urlify(string, k): string = "he ll o" length = len(string) temp = list(string) # ['h', 'e', ' ', 'l', 'l',' ','o'] answer = "" for index in range(length): if temp[index] == " ": temp[index] = "%20" answer += temp[index] #'he%20ll%20' return answer if __name__ == '__main__': for _ in range(int(input())): string = input() k = input() ans = urlify(string, k)
false
312c11fece3f25f89516d7cb03cb19f049657069
pablods90/ThePythonChallenge
/03/challenge03.py
1,693
4.40625
4
#!/usr/bin/env python # @Patan # Challenge 03: http://www.pythonchallenge.com/pc/def/equality.html # Comments: - Based on the title of the web "re" (suggests regular expr) and # the hint (exactly three big bodyguads on each side)... we can guess # that we need to find a letter that is "surrounded" by a regular # expression that repeats 3 times on each side of the letter. # - Good help: https://www.machinelearningplus.com/python/python-regex-tutorial-examples/ # - \w is equivalent to [^a-zA-Z_0-9]. # - The key is "EXACTLY THREE" (not, more than three). # Imports import re # Open the file and get the raw string (convert it to one line string) raw_text = "".join( open('raw_text.txt','rt').read().splitlines() ) # Apply a RegExp to retrieve the parttern reg_exp = r'[^A-Z][A-Z]{3}[a-z][A-Z]{3}[^A-Z]' findings = re.findall(reg_exp,raw_text,re.M) # Show the results if findings: print '\nFound: ', findings, "\n" # Findings is a list of strings that match the rule. The rule is matched with # a string like this (showing the string): # - [0] 1 lowercase letter # - [1] 1 Capital leter # - [2] 1 Capital leter # - [3] 1 Capital leter # # - [4] 1 lowercase letter (our key letter, the one we need to retrieve) # # - [5] 1 Capital leter # - [6] 1 Capital leter # - [7] 1 Capital leter # - [8] 1 lowercase letter # # If we keep the 4th position of each string we can get our keyword... # keyword = "" for match in findings: keyword += match[4] print '\nOur keyword is: ', keyword, "\n" else: print 'Nothing found!'
true
bf3ba41b40468fd54f05e4ca2dd88c054103d83e
neeraj1909/learn-python
/Shaw - Learn Python 3 the Hard Way/Chapter-42 Is-A, Has-A, Objects, and Classes/exercise_42_2.py
1,031
4.375
4
""" Is it possible to use a class like it’s an object? """ print("Everything in Python is an object, including classes.") print("This means you can reference classes, passing them around like arguments, store them in attributes,") print("(extra) names, lists, dictionaries etc.") print("\nThis is perfectely normal in Python: \n") print("class_map = {") print(" 'foo': A,") print(" 'bar': SomeOtherClass,") print(" 'baz': YetAnother") print("}\n") print("instance = class_map[some_variable]()\n") print("Now it depends on the some_variable what class was picked to create an instance;") print("the class_map dictionary values are all classes.\n") print("Classes are themselves instance of their type; this is called the metaclass.") print("You can produce a new class by calling type() with a name, a sequence of base classes,") print("and a mapping defining the attributes of the class:\n") print("type('DynamicClass', (), { 'foo': 'bar'})\n") print("cretae a new class object , with a foo attibute set to bar.")
true
9ec18dfc588efff76b43f9fc9fc7f892e16aca0c
neeraj1909/learn-python
/Think-Python-Exercises/Chapter-15 Classes and Objects/exercise_15_2.py
1,768
4.78125
5
""" Write a function called draw_rect that takes a Turtle object and a Rectangle and uses the Turtle to draw the Rectangle. See Chapter 4 for examples using Turtle objects. Write a function called draw_circle that takes a Turtle and a Circle and draws the Circle. """ from turtle import * class Point(object): """Represents a point in 2-D space.""" def __init__(self, x, y): self.x = x self.y = y class Rectangle (object): """docstring for Rectangle. attributes: width, height, corner. """ def __init__(self, width, height, corner): self.width = width self.height = height self.corner = corner class Circle(object): """docstring for Circle. attributes: center, radius. """ def __init__(self, center, radius): self.center = center self.radius = radius def draw_rect(bob, rectangle): turtle.pu() bob.setposition(rectangle.corner.x, rectangle.corner.y) turtle.pd() for _ in range(2): bob.forward(width) bob.lt(90) bob.forward(height) bob.lt(90) return bob = turtle.Turtle() width = 60 height = 100 corner = Point(10, 10) rectangle = Rectangle(width, height, corner) print(draw_rect(bob, rectangle)) def draw_circle(bob, circle): turtle.pu() bob.setposition(circle.center.x + circle.radius, circle.center.y) turtle.pd() bob.circle(circle.radius) if __name__ == '__main__': bob = turtle.Turtle() width = 60 height = 100 corner = Point(10, 10) rectangle = Rectangle(width, height, corner) print(draw_rect(bob, rectangle)) x = turtle.Turtle() center = Point(0, 0) radius = 20 circle = Circle(center, radius) print(draw_circle(x, circle))
true
0de0c1b73189b0f47185cf4a9a54bd114862ef05
amoor22/patterns
/v-shape pattern.py
467
4.125
4
num = int(input("Enter a number: ")) noom = num-1 num2 = 0 while noom > 0: for x in range(num2): print(' ',end='') print('*',end='') for x in range(noom): print(' ',end='') for x in range(noom -1): print(' ',end='') print('*') noom -= 1 num2 += 1 # last iteration if noom == 0: print(" " * (num2-1) , "*") # input: 6 # output: # * * # * * # * * # * * # * * # *
false
89a8c84f06137d1011c9920360e354a6e6991fc7
MrMilo900/Projekt-Euler
/Euler004.py
628
4.125
4
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # #Find the largest palindrome made from the product of two 3-digit numbers. mylistx = [] for x in range(100,1000): mylistx.append(x) mylistx = mylistx[::-1] palilist = [] def check(): for index1 in range(0,len(mylistx)): for index2 in range(0,len(mylistx)): pali = str(mylistx[index1] * mylistx[index2]) if pali == pali[::-1]: palilist.append(int(pali)) return palilist result = check() print(max(result))
true
ebb4521810d54cbcb83d87259736a104f000a83d
Kirushanr/Python
/Python Crash Course/motorcycles.py
500
4.21875
4
motorcycles =[] #empty list motorcycles.append('honda') # add an element to the end of the list motorcycles.insert(0,'yamaha') #insert an element in the specified position motorcycles.append('suzuki') del motorcycles[0] #delete the element in position print(motorcycles) print(motorcycles.pop()) #remove the last element from the list print(motorcycles) motorcycles.append('ducati') print(motorcycles) expensive_vehicle=motorcycles.pop(0); print('Too expensive motorcycle '+ expensive_vehicle)
true
a0905e031a51911a163b9991fc1fb2fc1ff92b09
huangjing2016/leetcode_python
/src/reverse_integer.py
888
4.1875
4
# Given a 32-bit signed integer, reverse digits of an integer. # # Example 1: # # Input: 123 # Output: 321 # Example 2: # # Input: -123 # Output: -321 # Example 3: # # Input: 120 # Output: 21 # Note: # Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. class Solution: MAX_NUM = 2 ** 31 def reverse(self, x: int) -> int: res = 0 flag = 1 if x >=0 else -1 while x != 0: res = abs(x) % 10 + res * 10 # 此处必须取绝对值,python 取余算法负数是向下取整 x = abs(x) // 10 return res * flag if res < self.MAX_NUM else 0 if __name__ == '__main__': x = -123 solution = Solution() print(solution.reverse(x))
true
a1ba7d4736e53f11df3bd98f345841b5fefc2a8b
hope-crichlow/Python
/fundamentals/oop/practice/user.py
2,461
4.21875
4
class User: def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 # adding the deposit method def make_deposit(self, amount): # takes an argument that is the amount of the deposit self.account_balance += amount # the specific user's account increases by the amount of the value received # this method decrease the user's balance by the amount specified def make_withdrawl(self, amount): self.account_balance -= amount # this method print the user's name and account balance to the terminal def display_user_balance(self): # eg. "User: Guido van Rossum, Balance: $150 print(f"User: {self.name}, Balance: ${self.account_balance}") # Bonus # have this method decrease the user's balance by the amount and add that amount to other other_user's balance def transfer_money(self, other_user, amount): self.account_balance -= amount other_user.make_deposit(amount) print(f"User: {self.name}, Balance: ${self.account_balance}") print(f"User: {other_user.name}, Balance: ${other_user.account_balance}") # Create 3 instances of the User class deidre = User("Deidre La Couse", "DeLaCouse@airs.com") makeda = User("Makeda de Lioncourt", "DeLionMaker@airs.com") olivia = User("Olivia de La Pieza", "OlaPieza@airs.com") # Have the first user make 3 deposits and 1 withdrawal and then display their balance print("starting balance: $", deidre.account_balance) deidre.make_deposit(70) deidre.make_deposit(100) deidre.make_deposit(67) deidre.make_withdrawl(45) print("ending balance: $", deidre.account_balance) # Have the second user make 2 deposits and 2 withdrawals and then display their balance print("starting balance: $", makeda.account_balance) makeda.make_deposit(75) makeda.make_deposit(50) makeda.make_withdrawl(45) makeda.make_withdrawl(45) print("ending balance: $", makeda.account_balance) # Have the third user make 1 deposits and 3 withdrawals and then display their balance print("starting balance: $", olivia.account_balance) olivia.make_deposit(1000) olivia.make_withdrawl(25) olivia.make_withdrawl(35) olivia.make_withdrawl(45) print("ending balance: $", olivia.account_balance) # BONUS: Add a transfer_money method; have the first user transfer money to the third user and then print both users' balances print("Deidre's starting balance: $", deidre.account_balance) print("Olivia's starting balance: $", olivia.account_balance) deidre.transfer_money(olivia, 50)
true
988dcbf170670d776ff84b7084e5181c2fe01b44
don-juancito/BrainsToBytes_CodeSamples
/DeepLearningBasics/NeuralNetwork_3-HCLearning/hot_cold_prediction_one_run.py
1,057
4.15625
4
def neural_network(input, weight): predicted_value = input * weight return predicted_value minutes_running = 20 actual_calories_burned = 180 # We perform this extra assignment just to keep consistency with the names input = minutes_running expected_value = actual_calories_burned weight = 7 predicted_value = neural_network(input, weight) print("According to my neural network, I burned {} calories".format(predicted_value)) error = (predicted_value - expected_value)**2 print("The error in the prediction is {} ".format(error)) learning_rate = 0.1 prediction_upwards = neural_network(input, weight + learning_rate) error_upwards = (prediction_upwards - expected_value)**2 print("The prediction with an updated weight of {} has an error of {}".format(weight+learning_rate, error_upwards)) prediction_downwards = neural_network(input, weight - learning_rate) error_downwards = (prediction_downwards - expected_value)**2 print("The prediction with an updated weight of {} has an error of {}".format(weight-learning_rate, error_downwards))
true
6dfc5f24e1e96fad17d1fc5addb535a5bb920e8e
j-217/python
/codewars/04_divisors.py
836
4.25
4
def divisors(integer): """ Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust). Example: divisors(12); #should return [2,3,4,6] divisors(25); #should return [5] divisors(13); #should return "13 is prime" """ list = [] for i in range(2, integer): if integer % i == 0: list.append(i) else: continue if len(list) != 0: # print(list) return list else: # print("{} is prime".format(integer)) return "{} is prime".format(integer) divisors(12)
true
1204baa5cf855bdb7e494a3e54a29abc061f259e
DanielSOhara27/DataBootcamp-PythonVanilla-Module
/PythonClass2/ClassActivity1_ForLoopsBonus.py
281
4.15625
4
option = "y" counter = 0 while option != "n": numbers = int(input("How many numbers should I print?")) for x in range(numbers): print(f"{counter}\n") counter += 1 option = input("Do you want to print another range of numbers? (y)es or (n)o?")
true
cd6396bbeaccd8a43396a6c1b46635c5df171ec6
AndreLovo/Python
/Desafio041.py
606
4.15625
4
from datetime import date ano= int(input('Entre com o ano de nascimento:')) atual= date.today().year idade=(atual-ano) print('Você tem {} anos'.format(idade)) if(idade<=9): print('Você nasceu em {} e sua categoria é a MIRIM'.format(ano)) elif(idade<=14): print('Você nasceu em {} e sua categoria é a INFANTIL'.format(ano)) elif (idade<=19): print('Você nasceu em {} e sua categoria é a JÚNIOR'.format(ano)) elif(idade<=25): print('Você nasceu em {} e sua categoria é a SENIOR'.format(ano)) else: print('Você tem acima de 20 anos e sua categoria é MASTER.')
false
99220cc8f6ee8e8be94e7bbc31afd0c5ce6d87b5
lxj19681972/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
/PS1-3.py
663
4.25
4
"""Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. In the case of ties, print the substring that appears first. """ working = s[0] longest = s[0] """Build strings where characters appear in alphabetical order""" for char in range(1, len(s)): if s[char] >= working[-1]: working += s[char] if len(working) > len(longest): longest = working else: if len(working) > len(longest): longest = working working = s[char] print("Longest substring in alphabetical order is: " + longest)
true
668f7dc460310571300e752e7902bcf6ed6e13fa
huijillain/Python-TriangleAreaVersion3
/Triangle Area Version 3.py
887
4.1875
4
# area of Triangle program. Modify the program after receiving input from the user for # the length of the base and the height of the triangle # program will be verified the values entered are not 0 or negative. # if they are, program will output a useful message, re-ask user again for the correct input #get the base value first base = int( input("Enter the length of the base:") ) while base <= 0 : print("**Error - the base length must be a positive number. You entered ", base) base = int(input("Enter the length of the base: ")) height = int( input("Enter the height:") ) while height <= 0 : print("**Error - the height must be a positive number. You entered ", height) height = int(input("Enter the height: ")) area = 1 / 2 * base * height print("The area of the triangel is", round (area/10000, 2) , "square metres")
true
cc6bc44e5fed85c0ae705eeec676f77aca67455b
guiconti/workout
/leetcode/9.palindrome-number/9.palindrome-number.py
889
4.28125
4
# Share # Given an integer x, return true if x is palindrome integer. # An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not. # Example 1: # Input: x = 121 # Output: true # Example 2: # Input: x = -121 # Output: false # Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. # Example 3: # Input: x = 10 # Output: false # Explanation: Reads 01 from right to left. Therefore it is not a palindrome. # Example 4: # Input: x = -101 # Output: false # Constraints: # -231 <= x <= 231 - 1 def solution(x: int) -> int: # Negative number will never be palindromes by the problem definition if x < 0: return False reversed_number = str(x)[::-1] try: reversed_number = int(str(x)[::-1]) except: return False return reversed_number == x
true
73dc99a1944bec81bf5c64a6e7a15a0847224cba
alex-xia/leetcode-python
/lib/calculator.py
1,419
4.25
4
''' Write a program that takes a single line of input, representing an arithmetic expression. The expression will consist of numeric digits (0-9), the plus operator (+) and the multiplication operator (*). The given expression will be a valid arithmetic expression (ie. "*2++" is not valid). Your task is to evaluate the arithmetic expression, following the normal rules of operator precedence, and print the result without any leading or trailing whitespace. The resulting numbers will fit in a normal integer. Note: Solutions such as "eval()" in python are elegant, but not what we are looking for here. Please evaluate the expressions with your own code :). Example Input 20+2*3 Example Output 26 ''' # This is Python 2 import sys def calc(s): nums = [] muls = [] num_str = '' for c in s: if c is '+': num = int(num_str) num_str = '' if len(muls) > 0: num = num * muls[0] del muls[0] nums.append(num) elif c is '*': num = int(num_str) num_str = '' if len(muls) == 0: muls.append(num) else: muls = [muls[0] * num] else: num_str += c print nums, muls num = int(num_str) if len(muls) > 0: num = num * muls[0] nums.append(num) return sum(nums) print calc('20+2*3*2')
true
c4bad089c4d54c690f6de806f72b7461025ff327
rwatson1799/tkinter-codemy-tutorial
/gui/grid.py
406
4.53125
5
from tkinter import * root = Tk() # Creating a Label widget myLabel1 = Label(root, text="Hello World!").grid(row=0, column=0) # could do this, but not as clean myLabel2 = Label(root, text="My Name Is Ryan Watson") myLabel3 = Label(root, text=" ") # Putting it onto the screen # myLabel1.grid(row=0, column=0) myLabel2.grid(row=1, column=2) myLabel3.grid(row=1, column=1) root.mainloop()
true
71f93dfa1577c0e52a0d47cbaefc0c08474193c5
kostcher/algorithmsPython
/hw_3/task_2.py
732
4.21875
4
# Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями # 8, 3, 15, 6, 4, 2, то во второй массив надо заполнить значениями 1, 4, 5, 6 (или 0, 3, 4, 5 - если индексация # начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа. import random result = [] numbers = [random.randint(0, 100) for _ in range(10)] for index, number in enumerate(numbers): if number % 2 == 0: result.append(index) print(numbers) print(result)
false
2f6de63d2ffaf36abf2ff8f0d07fbb67d1dc1f14
kostcher/algorithmsPython
/hw_1/task_5.py
871
4.28125
4
# Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв. first_letter = input('Введите первую букву:') second_letter = input('Введите вторую букву:') first_letter_in_alph = ord(first_letter) - (ord('a') - 1) second_letter_in_alph = ord(second_letter) - (ord('a') - 1) dist_between_letters = abs(second_letter_in_alph - first_letter_in_alph) if dist_between_letters != 0: dist_between_letters -= 1 print(f'Буква {first_letter} в алфавите №{first_letter_in_alph}') print(f'Буква {second_letter} в алфавите №{second_letter_in_alph}') print(f'Между буквой \'{first_letter}\' и \'{second_letter}\' {dist_between_letters} букв')
false
ad0caaa3338fb1f689870fd21d29f1fffc135229
kostcher/algorithmsPython
/hw_6/task_2.py
2,798
4.1875
4
# 1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех # уроков. Проанализировать результат и определить программы с наиболее эффективным использованием памяти. import sys import random # Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр. # Вывести на экран это число и сумму его цифр. count_input_numbers = 2 sum_digits_number = 0 max_number = 0 if count_input_numbers > 0: for i in range(count_input_numbers): number = random.randint(1, 100) tmp_sum_digits_number = 0 tmp_number = number while number > 0: last_number = number % 10 number = number // 10 tmp_sum_digits_number += last_number if tmp_sum_digits_number > sum_digits_number: sum_digits_number = tmp_sum_digits_number max_number = tmp_number # print(f'У числа {max_number} иаксимальная сумма чисел среди введенных, его сумма равна {sum_digits_number}') # print(f"Сумма цифр числа: {summ}") # print(f"Произведение цифр числа: {product}") def variables_sizes(): sizes_vars = {} default_types = [int, float, complex, list, tuple, range, str, bytes, bytearray, memoryview, set, frozenset, dict] for name, val in list(globals().items()): if not name.startswith('__'): for default_type in default_types: if isinstance(val, default_type): sizes_vars[name] = sys.getsizeof(val) return sizes_vars variables_sizes = variables_sizes().items() total_size = 0 for var, size in variables_sizes: print(f'Переменная {var} имеет размер {size} байт') total_size += size print(f'Общий размер {total_size} байт') # Переменная count_input_numbers имеет размер 14 байт # Переменная sum_digits_number имеет размер 14 байт # Переменная max_number имеет размер 14 байт # Переменная i имеет размер 14 байт # Переменная number имеет размер 12 байт # Переменная tmp_sum_digits_number имеет размер 14 байт # Переменная tmp_number имеет размер 14 байт # Переменная last_number имеет размер 14 байт # Общий размер 110 байт
false
611a4be12d465ad9c2213ade8864d763589ea12a
oneoffcoder/nextgencoders
/2020-08-21-python-no-tears/code/05-inputs.py
260
4.4375
4
# input are a way for you to get "inputs" from your user # echo example name = input('what is your name? ') print(f'hello, {name}! how are you today?') # f-string: interpolation (substitution) feeling = input('') print(f'i am glad you are feeling {feeling}')
true
9fa5a7b09285ab165ef371a70d735dd14d8898be
oneoffcoder/nextgencoders
/2020-08-21-python-no-tears/code/09-calculator.py
324
4.15625
4
# another calculator # subtraction # ask the user for 2 numbers # convert the string inputs to integers # subtract (compute answer) # print numbers and answer num_1 = input('number 1: ') num_2 = input('number 2: ') num_1 = int(num_1) num_2 = int(num_2) answer = num_1 - num_2 print(f'{num_1} - {num_2} = {num_1 - num_2}')
true
17b1d7958f2d44e398b72692b71a6b0045b7a532
veroon-eng/task_6
/my_package/transformers/string_transformer.py
249
4.3125
4
def reversing (): words=input("enter a word: ") words = words.split(' ') reverse=" ".join(reversed(words)) print(reverse) reversing () def capitalizing(): word=input("enter a word: ") print(word.capitalize()) capitalizing()
true
9f65b8ef12d6862f47c414829ab37de9adba2103
lapgar/lab01
/Lab-01-lapgar.py
2,742
4.3125
4
# Lindsay Apgar # Lab-01 # main # variables unlucky = 13 # integer pi = 3.14 # float iceCream = "strawberry" # string (favorite ice cream flavor) decimal = "5.6" # string with decimal # conversion print(float(unlucky)) # convert unlucky to a float print(int(pi)) # convert pi to an integer print(str(pi)) # convert pi to a string print(float(decimal)) # convert decimal to a float # input myInteger1 = int(input("Please enter a whole number")) myInteger2 = int(input("Please enter another whole number")) myFloat1 = float(input("Please enter a number with a decimal point")) myFloat2 = float(input("What is pi to two decimal points?")) # arithmetic print(myFloat1 + myFloat2) # add print(myFloat1 - myFloat2) # subtract print(myFloat1 * myFloat2) # multiply print(myFloat1 / myFloat2) # divide print(myFloat1 ** myFloat2) # raise to the power of print(myInteger1 % myInteger2) # remainder print(myInteger1//myInteger2) # integer division? myInteger1 += myInteger2 # myInteger1 = myInteger1 + myInteger2 myFloat1 *= myFloat2 print(myInteger1) print(myFloat1) # print(myFloat1 *= myFloat2), doesn't work because you can't print an expression # reminder: // is integer division, % calculates remainder # working with strings favCereal = input("What is your favorite kind of cereal?") print("I like " + favCereal + " too!") print(favCereal * 6) # use the * operation to repeat favCereal 6 times # comparison operations --- I do not think that I did this correctly comp1 = myInteger1 - myInteger2 if comp1 > 0: myBool1 = True print("myInteger1 is greater than myInteger2") else: myBool1 = False print("myInteger2 is greater than myInteger1") if myFloat1 == myFloat2: myBool2 = True print(myBool2) else: myBool2 = False print(myBool2) # If... value = int(input("Please enter a number between 1 and 12")) if 3 <= value <= 5: # between 3 and 5 print("Spring") elif 6 <= value <= 8: # between 6 and 8 print("Summer") elif 9 <= value <= 11: # between 9 and 11 print("Fall") elif value in [1, 2, 12]: # if they put 1, 2, or 12 --- Initially tried to say elif value == 1 or 2 or 12, led to numbers outside of the 1 to 12 range also getting the output 'winter' print("Winter") else: # if it is not between 1 and 12 -- also could do elif value != 1 <= value <= 12 print("Wrong number!") # While... countdown = int(input("Please input a positive integer between 1 and 10: ")) # countdown from whatever number is input while 0 <= countdown <= 10: print(countdown) countdown -= 1
true
edb3cff5f09d90cc2545563f7a6e12dbe40bd7a3
Tapan-24/python
/determine_exist_of_triangle.py
218
4.15625
4
print("Enter proposed length of triangle") x=float(input("x= ")) y=float(input("y= ")) z=float(input("z= ")) if x+y>z and x+z>y and y+z>x: print("Triangle exist") else: print("Triangle does not exist")
false
f4fca5657c6c34d24df442aba24d529a00b20c56
jogurdia/python-course-repository
/numbers.py
789
4.125
4
10 #integer 15.5 #float print(type(9)) print(type(10.5)) #Result : #JOGURDIA-M-X6MF:python-course jogurdia$ python numbers.py #<type 'int'> #<type 'float'> 3 + 1 2 - 1 5 * 6 6 / 2 2**3 # this is exponential 2^3 3 // 2 # this is called module and is used to get just the integer value and not the float 20 - 10 / 5 * 3**2 # will follow the same rule of order doing the operation (20 - 10) / (5 * 3**2) # we can make maths using () as well age = input("Insert your age :") # input is used to ask the user to enter the value, will be str print(age) age = input("Insert your age :") print(type(age)) new_age = age + 10 print(new_age) age = input("Insert your age :") new_age = int(age) + 5 # int is used to convert str age to integer, will only convert str "10" to 10 print(new_age)
true
7f12a8d82bc40f00cf5901213fa241b4d95612bb
cpoIT/Sorting
/project/iterative_sorting.py
2,183
4.28125
4
# Complete the selection_sort() function below in class with your instructor def selection_sort( arr ): # loop through n-1 elements for i in range(0, len(arr) - 1): # range(3) = 0, 1, 2 range(1, 3) = 1, 2 cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) # ret.append(smallest_index) for j in range(i+1, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j # TO-DO: swap arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index] return arr [1, 3, 5, 0, 2] [0, 3, 5, 1, 2] # TO-DO: implement the Insertion Sort function below def insertion_sort( arr ): for i in range(0, len(arr) - 1): left = arr[0:i+1] val = arr[i + 1] if val < left[-1:][0]: for ind, j in enumerate(left): if val < j: arr[i + 1], arr[ind] = arr[ind], arr[i + 1] return arr # STRETCH: implement the Bubble Sort function below def bubble_sort( arr ): for idx, el in enumerate(arr[:-1]): for i in range(0, len(arr) - 1): curr_val = arr[i] next_val = arr[i + 1] if curr_val > next_val: temp = curr_val arr[i] = next_val arr[i + 1] = temp return arr # STRETCH: implement the Count Sort function below def count_sort( arr, maximum=-1 ): #len 5 [1, 4, 4] empty = [0] * 10 # 0, 1, 1, 1, 3, ret = [0] * (len(arr) + 1) for ind, el in enumerate(empty): for e in arr: if e == ind: empty[ind] +=1 for ind, el in enumerate(empty): if ind != 0: prev_ind = ind - 1 empty[ind] += empty[prev_ind] for ind, el in enumerate(arr): if el < 0: return 'Error, negative numbers not allowed in Count Sort' empty_val = empty[el] ret[empty_val] = empty_val - 1 empty[el] -= 1 return ret[1:] print(count_sort([1, 4, 1, 2, 7, 5, 2]))
true
ceb3c838ac2ae4f2aefb0a022fe4b72a93cd6f2c
Nirvighan/Python_C105_Project
/StandardDeviation.py
956
4.15625
4
# IMPORT THE NEEDED LIBRARIES import csv import math # READ THE CSV FILE with open('data.csv',newline = '') as csv_data: reader = csv.reader(csv_data) file_data = list(reader) # STORE THE DATA IN A LIST data = file_data[0] #STANDARD DEVIATION STARTS # TAKE OUT THE MEAN OF THE DATA def MEAN(data): n = len(data) total = 0 for x in data: total+=int(x) mean = total/n return mean # SQUARING AND GETTING THE VALUES squarelist = [] for number in data: a = int(number)-MEAN(data) a = a**2 squarelist.append(a) # GETTING THE SUM sum = 0 for i in squarelist: sum = sum+i # DIVIDING THE SUM BY THE TOTAL VALUES result = sum/(len(data)-1) # GETTING THE STANDARD DEVIATION BY GETTING THE SQUARE ROOT OF THE RESULT standard_deviation = math.sqrt(result) print("THIS IS THE STANDARD DEVIATION OF THE VALUES") print(standard_deviation)
true
2c3205d7318e2c28e2d77ff427cf3fa25047e320
proffillipesilva/aulasdelogicaprogramacao
/aula1005_revisao/listas.py
1,304
4.1875
4
""" Usando nossas proprias funcoes """ def maximo( lista ): maximo = lista[0] for elemento in lista: if elemento > maximo: maximo = elemento return maximo def maximo_4_valores(a, b, c, d): if a > b and a > c and a > d: return a elif b > c and b > d: return b elif c > d: return c else: return d def maximo_4_valores_smart(a, b, c, d): return maximo([a, b, c, d]) def ordena_lista( lista ): # eu pego o primeiro menor # depois, o segundo menor # depois, o terceiro menor... for i in range( len(lista) ): for j in range(i+1, len(lista)): if lista[i] > lista[j]: temp = lista[i] lista[i] = lista[j] lista[j] = temp return lista def soma(lista): total = 0 for elemento in lista: total += elemento return total lista = [3, 1, 5, 2] print(maximo_4_valores(3, 1, 5, 2)) print(maximo_4_valores_smart(3, 1, 5, 2)) print( soma(lista)) print( ordena_lista(lista)[ -2 : ] ) """ somar os dois maiores elementos""" print( soma(ordena_lista(lista)[-2:]) ) """ media dos dois últimos elementos elementos""" print( soma(ordena_lista(lista)[-2:])/2 ) maiores = ordena_lista(lista)[-2:] print(soma(maiores)/len(maiores))
false
d47aec8e2839f372155912441a980557f6ee4038
proffillipesilva/aulasdelogicaprogramacao
/aula1005_revisao/funcoes_prontas.py
1,671
4.21875
4
""" 1) Operadores de uma linha max, min, sum, len, sorted 2) Operadores com lambda filter e map 3) Converter para texto --> str.join 3) Criação de lista com uma linha [ valor for x in range(tamanho_da_lista) ] """ lista = [8,6,5,4,12,2,-3,0,9] # maximo print( max(lista) ) # minimo print( min(lista) ) # soma print( sum(lista)) # tamanho print( len(lista)) # media --> soma/tamanho print( sum(lista)/len(lista)) # ordenacao print( sorted(lista)) # ordenacao decrescente print( sorted(lista, reverse=True)) # FILTRAGEM def eh_par(num): # --> lambda num: num % 2 == 0 if num % 2 == 0: return True else: return False print( eh_par(4) ) # print( filter( eh_par, lista ) ) # FILTER POR BAIXO DOS PANOS def meu_filtro( fn, lista): filtrados = [] for elemento in lista: if fn(elemento): filtrados.append(elemento) return filtrados print(meu_filtro( lambda num : num > 3, lista ) ) # Usando o filter do python print( list( filter( lambda num : num > 3, lista )) ) # stream --> #lista # Usando o MAP --> mapeia um elemento em outro # 1) Exemplo: Vou multiplicar por 2 cada elemento print( list(map( lambda n: n*2, lista ))) # 2) Exemplo: converter para numero lista_precos = ['13.99', '45.90', '1.99', '3.99'] print ( list( map( lambda preco: float(preco), lista_precos) )) # Quero converter uma lista em um texto, usando um delimitador para cada posição # JOIN é o contrário do SPLIT texto = "Aloha 123 Konoha Naruto" lista_texto = texto.split(' ') print(lista_texto) # Testando o JOIN print( str.join(' ', lista_texto)) print( str.join('--', lista_precos)) print( str.join('\n', lista_precos))
false
b4100dd85451905e5ba7a74fa2c7840e8fcbceb7
LucySargent/she-codes-python
/Reading_files_and_Functions/functions_exercises.py
1,357
4.4375
4
#1.Write a function that takes a temp in fahrenheit and returns the temp in celsius # def convert_f_to_c(temp_in_f): # convert_f_to_c = (temp_in_f - 32) *5/9 # return convert_f_to_c # print(convert_f_to_c(40)) ###### celsius to fahrenheit # def convert_c_to_f(temp_in_c): # convert_c_to_f = (temp_in_c * 9/5) +32 # return convert_c_to_f # print(convert_c_to_f(0)) #2.Write a function that accepts one parameter(an integer) # and returns True when parameter is odd # and returns False when parameter is even # def is_it_odd(num): # if num %2 == 0: # return False # else: # return True # print(is_it_odd(7)) #3> Write a function that returns the mean of a list of numbers # def mean(num_list): # return sum(num_list) /len(num_list) # # print(mean([4,3,2,6])) # print(mean([10,5,6])) # 4.write a function that takes two perameters: # the unit price of an item # how many units were purchased # return total cost as a string #v1 # def total_cost(unit_price,quantity): # total_cost = unit_price * quantity # return total_cost # print(total_cost(3,3)) #v2 # def total_cost(unit_price,quantity): # total_cost = unit_price * quantity # return total_cost # print(f"${total_cost(4.25,3)}") #v3 # def total_cost(price,quantity): # return price * quantity # print(f"${total_cost(4.25, 3)}")
true
4fddb76f25a10e7f7c91819d8c270feee4195c53
LucySargent/she-codes-python
/Loops/loops_exercises.py
1,272
4.34375
4
#Q1. Ask the user for a number. #Use a for loop to print the times tables for that number. # number = int(input("Enter a number: ")) # for i in range(1,number +1): # print(f"{number} * {i} = ", int(number) *int(i)) ######################################### #Q2. Ask the user for a number. #Use a for loop to sum from 0 to that number. # value = int(input("Enter a number: ")) # sum = 0 # for value in range(value+1): # sum = sum + value # print(sum) ####################################### #Q3. Given a list, use a for loop to sum all the numbers in the list. total = 0 list = [3, 5, 9, 1] for ele in range(0, len(list)): total = total +list[ele] print("Total:", total) # total = 0 # list = [-3, -5, 9, 1] # for ele in range(0, len(list)): # total = total +list[ele] # print("Total:", total) # total = 0 # list = [] # for ele in range(0, len(list)): # total = total +list[ele] # print("Total:", total) ############################################## #Q4. Use a for loop to format and print the following list # mailing_list = [ # ["Chilli", "chilli@thechihuahua.com"], # ["Roary", "roary@moth.catchers"], # ["Remus", "remus@kapers.dog"], # ["Prince Thomas of Whitepaw", "hrh.thomas@royalty.wp"], # ["Ivy", "noreply@goldendreamers.xyz"], # ] # for item, item in mailing_list: # print(f"{item}: {item}")
true
adf94e71d7a54a8fe6b864afe728b955d472a1ed
aviadfi2016/python_mix
/class3_exercise.py
1,951
4.125
4
##Python Exercise3_1## given_name = input("please enter your name: ") if given_name == "aviad": print("Hello ",given_name, " Have a great day!") else: print("Greetings, stranger.") ##Python Exercise3_2## score = float(input("please enter your score: ")) if score > 1.0: print("Error –Bad score –should be between 0.0 and 1.0.") if score < 0.9 and score >= 0.8: print("B") if score < 0.8 and score >= 0.7: print("C") if score < 0.7 and score >= 0.6: print("D") if score < 0.6 : print("F") ##Python Exercise3_3## hours = float(input("Enter Hours: ")) if hours < 40: print("not enough hours") elif hours >= 50: wage = float(input("Enter Wage: ")) print(hours*1.5*wage) elif hours < 50 and hours >= 40: wage = float(input("Enter Wage: ")) print(hours*wage) ##Python Exercise3_4## suit_cost = float(input("How much the suit costs ")) fifty_bill = float(input("How many 50$ bills?: ")) ten_bill = float(input("How many 10$ bills?: ")) five_bill = float(input("How many 5$ bills?: ")) num_of_fifty=int(suit_cost/50) suit_cost= suit_cost%50 num_of_ten=int(suit_cost/10) if num_of_ten == 0 : num_of_ten = 1 change = 10-(suit_cost%50) num_of_five = 0 print(num_of_fifty, num_of_ten, num_of_five) ##Python Exercise 3_5## circle1_x = int(input("enter x circle 1:")) circle1_y = int(input("enter y circle 1:")) circle1_radius = int(input("enter radius circle 1:")) circle2_x = int(input("enter x circle 2: ")) circle2_y = int(input("enter y circle 2: ")) circle2_radius = int(input("enter radius circle 2: ")) ##formula for checking if 2 circles overlapping ## if ((circle2_x-circle1_x)*0.5+(circle2_y-circle1_y)*0.5) < circle1_radius+circle2_radius: print("YES, the circles are overlapping.") else: print("No, the circles are not overlapping.")
true
42baec142bdc23fb8796cabc8f25e27444e1a754
riteshc6/ctci
/data_structures/4_trees_and_graphs/2_minimal_tree.py
1,400
4.21875
4
from binary_search_tree import Node, in_order_traversal def minimal_tree(array): """ Returns a binary search tree with minimum height Time Complexity = N log(N) """ array_length = len(array) # Find the index of middle element m = array_length // 2 if array_length % 2 else (array_length // 2) - 1 # Initialize tree with middle element as root root = Node(array[m]) # Initialize right and left indices to m, to loop in both direction from the middle of array right = left = m # Loop from the middle of the array in both direction for _ in range(array_length // 2): # Right loop right += 1 if right < array_length: print(array[right]) root.insert(array[right]) # left loop left -= 1 if left >= 0: print(array[left]) root.insert(array[left]) return root def minimal_tree_with_recursion(array, start, end): if end < start: return mid = (start + end) // 2 node = Node(array[mid]) node.left = minimal_tree_with_recursion(array, start, mid - 1) node.right = minimal_tree_with_recursion(array, mid + 1, end) return node array = [2, 4, 6, 8 , 10, 12, 14, 18] tree = minimal_tree(array) in_order_traversal(tree) print() node = minimal_tree_with_recursion(array, 0, len(array) - 1) in_order_traversal(node) print()
true
e89f5fc1fa507bd9b6ef7d11d8339926763b68c7
Poojanavgurukul/python_all_programm
/python/daily_challenge/discount.py
282
4.125
4
user_input=input("enter your quantity\n") total_cost=user_input*100 if total_cost<1000: print "No discount",total_cost else: discount=total_cost*10/100 total_payment=total_cost-discount print "discount",discount print "total payment after discount",total_payment
true
4d340841b4d895e9c38e87cf9b38b127f8ffef09
yayshine/pyQuick
/google-python-exercises/basic/wordcount.py
2,751
4.3125
4
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class The main() below is already defined and complete. It calls print_words() and print_top() functions which you write. 1. For the --count flag, implement a print_words(filename) function that counts how often each word appears in the text and prints: word1 count1 word2 count2 ... Print the above list in order sorted by word (python will sort punctuation to come before letters -- that's fine). Store all the words as lowercase, so 'The' and 'the' count as the same word. 2. For the --topcount flag, implement a print_top(filename) which is similar to print_words() but which prints just the top 20 most common words sorted so the most common word is first, then the next most common, and so on. Use str.split() (no arguments) to split on all whitespace. Workflow: don't build the whole program at once. Get it to an intermediate milestone and print your data structure and sys.exit(0). When that's working, try for the next milestone. Optional: define a helper function to avoid code duplication inside print_words() and print_top(). """ import sys def dictionizeFile(filename): """Returns a word/count dict for this filename""" countDict = {} f = open(filename, 'rU') for line in f: line = line.lower() line = line.split() for word in line: if countDict.get(word): countDict[word] += 1 else: countDict[word] = 1 f.close() return countDict def print_words(filename): """Prints one '<word> <count>' per line, sorted by words""" countDict = dictionizeFile(filename) count = sorted(countDict.keys()) for word in count: print word, countDict[word] def countSort(tuple): """Used to do custom sorting for the word counts""" return tuple[1] def print_top(filename): """Prints the top 20 most used words in the form of '<word> <count>'""" countDict = dictionizeFile(filename) top = sorted(countDict.items(), key=countSort, reverse=True) for item in top[:20]: print item[0], item[1] # This basic command line argument parsing code is provided and # calls the print_words() and print_top() functions which you must define. def main(): if len(sys.argv) != 3: print 'usage: ./wordcount.py {--count | --topcount} file' sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_words(filename) elif option == '--topcount': print_top(filename) else: print 'unknown option: ' + option sys.exit(1) if __name__ == '__main__': main()
true
7c701310ace4940ac9690d294d6a2f948129ad43
mathraim/deepmath
/deepmath/base_classes/layer.py
2,848
4.21875
4
import numpy as np class Layer(object): """ An "abstract" class that represents the layer in the network ... Attributes ---------- previous : Layer object previous layer in the network's queue of layers next : Layer object next layer in the queue of layers in the network network : Network object network that contains this layer nodes : int number of nodes optimizer : Optimizer object optimizer that is going to be used for the neural network Methods ------- help_init(self) helper mutator method for the child classes - Dense and Activation set_optimizer(self, optimizer) mutator method that sets the optimizer forward(self, input) Performes forward propagation thought the layer backward(self, input, grad_output) Performs a backpropagation step through the layer """ def __init__(self): """ Initializes the initial members for the Layer """ self.previous = None self.network = None self.next = None self.node = None self.optimizer = None def help_init(self): """ This mutator method for the child classes - Dense and Activation Dense - set weights and height Activation - set number of nodes """ pass def set_optimizer(self, optimizer): """ Mutator method that sets the optimizer Parameters ---------- optimizer : Optimizer object optimizer that is going to be used for the neural network """ pass def forward(self, input): """ Takes input to the layer and calculates the grad_output output = forward(input) Parameters ---------- input : numpy array(matrix) Value for the input to the layers Returns ------- numpy array(matrix) output of the layer """ return input def backward(self, input, grad_output): """ Performs a backpropagation step through the layer It uses chain rule to calaculate gradients Parameters ---------- grad_output : numpy array(matrix) (d loss / d output) to use it in the chain rule input : numpy array(matrix) input used to calaculate the output - nessesary for the gradients Returns ------- numpy array(matrix) return the gradient of the input variable with respect to loss (d loss / d input) We need it because it is grar_output for previous layer """ num_units = input.shape[1] d_layer_d_input = np.eye(num_units) return np.dot(grad_output, d_layer_d_input) # chain rule
true
8d7e1c5c08d252287128c418d156848923d5879d
millyhx/module2
/ch05_inheritance_association/ch5_melisa.py
1,781
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 5 10:09:07 2018 @author: milly """ """ A customer of ABC Bank with a checking account. Customers have the following properties: Attributes: name: A string representing the customer's name. balance: A float tracking the current balance of the customer's account. Return a Customer object whose name is *name* and starting balance is *balance*. Return the balance remaining after withdrawing *amount* dollars. Return the balance remaining after depositing *amount* dollars. """ #----------- #TASK 1 #----------- class Customer(object): def __init__(self,name,balance=0.0): self.name = name self.balance = balance def withdraw(self,amount): if amount > self.balance: raise RuntimeError("Amount greater than available balance.") self.balance -= amount return self.balance def deposit(self,amount): self.balance += amount return self.balance jason = Customer("Jason Taylor", 1000.0) #--------------- #TASK 2,3 AND 4 #--------------- class Animal(): def eat(self): print("yum") class Dog(Animal): def bark(self): print("Woof!") class Robot(): def move(self): print("... move move move...") class CleanRobot(Robot): def clean(self): print("I vacuum dust") class SuperRobot(): def __init__(self): self.o1 = Robot() self.o2 = Dog() self.o3 = CleanRobot() def move(self): return self.o1.move() def bark(self): return self.o2.bark() def clean(self): return self.o3.clean() machineDog = SuperRobot() machineDog.move() machineDog.bark() machineDog.clean()
true
f7b0a21f7f64b3136cf54e548b60dd86878ac6b5
Dmkk01/Small-Python-Projects
/RobotWorld/square.py
2,312
4.46875
4
class Square(): """ The class Square represents a single square in a robot world. A square can contain either a wall or a robot or it can be empty. """ def __init__(self, is_wall=False): """ Creates a new square. Initially there is no robot in the square. Parameter is_wall_square is a boolean value stating whether there is a wall in the square or not: boolean """ self.robot = None # most-recent holder (None if no robot in square) self.is_wall = is_wall # flag (one-way currently, since walls can not be removed) def get_robot(self): """ Returns the robot in the square or None if there is no robot in the square: Robot """ return self.robot def is_wall_square(self): """ Returns a boolean value stating whether there is a wall in the square or not: boolean """ return self.is_wall def is_empty(self): """ Returns a boolean value stating whether the square is empty (A square is empty if it does not contain a wall or a robot) or not: boolean """ return not self.is_wall_square() and self.robot is None def set_robot(self, robot): """ Marks the square as containing a robot, if possible. If the square was not empty, the method fails to do anything. Parameter robot is the robot to be placed in this square: Robot Returns a boolean value indicating if the operation succeeded: boolean """ if self.is_empty(): self.robot = robot return True else: return False def remove_robot(self): """ Removes the robot in this square. Returns the robot removed from the square or None, if there was no robot: Robot """ removed_robot = self.get_robot() self.robot = None return removed_robot def set_wall(self): """ Sets a wall in this square, if possible. If the square was not empty, the method fails to do anything. Returns a boolean value indicating if the operation succeeded: boolean """ if self.is_empty(): self.is_wall = True return True else: return False
true
52983be0246df4a486bcc376fa9a483d476c30fa
vrbro/Projects_n_Algos
/Python/Sorting algorithms/merge_sort.py
1,182
4.125
4
''' Merge sort ''' def merge ( lst1 , lst2 ): ''' This function merges 2 lists. :param lst1: :param lst2: :return list 1 merged with list 2: >>> merge ([1, 2, 4, 6] ,[3, 5, 7, 8]) [1, 2, 3, 4, 5, 6, 7, 8] ''' res = [] n1 , n2 = len( lst1 ) , len( lst2 ) i , j = 0 , 0 while i < n1 and j < n2 : if lst1 [ i ] <= lst2 [ j ]: res += [ lst1 [ i ]] i += 1 else : res += [ lst2 [ j ]] j += 1 return res + lst1 [ i :] + lst2 [ j :] def merge_sort ( lst ): ''' :param lst: :return sorted list: Input : list of elements Output : Sorted list of elements >>> merge_sort ([3, 7, 9, 6, 2, 5, 4, 1, 8]) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> merge_sort ([11, 0, 1, 5, 7, 2]) [0, 1, 2, 5, 7, 11] >>> merge_sort ([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ''' k , n = 1 , len ( lst ) while k < n : nxt = [] for a in range (0 , n , 2* k ): b , c = a + k , a + 2* k nxt += merge ( lst [ a : b ] , lst [ b : c ]) lst = nxt k = 2* k return lst
false
9320bd6b718e258a6cd4b50f22d10984dc99ebf3
ClaudioChagas/Introducao-a-Ciencia-da-Computacao-com-Python
/somacomwhile.py
226
4.1875
4
print("Digite um valor a ser somado terminada por 0: ") soma= 0 valor= 1 while valor != 0: valor= int(input("Digite um valor a ser somado: ")) soma= soma + valor print("O soma dos valores digitados é: ", soma)
false
72417040add8ef24aaff2383accfa4e8e6a62927
kazare/mini-projects
/rockpaperscissorsgame.py
2,575
4.34375
4
# User will play rock, paper, scissors with the computer # delcaring variables and importing random library import random rounds = 0 maxRounds = 6 userScore = 0 cpuScore = 0 options = ["rock", "paper", "scissors"] print(''' Welcome to rock, paper, scissors! Let's see who wins after %d rounds ''' % maxRounds) while rounds < maxRounds: cpu = random.choice(options) user = input("Please choose rock, paper, or scissors:") rounds += 1 print("Computer chose: " + cpu) print("You chose: " + user) # if computer chooses rock if cpu == "rock": if user == "paper": print("Congrats! You won!! Paper beats rock!") userScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) if user == "scissors": print("You lost! Rock beats scissors") cpuScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) if user == "rock": print("A tie!") userScore += 1 cpuScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) # if computer chooses paper elif cpu == "paper": if user == "scissors": print("Congrats! You won!! Scissors beats paper!") userScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) if user == "rock": print("You lost! Paper beats rock") cpuScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) if user == "paper": print("A tie!") userScore += 1 cpuScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) # if computer chooses scissors elif cpu == "scissors": if user == "rock": print("Congrats! You won!! Rock beats scissors!") userScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) if user == "paper": print("You lost! Scissors beats paper") cpuScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) if user == "scissors": print("A tie!") userScore += 1 cpuScore += 1 print(""" You're score: {0} Computer's score: {1} """.format(userScore, cpuScore)) if rounds == maxRounds: print(''' Game over! ''') if userScore > cpuScore: print("Congrats you won the game!") elif cpuScore > userScore: print("Sorry, the computer won. Better luck next time.") else: print(" The game ends in a tie! You both won!")
true
141369b0ecb1f591940e847e597f687c7e432c2c
Amal211/DS_level2
/module02_dijkstras_website_example.py
1,582
4.21875
4
# How to implement Dijkstra's algorithm in Python # https://www.educative.io/edpresso/how-to-implement-dijkstras-algorithm-in-python import sys import os os.system("cls") import warnings warnings.filterwarnings('ignore') def to_be_visited(): global visited_and_distance v = -10 for index in range(number_of_vertices): if visited_and_distance[index][0] == 0 and (v < 0 or visited_and_distance[index][1] <= visited_and_distance[v][1]): v = index return v vertices = [[0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]] edges = [[0, 3, 4, 0], [0, 0, 0.5, 0], [0, 0, 0, 1], [0, 0, 0, 0]] number_of_vertices = len(vertices[0]) visited_and_distance = [[0, 0]] for i in range(number_of_vertices - 1): visited_and_distance.append([0, sys.maxsize]) for vertex in range(number_of_vertices): to_visit = to_be_visited() for neighbor_index in range(number_of_vertices): if vertices[to_visit][neighbor_index] == 1 and visited_and_distance[neighbor_index][0] == 0: new_distance = visited_and_distance[to_visit][1] + edges[to_visit][neighbor_index] if visited_and_distance[neighbor_index][1] > new_distance: visited_and_distance[neighbor_index][1] = new_distance visited_and_distance[to_visit][0] = 1 i = 0 for distance in visited_and_distance: print("The shortest distance of ",chr(ord('a') + i), " from the source vertex a is:",distance[1]) i = i + 1
true
01587aa99c95e5d6be4298ec6860132c769df9b6
billbrayandurand/Python
/basics/Untitled.py
2,997
4.21875
4
#!/usr/bin/env python # coding: utf-8 # **Cabecera** # In[9]: # -*- coding: utf-8 -*- # ------------- Cantidad de segundos que has vivido ------------- # Definición de variables anios = 30 dias_por_anio = 365 horas_por_dia = 24 segundos_por_hora = 60 # Operación print (anios * dias_por_anio * horas_por_dia * segundos_por_hora) # **Definición de Variables** # In[ ]: anios = 30 diasPorAnio = 365 horasPorDia = 24 segundosPorHora = 60 # **Operación** # In[10]: print (anios * dias_por_anio * horas_por_dia * segundos_por_hora) # **Cadenas** # In[8]: # -*- coding: utf-8 -*- # --------------- Uso de cadenas --------------- # Cuando se imprime una palabra sin comillas Python # la interpreta como una variable, si ésta no existe # se arroja un error en tiempo de ejecución #print (Hola) # Las cadenas se pueden crear con comillas simples # o con comillas dobles print ('Curso') print (" de Python\n") # --------------- Cadenas y números --------------- nombre = "Marco" print ("Hola " + nombre + "! \n") num_tortugas = 2 # Los números se deben convertir a cadenas o # se arrojará un error #print (nombre + " tiene " + num_tortugas + " tortugas \n") # Los números se convierten a cadena a través # de la función str() print (nombre + " tiene " + str(num_tortugas) + " tortugas \n") # **Subcadenas** # In[15]: # -*- coding: utf-8 -*- # ------------- Cadenas y subcadenas ------------- # Cadena con 22 caracteres cadena = "parangaricutirimicuaro" # In[16]: print (cadena[0]) # Se obtiene el primer carácter print (cadena[21]) # Se obtiene el último carácter # In[17]: # Si se pone un indice negativo, la cuenta # empieza en el �ltimo elemento de la cadena print (cadena[-2]) # último carácter # In[18]: # Si se quiere acceder a un elemento fuera de rango # de la cadena, se obtiene el error # IndexError: string index out of range #print (cadena[22]) # Carácter fuera de rango print (cadena[5:13]) # imprime garicuti # In[19]: print (cadena[5:]) # imprime garicutirimicuaro # In[20]: print (cadena[:5]) # imprime param # In[21]: print (cadena[:]) # imprime la cadena completa # In[22]: # -*- coding: utf-8 -*- # ------------- Búsquedas en cadenas ------------- # Cadena original cadena = "Amor y deseo son dos cosas diferentes; que no todo lo que se ama se desea, ni todo lo que se desea se ama. (Don Quijote)" # Busca la cadena "ama" print (cadena.find("ama")) # In[33]: #Imprimie la subcadena print (cadena[cadena.find("ama"):]) # In[24]: # Busca la siguiente coincidencia de "ama" print (cadena[cadena.find("ama") + 1:].find("ama")) # In[25]: # Imprime la cadena a partir de la segunda coincidencia print (cadena[61 + 1 + 40:]) # In[26]: # Busca "corazon" en la cadena print (cadena.find("corazon")) # In[27]: # Busca a partir de un indice print (cadena.find("todo", 62)) # In[28]: # Imprime a partir de un �ndice y hasta el final print (cadena[78:]) # In[ ]:
false
caa6726af9990fd557ca3e02535d7ffefc874469
AxelDavid45/cli-crud-python
/slices.py
224
4.125
4
myword = 'ferrocarril' # Starts from the beginning to index 3 print(myword[:3]) # starts from the beginning print(myword[::-1]) # Starts from the beginning to the end in 2 steps print(myword[::2]) print(myword[-1::2])
true
f4b54dc1fa4ca5e41990857b45371d2f43d58a48
milena-marcinik/LeetCode
/Easy/1281 subtract the product and sum of digits of an integer.py
767
4.125
4
"""Given an integer number n, return the difference between the product of its digits and the sum of its digits. Example 1: Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 Example 2: Input: n = 4421 Output: 21 Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21 Constraints: 1 <= n <= 10^5 Accepted 107,069 Submissions 125,252 """ class Solution: def subtractProductAndSum(self, n: int) -> int: sum_of_digits = 0 product_of_digits = 1 for digit in list(str(n)): sum_of_digits += int(digit) product_of_digits *= int(digit) return product_of_digits - sum_of_digits
true
c30254fadc12a5cb28c6a558c2fc868f46495aed
owoshch/Cracking_the_coding_interview_5
/chapter_1_arrays_and_strings/rotate_matrix.py
441
4.15625
4
#using python3 import sys def rotate_matrix(matrix): matrix = tuple(zip(*matrix[::-1])) return matrix #reading the number of dimensions n = int(input().strip()) #reading matrix arr = [] for arr_i in range(n): arr_temp = map(int,input().strip().split(' ')) arr.append(arr_temp) #printing result print ('rotated matrix: ') arr = rotate_matrix(arr) for arr_str in arr: for element in arr_str: print(element, end=" ") print ()
true
502c2fb4759f116c70531bd8c39f7b247a67ffdb
AbdallahAhmed1999/WDMM-1402
/chapter3/try_except_arithmetic_errors_calc2.py
405
4.21875
4
# handle arithmetic errors (division by zero) n1 = int(input('enter 1st number: ')) n2 = int(input('enter 2nd number: ')) op = input('enter operator: ') if op == '*': print(n1 * n2) if op == '/': try: print('before') print(n1 / n2) # dangerous line print('after') except: print('division by zero error') print('2nd number can not be zero in division')
false
750d9387e9a967c67910f1e3cccb45d001d9e35b
AbdallahAhmed1999/WDMM-1402
/chapter6/string processsing.py
991
4.40625
4
''' اكتب برنامج لـطباعة التالي من نص - عدد الكلمة I - عدد الكلمات بالاحرف الكبيرة - عدد الكلمات بالاحرف الصغيرة - عدد الاحرف الخاصة special chars ''' text = ''' Hi , my name is Ahmed , and I like banana , Orange , and apple fruits - but I do not like APPLE COMPANY !!! I love Python , and python is cool ! :) I AM A PYTHON PROGRAMMER ! OK please share , comment #python ;) ''' words = text.split() print('word count', len(words)) i_count = 0 upper_count = 0 lower_count = 0 special_count = 0 for word in words: if word is 'I': i_count = i_count + 1 if word.isupper(): upper_count = upper_count + 1 if word.islower(): lower_count = lower_count + 1 if not word.isalnum(): special_count = special_count + 1 print('I count:', i_count) print('lower count', lower_count) print('upper count', upper_count) print('special count', special_count)
false
bd5684369e12fd592e6f63f85c7c2d84c456c634
AbdallahAhmed1999/WDMM-1402
/chapter6/loop_chars.py
389
4.28125
4
# iterate over letters of a string fruit = 'banana' # method 1: using index and for for i in range(len(fruit)): print(i, fruit[i]) print('-----------------------') # method 2: using an iteration variable (letter) for letter in fruit: print(letter) print('-----------------------') # method 3: using index and while i = 0 while i < len(fruit): print(i, fruit[i]) i = i + 1
true
d2a3e34e5fb52dc69dc8dee94c3d073584efcf08
AbdallahAhmed1999/WDMM-1402
/chapter3/try_except_input_errors.py
482
4.21875
4
''' write a program that asks the user to enter two numbers and the operator (*, /), and compute the result according the operator. You have to handle error in user's input ''' try: mark = int(input('enter mark: ')) except: print('error in mark') print('please enter a numeric value') mark = -1 # out of range mark if mark < 0: print('out of range') elif mark < 60: print('fail') elif mark <= 100: print('pass') else: # > 100 print('out of range')
true
abdab70d039066d011dc8c6d450815f68dd6f73e
AbdallahAhmed1999/WDMM-1402
/chapter7/calling_functions_with_return_value.py
381
4.25
4
# define the function def is_vowel(word): vowels = 'aeiouAEIOU' return word[0] in vowels # call a function with return value # method 1: assign to a variable result = is_vowel('apple') # method 2: print print(is_vowel('apple')) print(is_vowel('banana')) # method 3: wrong method is_vowel('apple') # it is like, save the cleaned text text = ' hello ' text = text.strip()
false
755b0d887ec3fb5e11800e8087ee0c8c112fe980
AbdallahAhmed1999/WDMM-1402
/chapter6/char_count.py
700
4.3125
4
''' اكتب برنامج لطباعة - عدد المسافات - عدد الاحرف الكبيرة - عدد الاحرف الصغيرة في نص ''' text = ''' Hi , my name is Ahmed , and I like banana , Orange , and apple fruits - but I do not like APPLE COMPANY !!! I love Python , and python is cool ! :) I AM A PYTHON PROGRAMMER ! OK please share , comment #python ;) ''' space_count = 0 upper_count = 0 lower_count = 0 for char in text: if char.isspace(): space_count += 1 if char.islower(): lower_count += 1 if char.isupper(): upper_count += 1 print('space count', space_count) print('upper count', upper_count) print('lower count', lower_count)
false
e02a3b5345543e351623052881a9cbbfdccecfed
diegoami/datacamp-courses-PY
/pandas_12/pandas12_4.py
469
4.15625
4
# Import pandas import pandas as pd year=\ ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] weather1 = pd.read_csv('../data/monthly_mean_temp.csv',index_col=0) # Reindex weather1 using the list year: weather2 weather2 = weather1.reindex(year) # Print weather2 print(weather2) # Reindex weather1 using the list year with forward-fill: weather3 weather3 = weather1.reindex(year).ffill() # Print weather3 print(weather3)
false
9aa853d1f53062af58c8221ce877476edd17c641
PrashantShivajiBhapkar/PythonPractice
/Tuples.py
2,029
4.3125
4
# Tuples are immutable lists and usually contain heterogenous elements as # opposed to lists which are mutable and generally contain homogenous elements # Currently there are 3 SEQUENCE data types: list, tuple, range t = 12345, 4568 # Tuple packing print(t) t1 = 12, 45, 'Hello!' print(t1) print(t.index(12345)) print(t1.index('Hello!')) t2 = 12, 45, ('nested', 'tuple') # Typles are IMMUTABLE # t[o] = 4568798 #invalid t3 = ([1, 2, 3], [4, 5, 6], [7, 8, 9]) print(t3) print('----') a, b, c = t3 # Tuple unpacking print(a, b, c) # Interesting cases of defining a tupple with 0 and 1 elements tEmpty = () print(tEmpty) tSingleton = 45 print(tSingleton) print(type(tSingleton)) tSingleton = (45) print(tSingleton) print(type(tSingleton)) # tSingleton = tuple(45) #throws error # CORRECT WAY for defining a tuple with one element tSingleton = 45, print(tSingleton) print(str(type(tSingleton)) + ' Now we got it!!') # + for string tSingleton = (45,) print(tSingleton) print(str(type(tSingleton)) + ' Now we got it!!') # + for string print(type(tSingleton), 'Now we got it!!') t = tuple([1, 2, 30]) # parametered a list print(t) print(type(t)) t = tuple((1, 2, 30)) # parametered a tuple print(t) print(type(t)) l = list([1, 2, 3]) # parametered a list print(l) print(l[0]) l = list((1, 2, 3)) # parametered a tuple print(l) l1 = list([[1, 2, 3]]) print(l1) # Tuple of list is MUTABLE as list is mutable. Here we have one list in the # tuple. And that list is mutable t = ([[1, 2, 3]],) print(t) print(type(t)) t[0].append('asd') print(t) t = ([1, 2, 3, 4],) print(t) print(type(t)) t[0][1] = 999 print(t) import numpy as np a = np.array([[0], [1], [2]]) print(a) print(a.shape) import numpy as np A = np.random.randn(4, 3) B = np.sum(A, axis=0, keepdims=True) print(B) print(B.shape) print(type(B)) C = np.sum(A, axis=0, keepdims=0) print(C) print(C.shape) print(type(C)) B = np.sum(A, axis=1, keepdims=0) print(B) print(B.shape) print(type(B)) B = np.sum(A, axis=1, keepdims=1) print(B) print(B.shape) print(type(B))
true
0b5298a314e8566240a0f4b2e8df7ab3cd8c9923
CodeSofty/SimpleQuestionGame
/SimpleQuestionGame.py
2,507
4.4375
4
# This program is a simply question game that prompts the user to start playing # by typing "roll" and then printing a question that corresponds to the number generated # The answer is compared to the answer and the result will either announce a win or loss and # then the program will restart #What I learned: # - How to print to the screen # - Boolean operator (and, or, not) # - Comparing two values with comparison operators # - While loops # - For loops # - The use of If, elif, and else statements # - Break and Continue # - Range in a for loop # - Import keyword import random # Creates an infinite loop to restart the game when the player wins while True: # Sets roll as empty string roll = '' # Creates an infinite loop to ask player to type roll while True: print('~~~~~PLEASE TYPE "roll" TO START~~~~~~~~') roll = input() if roll != 'roll': continue if roll == 'roll': break # When player starts the game, a random number is generated and printed out num = random.randint(1,6) print('You rolled a ' + str(num)) # A question is chosen based on the number, using some comparison operators and boolean operators # Question 1 if num >= 1 and num <= 3: print('What color is the sky? (tip: use lowercase)') answer = input() realAnswer = 'blue' if answer == realAnswer: for i in range (3): print('You guessed correct! You won!!!') else: print('Incorrect, restarting program') # Question 2 elif num == 4 or num == 5: print('Is Python a programming language or a snake? (tip: use lowercase)') answer = input() realAnswer = 'both' if answer == realAnswer: for i in range (3): print('You guessed correct! You won!!!') else: print('Incorrect, restarting program') # Question 3 elif num == 6: print('Just type "i win" (tip: use lowercase)') answer = input() realAnswer = 'i win' if answer == realAnswer: for i in range (3): print('You guessed correct! You won!!!') else: print('Incorrect, restarting program') # The roll can only be between 1-6, so this will never be chosen else: print('you won because you rolled an impossible number!') print('#############THE PROGRAM WILL NOW RESTART###############')
true
05969904bd3d494aeed2f585c6e70b2260fb87cd
BanisharifM/Training
/Python/W3school/Python Variables.py
890
4.34375
4
x = 5 y = "John" print(x,type(x)) print(y,type(y)) # is the same as x = "John" x = 'John' #Legal variable names: myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" #Illegal variable names: """ 2myvar = "John" my-var = "John" my var = "John" """ #Assign Value to Multiple Variables x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) x = y = z = "Orange" print(x) print(y) print(z) x = "Python is " y = "awesome" z = x + y print(z) x = 5 y = 10 print(x + y) #error: """ x = 5 y = "John" print(x + y) """ #Global Variables x = "awesome" def myfunc(): x = "fantastic" print("Python is " + x) myfunc() print("Python is " + x) #The global Keyword def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) x = "awesome" def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x)
false
0795e07d928d90e187726fb61510f724d915117b
vtemian/interviews-prep
/leetcode/easy/n-ary-tree-postorder-traversal.py
734
4.1875
4
""" Given an n-ary tree, return the postorder traversal of its nodes' values. For example, given a 3-ary tree: Return its postorder traversal as: [5,6,3,2,4,1]. Note: Recursive solution is trivial, could you do it iteratively? """ """ # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children """ class Solution: def postorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return [] if not root.children: return [root.val] kids = [] for kid in root.children: kids += self.postorder(kid) return kids + [root.val]
true
cf6ea186bae2e12c7a9edc5ec865cc6413a9389b
vtemian/interviews-prep
/leetcode/easy/self-dividing-numbers.py
1,189
4.1875
4
""" A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Also, a self-dividing number is not allowed to contain the digit zero. Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. Example 1: Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] Note: The boundaries of each input argument are 1 <= left <= right <= 10000. """ class Solution: def is_self_dividing(self, number): aux = map(int, str(number)) for digit in aux: if not digit or number % digit != 0: return False return True def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ result = [] self.cache = {} while left <= right: if self.is_self_dividing(left): result.append(left) left += 1 return result result = Solution().selfDividingNumbers(1, 22) print(result)
true
ca8f2330b7257c571547fa514a52cf7ad41ea27e
fwchj/cursoJavaAbm2018S2
/ejemplosClase/python/EjemploArray.py
847
4.125
4
## Equivalente en Python del EjemploArray.java ## Python es mas facil para arreglos, ya que la construccion se hace de forma mas sencilla # Definir 'grades' directamente. Python detecta el tipo automáticamente # Arrays se llaman 'lists' en python grades =[6.8,8.9,10.1] print(grades) # Array de integers edad =[0]*3 # Si queremos hacer el arrgelo vacio (=0.0), es la forma de hacerlo print(edad) edad[0] = 65 edad[1] = 38 edad[2] = 99 # Array de strings letras = [""]*4 print(letras) letras[0] = "a" letras[1] = "b" letras[2] = "c" letras[3] = "d" print(letras) ## Comportamiento al copiar arrays/listas import copy x = [1,2,3,4] y = x z = copy.deepcopy(x) # this is equivalent to .clone() in Java print(x,y,z) x[3]=55 print(x,y,z) ## Looping through arrays for i in edad: print(i) print("The average is",sum(edad)/len(edad))
false
8653f0dd1884337d61bf6f9c9c75b31339fe78b5
Loganhampton/Logan
/game.py
409
4.15625
4
ans = raw_input("Would you like to know your fortune? Y or No") ans1 = "A giant dragon will become your friend" ans2 = "Shrimp" ans3 = "You become a famous soccer player" if ans == "Y": choice = raw_input("Pick a number from 1-3") if choice == 1: print(ans1) elif choice == 2: print(ans2) elif choice == 3: print(ans3) else: print("Nothing happens")
false
b4057cc49f57961d64aa94870ac2c70bd1480d60
sandeepshiven/python-practice
/object oriented programming/methods.py
1,003
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 9 18:15:49 2019 @author: sandeep """ class Circle(): pi = 3.14 # circle gets initiated with radius one def __init__(self,radius = 1): self.radius = radius self.area = self.radius * self.radius * Circle.pi # we can use self.circle but convention is class_name.(class object attribute) # method for resetting radius def set_radius(self,new_radius): self.radius = new_radius self.area = self.radius * self.radius * Circle.pi # method for getting circumference def get_circumference(self): return 2 * Circle.pi * self.radius c = Circle() print(f"Radius is {c.radius}") print(f"Circumference is {c.get_circumference()}") print(f"Area is {c.area}") c2 = Circle() c2.set_radius(2) print(f"Radius is {c2.radius}") print(f"Circumference is {c2.get_circumference()}") print(f"Area is {c2.area}")
true
a7c7e6d8f1e3af6b952ec1ef6efa0659a2b5c8fb
sandeepshiven/python-practice
/simple questions on loops and list comprehensions/Use for, .split(), and if to create a Statement that will print out words that start with 's'.py
255
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 18 17:02:25 2019 @author: sandeep """ st = 'Print only the words that start with s in this sentence' for word in st.split(): if word[0] == 's': print(f"{word} ")
true
ef3bc875c4ec5dcd6397e60d3918abcaa9c78d7f
sandeepshiven/python-practice
/basic data types/dictionaries.py
962
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 10 00:13:26 2019 @author: sandeep """ my_dict = {"key1":1234,'key2':3.43,'key3':'sandeep','key4':[1,3.4,'Ikshit'],'key5':{'key6':'anything'}} print(f"{my_dict}") print(f"Grabbing a dictonary element by a key:\n{my_dict['key2']}") print(f"Printing a specific element from the list inside the dictionary:\n{my_dict['key4'][2]}") # can do same for dictionaries inside a dictionary e.g. my_dict['key5']['key6'] print(f"Now grabbing a single element and convertiing it into uppercase:\n{my_dict['key4'][2].upper()}") #this change is not permanent # Now playing with values of key my_dict['key1'] -= 1000 my_dict['key3'] = 'shiven' # finally adding a new key my_dict['key7']='new' print(f"{my_dict}") print(f'{my_dict.keys()}' ) # shows keys in a dictionary print(f'{my_dict.values()}') # shows values inside the dictionary print(f'{my_dict.items()}') # shows keys and values in pair
true
c34ba6eaaa29c491163df4065a13cbcfa0ba7fb4
sandeepshiven/python-practice
/object oriented programming/cylinder.py
640
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 10 15:08:03 2019 @author: sandeep """ class Cylinder: pi = 3.14 def __init__(self,height=1,radius=1): self.height = height self.radius = radius def volume(self): return (Cylinder.pi * ((self.radius )**2) * self.height) def surface_area(self): return ((2* Cylinder.pi *( self.radius **2)) +(2 * Cylinder.pi * self.radius * self.height) ) # EXAMPLE OUTPUT c = Cylinder(2,3) print("The volume of the cylinder is ",c.volume()) print("The total surface area of the cylinder is ",c.surface_area())
true
bae4ee6bb0484e1126b140b8c4dce3b2cbda82d4
sandeepshiven/python-practice
/guessing game/guessing_game.py
1,923
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 20 18:38:02 2019 @author: sandeep """ from random import randint random = randint(1,100) # assings a random integer to the random variable # below are the rules print("Welcome to Guessing game!!!!!") print("Rules for playing the game are following:") print("1. Guess a number between 1 and 100") print("2. If your guessed number is 10 numbers far from my number then I will tell you're 'COLD!'") print("3. If your guessed number is within 10 number of my number I'll tell you're 'WARM!'" ) print("4. If your guess is farther from your previous guess then I will tell you're getting 'COLDER!' ") print("5. If your guess is closer to your previous guess then I'll tell you're getting 'WARMER!'") print("Now let's start the game") # creating a list to store the guesses giben by the user guesses = [0] # this loop gets the input and evaluates while True: guess = int(input("Guess a number between 1 and 100\n")) # input guess if guess < 1 or guess >100: # range print("OUT OF BOUNDS!") continue if guess == random: print(f"You have guessed correctly and took {len(guesses)} guesses") break guesses.append(guess) # appending current guess to list of guesses if guesses[-2]: # guesses[-2] is the previous guess if abs(guess - random)< abs(random - guesses[-2]): # abs gives the absolute difference between two integers # if current guess is less than previous guess i.e. guess is closer print("WARMER!") else: print("COLDER!") else: if abs(guess - random) <= 10: # if the guess is closer within 10 numbers print("WARM!") else: print("COLD!")
true
04617f62a89a44ed04cbf668475ffc1c6d85e091
sandeepshiven/python-practice
/simple questions on loops and list comprehensions/even!
269
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 18 17:45:14 2019 @author: sandeep """ st = 'Print every word in this sentence that has an even number of letters' for x in st.split(): if len(x)%2 == 0: print(f"Even! -- {x}")
true
da621513c719cb57df753aaf2c86c1d2d5f0701c
sandeepshiven/python-practice
/object oriented programming/oops2/addding_instance_methods.py
1,148
4.1875
4
class User: def __init__(self,first,last,age): # this init method is always called first on self.first = first # instantiating a class self.last = last # self is used to create a seperate variable self.age = age #or method for each instance def full_name(self): return f"My name is {self.first} {self.last}" def initials(self): return f"Initials : {self.first[0].upper()}.{self.last[0].upper()}." def likes(self,thing): return f"{self.first} likes {thing}" def is_senior(self): return self.age>=65 def birthday(self): self.age += 1 return f"Happy {self.age}th birthday {self.first}" user1 = User('Sandeep','Shiven',20) user2 = User('Ansh','Shrivastava',68) print(user1.full_name()) print(user2.full_name()) print(user1.initials()) print(user2.initials()) print(user1.likes('coding')) print(user2.likes('chatting')) print(user1.is_senior()) print(user2.is_senior()) print(user1.age) print(user1.birthday()) print(user1.age) print(user2.age) print(user2.birthday()) print(user2.age)
false
03c0818891bd7d0d97a383dd0a024f0d8fa93b47
sandeepshiven/python-practice
/basic data types/lists.py
1,494
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 8 22:38:35 2019 @author: sandeep """ my_list=[1,'one',2,'two',3,'three',4,'four',5,'five'] print(f"The list :{my_list}") print(f"Length of the list: {len(my_list)}") print(f"Now element at index 5:{my_list[5]}") print(f"Now some slicing examples:- \n{my_list[2::2]}\n{my_list[:4]}\n{my_list[2:4]}") print(f"Now a example of concatenation:\n{my_list+['sandeep']}") # this does not changes the original list print(f"{my_list}") my_list = my_list + ['sandeep'] print(f"Now some reassingment:\n{my_list}") print(f"Making the list double:\n{my_list*2}") # This does not change the actual list print(f"Now some list methods:") my_list.append('shiven') #appends the argument given in .append() to the last of the list print(f"The appending:\n{my_list}") my_list.pop(5) # pops out or delete the item at given index the default index is -1 # now this poped out value can be assined to the variable like this: var=list.pop()// print(f"The poping:\n{my_list}") my_list.reverse() print (f'Revesing the list:\n{my_list}') new_list = [1,3,5,2,4,52,567,546,325,6747,3] print(f"Sorting of list:\n{new_list}") new_list.sort() print(f'{new_list}') mult_D = [[3,324,.23,235.32],['sandeep','shiven','unni'],['sandeep',23.324,'shiven',34,'unni',432]] print(f'The multidimensional array:\n{mult_D}') print(f"Grabbing a single list:\n{mult_D[1]}") print(f"Now grabbing a single element:\n{mult_D[2][3]}")
true
2d4634241c72b47b68292f63a36e8a493f7226d3
SACHSTech/ics2o1-livehack---2-FloorCheese
/problem1.py
543
4.15625
4
antennas_input = int(input("Enter amount of antenna: ")) eyes_input = int(input("Enter amount of eyes: ")) if antennas_input >= 3 and eyes_input <= 4: print ("Life form detected: AudreyMartian") if antennas_input <= 6 and eyes_input >= 2: print ("Life form detected: MaxMartian") elif antennas_input <= 2 and eyes_input >= 3: print ("Life form detected: BrooklynMartian") elif antennas_input == 0 and eyes_input == 2: print ("Life form detected: MattDamonMartian") else: print ("No life form detected")
true
a51def05247b0ed5401c273ac9c937907c2ed8e4
HappyRocky/pythonAI
/LeetCode/59_Spiral Matrix_II.py
1,528
4.28125
4
# -*- coding: utf-8 -*- ''' Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. 给定一个正整数 n,生成一个方阵,里面的元素为1到n^2按照螺旋顺序排列。 Example: Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] ''' def generateMatrix(n): """ :type n: int :rtype: List[List[int]] 分治法。 按照定义,从左上角开始,依次按照顺序生成1到n^2的数。 每次生成最外圈,然后递归生成剩余元素。 """ board = [[0 for i in range(n)] for i in range(n)] def generate(k, nextvalue): ''' 生成第k个外圈以及内部所有元素。 ''' nonlocal board # 计算最外圈的两行两列位置 minr = k-1 # 上行、左列 maxr = n-k # 下行、右列 # 递归结束条件 if minr > maxr: return if minr == maxr: board[minr][minr] = nextvalue return # 开始生成最外圈 for i in range(4): # 逆时针旋转4次 # 最上面一行赋值 board[minr][minr:maxr] = list(range(nextvalue, nextvalue + maxr - minr)) nextvalue = board[minr][maxr-1] + 1 board = [list(x) for x in zip(*board)][::-1] # 逆时针旋转 # 递归生成里面的圈 generate(k+1, nextvalue) generate(1, 1) return board if '__main__' == __name__: n = 3 print(generateMatrix(n))
false
1a257164476f59fd1cb8806391a52c2c775c0e88
HappyRocky/pythonAI
/LeetCode/130_Surrounded_Regions.py
2,700
4.1875
4
# -*- coding: utf-8 -*- """ Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. 给定一个二维面板,包含'X'和'O',寻找所有被'X'包围的区域,将里面的'O'变为'X'。 备注: 1、这种区域不能包含斌姐,即边界上的任何'O'不会被转为'X'。 2、任何不在边界且不和边界上的'O'相连接的'O',都应该被转为'X'。 3、两个单元相连接,指的是他们在水平或竖直方向上相邻。 Example: X X X X X O O X X X O X X O X X After running your function, the board should be: X X X X X X X X X X X X X O X X Explanation: Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically. """ def solve(board: list) -> None: """ 寻找所有能够与边界相连接的'O'并标记。 然后除了这些'0'之外的所有'O'都转为'X' """ if not board or len(board) <= 2 or len(board[0]) <= 2: return m, n = len(board), len(board[0]) # 寻找与边界连通的'O' border_set = set() # 存放与边界连通的'O'的坐标 stack = list() # 存放'O'的候选者 # 初始化stack,将四个边界的'O'放进去 for i in range(n): if board[0][i] == 'O': stack.append((0, i)) if board[m-1][i] == 'O': stack.append((m - 1, i)) for i in range(1, m-1): if board[i][0] == 'O': stack.append((i, 0)) if board[i][-1] == 'O': stack.append((i, n - 1)) # 开始扫描stack while(stack): i, j = stack.pop() if 0 <= i < m and 0 <= j < n and board[i][j] == 'O' and (i, j) not in border_set: border_set.add((i, j)) # 将相邻的'0'压入栈 stack.append((i + 1, j)) stack.append((i - 1, j)) stack.append((i, j + 1)) stack.append((i, j - 1)) # 扫描面板,转换'O' for i in range(1, m - 1): for j in range(1, n - 1): if board[i][j] == 'O' and (i, j) not in border_set: board[i][j] = 'X' if '__main__' == __name__: board = [["O","X","O","O","X","X"], ["O","X","X","X","O","X"], ["X","O","O","X","O","O"], ["X","O","X","X","X","X"], ["O","O","X","O","X","X"], ["X","X","O","O","O","O"]] solve(board) print(board)
false
13e212cec75a2a94a0f73a28ffb6e12ec3953e44
HappyRocky/pythonAI
/LeetCode/121_Best_Time_to_Buy_and_Sell_Stock.py
1,804
4.125
4
# -*- coding: utf-8 -*- """ 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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. 给定一个序列,第i个元素是第i天的股票价格。 你只允许最多交易一次(即,完成一次买股票和卖股票),设计一个算法,来找到最大利润。 在卖股票前必须要买股票。 Example 1: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price. Example 2: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. """ def maxProfit(prices: list) -> int: """ 动态规划。 前i天的最大利润,有两种可能,一种是在前i-1天就完成了买和卖,一种是在前i-1天买,在第i天卖。取这两种方法的较大利润。 维护一维向量dp,dp[i] 表示前i天的最大利润,则: dp[i] = max(dp[i-1], 第i天价格 - 前i-1天最低价格) """ # 无法买卖 m = len(prices) if m <= 1: return 0 # 初始化 dp = [0] * m # dp[i]为前i天的最大利润,i从0开始 min_list = [0] * m # min_list[i]为前i天的最低价格 min_list[0] = prices[0] # 第0天,只有最低价格,没有利润 for i in range(1, m): dp[i] = max(dp[i-1], prices[i] - min_list[i-1]) min_list[i] = min(prices[i], min_list[i-1]) return dp[m-1] if '__main__' == __name__: prices = [7,6,4,3,1] print(maxProfit(prices))
false
f0f8fe79faf7d30d275b69b6ef0b05e617ae2956
HappyRocky/pythonAI
/LeetCode/152_Maximum_Product_Subarray.py
861
4.40625
4
# -*- coding: utf-8 -*- """ Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. 给定一个整数数组,找到连续子数组(至少包含一个数字)的最大乘积。 Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. """ def maxProduct(nums: list) -> int: """ 线性规划 """ imax = imin = nums[0] result = nums[0] for num in nums[1:]: if num < 0: imax, imin = imin, imax imax = max(imax*num, num) imin = min(imin*num, num) result = max(result, imax) return result if '__main__' == __name__: nums = [2,3,-2,4] print(maxProduct(nums))
true
f4f95526bc4e55cca8f4fd7e6fa9317edc1ca3e4
HappyRocky/pythonAI
/LeetCode/112_Path _Sum.py
1,507
4.15625
4
# -*- coding: utf-8 -*- """ Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node with no children. 给定一个二叉树和一个值 sum,判断这个树是否有一个从根到叶节点的路径,这个路径上所有节点值之和等于给定的值 sum。 备注:一个叶节点指的是没有子节点的节点。 Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. """ class TreeNode: def __init__(self, x): if isinstance(x, dict): self.val = x['v'] self.left = TreeNode(x['l']) if 'l' in x else None self.right = TreeNode(x['r']) if 'r' in x else None else: self.val = x self.left = None self.right = None def hasPathSum(root: TreeNode, sum: int) -> bool: """ 递归,存在这种路径 <=> 存在左/右子树的一条路径上节点之和 + 根节点值 = sum """ # 递归结束条件 if not root: return False if not root.left and not root.right: return root.val == sum return hasPathSum(root.left, sum - root.val) or hasPathSum(root.right, sum - root.val) if '__main__' == __name__: r = TreeNode({'v':1,'l':{'v':2,'l':4,'r':5},'r':3}) print(hasPathSum(r, 7))
false
d5376acf4655471d8e9b47309f985195ec6d6615
NaraVictor/python-fun-projects
/mean_n_standard_deviation.py
892
4.21875
4
# assignment 4: a programe that prompts user for ten numbers then # displays the mean n standard deviation of those numbers from math import sqrt def calculate_mean(list_of_nums): sum = 0 for i in list_of_nums: sum += i return round(sum/len(list_of_nums),2) def standard_deviation(numbers): mean = calculate_mean(numbers) new_list = [] for i in numbers: new_num = (i - mean) new_list.append(new_num * new_num) new_mean = calculate_mean(new_list) return round(sqrt(new_mean), 5) if __name__ == '__main__': print('Enter ten numbers') ten_nums = [] count = 1 while len(ten_nums) < 10: num = int(input(f'{count} - input number: ')) ten_nums.append(num) count += 1 print(f'\nThe mean is: {calculate_mean(ten_nums)}') print(f'The standard deviation is: {standard_deviation(ten_nums)}')
true
1632268aadf17f3a9c9cb4ab0eb6a8f47d2447fe
TobiahRex/pythonLibrary
/pyScripts/cciScript.py
493
4.25
4
def match(expression): # "def" is required when defining a function ### This is called a 'docstring'. It uses 3 pound signs on the outside. You can think of it like JS's /**/ comment syntax. ### stack = [] dict = {'(':')', '[':']', '{':'}'} for x in expression: if dict.get(x): stack.append(dict[x]) else: if len(stack) == 0 or x != stack[len(stack)-1]: return False stack.pop() return len(stack) == 0
true
96a83c42164367811c806b5579d3fa7ee806edd4
utshav2008/python_training
/random/strings.py
1,073
4.28125
4
# Strings are immutable and can not be changed a = "Hello, World!" # String literals in python are surrounded by either single quotation marks, or double quotation marks. print(a) # Print the string print(a[1]) # Print character at position 1 print(a[2:5]) # Does the slicing and prints the characters from position 2 to 4 print(len(a)) # Get the length of String print(a.strip()) # Removes any whitespaces from the beginning or the end print(a.lower()) # Convert all characters to lower print(a.upper()) # Converts all characters to upper print(a.replace('H','J')) # It creates a new string as the string are immutable print(a) # This proves that the original string was not changed print(a.split(',')) # This is used to split the strings with a given separator #============== x = input("Enter your name:") # Take input from the user print("Hello, ", x) # one way of printing print("Hello, {}".format(x)) # Other way pf printing and this should be preferred
true
f31ebe6e91c6b8f4df5f663c0dec6223272daefb
aaroncymor/codefights
/solved/add_digits.py
1,046
4.34375
4
""" Given positive integer numbers a, b and n return the maximum number that can be obtained by lengthening number a repeatedly no more than n times. Lengthening number a means appending exactly one digit (in the decimal notation) to the right hand side of a such that the resulting number is divisible by number b. If it is impossible to obtain a number that is divisible by b, then the lengthening operation cannot be performed. Example For a = 12, b = 11 and n = 2, the output should be addDigits(a, b, n) = "1210". Lengthening operations can be 12->121->1210. """ def addDigits(a, b, n): ans = a end = False for i in range(n): a = (a * 10) + 9 for j in range(10): #print(a) if a % b == 0: ans = a #print("ans",ans) break a = a - 1 #print("j",j) if j == 9: end = True if end == True: break return ans print(addDigits(12,11,2)) print(addDigits(4,13,10)) print(addDigits(4,3,9)) print(addDigits(412,11,4))
true
ffb008592f51d13606164abfcd14e7e32b98b316
aaroncymor/codefights
/solved/triangle_coordinates.py
601
4.40625
4
def TriangleCoordinates(n): """ You are given 3 points on the Cartesian plane that form a triangle. Find the area of this triangle. Example TriangleCoordinates([[2, 7], [12, 7], [6, 17]]) = 50 TriangleCoordinates([[-182, -152], [-192, -141], [-164, -138]]) = 169 TriangleCoordinates([[0, 0], [3, 0], [2, 8]]) = 12 area = |Ax(By-Cy)+Bx(Cy-Ay)+Cx(Ay-By)/2| """ return abs((n[0][0]*(n[1][1]-n[2][1]) + n[1][0]*(n[2][1]-n[0][1]) + n[2][0]*(n[0][1]-n[1][1]))/2) print TriangleCoordinates([[2,7],[12,7],[6,17]]) print TriangleCoordinates([[-182,-152],[-192,-141],[-164,-138]])
false