blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
fcc5b1cf3dc24a7f146f66147223bc577a753eef
vkagwiria/thecodevillage
/Python Week 5/Day 2/Day 3/Object Oriented Programming/classes.py
810
4.1875
4
# attributes (variables within a class) # class Car(): # capacity = 2000 # colour = 'white' # mazda = Car() # print(mazda.capacity,mazda.colour) # # methods (functions within a class) # class Dog(): # def bark(): # return bark # german_shepherd = Dog() # # access methods # german_shepherd.bark() # using init method class Car(): # initialization function or constructor method # self keyword refers to the current instance of the class def __init__(self,color,capacity): self.color = color self.capacity = capacity # create an instance - an instance of a class is an object toyota = Car("red",2000) toyota1 = Car("white",1500) mazda = Car("grey",1800) print(toyota.color) print(toyota1.capacity) print(mazda.color)
true
5ddd60d5209a8d63bb1517ca403b4bfe4ad0d9f6
vkagwiria/thecodevillage
/Python week 1/Python Day 1/if_statements.py
924
4.5
4
if statements give us the ability to have our programs decide what lines of code to run, depending on the user inputs, calculations, etc Checks to see if a given condition is True or False if statements will execute only if the condition is True # syntax: if some condition: do something """ number1 = 5 number2 = 7 # Equality == if number2 == number1: print("Equal") # Inequality != if number2 != number1: print("Not equal") # Greater than > if number2 > number1: print("Number is greater") # Less than < if number2 < number1: print("Number is less") # Greater than or equal >= if number2 >= number1: print("Number is greater than or equal to") # Less or equal <= if number1 <= number2: print("Number is less than or equal to") # test for even numbers # user inputs a number # check whether the number is even # output to the user "Number is even"
true
438acb1aa54264e70c4444ff16c751b527e5df75
pratyusa98/Compitative_Programme
/Array/Wave Array.py
303
4.15625
4
def sortInWave(arr,x): # sort the array Step 1 arr.sort() # Swap adjacent elements Step 2 for i in range(0, x - 1, 2): arr[i], arr[i + 1] = arr[i + 1], arr[i] arr = [2,4,7,8,9,10] sortInWave(arr, len(arr)) for i in range(0,len(arr)): print (arr[i],end=" ")
false
28d1ddc682cd7054814d9598f7a7f938140cf5e5
samdarshihawk/python_code
/sum_array.py
1,169
4.5
4
''' Given a 2D Array We define an hourglass in to be a subset of values with indices falling. There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in, then print the maximum hourglass sum. Function Description Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array. hourglassSum has the following parameter(s): arr: an array of integers Output Format Print the largest (maximum) hourglass sum found in arr. ''' import numpy as np # this function only work on 6X6 2d array def sum_2darray(arr): if(type(arr)!='numpy.ndarray'): a=np.asarray(arr) else: a=arr end_row = 3 l = [] for i in range(6): end_column = 3 for j in range(6): # the nested for loop creates only 3X3 2D array d=np.array(a[i:end_row,j:end_column]) end_column += 1 if(d.shape == (3L,3L)): d[1,0] = 0 d[1,2] = 0 l.append(np.sum(d)) else: continue end_row += 1 return(max(l))
true
0a4aa3128121334cb84eb728b4316dde61f2f6a1
zuoshifan/sdmapper
/sdmapper/cg.py
2,471
4.15625
4
""" Implementation of the Conjugate Gradients algorithm. Solve x for a linear equation Ax = b. Inputs: A function which describes Ax <-- Modify this vector -in place-. An array which describes b <-- Returns a column vector. An initial guess for x. """ import numpy as np import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt def cg_solver(x0, Ax_func, b_func, args=(), max_iter=200, tol=1.0e-6, verbose=False): """ Returns x for a linear system Ax = b where A is a symmetric, positive-definite matrix. Parameters ---------- x0 : np.ndarray Initial guess of the solution `x`. Ax_func : function Function returns the product of `A` and `x`, has form Ax_func(x, Ax, *args), the result is returned via the inplace modification of `Ax`. b_func : function Function returns the right hand side vector `b`, has form b_func(x, *args), args : tuple, optional Arguments that will be pass to `Ax_func` and `b_func`. max_iter : interger, optional Maximum number of iteration. tol : float, optional Tolerance of the solution error. verbose : boolean, optional Output verbose information. Returns ------- x : np.ndarray The solution `x`. """ # get value of b b = b_func(x0, *args) # initial guess of Ax Ax = np.zeros_like(b) # Ad = np.zeros_like(b) Ax_func(x0, Ax, *args) x = x0 # re-use x0 r = b - Ax d = r.copy() delta_new = np.dot(r, r) delta0 = delta_new it = 0 while it < max_iter and delta_new > tol**2 * delta0: Ax_func(d, Ax, *args) # re-use Ax for Ad alpha = delta_new / np.dot(d, Ax) # re-use Ax for Ad x += alpha * d if (it + 1) % max(50, np.int(it**0.5)) == 0: Ax_func(x, Ax, *args) r[:] = b - Ax # re-use the existing r else: r -= alpha * Ax # re-use Ax for Ad delta_old = delta_new delta_new = np.dot(r, r) beta = delta_new / delta_old # d[:] = r + beta * d d *= beta d += r it += 1 if verbose: sgn = '>' if delta_new > tol**2 * delta0 else '<' print 'Iteration %d of %d, %g %s %g...' % (it, max_iter, (delta_new/delta0)**0.5, sgn, tol) if delta_new > tol**2 * delta0: print 'Iteration %d of %d, %g > %g...' % (it, max_iter, (delta_new/delta0)**0.5, tol) return x
true
98d1f01500ee4038a2acba3d39b3e820b0af7f21
bjday655/CS110H
/901815697-Q1.py
1,651
4.5
4
''' Benjamin Day 9/18/2017 Quiz 1 ''' ''' Q1 ''' #input 3 values and assign them to 'A','B', and 'C' A=float(input('First Number: ')) B=float(input('Second Number: ')) C=float(input('Third Number: ')) #check if the numbers are in increasing order and if so print 'the numbers are in increasing order' if A<B<C: print('the numbers are in increasing order') #check if the numbers are in decreasing order and if so print 'the numbers are in decreasing order' elif A>B>C: print('the numbers are in decreasing order') #otherwise print that the numbers are random else: print('the numbers are in a random order') ''' Q2 ''' #assign a desired value to 'A' A=int(input('Give me a number between 1 and 12: ')) if A>=1 and A<=12: #check to see if the input value is between 1 and 12 if A==1: print('That is January') elif A==2: print('That is February') elif A==3: print('That is March') elif A==4: print('That is April') elif A==5: print('That is May') elif A==6: #checks the value of 'A' and prints corresponding month print('That is June') elif A==7: print('That is July') elif A==8: print('That is August') elif A==9: print('That is September') elif A==10: print('That is October') elif A==11: print('That is November') elif A==12: print('That is December') else: #if the number is outtside the range between 1 nad 12 then prints a response to the user print('I said BETWEEN 1 and 12!')
true
02a0f0066228cbc46e77a0a066b203617f4eb451
RandomTurtles/turtle_cats
/turtle_cats.py
1,603
4.25
4
import turtle import random def circle(turtle): for i in range(30): turtle.forward(10) turtle.left(25) def spiral(turtle): # small loop for i in range(100): turtle.forward(10) turtle.left(i) def random_color(my_turtle): r = random.random() g = random.random() b = random.random() my_turtle.color(r, g, b) def random_spirals(turtle): r = random.random() if r < 0.5: # small loop for i in range(100): turtle.forward(10) turtle.left(i) else: # big loop for i in range(50): turtle.forward(i) turtle.left(15) def make_spirals(my_turtle): odie.forward(10) for i in range(13): size = random.randint(1, 10) random_color(my_turtle) my_turtle.pensize(size) random_spirals(odie) def make_flower(t, func): # Makes a flower by drawing circles petals = 7 for i in range(petals): random_color(t) t.home() t.left(360/petals * i) t.forward(15) #circle(t) func(t) if __name__ == '__main__': ## Set up our turtle odie = turtle.Turtle() odie.shape('turtle') odie.speed(0) odie.hideturtle() ## Make a starter circle # circle(odie) # odie.forward(10) ## Make some random spirals # make_spirals(odie) ## Make 1 spiral #spiral(odie) ## Make a flower make_flower(odie, spiral) make_flower(odie, circle) odie.showturtle() odie.home() print 'Thanks for watching!' turtle.exitonclick()
false
83e91333dcc783026f7383020e919ff7cb29432b
gracewanggw/PrimeFactorization
/primefactors.py
972
4.28125
4
# -*- coding: utf-8 -*- """ PrimeFactors @Grace Wang """ def prime_factorization(num): ## Finding all factors of the given number factors_list = [] factor = 2 while(factor <= num): if(num % factor == 0): factors_list.append(factor) factor = factor + 1 print(factors_list) ## Finding which of the factors are prime prime_factors = [] for i in factors_list: for j in range(2,i): if(i % j == 0): break else: prime_factors.append(i) ## Prints results num = str(num) prime_factors = str(prime_factors) print("The prime factors of " + num + " are " + prime_factors) ## Takes user input and calls on the prime factorization function while True: a = int(input('give me a number greater than 1 or enter 0 to quit: ')) if (a == 0): break prime_factorization(a)
true
28a302e680fecebd3acfc1f4f8c0aa183b5efa0b
dstrube1/playground_python
/codeChallenges/challenge9.py
1,375
4.125
4
#challenge9 #https://www.linkedin.com/learning/python-code-challenges/simulate-dice?u=2163426 #Simulate dice #function to determine the probability of certain outcomes when rolling dice #assume d6 #Using Monte Carlo Method: Trial 1 - 1,000,000 #Roll dice over and over, see how many times each occurs, calculate probability from that import random #input: variable number of arguments for sides of dice #output: table of probability for each outcome def diceRoll(numSides): counts = [] for x in range(1, numSides+1): counts.append(0) #print("x: " + str(x)) maxRolls = 1_000_000 #neat trick to make big numbers more human readable for x in range(maxRolls): dice = random.randint(1, numSides) counts[dice-1] += 1 print("results:") for x in range(numSides): print(str(x+1) + " probability: {:0.2f}% chance ".format((counts[x] / maxRolls) * 100) ) #instructor's solution- I underestimated what he meant by the input & output from collections import Counter def roll_dice(*dice, num_trials=1_000_000): counts = Counter() for roll in range(num_trials): counts[sum((random.randint(1, sides) for sides in dice))] += 1 print("\nOutcome\tProbability") for outcome in range(len(dice), sum(dice)+1): print("{}\t{:0.2f}%".format(outcome, counts[outcome]*100/num_trials)) #main diceRoll(10) roll_dice(4,6,6) #ok, compactified logic aside, that is pretty cool
true
479f2b2aa2fe422659aa9a7667bdc135d4117ac7
jkalmar/language_vs
/strings/strings.py
1,751
4.4375
4
#!/usr/bin/python3 """ Python strings """ def main(): """ Main func """ hello = "Hello" world = "World" print(hello) print(world) # strings can be merged using + operator print(hello + world) # also creating a new var using + operator concat = hello + world print(concat) # space can be added easily print(hello + " " + world) # or a little differently # but this first creates a list from the two strings and then # join the list into a string using space print(" ".join([hello, world])) # this do the same but without the middle man helloworld = hello + " " + world print(helloworld) # string slicing is nice print("substring from 0 to 5th char: " + helloworld[:5]) print("substring from 5 to the rest of var: " + helloworld[5:]) # indexing is natural(at least for C developers :) ) print(hello[4] + world[0] + hello[2]) # nice feature is that the operator * repeates the whole string print("*" * 80) print("*" + " " * 78 + "*") print(("*" + " " * 78 + "*\n") * 2, end='') print("*" + " "* int(78 / 2 - len(helloworld) / 2) + helloworld + " " * int(78 / 2 - len(helloworld) / 2 + 1) + "*") print(("*" + " " * 78 + "*\n") * 3, end='') print("*" * 80) # strings can draw in the terminal base = 30 for row in range(1, base, 2): print(" " * int(base / 2 - row / 2) + "+" * row) # searching string in another string is very natural print("Is hello in Hello World?") print("hello" in helloworld) # but please note that seach is case-sensitive # so ones more print("Is hello in Hello World?") print("hello" in helloworld.lower()) if __name__ == '__main__': main()
true
ed61e2b7e6bd538502c76470ed1decc74400ce18
Muntasir90629/Python-Basic-Code
/if.py
264
4.15625
4
saarc=["Ban","afg","bhu","nepal","india","sri"] country=input("Enter the name country: ") if country in saarc: print(country,"Is a member of saarc") else: print(country,"is not a member of saarc") print("Programme Terminated")
false
225877fca1af5d782e1fb5ac0f694b4dfa703014
samandeveloper/Object-Oriented-Programming
/Object Oriented Programming.py
672
4.4375
4
#Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats cat1=Cat('Loosy',1) cat2=Cat('Tom',5) cat3=Cat('Johnny',10) print(cat1.name) print(cat1.age) print(cat2.name) print(cat2.age) print(cat3.name) print(cat3.age) # 2 Create a function that finds the oldest cat def oldest_cat(*args): return max(args) print(oldest_cat(cat1.age,cat2.age,cat3.age)) # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2 print(f'The oldest cat is {oldest_cat(cat1.age,cat2.age,cat3.age)} years old.')
true
792874672ab2d914b09da268bc5e995f0916f842
leadschool-ccs/python-lead-academy
/Calculator.py
452
4.1875
4
print("Operations:") print("To add - select 1") print("To subtract - select 2") print("To multiply - select 3") choice = int(input()) # Input operation print("Enter 1st number:") number1 = int(input()) print("Enter 2nd number:") number2 = int(input()) if(choice == 1): output = number1 + number2 elif(choice == 2): output = number1 - number2; else: output = number1 * number2 print(output) # output operation print("apple") print(1)
false
b5a0c7b1e3d99afef07497fc70019ee271ff3aa7
FabianForsman/Chalmers
/TDA548/Exercises/week6/src/samples/types/CollectionsSubtyping.py
2,098
4.125
4
# package samples.types # Using super/sub types with collections from typing import List from abc import * def super_sub_list_program(): d = Dog("Fido", 3) c = Cat("Missan", 4, False) pets: List[Pet] = [] pets.append(d) # Ok, Dog is a Pet pets.append(c) # Ok, Cat is a Pet pets[0].get_name() speakers: List[CanSpeak] = [] speakers.append(d) # Ok, Dog can speak speakers.append(c) # Ok, Cat can speak speakers[0].say() speakers[0].get_name() # No guarantee there is such a method! speakers = pets # Whoa, dangerous! (Why?) pets = speakers # This is even worse, but at least here we get a warning. pets.append(speakers[0]) # A speaker might not be a Pet! speakers.append(pets[0]) # But any pet can speak speakers.extend(pets) # We can add all pets to a list of speakers pets.extend(speakers) # ... but not all speakers to a list of pets for speaker in speakers: if isinstance(speaker, Pet): # Check if object is Pet or subclass to pets.append(speaker) # then we know we can add it safely # --------------- Types ----------------- class CanSpeak(ABC): @abstractmethod def say(self): pass class Pet(CanSpeak, ABC): def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name def get_age(self): return self.age class Dog(Pet): def __init__(self, name, age): # Redundant code gone super().__init__(name, age) def say(self): # Dog is subtype to Pet and CanSpeak, must implement method! return f"{self.name} says Arf" class Cat(Pet): def __init__(self, name, age, is_evil): super().__init__(name, age) self.is_evil = is_evil def is_evil(self): return self.is_evil() def say(self): return f"{self.name} says Meow" if __name__ == "__main__": super_sub_list_program()
true
c4df0605b50f9bff5df32e5bcb89bb1ab6f51305
FabianForsman/Chalmers
/TDA548/Exercises/week4/src/samples/Stack.py
1,900
4.46875
4
# package samples # Python program to demonstrate stack implementation using a linked list. # Class representing one position in the stack; only used internally class Stack: class Node: def __init__(self, value): self.value = value self.next = None # Initializing a stack. def __init__(self): self.head = None # Node("head") self.size = 0 # String representation of the stack, for printouts def __str__(self): cur = self.head out = "" while cur is not None: out += str(cur.value) + "->" cur = cur.next return "[ " + out[:-2] + " ]" # Get the current size of the stack def get_size(self): return self.size # Check if the stack is empty def is_empty(self): return self.size == 0 # Get the top item of the stack, without removing it def peek(self): if self.is_empty(): raise ValueError("Peeking from an empty stack") return self.head.next.value # Push a value onto the stack def push(self, value): new_node = Stack.Node(value) new_node.next = self.head self.head = new_node self.size += 1 # Remove a value from the stack and return it def pop(self): if self.is_empty(): raise ValueError("Popping from an empty stack") node_to_pop = self.head self.head = self.head.next self.size -= 1 return node_to_pop.value # Remove all elements from the stack def clear(self): self.head = None self.size = 0 def test(): stack = Stack() for i in range(1, 11): stack.push(i) print(f"Stack: {stack}") for _ in range(1, 6): remove = stack.pop() print(f"Pop: {remove}") print(f"Stack: {stack}") # Driver Code if __name__ == "__main__": test()
true
5d696e7556db84b16e050e5d4f7263e13f937423
bz866/Data-Structures-and-Algorithms
/bubblesort.py
668
4.25
4
# Bubble Sort # - Assume the sequence contains n values # - iterate the sequence multiple times # - swap values if back > front (bubble) # - Time: O(n^2) # - [(n -1) + 1] * [(n - 1 + 1) / 1 + 1] / 2 # - 0.5 * n^2 + 0.5 * n # - Spac: O(1) # - sorting done by swapping import warnings # implementation of the bubble sort algorithm def bubbleSort(theValues): if len(theValues) == 0: warnings.warn("User is sorting empty sequence.") n = len(theValues) for i in range(0, n - 1): for j in range(0, n - i - 1): if theValues[j] > theValues[j+1]: # Swap temp = theValues[j] theValues[j] = theValues[j+1] theValues[j+1] = temp return theValues
true
4cc05e77f7d7fabc3f2498c8d93426425cfabcc9
bz866/Data-Structures-and-Algorithms
/radixSort.py
637
4.15625
4
# Implementation of the radix sort using an array of queues # Sorts a sequence of positive integers using the radix sort algorithm from array import array from queueByLinkedList import Queue def radixSort(intList, numDigits): # Create an array of queues to represent the bins binArray = Array(10) for k in range(10): binArray[k] = Queue() # The value of the current column column = 1 # Iterate over the number of digits in the largest value for d in range(numDigits): digit = (key // column) % 10 binArray[digit].enqueue(key) # Gather the keys from the bins and place them back intList i = 0 for bin in binArray:
true
c9a567f4bcd0536dd1f3933c081d35d59ccad7a7
bz866/Data-Structures-and-Algorithms
/linkedListMergeSort.py
2,267
4.40625
4
# The merge sort algorithm for linked lists # Sorts a linked list using merge sort. A new head reference is returned def linkedListMergeSort(theList): # If the list is empty, return None if not theList: return None # Split the linked list into two sublists of equal size rightList = _splitLinkedList(theList) leftList = theList # Perform the same operation on the left half & right half leftList = linkedListMergeSort(leftList) rightList = linkedListMergeSort(rightList) # merge the two ordered sublists theList = _mergeLinkedLists(leftList, rightList) # Return the head pointer of the ordered sublist return theList # Splits a linked list at the midpoint to create two sublists. The head reference of the right sublist is # returned. The left sublist is still referenced by the original head reference def _splitLinkedList(subList): # Assign a reference to the first and second nodes in the list midPoint = subList curNode = midPoint.next # Iterate through the list until curNode falls off the end while curNode is not None: # Advance curNode to the next Node curNode = curNode.next # if there are more nodes, advance curNode again and midPoint once if curNode is not None: midPoint = midPoint.next curNode = curNode.next # Set rightList as the head pointer to the right subList rightList = midPoint.next # Unlink the right subList from the left subList midPoint.next = None # Return the right subList head reference return rightList # Merges two sorted linked list; returns head reference for the new list def _mergeLinkedLists(subListA, subListB): # Create a dummy node and insert it at the front of the list newList = ListNode(None) newTail = newList # Append nodes to the newList until one list is empty while subListA is not None and subListB is not None: if subListA.data <= subListB.data: newTail.next = subListA subListA - subListA.next else: newTail.next = subListB subListB = subListB.next newTail = newTail.next newTail.next = None # if self list contains more terms, append them if subListA is not None: newTail.next = subListA else: newTail.next = subListB # Return the new merged list, which begins with the first node after the dummy node return newList.next
true
752c7275e39eb3b4ce0e30cd99d738d8406733dd
cBarnaby/helloPerson
/sine.py
420
4.125
4
import math def sin(x): if x > 360: x = x%360 print(x) x = x/180*math.pi term = x sum = x eps = 1E-8 n = 2 while abs(term/sum) > eps: term = -(term*x*x)/(((2*n)-1)*((2*n)-2)) sum = sum + term n += 1 return sum print(sin(3000)) x = (float(input("Enter an angle in degrees: "))) result = math.sin(x/180*math.pi) print("sin(x) = ", result)
true
8e6c241216f935be862425a1b8854c4876757e75
cyinwei/crsa-rg-algs-1_cyinwei
/bin/divide_and_conquer/mergesort.py
1,015
4.21875
4
def merge(left, right): combined = [None] * (len(left) + len(right)) i = 0 #left iterator j = 0 #right iterator for elem in combined: #first do cases where one arr is fully used #note that we won't have out bounds, since the length # of combined is the the two smaller blocks' length if i == len(left): elem = right[j] j += 1 elif j == len(right): elem = left[i] i += 1 #then do cases with both arrs aren't used yet elif left[i] <= right[j]: elem = left[i] i += 1 else: elem = right[j] j += 1 return combined def mergesort(arr): #base case if len(arr) <= 1: return arr #recursive case left = mergesort(arr[:len(arr)//2]) right = mergesort(arr[len(arr)//2:]) return merge(left, right) #example test = [10, 8, 6, 4, 2, 9, 7, 5, 3, 1] sorted_arr = mergesort(test)
true
c6e2055639c973495cabb7d72f67680c836d5dc8
aledoux45/ProjectEuler_Solutions
/p7.py
714
4.25
4
## NOTE: we know from the prime number theorem # that the number of primes <= N is N / log(N) import math def list_primes(n): """ Returns the list of primes below n """ isprime = [False, False, True] + [True, False] * ((n-1) // 2) if n % 2 != 0: isprime = isprime[:-1] r = math.sqrt(n) for k in range(3, int(r)+1, 2): if isprime[k]: k1 = 2 while k1*k <= n: isprime[k1*k] = False k1 += 1 list_p = [i for i, k in enumerate(isprime) if k] return list_p if __name__ == "__main__": i = 10001 n = i while n / math.log(n) < i*1.1: n += 1 list_p = list_primes(n) print(list_p[i-1])
false
176f3cede6656a83f21adf57e69af59538c1cc61
vlad-belogrudov/jumping_frogs
/jumping_frogs.py
1,307
4.1875
4
#!/usr/bin/env python3 """ Jumping frogs and lamps - we have a number of either. All lamps are off at the beginning and have buttons in a row. Frogs jump one after another. The first frog jumps on each button starting with the first button, the second frog on button number 2, 4, 6... the third on button number 3, 6, 9... This program emulates state of lamps (on, off) """ class Lamps: """This class represents state of lamps""" def __init__(self, num) -> None: """Initialize state of all lamps - all off""" self.state = [False for _ in range(0, num)] def __str__(self) -> str: """To string""" return "".join((str(int(s)) for s in self.state)) def __int__(self) -> int: """To int""" return int(str(self), 2) def press(self, num) -> None: """Press button""" self.state[num] = not self.state[num] if __name__ == "__main__": NUM_LAMPS = 10 NUM_FROGS = 10 lamps_state = Lamps(NUM_LAMPS) for iteration in range(1, NUM_LAMPS + 1): for frog in range(1, NUM_LAMPS + 1): lamp_num = frog * iteration -1 if lamp_num < NUM_LAMPS: lamps_state.press(lamp_num) else: break print(lamps_state) print(hex(int(lamps_state)))
true
956022f43bef011c45ebee0e2a5a1b8cf7e4c820
Soham2020/Python-basic
/General-Utility-Programs/Calculator.py
893
4.28125
4
# A Simple Calculator # Function Declarations def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y # Input From User print("Calculator \n\nSelect The Operation") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Exponent & Power") choice = input("Enter Your Choice (1-5) :") n1 = int(input("Enter First Number: ")) n2 = int(input("Enter Second Number: ")) # Conditional Rendering if choice == '1': print(n1,"+",n2,"=", add(n1,n2)) elif choice == '2': print(n1,"-",n2,"=", subtract(n1,n2)) elif choice == '3': print(n1,"*",n2,"=", multiply(n1,n2)) elif choice == '4': print(n1,"/",n2,"=", divide(n1,n2)) elif choice == '5': print(n1,"^",n2,"=", n1**n2) else: print("Invalid Input")
false
9bc9a24e5de1f990442b9c544c04bb56121e3a9e
Soham2020/Python-basic
/General-Utility-Programs/LCM..py
258
4.15625
4
# Calculate LCM of Two Numbers a = int(input("Enter First Number : ")) b = int(input("Enter Second Number : ")) if(a>b): min = a else: min = b while(1): if(min%a == 0 and min%b == 0): print("LCM is",min) break min = min + 1
true
63b0bea5d35da88ba81085015b6ddc63dff2bb01
Soham2020/Python-basic
/General-Utility-Programs/FibonacciSeries.py
208
4.1875
4
# Fibonacci Series a = 0 b = 1 n = int(input("Enter The Number of Terms : ")) print("FIBONACCI SERIES") print(a," ",b,end="") for i in range(n): c = a + b a = b b = c print(" ",c,end="")
false
92764bc93100ff1c7472e93608a96d88c4936ebd
Soham2020/Python-basic
/Numpy/Arrays.py
576
4.15625
4
""" The NumPy (Numeric Python) package helps us manipulate large arrays and matrices of numeric data. To use the NumPy module, we need to import it using: import numpy A NumPy array is a grid of values. They are similar to lists, except that every element of an array must be the same type. Task You are given a space separated list of numbers. Your task is to print a reversed NumPy array with the element type float. """ import numpy def arrays(arr): a = numpy.array(arr[::-1],float) return(a) arr = input().strip().split(' ') result = arrays(arr) print(result)
true
b967ab6ff9ee403d6be5704d0efec47b8b4a7654
Soham2020/Python-basic
/General-Utility-Programs/Sum-of-Squares.py
292
4.25
4
# Python Program to find sum of square of first n natural numbers # From the knowledge of mathematics, we know - # Sum of squares upto n = (n * (n+1) / 2) * (2 * n+1) / 3 def sum_of_squares(n): return (n * (n+1) / 2) * (2 * n+1) / 3 n = int(input()) print(sum_of_squares(n))
false
e5c118e589dc2e47944ef452cb70660c7f854c88
Soham2020/Python-basic
/General-Utility-Programs/GCD_HCF.py
247
4.125
4
# Calculate The GCD/HCF of Two Numbers def gcd(a, b): if(b==0): return a else: return gcd(b, a%b) a = int(input("Enter First Number : ")) b = int(input("Enter Second Number : ")) ans = gcd(a, b) print("The GCD is",ans)
true
520d2852a0a98263711079ea0d42fc41b5575370
Soham2020/Python-basic
/Strings/vowelCount.py
294
4.28125
4
# Program to Calculate The Number of Vowels in a Given String str1 = str(input("Enter A String : ")) count = 0 for i in str1: if(i=='A' or i=='a' or i=='i' or i=='I' or i=='o' or i=='O' or i=='u' or i=='U'): count = count + 1 print("Number of Vowels in the Entered String : ", count)
false
ec160ee9cf8ba837fd261d5e922cf29f73ca6af0
Bharti20/python_if-else
/age_sex.py
546
4.15625
4
age=int(input("enter the age")) sex=(input("enter the sex")) maretial_status=input("enter the status") if sex=="female": if maretial_status=="yes" or maretial_status=="no": print("she will work only urban area") elif sex=="male": if age>=20 and age<=40: if maretial_status=="yes" or maretial_status=="no": print("he can work anywhere") elif age>=40 and age<=60: if maretial_status=="yes" or maretial_status=="no": print("he will work in urban areas") else: print("error")
true
038d62269c5f5db1a117c8926f1035603a075672
ladyvifra/ejercicios_basicosPython
/Ejercicios/practica_tuplas.py
921
4.3125
4
# Tuplas- Listas inmutables. No se puede modifica(no append, extend, remove) #Se puede comprobar si hay elementos en una tupla #Ventajas: rápidas al ejecutar, menos espacio, formatean strings, se pueden usar como claves en un diciconario, las listas no lo hacen. mitupla=("Juan", 13, 12, 1995) print(mitupla[2]) #convertir tupla en lista milista=list(mitupla) print(milista) lista1=["Pablo","Jorge","Luis",3] tupla=tuple(lista1) print(tupla) #comprobar los elelmtos en la tupla print("Juan"in mitupla) #count-averugua cuántos elementos hay een una tupla print(mitupla.count(13)) #saber la longitud d ela tupla print(len(mitupla)) #se pueden crear tuplas unitarias tupla2=("Juan",) print(len(tupla2)) #se pueden crear tuplas sin préntesis, pero se recomienda ponerlos tupla3="Pedro",13,2,1990 print(tupla3) #desenpaquetar una tupla nombre, dia, mes, agno=tupla3 print(nombre) print(dia) print(mes) print(agno)
false
ca79f69bcb7096b0e6d13c61bcef7785c0de1e35
phattarin-kitbumrung/basic-python
/datetime.py
411
4.28125
4
import datetime #A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. x = datetime.datetime.now() print(x) print(x.year) print(x.strftime("%A")) #To create a date, we can use the datetime() class (constructor) of the datetime module. x = datetime.datetime(2020, 5, 17) print(x) x = datetime.datetime(2018, 6, 1) print(x.strftime("%B"))
true
c0092b3f689d8cf5db0b069632f48949e7fbfd1b
ohanamirella/TrabalhosPython
/media.py
1,203
4.15625
4
nota1 = float(input('Digite a primeira nota: ')) nota2 = float(input('Digite a segundo nota: ')) nota3 = float(input('Digite a tereira nota: ')) nota4 = float(input('Digite a quarta nota: ')) if nota1 > nota2 and nota1 > nota3 and nota1 > nota4: print (f'Nota {nota1} é a maior nota') elif nota2 > nota1 and nota2 > nota3 and nota2 > nota4: print (f'Nota {nota2} é maior nota') elif nota3 > nota1 and nota3 > nota2 and nota3 > nota4: print(f'Nota {nota3} é maior nota') elif nota4 > nota1 and nota4 > nota2 and nota4 > nota3: print(f'Nota {nota4} é maior nota') if nota1 < nota2 and nota1 < nota3 and nota1 < nota4: print (f'Nota {nota1} é a menor nota') elif nota2 < nota1 and nota2 < nota3 and nota2 < nota4: print(f'Nota {nota2} é a menor nota') elif nota3 < nota1 and nota3 < nota2 and nota3 < nota4: print (f'Nota {nota3} é a menor nota') elif nota4 < nota1 and nota4 < nota2 and nota4 < nota3: print (f'Nota {nota4} é a menor nota') else: print(f'As notas são iguais {nota1} , {nota2} , {nota3} e {nota4} ') media = (nota1 + nota2 + nota3 + nota4) / 4 print (f'{media}') if media >= 7: print('Aluno aprovado') else : print('Aluno reprovado')
false
3b15fff39e3e4cc1ecbf5ed0e7d95fdcd15f662d
tj1234567890hub/pycharmed
/i.py
514
4.25
4
def findPrime(num): prime = True if num < 1: print("This logic to identify Negative prime number is not yet developed.. please wait") else: for i in range(2, num - 1, 1): if num % i == 0: prime = False break print (prime) return prime if __name__ == '__main__': num = input ("Enter the number to check if it is prime:") try: num = int(num) findPrime(num) except: print("Correct your entry")
true
0faccfc350ba25e81ae58256cfa90186a7310d12
tchitchikov/data_structures_and_algorithms
/sorting/insertion_sort.py
1,258
4.375
4
__author__ = 'tchitchikov' """ An insert sort will allow you to compare a single element to multiple at once The first value is inserted into the sorted portion, all others remain in the unsorted portion. The next value is selected from the unsorted array and compared against each value in the sorted array and inserted in its proper ascending or descending order depending on how you code this. Run so all values are in the sorted array. """ from base_class import Sort class InsertSort(Sort): def sorting_process(self, input_array): """ Uses only a single list and compares the two indexed values """ unsorted = input_array for index in range(1, len(unsorted)): value = unsorted[index] index_2 = index - 1 while(index_2 >= 0 and unsorted[index_2] > value): unsorted[index_2+1] = unsorted[index_2] # shift number in slot i to slot i + 1 unsorted[index_2] = value # shift value left into slot i index_2 = index_2-1 return unsorted if __name__ == '__main__': sorting = InsertSort() sorting.main() print('Subclass: ', issubclass(InsertSort, Sort)) print('Instance: ', isinstance(InsertSort(), Sort))
true
a47002a92364beda833760095fdb204a48b68c29
Serge-N/python-lessons
/Basics/strings/exercise2.py
305
4.125
4
user = input('Would you like to continue? ') if(user=='no' or user =='No' or user == 'NO' or user=='n'): print('Exiting') elif (user=='yes' or user =='Yes' or user == 'YES' or user=='y'): print('Continuing...') print('Complete!') else: print('Please try again and respond with yes or no')
true
d279c333259192f4c397269c8dde2fdb605527c4
Serge-N/python-lessons
/Basics/Numeric/calculator.py
1,484
4.375
4
print ('Simple Calculator!') first_number = input ('First number ?') operation = input ('Operation ?') second_number = input ('Second number ?') if not first_number.isnumeric() or not second_number.isnumeric(): print('One of the inputs is not a number.') operation = operation.strip() if operation == '+' : first_number = int(first_number) second_number = int (second_number) print(f'Sum of {first_number} + {second_number} = {first_number+second_number}') elif operation =='-': first_number = int(first_number) second_number = int (second_number) print(f'Difference of {first_number} - {second_number} = {first_number-second_number}') elif operation =='*': first_number = int(first_number) second_number = int (second_number) print(f'Product of {first_number} * {second_number} = {first_number*second_number}') elif operation =='/': first_number = int(first_number) second_number = int (second_number) print(f'Dividend of {first_number} / {second_number} = {first_number/second_number}') elif operation =='**': first_number = int(first_number) second_number = int (second_number) print(f'{first_number} power {second_number} = {first_number**second_number}') elif operation =='%': first_number = int(first_number) second_number = int (second_number) print(f'Modulus of {first_number} % {second_number} = {first_number%second_number}') elif operation: print('Operation not recognized.')
true
ce7678a04a4faf67239c8131b7db9f42bfcaf579
mikelhomeless/CS490-0004-python-and-deep-learning-
/module-1/python_lesson_1.py
1,345
4.375
4
# QUESTION 1: What is the difference between python 2 and 3? # Answer: Some of the differences are as follows # Print Statement # - Python 2 allowed for a print statement to be called without using parentheses # _ Python 3 Forces parentheses to be used on the print statement # # Division Operations # 2/3 in python 2 will result in integer division => 1 # 2/3 in python 3 will result in a floating point division => 1.5 # # Input Function # The input method in python 2 is raw_input() # The input method in python 3 is simply input() # QUESTION 2 user_string = input('Please type "python": ') print(user_string[::2][::-1]) num1 = int(input('Please enter a number: ')) num2 = int(input('Please enter another number: ')) print('The sum of the numbers you entered is %s' % (num1 + num2)) print('The power of the first number by the second number is %s' % num1 ** num2) print('The remainder of the first number divided by the second number is %s' % (num1 % num2)) # QUESTION 3 string_of_pythons = input('Please enter a string containing at least one "python": ') # split the string on the word python and rejoin with pythons in the split locations new_string = 'pythons'.join(string_of_pythons.split('python')) print(new_string)
true
24b044daf5c53f0a8500738ebba7477b54f6c30b
dzlzhenyang/FlaskFrameWork
/FlaskPoject/app/common_code/get_calendar.py
2,371
4.15625
4
""" 当前类实现的功能 1. 返回列表嵌套列表的日历 2. 按照日历的格式打印日历 """ import datetime class Calendar(): def __init__(self, year=2019, month=9): # 定义列表返回的结果 self.result = [] # 定义最大月份和最小月份 big_month = [1, 3, 5, 7, 8, 10, 12] small_month = [4, 6, 9, 11] if month in big_month: day_range = range(1, 32) elif month in small_month: day_range = range(1, 31) else: # 判断是否为闰年 if year % 400 == 0 or year % 4 == 0 and year % 100 != 0: day_range = range(1, 30) else: day_range = range(1, 29) # 将day_range 转换为列表 self.day_range = list(day_range) # 获取当月的第一天 年 月 日 时 分的形式显示 first_day = datetime.datetime(year, month, 1, 0, 0) # 获取当月第一天是一周中的第几天 where_day = first_day.weekday() # 第一行 line1 = [] # 比如第六天,6个空 for i in range(where_day): line1.append("null") # 第六天,7-6个有值 for j in range(7 - where_day): # 将day_range列表中的第一个元素弹出来,以字符串的方式添加到line1中 line1.append(str(self.day_range.pop(0))) # 将line1添加到result中 self.result.append(line1) # 第2-n行 while self.day_range: line = [] # 每行打印7个 for i in range(7): # self.day_range 不存在时,进入else if self.day_range: line.append(str(self.day_range.pop(0))) else: line.append("null") # 在循环中,每打印一行line,添加一次 self.result.append(line) def return_calendar(self): return self.result def print_calendar(self): print("周一", "周二", "周三", "周四", "周五", "周六", "周日") for line in self.result: for day in line: print(day, end=" ") print() # 验证 if __name__ == '__main__': calendar = Calendar(2018, 6) print(calendar.return_calendar()) calendar.print_calendar()
false
cdddf8d99ef523049380a7a9d659f6c02a77572a
tsholmes/leetcode-go
/02/84-peeking-iterator/main.py
1,846
4.34375
4
# Below is the interface for Iterator, which is already defined for you. # class Iterator(object): def __init__(self, nums): """ Initializes an iterator object to the beginning of a list. :type nums: List[int] """ self.nums = nums def hasNext(self): """ Returns true if the iteration has more elements. :rtype: bool """ return len(self.nums) > 0 def next(self): """ Returns the next element in the iteration. :rtype: int """ v = self.nums[0] self.nums = self.nums[1:] return v class PeekingIterator(object): def __init__(self, iterator): """ Initialize your data structure here. :type iterator: Iterator """ self.it = iterator self.p = None def peek(self): """ Returns the next element in the iteration without advancing the iterator. :rtype: int """ if self.p is None: self.p = self.it.next() return self.p def next(self): """ :rtype: int """ if self.p is not None: v = self.p self.p = None return v return self.it.next() def hasNext(self): """ :rtype: bool """ return self.p is not None or self.it.hasNext() # Your PeekingIterator object will be instantiated and called as such: # iter = PeekingIterator(Iterator(nums)) # while iter.hasNext(): # val = iter.peek() # Get the next element but not advance the iterator. # iter.next() # Should return the same value as [val]. if __name__ == '__main__': it = Iterator([1,2,3,4,5]) pit = PeekingIterator(it) while pit.hasNext(): print(pit.peek()) print(pit.next())
true
053f6d6c048fe78166f8a2943b1f1a9c6181c749
xLinkOut/python-from-zero
/snippets/13-slicing.py
444
4.1875
4
s = "Python" # Dichiaro la stringa s # stringa[inizio:fine] print(s[1:-2]) # Da s[1] a s[-2] (=s[3]) print(s[-1:2]) # Non è possibile "reversare" la stringa print(s[-1:-3]) # Appunto... print(s[-3:-1]) # Da s[-3] (=s[3]) a s[-1] (=s[5]) print(s[3:5]) # Come sopra ma con indici positivi print(s[-3:5]) # Un altro modo ancora... print(s[-2:1]) # Se lo slicing è incompatibile, ritorna una stringa vuota print(s[5::-1]) # Extended Slices
false
818637ab82f7c9aea4e5362a45407e77d8c424cf
DamonKoy/python_exercises
/work20200624.py
2,541
4.28125
4
""" 1、定义一个函数,接收2个参数num_list、num,其中num_list是一个已经排好序的数字列表,函数的作用是把num按照排序规律插入到num_list中并返回num_list,例如[1, 4 , 7, 8, 12], 5 -> [1, 4, 5, 7, 8, 12](注:不要使用内置的排序方法) 2、定义一个函数custom_replace(),实现的是str.replace()的功能,例如custom_replace('good good study, good or bad', 'good', 'haha'),返回的是‘haha haha study, haha or bad’ 3、定义一个函数,接收一个正整数num,把这个正整数num分解质因数。例如:num=110,输出110=2*5*11 """ num_list = [1, 4, 7, 8, 12] def insert_list(num_list, num): # 判断是从大到小排序 if num_list[0] >= num_list[-1]: for i in range(0, len(num_list)): if num >= num_list[i]: num_list.insert(i, num) break # 如果for循环正常结束,else中语句执行。如果是break的,则不执行。 else: num_list.append(num) # 如果是从小到大 else: for i in range(0, len(num_list)): if num <= num_list[i]: num_list.insert(i, num) break else: num_list.append(num) return num_list print(insert_list(num_list, 5)) # 2、定义一个函数custom_replace(),实现的是str.replace()的功能,例如custom_replace('good good study, good or bad', 'good', 'haha'),返回的是‘haha haha study, haha or bad’ def custom_replace(content: str, word: str, change: str): content.replace(word, change) print(content) custom_replace('good good study, good or bad', 'good', 'haha') # 3、定义一个函数,接收一个正整数num,把这个正整数num分解质因数。例如:num=110,输出110=2*5*11 # 了解质因数 # 迭代判断是否为合数 # 收集质因数 num_list = [] def get_num(num: int): for i in range(2, num): if num % i == 0: # 要添加字符串的i,最后才能输出X*X*X num_list.append(str(i)) get_num(num // i) break # 如果for循环正常结束,else中语句执行。如果是break的,则不执行。 else: # 把最后的质数加入列表里 num_list.append(str(num)) print(num_list) # 判断num本身是否为质数 if len(num_list) == 1: return f"{num}是质素" # 输出答案 return f"{num}={'*'.join((num_list))}" print(get_num(1110))
false
42bffa94a075331b4c2d0279dfbdb83e64d95b4b
GinnyGaga/HM_cope_HM_01
/hm_07_买苹果增强版.py
449
4.15625
4
# 输入苹果单价 # price_str = input("请输入苹果的单价:") # 要求苹果的重量 # weight_str = input("请输入苹果的重量:") #将单价转换成小数 # price = float(price_str) price = float(input("请输入苹果的单价:")) # 将重量转换成小数 # weight = float(weight_str) weight = float(input("请输入苹果的重量:")) # 计算苹果的总价 Money = price * weight print ("总价为:", Money)
false
c9d1bf857bd0a38c69c14069dc6801e8a034b143
icarlosmendez/dpw
/wk1/day1.py
2,249
4.15625
4
# print 'hello' # # if, if/else # grade = 60 # message = 'you really effed it up!' # if grade > 89: # message = "A" # elif grade > 79: # message = 'B' # elif grade > 69: # message = 'C' # # print message # # if, if/else # # name = 'bob' # # if(name == 'bob'): # print 'your name is bob' # elif(name == 'joe'): # print 'your name is bob' # else: # print "you're a nobody" # # simple iterative loop # # for i in range(10): # print i # # iterative loop with a starting point, end point and a metric # # for i in range(2,11,2): # print i # # iterate over a list (array) # # grades = [70, 80, 90] # grades.append(100) # grades.splice(1,1) javaScript for removing an index # grades.pop() - get rid of the last element # grades.pop(0) - get rid of an element at a specific index # print grades # # functions # # an empty function # def greetings(): # pass # # def add(a, b): # total = a + b # return total # # print add(2, 2) # calculate avg function # # test = [70, 80, 90, 90] # test is our variable # def avg(n): # n is a generic variable representing a numerical value # total = 0 # for i in n: # total += i # average = total/len(n) # return average # pass in the variable test which will be represented in the function by n # print avg(test) # sum of all odd numbers in a list # # nums = [1,2,3,4,5,6,7,8,9] # def odd_sum(n): # odd_total = 0 # for i in n: # if i %2 != 0: # odd_total += i # return odd_total # print odd_sum(nums) # verify vowels in a string # print 'This program will output a list of vowels contained in any word you enter.' word = raw_input("Type a word: ") def vowels(w): vowel_container = [] for i in w: if i == 'a': vowel_container.append(i) elif i == 'e': vowel_container.append(i) elif i == 'i': vowel_container.append(i) elif i == 'o': vowel_container.append(i) elif i == 'u': vowel_container.append(i) if len(vowel_container) == 0: return 'There are no vowels in this word' else: return sorted(vowel_container) print vowels(word) # extra credit: # no duplicate values
true
09405c197f8fdd64081dda2c24197c37ad5da468
kfactora/coding-dojo-python
/python_oop/bankAccount.py
1,319
4.5
4
# Assignment: BankAccount # Objectives # Practice writing classes # The class should also have the following methods: # deposit(self, amount) - increases the account balance by the given amount # withdraw(self, amount) - decreases the account balance by the given amount if there are sufficient funds; if there is not enough money, print a message "Insufficient funds: Charging a $5 fee" and deduct $5 # display_account_info(self) - print to the console: eg. "Balance: $100" # yield_interest(self) - increases the account balance by the current balance * the interest rate (as long as the balance is positive) class BankAccount: def __init__(self, int_rate, balance): self.int_rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): self.balance -= amount return self def display_account_info(self): print("Balance:", "$",self.balance) def yield_interest(self): self.balance *= self.int_rate return self bank1 = BankAccount(1.01,0) bank1.deposit(100).deposit(100).deposit(100).withdraw(50).yield_interest().display_account_info() bank2 = BankAccount(1.01,0) bank2.deposit(100).deposit(100).withdraw(25).withdraw(25).withdraw(25).withdraw(25).yield_interest().display_account_info()
true
b5e29623a4fef94147d67612b907baa85249cc9e
airportyh/begin-to-code
/lessons/python/lesson-5/all-cap-strong.py
370
4.3125
4
sentence = input('Enter sentence: ') new_sentence = '' all_caps_mode = False for char in sentence: if all_caps_mode: if char == '!': all_caps_mode = False else: new_sentence += char.upper() else: if char == '!': all_caps_mode = True else: new_sentence += char print(new_sentence)
false
1e99ffac6aebd8568435cd24162c5c20cd20185b
airportyh/begin-to-code
/lessons/javascript/guess_number_bonus.py
948
4.125
4
while True: import random secret_number = random.randint(1, 10) counter = 0 guess = int(input("I'm thinking of a number from 1-10. Pick one!")) while counter <= 3: if guess > secret_number: print("Nope. Too high! Keep guessing!") if guess < secret_number: print("Nope. Too low! Keep guessing!") if guess == secret_number: print("You got it!") guess = int(input("Go again? y or n")) counter = counter + 1 if guess != "y": break print("Bye bye!") ''' Stage 4 Make it so that the player can only guess 5 times at most. If they guessed 5 times and still miss, print "You used up all your guesses!". Hint: you'll need to introduce the loop counter pattern into your code by adding a loop counter, and repeating condition, and a incrementer statement. '''
true
91cbeb7914b033c2983011c6e270a5efa10a8f31
Success2014/AlgorithmStanford
/QuickSort.py
2,141
4.125
4
__author__ = 'Neo' def QuickSort(array, n): """ :param array: list :param n: length of the array :return: sorted array and number of comparison """ if n <= 1: return array, 0 pivot = ChoosePivot2(array, n) pivot_idx = array.index(pivot) array = Partition(array, pivot_idx) pivot_idx = array.index(pivot) first_array = array[0: pivot_idx] second_array = array[pivot_idx + 1:] first_array_new, facNum = QuickSort(first_array, len(first_array)) second_array_new, secNum = QuickSort(second_array, len(second_array)) return first_array_new + [pivot] + second_array_new, (n - 1) + facNum + secNum def Partition(array, index): """ :param array: :param index: index of the pivot :return: partitioned array """ if len(array) <= 1: return array i = 1 array[0], array[index] = array[index], array[0] for j in range(1,len(array)): if array[j] < array[0]: array[i], array[j] = array[j], array[i] i += 1 array[0], array[i - 1] = array[i - 1], array[0] return array def ChoosePivot1(array, n): """ choose the first item as the pivot :param array: :param n: length of the array :return: pivot """ return array[0] def ChoosePivot2(array, n): """ :param array: :param n: length of the array :return: pivot """ return array[-1] def ChoosePivot3(array, n): """ use the median-of-three :param array: :param n: length of the array :return: pivot """ if n % 2 == 0: median = array[n / 2 - 1] else: median = array[n / 2] comArray = [array[0], median, array[-1]] max = -100000000 maxSec = -200000000 for value in comArray: if value > max: maxSec = max max = value elif value > maxSec: maxSec = value return maxSec fhand = open('QuickSort.txt') testarray = [] count = 0 for line in fhand: line = int(line) testarray.append(line) count += 1 #print testarray print type(testarray) x,y = QuickSort(testarray, count) print y
true
864fb4584710cd28db4f0f9cec58ab1e60068662
FakeEmpire/Learning-Python
/inheritance vs composition.py
1,819
4.5
4
# Most of the uses of inheritance can be simplified or replaced with composition # and multiple inheritance should be avoided at all costs. # here we create a parent class and a child class that inherits from it class Parent(object): def override(self): print("PARENT override()") def implicit(self): print("PARENT implicit()") def altered(self): print("PARENT altered()") class Child(Parent): # note here that override is going to override the inheritance from the Parent # class def override(self): print("CHILD override()") # in this case, super (Child, self) looks for the parent class of Child # and then returns Parent.altered() def altered(self): print("CHILD, BEFORE PARENT altered()") super(Child, self).altered() print("CHILD, AFTER PARENT altered()") dad = Parent() son = Child() dad.implicit() son.implicit() dad.override() son.override() dad.altered() son.altered() # Using composition instead of inheritance # good for has-a rather than is-a relationships class Other(object): def override(self): print("OTHER override()") def implicit(self): print("OTHER implicit()") def altered(self): print("OTHER altered()") class Child(object): def __init__(self): self.other = Other() def implicit(self): self.other.implicit() def override(self): print("CHILD override()") def altered(self): print("CHILD, BEFORE OTHER altered()") self.other.altered() print("CHILD, AFTER OTHER altered()") son = Child() son.implicit() son.override() son.altered() # In this case the child class takes what it needs from other, not everthing
true
f38e472b66609a02b34c26746d4280f6fb869157
FakeEmpire/Learning-Python
/lists.py
1,192
4.46875
4
# They are simply ordered lists of facts you want to store and access randomly or linearly by an index. # use lists for # If you need to maintain order. Remember, this is listed order, not sorted order. Lists do not sort for you. # If you need to access the contents randomly by a number. Remember, this is using cardinal numbers starting at 0. # If you need to go through the contents linearly (first to last). Remember, that's what for-loops are for. # you can ONLY use numbers to get things out of lists ten_things = "Apples Oranges Crows Telephone Light Sugar" print("Wait there are not 10 things in that list. Let's fix that.") stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print("Adding: ", next_one) stuff.append(next_one) print(f"There are {len(stuff)} items now.") print("There we go: ", stuff) print("Let's do some things with stuff.") print(stuff[1]) print(stuff[-1]) # whoa! fancy print(stuff.pop()) print(' '.join(stuff)) # what? cool! print('#'.join(stuff[3:5])) # super stellar!
true
328645b0543f27cc5b2bb471fb71bc33f6adf9ca
momentum-cohort-2019-02/w2d1--house-hunting-lrnavarro
/house-hunting.py
1,143
4.40625
4
print("How many months will it take to buy a house? ") annual_salary = int(input("Enter your annual salary: ") ) portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ") ) total_cost = int(input("Enter the cost of your dream home: ") ) down_payment_percent = input("Enter the percent of your home's cost to save as down payment [0.25]: ") if down_payment_percent == "": down_payment_percent = 0.25 annual_rate_of_return = input("Enter the expected annual rate of return [0.04]: ") if annual_rate_of_return == "": annual_rate_of_return = 0.04 current_savings = 0 portion_down_payment = (total_cost) * float(down_payment_percent) # r = 0.04 # current_savings*r/12 total_months = 0 monthly_savings = (annual_salary/12)*portion_saved # At the end of each month, your savings will be increased by the return on your investment, plus a percentage of your monthly salary (annual salary / 12) while current_savings < portion_down_payment: current_savings += monthly_savings + current_savings * float(annual_rate_of_return)/12 total_months += 1 print("Number of months: " + str(total_months) )
true
845aa9b083a40ac518a1bf24f091232d526749df
filipmellgren/Macro
/Assignment 1
2,348
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 28 08:20:14 2018 @author: filip """ import pandas as pd def steady_k(s, A, n, delta, theta): ''' Calculates the steady state level of capital''' k = ((s * A)/(n + delta))**(1/(1 - theta)) return k def growth_periods(step, k_steady_state, theta): ''' Calculates the number of periods an economy needs to grow between a starting fraction of the steady state capital level, to an ending fraction of the steady state capital level. ''' k = growth_fraction[step] * k_steady_state i = 0 while k < k_steady_state * growth_fraction[step + 1]: k = 1/(1 + n)* (s * A * k**(theta) + (1- delta)*k) i = i+1 return i # Given parameters: delta = 0.08 # Each period is a year n = 0 # Population growth s = 0.2 # Savings rate theta = [0.1, 0.3, 0.5, 0.7, 0.9] growth_fraction = [0.1, 0.6, 0.8, 0.9, 0.95, 0.975] # Will be used as intermediary # steps. How many years to travel from one to the next? # Create a data frame that we will populate with theta and k df = pd.DataFrame({"theta":theta}) #### Question (a) #### # Steady state value of capital, K A = 1 # Total factor productivity k_a = steady_k(s, A, n, delta, df["theta"]) # Steady states of k. df["k_steady_state"] = k_a for step in range(0, len(growth_fraction)-1): ''' Calculates time to travel from one step to the next for every economy before proceeding to calculate the next level to the one after that. ''' iterations = [] for economy in [0,1,2,3,4]: periods = growth_periods(step, df["k_steady_state"].iloc[economy], df["theta"].iloc[economy]) iterations.append(periods) df[str(growth_fraction[step]*100) + "% to " + str(growth_fraction[step + 1]*100) + "%"] = iterations print(df.to_latex(escape = False)) #### Question (b) #### # Theta = 0.5 corresponds to economy 2 (first value being 0). A = 2 k_b = steady_k(s, A, n, delta, 0.5) iterations = [] for step in range(0, len(growth_fraction)-1): periods = growth_periods(step, k_b, 0.5) iterations.append(periods) print(iterations) A = 4 k_b2 = steady_k(s, A, n, delta, 0.5) iterations2 = [] for step in range(0, len(growth_fraction)-1): periods = growth_periods(step, k_b2, 0.5) iterations2.append(periods)
false
ac1558fae111c31f0d18e714807f93178e6ec275
eflipe/python-exercises
/codewars/string_end_with.py
682
4.28125
4
''' Link: https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d/train/python Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). Examples: solution('abc', 'bc') # returns true solution('abc', 'd') # returns false ''' def solution(string, ending): end_value = len(string) print('end', end_value) ends_with = string.endswith(ending, 0, end_value) return ends_with if __name__ == '__main__': string_test_1 = 'abc' end_test_1 = 'bc' string_test_2 = 'abc' end_test_2 = 'd' string_test_3 = 'abc' end_test_3 = 'abc' print(solution(string_test_3, end_test_3))
true
9dd2f246428cf6227a0f110cc2cf4efb468ad292
eflipe/python-exercises
/apunte-teorico/gg/reverse_string.py
249
4.28125
4
# https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/ def reverse(s): str = "" for i in s: str = i + str return str # otra # Function to reverse a string def reverse(string): string = string[::-1] return string
true
9c8fd4d8675080e4551348d61e1846d2a9b14f62
eflipe/python-exercises
/automateStuff/strings_manipulation_pyperclip.py
748
4.3125
4
''' Paste text from the clipboard Do something to it Copy the new text to the clipboard #! python3 # Adds something to the start # of each line of text on the clipboard. ''' import pyperclip text = pyperclip.paste() print('Texto original :') print(text) print(type(text)) # split() return a list of strings, one for each line in the original string lines = text.split('\n') print(type(lines)) for i in range(len(lines)): # print(i) lines[i] = '- ' + lines[i].lower() # agregamos '- ' y lowercase # print(lines[i]) # join(): to make a single string value from the list Lines text = '\n'.join(lines) print('Texto modificado :\n') print(text) print(type(text)) print('\n El texto ha sido modificado con éxito') pyperclip.copy(text)
true
a854977aeab48172b818526ab814c99b2846fc72
julianikulski/cs50
/sentimental_vigenere/vigenere.py
1,911
4.21875
4
import sys from cs50 import get_float, get_string, get_int # get keyword if len(sys.argv) == 2: l = sys.argv[1] else: print("Usage: python vigenere.py keyword") sys.exit("1") # if keyword contains a non-alphabetical character for m in range(len(l)): if str.isalpha(l[m]) is False: print("Please enter a keyword with letters and no numbers") sys.exit("1") # request plaintext s = get_string("plaintext: ") # declaring j to ensure that enciphering is only done is character in l isalpha j = 0 # encipher the plaintext using the keyword print("ciphertext: ", end="") for i in range(len(s)): # keeping j independent of i and only moving forward if char in l isalpha j = j % len(l) # for all alphabetic values if str.isalpha(s[i]): # preserve case if str.isupper(s[i]): # shift upper case plaintext character by key if str.isupper(l[j]): # ensure that characters in l will be treated irrespective of case o = (((ord(s[i])) - 65) + (ord(l[j]) - 65)) % 26 print(f"{chr(o + 65)}", end="") else: o = (((ord(s[i])) - 65) + (ord(l[j]) - 97)) % 26 print(f"{chr(o + 65)}", end="") else: # shift lower case plaintext character by key if str.isupper(l[j]): # ensure that characters in l will be treated irrespective of case o = (((ord(s[i])) - 97) + (ord(l[j]) - 65)) % 26 print(f"{chr(o + 97)}", end="") else: o = (((ord(s[i])) - 97) + (ord(l[j]) - 97)) % 26 print(f"{chr(o + 97)}", end="") # increasing j if ith character in l islpha is True j += 1 else: # anything non-alphabetic will be printed without changes print(f"{s[i]}", end="") # skip to next row at the end print("")
true
ff7b5178b78cfe6d124c893734fa147d03dad6ea
cifpfbmoll/practica-3-python-joseluissaiz
/P3E7.py
1,214
4.1875
4
# Practica 3 # Ejercicio 7 # Pida al usuario tres número que serán el día, mes y año. Comprueba que # la fecha introducida es válida. # #----------------inputs dia = input("Introduce el dia :") mes = input("Introduce el mes :") anyo = input("Introduce el año :") # # #----------------Variables #error counting countError = 0 bisiesto = False # #---------------Logic #comprobante de tamaño if int(dia) > 31 or int(dia) <= 0 or int(mes) <= 0 or int(mes) > 12 or \ (int(mes) == 2 and int(dia) > 29): countError += 1 # #comprobante de meses que tienen 31 dias if (int(dia) > 31 and int(mes) == 4) or (int(dia) > 31 and int(mes) == 6) or \ (int(dia) > 31 and int(mes) == 9) or (int(dia) > 31 and int(mes) == 11): countError += 1 # #comprobante de años bisiestos if int(anyo) % 4 == 0: if int(anyo) % 100 == 0: if int(anyo) % 400 == 0: bisiesto = True else: bisiesto = False else: bisiesto = True else: bisiesto = False # # if bisiesto == True and int(mes) == 2 and int(dia) > 28: countError += 1 # # # #--------------Resultado if countError == 0: print ("La fecha es correcta") else: print("La fecha NO es correcta")
false
4a35f649b74b1103a6520c8d04551038636613ba
JRMfer/dataprocessing
/Homework/Week_3/convertCSV2JSON.py
695
4.34375
4
#!/usr/bin/env python # Name: Julien Fer # Student number: 10649441 # # This program reads a csv file and convert it to a JSON file. import csv import pandas as pd import json # global variable for CSV file INPUT_CSV = "unemployment.csv" def csv_reader(filename, columns): """ Loads csv file as dataframe and select columns to analyze """ data = pd.read_csv(filename) data = data[columns] return data def make_json(data): """ Coverts dataframe to JSON file with date as index """ data.set_index("DATE").to_json("data.json", orient="index") if __name__ == "__main__": data = csv_reader(INPUT_CSV, ["DATE", "UNEMPLOYMENT"]) make_json(data)
true
3152f88c91ac47190be22d71cc04623d4b8029ce
MarioAP/saturday
/sabadu/three.py
390
4.15625
4
# Create a variable containing a list my_list = ['ano', 'mario', 'nando', 'niko'] # print that list print my_list # print the length of that list print len(my_list) # add an element to that list my_variable = "hello world" my_list.append(my_variable) # print that list print my_list # print the length of that list print len(my_list) # print the first element in that list print my_list[0]
true
efccc9931fcb7b9594a54e383449557fa7a38ea7
PalakSaxena/PythonAssigment
/Python Program that displays which letters are in two strings but not in both.py
549
4.15625
4
List1 = [] List2 = [] def uncommon(List1, List2): for member in List1: if member not in List2: print(member) for member in List2: if member not in List1: print(member) num1 = int(input(" Enter Number of Elements in List 1 : ")) for i in range(0, num1): ele = int(input(" Enter Element : ")) List1.append(ele) num2 = int(input(" Enter Number of Elements in List 2 : ")) for i in range(0, num2): ele = int(input(" Enter Elements : ")) List2.append(ele) uncommon(List1, List2)
true
409615f7a9e1c85e8402fcde1e1ee1e3a20dcc78
spartus00/PythonTutorial
/lists.py
2,324
4.46875
4
#Showing items in the list food = ['fruit', 'vegetables', 'grains', 'legumes', 'snacks'] print(food) print(food[-2]) print(food[0:-2]) #Add an item to a list food.append('carbs') print(food) #Insert a new thing to a certain area in the list food.insert(-1, 'beverages') print(food) #Extend method - add the items from another list specific_food = ['lettuce', 'tomates'] food.extend(specific_food) print(food) #Remove items in the list food.remove('lettuce') print(food) popped = food.pop() print(popped) #Reverse a list food.reverse() print(food) #Sort a list in alphabetical order food.sort() print(food) num_sort = [4, 3, 6, 7, 2, 1 ] num_sort.sort() print(num_sort) #Sort values in descending order num_sort.sort(reverse=True) print(num_sort) #Get a sorted version of a list without changing the actual list sorted_food = sorted(food) #sorted is a function print(sorted_food) #Built in functions numbers = [7, 4, 2, 7, 1, 0, 9] print(min(numbers)) #min number of the list print(max(numbers)) print(sum(numbers)) #Find values in the list print(food) print(food.index('fruit')) #See if a value is in a list. The "in" operator is very important. print('cat' in food) print('grains' in food) #Looping through values using a for loop for item in food: print(item) #Index value we are on using enumerate for index, item in enumerate(food, start=1): print(index, item) #Turning lists into strings food_str = ', '.join(food) print(food_str) food_str = ' - '.join(food) print(food_str) new_food = food_str.split(' - ') print(new_food) #Tuples (cannot modify tuples) tuple_1 = ('fruit', 'vegetables', 'grains', 'legumes', 'snacks') tuple_2 = tuple_1 # tuple_1[0] = 'Cat food' print(tuple_1) #Sets (order can change) - Sets don't care about order. Throw away duplicates set_food = {'fruit', 'vegetables', 'grains', 'legumes', 'snacks'} print(set_food) print('fruit' in set_food) #Sets - compare set_food_2 = {'fruit', 'vegetables', 'grains', 'legumes', 'cat food'} print(set_food.intersection(set_food_2)) print(set_food.difference(set_food_2)) print(set_food.union(set_food_2)) #Create empty lists, tuples, and sets # Empty Lists empty_list = [] empty_list = list() # Empty Tuples empty_tuple = () empty_tuple = tuple() # Empty Sets empty_set = {} # This isn't right! It's a dict empty_set = set()
true
21e89e64e740ec1be94031ce46b3d0a5a4e3440e
lilleebelle/InformationTechnology
/calculator.py
683
4.34375
4
print("Welcome to the calculator, please input your 2 numbers and operator (e.g. *, /, +, -) when prompted") def restart(): num1 = float(input("Enter number 1: ")) num2 = float(input("Enter number 2: ")) op = input("Enter the operator: ") if op == "*": ans = num1 * num2 print(num1, op, num2, "=", ans) elif op == "/": ans = num1 / num2 print(num1, op, num2, "=", ans) elif op == "+": ans = num1 + num2 print(num1, op, num2, "=", ans) elif op == "-": ans = num1 - num2 print(num1, op, num2, "=", ans) else: print("Invalid operator entered") restart() restart()
false
11fdf182212f1cabf7d32f2e741890f7d18923f1
muyie77/Rock-Paper-Scissors
/RPS.py
2,528
4.1875
4
from random import randint from sys import exit # Function Declarations # Player def player(): while True: choice = int(input("> ")) if choice == 1: print("You have chosen Rock.") break elif choice == 2: print("You have chosen Paper.") break elif choice == 3: print("You have chosen Scissors.") break else: print("Invalid choice! Choose again.") return choice # Computer def computer(): choice = randint(1, 3) if choice == 1: print("Computer have chosen Rock.\n") elif choice == 2: print("Computer have chosen Paper.\n") else: print("Computer have chosen Scissors.\n") return choice # Comparing choice def compare(): win = 0 lose = 0 draw = 0 while True: print("--------------") print("| 1. Rock |\n| 2. Paper |\n| 3. Scissors|") print("--------------") user = player() ai = computer() if user == 1: # User chose Rock if ai == 1: # Computer chose Rock print("Draw!\n") draw += 1 elif ai == 2: # Computer chose Paper print("You lose!\n") lose += 1 else: # Computer chose Scissors print("You win!\n") win += 1 elif user == 2: # User chose Paper if ai == 1: # Computer chose Rock print("You win!\n") win += 1 elif ai == 2: # Computer chose Paper print("Draw!\n") draw += 1 else: # Computer chose Scissors print("You lose!\n") lose += 1 else: # User chose Scissors if ai == 1: # Computer chose Rock print("You lose!\n") lose += 1 elif ai == 2: # Computer chose Paper print("You win!\n") win += 1 else: # Computer chose Scissors print("Draw!\n") draw += 1 print(f"Win: {win}\tLose: {lose}\tDraw: {draw}") print("Do you want to play again? y/n") while True: ch = input("> ") if ch == 'y' or ch == 'Y': print("") """Play again""" break elif ch == 'n' or ch == 'N': exit(0) else: print("Invalid choice!\n") compare()
true
3fd9efdb51612106ecb7284f02490157906a7aaf
jitesh-cloud/password-guesser
/passGuesser.py
1,082
4.375
4
# importing random lib for checking out random pass from random import * # Taking a sample password from user to guess give_pass = input("Enter your password: ") # storing alphabet letter to use thm to crack password randomPass = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v', 'w', 'x', 'y', 'z'] # initializing an empty string actualguess = "" count = 0 # using loop to catch the give_pass by random guesses # it is also showing count of the passes while (actualguess != give_pass.lower()): actualguess = "" # generating random passwords using for loop for letter in range(len(give_pass)): guess_letter = randomPass[randint(0, 25)] actualguess = str(guess_letter) + str(actualguess) # printing guessed passwords print(actualguess,"-",count+1) count+=1 # printing the matched password print("--------------------------------------------------------") print("Your input is", give_pass,"-->","Your password is",actualguess)
true
a14555c06dd744a6178808ede70d913c8b8f67b4
innacroft/Python_codes
/Usefull_python2/iteracion.py
381
4.15625
4
for i in range(30): if i % 3 != 0: #si i no es exactamente divisible en 3 continue #sigue dentro de la iteracion else: # si i es divisible print(i**2) #i es elevado al cuadrado for i in range(30): if i % 3 == 0: # si i es exactamente divisible en 3 print(i**2) #i es elevado al cuadrado elif i==22: # si i es igual a 22 break #termina la iteracion
false
5da4f6ff26a580665ead28ed30b01cfc93cdf29a
devtony168/python-100-days-of-code
/day_09/main.py
861
4.15625
4
from replit import clear from art import logo #HINT: You can call clear() to clear the output in the console. print(logo) print("Welcome to the secret auction program!") bidders = {} def add_bid(): name = input("What is your name? ") # Key bid = int(input("What is your bid? $")) # Value bidders[name] = bid add_bidders = True add_bid() while add_bidders: result = input("Are there any other bidders? Enter 'yes' or 'no': ") if result == "no": add_bidders = False clear() elif result == "yes": add_bidders = True clear() add_bid() else: input("Invalid input. Press enter to continue. ") clear() highest_bid = 0 winner_name = "" for name in bidders: if bidders[name] > highest_bid: highest_bid = bidders[name] winner_name = name print(f"The winner is {winner_name} with a bid of ${highest_bid}!")
true
1ec0b788396ab26dc35aa550923315e61d2cd162
carlosescorche/pythoneando
/ex12.py
495
4.21875
4
#!/usr/bin/env python3 #nombre.capitalize() #nombre.upper() #nombre.title() #nombre.lower() while True: try: print("Escribe tu nombre de usuario") nombre = input(">") if not(len(nombre) > 6 and len(nombre) < 12): print('El nombre debe tener entre 6 a 12 caracteres') elif not nombre.isalnum(): print('El nombre debe ser alfanumerico') else: break except: print("Problema con el nombre ingresado")
false
9c37922b5a0ba496ebec6937fd53e37b495a7c33
carlosescorche/pythoneando
/teoria/06_listas.py
1,066
4.53125
5
#!/usr/bin/python #coding=utf-8 # Son los arrays o vectores de Python y son muy flexibles # Pueden contenter cualquier tipo de dato, incluso otras listas lista = [2, 0x13, False, "Una cadena de texto", [1, 7.0]] print(lista[0], type(lista[0])) print(lista[3], type(lista[3])) print(lista[4], type(lista[4])) #elemento de una lista mutidimensional print(lista[4][1], type(lista[4][1])) #las lista no son inmutables lista[1] = 10 print(lista) #accediendo al ultimo elemento print(lista[-1]) #slicing print(lista[:3]) print(lista[1:-1]) print(lista[::2]) #slicing con saltos #inserciones lista.append('será eliminado luego') #agregar el valor en la ultima posición print(lista) lista.insert(1,200) #inserta el elemento segun el index que indiques print(lista) #eliminar lista.remove(200) print(lista) #eliminar el ultimo elemento lista.pop() print(lista) #buscar print(200 in lista) print(2 in lista) #buscar index print(lista.index(2)) #cantidad de elementos print(len(lista)) #elemento minimo print(min(lista)) #elemento maximo print(max(lista))
false
1888175e01d6c4548fdd943699435df2d6d8ab44
TravisMWeaver/Programming-Languages
/ProblemSet5/SideEffects2.py
391
4.125
4
#!/usr/bin/python # Note that as arr1 is passed to changeList(), the values are being changed # within the function, not from the return of the function. As a result, this # behavior is indicative of a side effect. def changeList(arr): arr[0] = 9 arr[1] = 8 arr[2] = 7 arr[3] = 6 arr[4] = 5 return arr arr1 = [1, 2, 3, 4 , 5] arr2 = changeList(list(arr1)) print(arr1) print(arr2)
true
cffe973b153db29bc9b58010da4c7a0204a02169
bhanukirant99/AlgoExpert-1
/Arrays/TwoNumberSum.py
465
4.125
4
# time complexity = o(n) # space complexity = o(n) def twoNumberSum(array, targetSum): # Write your code here. dicti = {} for i in range(len(array)): diff = targetSum - array[i] # calculate diff between target and every other item in the array if diff in dicti: return ([diff, array[i]]) else: dicti[array[i]] = diff return [] # if the array has no element or just one element or if there was no pair then return the empty list
true
33db8dfb7183882637b43388002d68b16a61bda0
Travisivart/ADAPTS
/python/style.py
1,124
4.21875
4
class Style(object): """This class is used for the text formatting.""" def __init__(self): self.__purple = '\033[95m' self.__cyan = '\033[96m' self.__darkCyan = '\033[36m' self.__blue = '\033[94m' self.__green = '\033[92m' self.__yellow = '\033[93m' self.__red = '\033[91m' self.__bold = '\033[1m' self.__underline = '\033[4m' self.__terminate = '\033[0m' def setColor(self,color): if color == 'purple': return self.__purple elif color == 'cyan': return self.__cyan elif color == 'darkcyan': return self.__darkCyan elif color == 'blue': return self.__blue elif color == 'green': return self.__green elif color == 'yellow': return self.__yellow elif color == 'red': return self.__red else: return '' def setBold(self): return self.__bold def setUnderline(self): return self.__underline def end(self): return self.__terminate
false
b0545ce4169a0b4f176f128cc990001be3068ebe
QiuFeng54321/python_playground
/while/Q5.py
424
4.125
4
# Quest: 5. Input 5 numbers, # output the number of positive numbers and # negative number you have input i: int = 0 positives: int = 0 negatives: int = 0 while i < 5: num: float = float(input(f"Number {i + 1}: ")) if num >= 0: positives += 1 else: negatives += 1 i += 1 print(f"There are {positives} positive numbers and " f"{negatives} negative numbers")
true
25116ccdfd3d7e7663d1764544bbd3bc4de4a664
QiuFeng54321/python_playground
/loop_structure/edited_Q2.py
323
4.1875
4
# Quest: 2. Input integer x, # if it is an odd number, # output 'it is an odd number', # if it is an even number, # output 'it is an even number'. print( [ f"it is an {'odd' if x % 2 == 1 else 'even'} number" for x in [int(input("Input a number: "))] ][0] )
true
4136548b19ad2db621e1cf6c02379e17d60132fa
rodrigocode4/estudo-python
/prog_funcional/map.py
626
4.1875
4
from typing import List, Dict lista1: List[int] = [1, 2, 3] dobro: map = map(lambda x: x * 2, lista1) print(list(dobro)) lista2: List[Dict[str, int]] = [ {'nome': 'João', 'idade': 31}, {'nome': 'Maria', 'idade': 37}, {'nome': 'José', 'idade': 26} ] so_nomes: List[str] = list(map(lambda n: n['nome'], lista2)) print(so_nomes) so_idades: List[int] = list(map(lambda i: i['idade'], lista2)) print(so_idades) # Desafio: usuando map, retorne a frase: '<Nome> tem <idade> anos.' frases: List[str] = list( map( lambda f: f"{f['nome']} tem {f['idade']} anos.", lista2 ) ) print(frases)
false
6ed9d9b9a39a91941c3c9ce522a9b2427b922be5
koushikbhushan/python_space
/Arrays/replce_next_greatest.py
562
4.28125
4
"""Replace every element with the greatest element on right side Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is {16, 17, 4, 3, 5, 2}, then it should be modified to {17, 5, 5, 5, 2, -1}. """ arr = [16, 17, 4, 3, 5, 2] arr_length = len(arr) i = arr_length - 1 max = -1 print(i) while i >= 0: temp = arr[i] arr[i] = max if temp > max: max = temp i = i-1 print(arr)
true
2d157098f1f22a0940dd413d5459cd8e6027fc0b
mikaylakonst/ExampleCode
/loops.py
1,222
4.375
4
# This is a for loop. # x takes on the values 0, 1, 2, 3, and 4. # The left end of the range is inclusive. # The right end of the range is exclusive. # In other words, the range is [0, 5). for x in range(0, 5): print(x) # This is another for loop. # x takes on the values 0, 1, 2, 3, and 4. In other words, # x takes on all values between 0 (inclusive) and 5 (exclusive). # This loop is equivalent to the for loop above # and prints the exact same thing. for x in range(5): print(x) # This for loop does the same thing as the other ones. # x goes from 0 to 5 by steps of size +1. # As before, the 0 is inclusive and the 5 is exclusive, # so x takes on the values 0, 1, 2, 3, and 4. for x in range(0, 5, 1): print(x) # This is a while loop. # Every time the loop executes, # x is printed, and then x is increased by 1. # x takes on the values 0, 1, 2, 3, and 4. # This loop does the same thing as the for loop above. x = 0 while x < 5: print(x) x = x + 1 # This is also a while loop. # A loop that starts with while True # will run forever unless it is broken # by a break statement. # This loop does the same thing as the loops above. x = 0 while True: print(x) x = x + 1 if x >= 5: break
true
b4b3197fdd4fbea2e6b219e55e4bd87653123005
Nishith/Katas
/prime_factors.py
879
4.21875
4
import sys """List of primes that we have seen""" primes = [2] def generate(num): """Returns the list of prime factors for the given argument Arguments: - `num`: Integer Returns: List of prime factors of num """ factors = [] if num < 2: return factors loop = 2 while loop < num: if num % loop == 0 and is_prime(loop): while(num % loop == 0): num /= loop factors.append(loop) loop = loop + 1 factors.sort() return factors def is_prime(n): """ Checks whether the given number is a prime """ if n in primes: return 1 if n % 2 == 0: return 0 for i in range(3, n//2 + 1, 2): if n % i == 0: return 0 primes.append(n) return 1 if __name__ == '__main__': print(generate(sys.maxsize))
true
c355a311ae7d97d282cf9c5788d05d77e6a9de83
pruty20/100daysofcode-with-python-course
/days/01-03-datetimes/code/Challenges/challenges_3_yo.py
1,743
4.28125
4
# https://codechalleng.es/bites/128/ from datetime import datetime from time import strptime, strftime THIS_YEAR = 2018 """ In this Bite you get some more practice with datetime's useful strptime and stftime. Complete the two functions: years_ago and convert_eu_to_us_date following the instructions in their docstrings. This is the defintion and difference between the two: - strptime: parse (convert) string to datetime object. - strftime: create formatted string for given time/date/datetime object according to specified format. Reference: 8.1.8. strftime() and strptime() Behavior. Link: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior Good luck and keep calm and code in Python! """ def years_ago(date): """Receives a date string of 'DD MMM, YYYY', for example: 8 Aug, 2015 Convert this date str to a datetime object (use strptime). Then extract the year from the obtained datetime object and subtract it from the THIS_YEAR constant above, returning the int difference. So in this example you would get: 2018 - 2015 = 3""" date_parsed = strptime(date, '%d %b, %Y') year = date_parsed.tm_year return THIS_YEAR - year def convert_eu_to_us_date(date="08/12/2015"): """Receives a date string in European format of dd/mm/yyyy, e.g. 11/03/2002 Convert it to an American date: mm/dd/yyyy (in this case 03/11/2002). To enforce the use of datetime's strptime / strftime (over slicing) the tests check if a ValueError is raised for invalid day/month/year ranges (no need to code this, datetime does this out of the box)""" dt = datetime.strptime(date, "%d/%m/%Y") return dt.strftime("%m/%d/%Y") convert_eu_to_us_date()
true
c7f351833cc35883cbc542a76d6659a112607a93
kiddlu/kdstack
/python/programiz-examples/flow-control/if-else.py
1,415
4.53125
5
#!/usr/bin/env python num = 3 if num > 0: print(num, "is a positive number.") print("This is always printed.") num = 1 if not num <= 0: print(num, "is a positive number.") print("This is also always printed.") num = 3 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") #num = int(input("\nEnter a number: ")) if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) year = int(input("\nEnter one year: ")) # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) # change the values of num1, num2 and num3 # for a different result num1 = 10 num2 = 14 num3 = 12 # uncomment following lines to take three numbers from user #num1 = float(input("Enter first number: ")) #num2 = float(input("Enter second number: ")) #num3 = float(input("Enter third number: ")) if (num1 > num2) and (num1 > num3): largest = num1 elif (num2 > num1) and (num2 > num3): largest = num2 else: largest = num3 print("The largest number between",num1,",",num2,"and",num3,"is",largest)
true
d479ed7e914735945533234370a43ae829a26d3b
demidenko-svetlana/lesson1
/task6.py
471
4.125
4
weather = { "city": "Moscow", "temperature": 20 } print(weather["city"]) weather["temperature"] = weather["temperature"] - 5 #print(weather) #print(weather.get("country")) #print(weather.get("country","Russia")) # не меняется словарь,просто устанавливается дефолтно, но не добавляет weather.update({ "country":"Russia" }) weather["district"] = "South" weather["date"] = "27.05.19" print(len(weather))
false
b5ca219951a291a323d3e93c8b2c46369de54ba9
alex99q/python3-lab-exercises
/Lab2/Exercise5.py
676
4.15625
4
range_start = int(input("Beginning of interval: ")) range_end = int(input("End of interval: ")) if range_start < range_end: for num in range(range_start, range_end + 1): if 0 < num < 10: print(num) continue elif 10 <= num < 100: continue else: power_of_armstrong_num = len(str(num)) armstrong_num = 0 for digit in str(num): armstrong_num += pow(int(digit), int(power_of_armstrong_num)) if num == armstrong_num: print(armstrong_num) else: print("End of interval can't be higher than beginning of interval")
true
87f1b7e450c3fe5e0f9e5457c16cd83e2718d13a
atasky/Python-data-structures-and-algorithms
/Arrays/array rotation - right
627
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 6 13:43:36 2019 @author: vaidehee_barde """ #function to rotate an array on right def rotateRight(arr,d): for i in range(d): rotateRightByOne(arr) #function to rotate the array on right by one def rotateRightByOne(arr): n=len(arr) temp=arr[n-1] for i in range(n-1,0,-1): arr[i]=arr[i-1] arr[0]=temp #function to print an array def printArray(arr): for i in range(len(arr)): print("%d" %arr[i], end=" ") #driver function arr=[1,2,3,4,5] rotateRight(arr, 2) printArray(arr) #output #4 5 1 2 3
false
3a5ac90e5105ef1d1be19c786f79f553dfc5b7db
honda0306/Intro-Python
/src/dicts.py
382
4.21875
4
# Make an array of dictionaries. Each dictionary should have keys: # # lat: the latitude # lon: the longitude # name: the waypoint name # # Make up three entries of various values. waypoints = [ {'hometown': 'Rescue, CA'}, {'age': 42}, {'hobbies': 'smiling'} ] # Write a loop that prints out all the field values for all the waypoints for i in waypoints: print(i)
true
347b668776a32e4010be76e875743cc75b80c6e0
shefali1310/Python_Practice
/basic_calculator.py
501
4.34375
4
num_1 = int(raw_input("Enter your first number: ")) num_2 = int(raw_input("Enter your second number: ")) operator = raw_input("Enter the arithmetic operator you wish to perform on your entered numbers: ") if operator == "+" : print num_1 + num_2 elif operator == "-" : if num_1>num_2 : print num_1 - num_2 else: print num_2 - num_1 elif operator == "/" : print num_1 / num_2 elif operator == "*" : print num_1 * num_2 elif operator == "%" : print num_1 % num_2
false
7c1667f2c28599a74f27953fa8752f8162e05987
krishia2bello/N.B-Mi-Ma-Sorting-Algorithm
/NB_MiMa_Sorting_Algorithm.py
2,046
4.34375
4
def sort_list(list_of_integers): list_input = list_of_integers # copying the input list for execution sorted_list = [] # defining the new(sorted) list min_index = 0 # defining the index of the minimum value to be inserted in the new list max_index = 1 # defining the index of the maximum value to be inserted in the new list while len(list_input) != 0: # while there is still an integer in the input list sorted_list.insert(min_index, min(list_input)) # inserting the least value of the input list to the new list list_input.remove(min(list_input)) # removing what was inserted from the previous line min_index = min_index + 1 # setting the next index of the least value to be inserted in the new list if len(list_input) != 0: # if there are still integers in the list remaining sorted_list.insert(max_index, max(list_input)) # insert the greatest value of the input list to the new list list_input.remove(max(list_input)) # removing what was inserted from the previous line max_index = max_index + 1 # setting the next index of the greatest value to be inserted in the new list return sorted_list # returning the new list as output print(Test Cases!) # empty list, sort_list([]) # expect [] # even length, sort_list([4, 3, 2, 1]) # expect 1 2 3 4 # odd length, sort_list([2, 3, 4, 5, 1]) # expect 1 2 3 4 5 # consist of positive and negative integer values, sort_list([3, -3, 2, -2, 1, 0, -1 ]) # expect -3 -2 -1 0 1 2 3 # consist of integers having the same value in the list, sort_list([10, -3, 0, 6, 4, 5, 2, 7, 3, 1, -1, 8, 7, 9, -2, -3, 10, 2]) # expect -3 -3 -2 -1 0 1 2 2 3 4 5 6 7 7 8 9 10 10
true
a333e519c0b53b1649c07102417a38ae4f13c8a5
Ler4onok/ZAL
/3-Calculator/calculator.py
2,010
4.21875
4
import math def addition(x, y): addition_result = x + y return addition_result def subtraction(x, y): subtraction_result = x - y return subtraction_result def multiplication(x, y): # multiplication_result = args[0]*args[1] multiplication_result = x * y return multiplication_result def division(x, y): if y != 0: division_result = x/y return division_result else: raise ValueError('This operation is not supported for given input parameters') def modulo(x, y): if 0 < y <= x: modulo_result = x % y return modulo_result else: raise ValueError('This operation is not supported for given input parameters') def secondPower(x): secondPower_result = x * x return secondPower_result def power(x, y): if y >= 0: power_result = x ** y return float(power_result) else: raise ValueError('This operation is not supported for given input parameters') def secondRadix(x): if x > 0: secondRadix_result = math.sqrt(x) return secondRadix_result else: raise ValueError('This operation is not supported for given input parameters') def magic(x, y, z, k): l = x + k m = y + z if m == 0: raise ValueError('This operation is not supported for given input parameters') z = ((l/m) + 1) return z def control(a, x, y, z, k): if a == 'ADDITION': return addition(x, y) elif a == 'SUBTRACTION': return subtraction(x, y) elif a == 'MULTIPLICATION': return multiplication(x, y) elif a == 'DIVISION': return division(x, y) elif a == 'MOD': return modulo(x, y) elif a == 'POWER': return power(x, y) elif a == 'SECONDRADIX': return secondRadix(x) elif a == 'MAGIC': return magic(x, y, z, k) else: raise ValueError('This operation is not supported for given input parameters') #print (control('SECONDRADIX', -3, 1, 1, 1))
true
55873f77d5e19e886a182236b4658eee94b21ec2
clairepeng0808/Python-100
/07_mortgage:-calculator.py
2,756
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 9 18:04:17 2020 @author: clairepeng Mortgage Calculator - Calculate the monthly payments of a f ixed term mortgage over given Nth terms at a given interest rate. Also figure out how long it will take the user to pay back the loan. For added complexity, add an option for users to select the compounding interval (Monthly, Weekly, Daily, Continually). """ print('Welcome to mortgage Calculator!') def enter_terms(): while True: try: terms = int(input('Enter the morgage term(in years): ')) if terms >= 50: print('Sorry, the term should be under 50 years.') elif terms <= 0: print('The term should be a positive integer.') continue else: return terms break except ValueError: print('Please enter an integer.') def enter_rate(): while True: try: rate = float(input('Enter the interest rate(%): ')) if rate > 100: print('Sorry, the rate should be under 100.') continue elif rate < 0: print('Sorry, the rate should be a positive number.') continue else: return rate break except ValueError: print('Please enter a valid number.') def enter_loan(): while True: try: loan = float(input('Enter the loan(in dollars): ')) if loan < 10000: print('Sorry, the minimum loan is 10000 dollars.') continue elif loan < 0: print('Sorry, the loan should be a positive number.') continue else: return loan break except ValueError: print('Please enter a valid number.') if __name__ == '__main__': terms = enter_terms() rate = enter_rate() loan = enter_loan() monthly_rate = rate / 12 /100 months = terms * 12 monthly_payback_rate = (((1 + monthly_rate) ** months) * monthly_rate) / ((( 1 + monthly_rate) ** months) -1) monthly_payment = loan * monthly_payback_rate # 每月應付本息金額之平均攤還率= # {[(1+月利率)^月數]×月利率}÷{[(1+月利率)^月數]-1} # 平均每月應攤付本息金額=貸款本金×每月應付本息金額之平均攤還率 print(f'Your monthly payment is {monthly_payment:.2f} dollars.')
true
4f483712e0265702305407df328a349d9ad00b84
clairepeng0808/Python-100
/08_change_return_program.py
2,610
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 9 18:53:27 2020 @author: clairepeng Change Return Program - The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. """ def enter_cost(): while True: try: cost = round(float(input('Please enter the cost.')),2) if cost <= 0: print('The cost must be a positive number!') continue else: return cost break except ValueError: print('Please enter a number.') continue def enter_paid(): while True: try: paid = round(float(input('Please enter the money you paid.')),2) if paid < cost: print('\nYour paid amount must exceed the cost.') continue else: return paid break except ValueError: print('Please enter a number.') continue if __name__ == '__main__': print('Welcome to the change return program!') while True: cost = enter_cost() paid = enter_paid() change = paid - cost if change >= 1: print('Error! The change must be under 1 dollar.') continue elif change < 0: print('Error! Your paid amount must exceed your cost.') elif change == 0: print("There's no change.") break else: # Tony's solution coins = [0.25, 0.1, 0.05, 0.01] used = [] left = change for c in coins: c_used = left // c left -= ((c_used) * c) used.append(c_used) # Claire's solution quarters = change // 0.25 # left = (change % 0.25) dimes = (change % 0.25) // 0.1 # left = (change % 0.25) % 0.1 nickles = ((change % 0.25) % 0.1) // 0.05 # left = (left % 0.05) % 0.1 pennies = (round((((change % 0.25) % 0.1) % 0.05),2) // 0.01) print(f'You will receive {change:.2f} dollars in change.') print(f'You will get {quarters:.0f} quarters, {dimes:.0f} dimes, {nickles:.0f} nickles, and {pennies:.0f} pennies.') break
true
0932555326668cc6127d1d4b3adfe644e6da19f8
clairepeng0808/Python-100
/37_check_if_palindrome.py
753
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 27 15:52:44 2020 @author: clairepeng **Check if Palindrome** - Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar” """ from utility import utility as util def enter_string(): string = input('Enter a string: ').lower() return string def check_palindrome(string): return string[:] == string[::-1] while True: string = enter_string() if check_palindrome(string): print(f'Congrats! The string \'{string}\' is a palindrome.') else: print(f'Sorry, the string \'{string}\' is not a palindrome.') if not util.replay(): break
true
2413e3107fbf48938c305f595a678c8ab1b5dbaa
thuytran100401/HW-Python
/multiply.py
549
4.28125
4
""" Python program to take in a list as input and multiply all of the elements in the list and return the result as output. Parameter inputList: list[] the integer list as input result: int the result of multiplying all of the element """ def multiply_list(inputList): result = 1; for i in range(0, len(inputList)): try: int(inputList[i]) except: return False for number in inputList: result = result * int(number) return result
true
606ec0c1d44fbbf5bdf56fe859f20d96fbb91a22
SamCadet/PythonScratchWork
/bitwiseExample.py
291
4.3125
4
# Python program to show # shift operators a = 10 b = -10 # print bitwise right shift operator print("a >> 1 =", a >> 1) print("b >> 1 =", b >> 1) a = 5 b = -10 # print bitwise left shift operator print("a << 1 =", a << 1) print("b << 1 =", b << 1) x = 10 print(bin(x)) print(bin(~x))
false
871e54ac66b3349a0e66a0117f4a800177f18a2b
SamCadet/PythonScratchWork
/Birthdays.py
494
4.21875
4
birthdays = {'Rebecca': 'July 1', 'Michael': 'July 22', 'Mom': 'August 22'} while True: print('Enter a name: (blank to quit)') name = input() if name == '': break if name in birthdays: print(birthdays[name] + ' is ' + str(name) + '\'s birthday.') else: print('I do not have birthday information for ' + name) print('What is their birthday?') bday = input() birthdays[name] = bday print('Birthday database updated.')
true
8088d914ee796784cd7284818541f31d4a0bd0ef
Jhordancito/Python
/Generadores.py
2,109
4.125
4
#def generaPares(limite): # num=1 # miLista=[] #Creamos una lista vacia # while num<limite: # miLista.append(num*2) #Agregamos un numero a la lista en este caso 1*2 # num=num+1 #return miLista #print(generaPares(10)) #CON GENERADOR Ejercicio 1 def generaPares(limite): num=1 while num<limite: yield num*2 # yield almacena el numero del generador num=num+1 devuelvePares=generaPares(10) #Almacenamor¿s la funcion en una variable #for i in devuelvePares: # print(i) #Muestra en lista los numeros print(next(devuelvePares)) #next Imprime sel primer un numero del generador print("Aqui podria ir mas código...") print(next(devuelvePares)) #Imprime el segundo numero del generador print("Aqui podria ir mas código...") print(next(devuelvePares)) #Imprime el tercer numero generado #Ejercicio 2 para Sacar frase por frase def devuelve_ciudades(*ciudades): #recibira un numero indeterminado de elementos y sera en forma de tupla for elemento in ciudades: yield elemento #Genrador va contando de frase a frase ciudades_devueltas=devuelve_ciudades("Madrid", "Barcelona", "Bilbao", "Valencia") print(next(ciudades_devueltas)) #Imprime la primera frase print(next(ciudades_devueltas)) #Imprime la segunda frase #Ejercicio 3 para Sacar letra por letra def devuelve_ciudades(*ciudades): #recibira un numero indeterminado de elementos y sera en forma de tupla for elemento in ciudades: for Subelemento in elemento: yield elemento #Genrador va contando de letra en letra ciudades_devueltas=devuelve_ciudades("Madrid", "Barcelona", "Bilbao", "Valencia") print(next(ciudades_devueltas)) #Imprime la primera letra print(next(ciudades_devueltas)) #Imprime la segunda letra # Utilizamos el yield from para sacar la lista de palabra a palabra #for elemento in ciudades: # for Subelemento in elemento: # yield elemento #Genrador va contando de letra en letra #En vez de esto simplicamos de la siguiente manera #for elemento in ciudades: # yield from elemento
false
92e5f2a01a7b56de9d54bf8a70258e3d8598f6e8
Jhordancito/Python
/sentenciaFor.py
1,714
4.21875
4
#for i in [1,2,3]: #for cuenta los elementos ya sea caracteres o cualquier simbolo #print("Hola") imprime 3 veces HOLA #for i in ["Primaver","Verani","Otoño","Invierno"]: #for cuenta los elementos ya sea caracteres o cualquier simbolo #print("i") //muestra todos las estaciones del año #for i in ["Pildoras", "Informaticas", 3]: # print("Hola", end=" ") #Imprime hola seguido si le damos espacio repetira hola, hola ,hola #Ejemplo de for #email = False #for i in "Juan@oildorasinformaticas.es": # if(i=="@"): # email=True #if email == True: # print("Email es correcto") #else: # print("El email no es correcto") #Ejemplo2 de for #email = False #miemail=input("Introduce tu dirección Email: ") #for i in miemail: # if(i=="@"): # miemail=True #if miemail == True: # print("Email es correcto") #else: # print("El email no es correcto") #Ejemplo3 de for #contador = 0 #miemail=input("Introduce tu dirección Email: ") #for i in miemail: # if(i=="@" or i=="."): # contador = contador+1 #if contador == 2: # print("Email es correcto") #else: # print("El email no es correcto") #for i in range(5): #range es como el array almacena los datos en este caso seria 0,1,2,3,4, #range(5,10) comienza en 5 y termina en 10 #range(5,50,3) contea los numeros desde el 5 y va de 3 en 3 hasta el 50 # print(f"valor de la variable {i}") #valido=False #email=input("Introduce tu Email: ") #for i in range(len(email)): #saca la cantidad de letras q se introduce como 0,1,2,3 # if email[i]=="@": #Verifica si en un de sus almacenados tiene la letra @ # valido =True #if valido: # print("Email correcto") #else: # print("Email incorrecto")
false
c72c90e0c2dfe865eab1d40b99073a8e757cca95
taharBakir/code_cademy-python
/string_stuff.py
1,121
4.375
4
#Print a s="Hella"[4] print s #Print the length of the string parrot = "Norwegian Blue" print len(parrot) #Print the string in lower case parrot = "Norwegian Blue" print parrot.lower() #Print the string in upper case parrot = "norwegian blue" print parrot.upper() #toString pi = 3.14 print str(pi) #Methods that use dot notation only work with strings. #On the other hand, len() and str() can work on other data types. ministry = "The Ministry of Silly Walks" print len(ministry) print ministry.upper() print "Spam\n" + "and\n" + "eggs" print "The value of pi is around " + str(3.14) '''The % operator after a string is used to combine a string with variables. The % operator will replace a %s in the string with the string variable that comes after it. ''' string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) name = raw_input("What is your name? ") quest = raw_input("What is your quest? ") color = raw_input("What is your favorite color? ") print "Ah, so your name is %s, your quest is %s, " \ "and your favorite color is %s." % (name, quest, color)
true
ccebdf820de15e6ff5c5e06b20fa75bbd06448f9
mitchell-hardy/CP1404-Practicals
/Week 3/asciiTable.py
1,280
4.125
4
__author__ = 'Mitch Hardy' def main(): NUMBER_MINIMUM = 33 NUMBER_MAXIMUM = 127 # get a number from the user (ASCII) and print the corresponding character. user_number = get_number(NUMBER_MINIMUM, NUMBER_MAXIMUM) # get a character from the user and print the corresponding ASCII key print("The character for {} is {}".format(user_number, chr(user_number))) user_character = str(input("Enter a character: ")) print("The ASCII code for {} is {}".format(user_character,ord(user_character))) for i in range(NUMBER_MINIMUM, NUMBER_MAXIMUM): print("{:^10d}{:^10s}".format(i, chr(i))) # Get a number from the user, error check and return to main. def get_number(NUMBER_MINIMUM, NUMBER_MAXIMUM): number = int(input("Enter a number between {} and {}: ".format(NUMBER_MINIMUM, NUMBER_MAXIMUM))) while number < NUMBER_MINIMUM or number > NUMBER_MAXIMUM: try: print("Invalid number, please choose from between {} and {}:".format(NUMBER_MINIMUM, NUMBER_MAXIMUM)) number = int(input("Enter a number between {} and {}: ".format(NUMBER_MINIMUM, NUMBER_MAXIMUM))) except: number = ValueError number = 0 print("Please only enter numbers!") return number main()
true
a48c5ea84c3d9d6a8af8517150977ae2c99b8ad7
abhisheknm99/APS-2020
/52-Cartesian_product.py
245
4.3125
4
from itertools import product #only with one list arr=[1,2,3] #repeat=2 i.e arr*,repeat=3 i.e arr*arr*arr l=list(product(arr,repeat=3)) #different arrays arr1=[1,2,3] arr2=[2,3] arr3=[3] cartesian=list(product(arr1,arr2,arr3)) print(cartesian)
true
3e05e88a61f112f293f4efb6a0a81f63e0909410
abdullahw1/CMPE131_hw2
/calculator.py
1,529
4.46875
4
def calculator(number1, number2, operator): """ This function will allow to make simple calculations with 2 numbers parameters ---------- number1 : float number2 : float operator : string Returns ------- float """ # "+" operator will perform addition if operator == "+": print(number1 + number2) # else if "-" operator used, then subtraction performed elif operator == "-": print(number1 - number2) # else if "*" operator used, multiplication will be performed elif operator == "*": print(number1 * number2) # else if "/" operator is used, division performed elif operator == "/": # return false if num2 is 0 as result wont exist print(number1 / number2) # perform integral division with "//" operator elif operator == "//": print(number1 // number2) # else perform power operation with "**" operator elif operator == "**": print(number1 ** number2) def parse_input(): """ gets user input and splits. This function splits user input into number1, number2, and operator. passes variables to calculator() function. """ EquatOutout = input("Enter Equation: ") equat = EquatOutout.split() number1, operator, number2 = equat number1 = float(number1) number2 = float(number2) # pass user input to calculator() function return(calculator(number1, number2, operator)) #parse_input()
true
872fe63e47975aaf586df582e37aced46ed5f8c2
ZY1N/Pythonforinfomatics
/ch9/9_4.py
940
4.28125
4
#Exercise 9.4 Write a program to read through a mail log, and figure out who had #the most messages in the file. The program looks for From lines and takes the #second parameter on those lines as the person who sent the mail. #The program creates a Python dictionary that maps the senders address to the total #number of messages for that person. #After all the data has been read the program looks through the dictionary using #a maximum loop (see Section 5.7.2) to find who has the most messages and how #many messages the person has. fname = raw_input("Enter a file name : ") handle = open(fname) dictionary = dict() for line in handle: words = line.split() if "From" in words: dictionary[words[1]] = dictionary.get(words[1], 0) + 1 largest = None for element in dictionary: if largest == None or element > largest: largest = element print largest print 'Largest :', largest, dictionary [largest]
true
d33211f78829e397346809c11dd08ea732d61363
ZY1N/Pythonforinfomatics
/ch11/11_1.py
491
4.15625
4
#Exercise 11.1 Write a simple program to simulate the operation of the the grep #command on UNIX. Ask the user to enter a regular expression and count the number of lines that matched the regular expression: import re fname = open('mbox.txt') rexp = raw_input("Enter a regular expression : ") count = 0 for line in fname: line = line.rstrip() x = re.findall(rexp, line) if len(x) > 0: count = count + 1 print "mbox.txt had %d lines that matched %s" % (count, rexp)
true