blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
330654c09eb6cbb1f913f2734102f51b225c8bcd
oneyedananas/learning
/for Loops.py
553
4.5
4
# performs code on each item in a list i.e. iteration. loops are a construct which can iterate through a list. # uses a while loop and a counter variable words = ["milda", "petr", "karel", "pavel"] counter = 0 max_index = len(words) - 1 # python starts counting from 0 so -1 is needed # print(max_index) now returns 3: range of the list - 1 while counter <= max_index: word = words[counter] # take appropriate string from the list 'words' print(word + "!") # concatenation counter = counter + 1 # so that we can move to the next item
true
0685f623b4f9cb897a13d09f537b410e4bf76868
apranav19/FP_With_Python
/map_example.py
499
4.40625
4
""" Some simple examples that make use of the map function """ def get_name_lengths(names): """ Returns a list of name lengths """ return list(map(len, names)) def get_hashed_names(names): """ Returns a list of hashed names """ return list(map(hash, names)) if __name__ == '__main__': people = ["Mary", "Isla", "Sam"] print("Length of names: " + str(get_name_lengths(people))) print("=================") print("Hashed Names: " + str(get_hashed_names(people))) print("=================")
true
fe4ba27c40751233f94c4468944fd300c65ac1f8
luizpericolo/PythonProjects
/Text/count_words.py
793
4.46875
4
# Count Words in a String - Counts the number of individual words in a string. For added complexity read these strings in from a text file and generate a summary. string = '' while string.upper() != 'QUIT': string = raw_input("Enter a text to get a summary of strings or 'quit' to exit: ") if string.upper() != 'QUIT': words = {} symbols = [',', '.', '!', '?', '@', '#', '$', '%', '&', '*', '(', ')', '-', '+', '/', '\\', '{', '}'] for word in string.split(' '): if word != ' ': for symbol in symbols: if word.find(symbol): word = word.replace(symbol, '') if word not in words: words[word] = 1 else: words[word] += 1 for word, count in words.iteritems(): print "Word '{0}' appeared {1} time(s) in the text.".format(word, count) print 'Bbye!'
true
54c7954e9b17b56aff806ec9f0ba48216e308f9a
IncapableFury/Triangle_Testing
/triangle.py
2,034
4.25
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 13:44:00 2016 Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple python program to classify triangles @author: jrr @author: rk @ """ def classify_triangle(side1: int, side2: int, side3: int) -> str: """ Your correct code goes here... Fix the faulty logic below until the code passes all of you test cases. This function returns side1 string with the type of triangle from three integer values corresponding to the lengths of the three sides of the Triangle. return: If all three sides are equal, return 'Equilateral' If exactly one pair of sides are equal, return 'Isoceles' If no pair of sides are equal, return 'Scalene' If not side1 valid triangle, then return 'NotATriangle' If the sum of any two sides equals the squate of the third side, then concatenate result with 'Right' BEWARE: there may be side1 bug or two in this code """ def check_if_right(side1, side2, side3, epsilon=0.001): return abs(1 - (side1 * side1 + side2 * side2) / (side3 * side3)) < epsilon # require that the input values be >= 0 and <= 200 and have type integer if side1 > 200 or side2 > 200 or side3 > 200: return 'InvalidInput' if side1 <= 0 or side2 <= 0 or side3 <= 0: return 'InvalidInput' if not (isinstance(side1, int) and isinstance(side2, int) and isinstance(side3, int)): return 'InvalidInput' # now we know that we have side1 valid triangle (side1, side2, side3,) = sorted([side1, side2, side3]) # side1<side2<c if not side1 + side2 > side3: return "NotATriangle" is_right = check_if_right(side1, side2, side3) if side1 == side2 == side3: triangle_type = "Equilateral" elif side1 == side2 or side2 == side3 or side1 == side3: triangle_type = "Isoceles" else: triangle_type = "Scalene" return triangle_type + "+Right" if is_right else triangle_type
true
d0935a48ad03c078bcb50b9adef38fa64e53df8f
cdueltgen/markov_exercise
/markov.py
1,053
4.28125
4
""" markov.py Reference text: section 13.8, how to think like a computer scientist Do markov analysis of a text and produce mimic text based off the original. Markov analysis consists of taking a text, and producing a mapping of prefixes to suffixes. A prefix consists of one or more words, and the next word to follow the prefix in the text. Note, a prefix can have more than one suffix. Eg: markov analysis with a prefix length of '1' Original text: "The quick brown fox jumped over the lazy dog" "the": ["quick", "lazy"] "quick": ["brown"] "brown": ["fox"] "fox": ["jumped"] ... etc. With this, you can reassemble a random text similar to the original style by choosing a random prefix and one of its suffixes, then using that suffix as a prefix and repeating the process. You will write a program that performs markov analysis on a text file, then produce random text from the analysis. The length of the markov prefixes will be adjustable, as will the length of the output produced. """
true
e4e4d1aa65cca834a26d27edd85da4a0543a96f7
NYU-Python-Intermediate-Legacy/jarnold-ipy-solutions
/jarnold-2.2.py
2,270
4.15625
4
#usr/bin/python2.7 import os import sys def unique_cities(cities): # get rid of empty items if cities.has_key(''): del cities[''] unique_cities = sorted(set(cities.keys())) return unique_cities def top_ten_countries(countries): # get rid of empty items if countries.has_key(''): del countries[''] # sort by integer of value top_ten_countries = sorted(countries, key=lambda i: int(countries[i]), reverse=True) return top_ten_countries[0:9] def top_ten_machine_names(machine_names): # get rid of empty items if machine_names.has_key(''): del machine_names[''] # sort by integer of value top_ten_machine_names = sorted(machine_names, key=lambda i: int(machine_names[i]), reverse=True) return top_ten_machine_names[0:9] # find out what info the user wants def what_would_you_like(cities, countries, machine_names): print """What information would you like from the bit.ly data? a) A set of unique cities b) The top ten most popular country codes c) The top ten most popular machine names """ answer = raw_input("Please type the letter name of your selection: ") if answer == "a": print unique_cities(cities) elif answer == "b": print top_ten_countries(countries) elif answer == "c": print top_ten_machine_names(machine_names) else: print "Sorry, I didn't get that answer" # recursively calls itself to run the prompt again what_would_you_like(cities, countries, machine_names) def main(): # set up empty dicts cities = {} countries = {} machine_names = {} # get the data from the tsv for line in open('bitly.tsv').readlines()[1:]: elements = line.strip('\n\s').split('\t') # read the data into the dictionaries try: city = elements[3] country = elements[4] machine_name = elements[2].split('/')[2] if city in cities: cities[city] += 1 else: cities[city] = 1 if country in countries: countries[country] += 1 else: countries[country] = 1 if machine_name in machine_names: machine_names[machine_name] += 1 else: machine_names[machine_name] = 1 # keep going if the information isn't found except: continue # provide data to user what_would_you_like(cities, countries, machine_names) main()
true
424c14cc7e7547593ae9bf715e78108b363d2cc3
ZuzaRatajczyk/Zookeeper
/Problems/Lucky ticket/task.py
466
4.125
4
# Save the input in this variable ticket = (input()) first_digit = int(ticket[0]) second_digit = int(ticket[1]) third_digit = int(ticket[2]) fourth_digit = int(ticket[3]) fifth_digit = int(ticket[4]) sixth_digit = int(ticket[5]) # Add up the digits for each half half1 = first_digit + second_digit + third_digit half2 = fourth_digit + fifth_digit + sixth_digit # Thanks to you, this code will work if half1 == half2: print("Lucky") else: print("Ordinary")
true
8da21b78fd90a65b70bb461f0370564724ab1dc8
ckabuloglu/interview_prep
/levelOrder.py
939
4.15625
4
''' Level Order Traversal Given a binary tree, print the nodes in order of levels (left to right for same level) ''' # Define the Tree structure class BSTNode: def __init__(self, val): self.val = val self.left = None self.right = None # Define the add method to add nodes to the tree def add(root, val): if not root: return BSTNode(val) elif root.val < val: root.right = add(root.right, val) else: root.left = add(root.left, val) return root # Define the function that print the level order tree Traversal def levelOrder(root): queue = [root] levels = [] while queue: current = queue.pop(0) if current: levels.append(current.val) queue.append(current.left) queue.append(current.right) else: levels.append(None) return levels # Define the trees and test cases a = BSTNode(4) add(a, 3) add(a, 1) print levelOrder(a)
true
2c50bed4074123edcc2f4feab539c300a65071be
Garrison50/unit-2-brid
/2.3 Vol/SA.py
279
4.15625
4
def main(): import math radius = float(input("Enter the radius of the sphere")) volume = ((4/3) * math.pi * (pow(radius,3))) sa = (4 * math.pi * (pow(radius,2))) print ("The volume is:", round(volume,2)) print ("The surface area is:", round(sa,2)) main()
true
643730d15360ecc6c8e59db671e489a17932fe08
shakyaruchina/100DaysOfCode
/dayTen/calculator.py
1,182
4.25
4
#Calculator from art import logo #add function def add(n1,n2): return n1+n2 #subtract functuon def subtract(n1,n2): return n1-n2 #divide function def divide(n1,n2): return n1/n2 #multiply function def multiply(n1,n2): return n1*n2 #operation dictionary{key:value} operations = { "+":add, "-":subtract, "/":divide, "*":multiply, } def calculator(): print(logo) num1 = float(input("What is the first number ? ")) #prints each operations key for operation in operations: print(operation) go_continue = True while go_continue: operation_symbol = input("Pick an operation ") num2 = float(input("What is the next number ? ")) #key value calculation = operations[operation_symbol] #add(n1,n2), subtract(n1,n2) answer = calculation(num1,num2) print(f"{num1} {operation_symbol}{num2} = {answer}") if input(f"Type 'y' to continue calculating with {answer}: or type 'n' to start a new calculation:") == "y": num1 = answer else: go_continue = False calculator() #recursion : function that calls itself calculator()
true
4f6d15c068cce2a7b00df861c2feea7d41a326cb
SamanehGhafouri/DataStructuresInPython
/doubly_linked_list.py
2,468
4.125
4
# Doubly Linked List # Advantages: over regular (singly) linked list # - Can iterate the list in either direction # - Can delete a node without iterating through the list (if given a pointer to the node) class Node: def __init__(self, d, n=None, p=None): self.data = d self.next_node = n self.prev_node = p def __str__(self): return '(' + str(self.data) + ')' class DoublyLinkedList: def __init__(self, r = None): self.root = r self.last = r self.size = 0 def add(self, d): if self.size == 0: self.root = Node(d) self.last = self.root else: new_node = Node(d, self.root) self.root.prev_node = new_node self.root = new_node self.size += 1 def find(self, d): this_node = self.root while this_node is not None: if this_node.data == d: return d elif this_node.next_node == None: return False else: this_node = this_node.next_node def remove(self, d): this_node = self.root while this_node is not None: if this_node.data == d: if this_node.prev_node is not None: if this_node.next_node is not None: this_node.prev_node.next_node = this_node.next_node this_node.next_node.prev_node = this_node.prev_node else: this_node.prev_node.next_node = None self.last = this_node.prev_node else: self.root = this_node.next_node this_node.next_node.prev_node = self.root self.size -= 1 return True else: this_node = this_node.next_node return False def print(self): if self.root is None: return this_node = self.root print(this_node, end='->') while this_node.next_node is not None: this_node = this_node.next_node print(this_node, end='->') print() dll = DoublyLinkedList() for i in [5, 9, 3, 8, 9]: dll.add(i) print("size= "+str(dll.size)) dll.print() dll.remove(8) print("size="+str(dll.size)) print(dll.remove(15)) print(dll.find(15)) dll.add(21) dll.add(22) dll.remove(5) dll.print() print(dll.last.prev_node)
true
66352731d8b952a633dea499c56cc58903051b4d
nikitakumar2017/Assignment-4
/assignment-4.py
1,450
4.3125
4
#Q.1- Reverse the whole list using list methods. list1=[] n=int(input("Enter number of elements you want to enter in the list ")) for i in range(n): n=int(input("Enter element ")) list1.append(n) print(list(reversed(list1))) #Q.2- Print all the uppercase letters from a string. str1=input("Enter string ") for i in str1: if (i>='A' and i<='Z'): print(i) #Q.3- Split the user input on comma's and store the values in a list as integers. str1=input("Enter some numbers seperated by comma's ") list1=[] list2=[] list1=str1.split(',') for i in list1: i=int(i) list2.append(i) print(list2) #Q.4- Check whether a string is palindromic or not. str1=input("Enter a string ") length=len(str1) high=length-1 i=0 low=0 flag=0 while (i<length and flag==0): if(str1[low]==str1[high]): high-=1 low+=1 flag=0 else: flag=1 i+=1 if(flag==0): print("Yes") else: print("No") #Q.5- Make a deepcopy of a list and write the difference between shallow copy and deep copy. import copy as c list1=[1,2,[3,4],5] list2=c.deepcopy(list1) list1[2][0]=7 print(list1) print(list2) ''' Difference between shallow copy and deep copy is that in shallow copy if the original object contains any references to mutable object then the duplicate reference variable will be created pointing to the old object and no duplicate object is created whereas in deep copy a duplicate object is created. '''
true
2abdecd0c2820f8db9ae2efc4252f9815c80d18d
bsdharshini/Python-exercise
/1)printprintprint.py
1,189
4.375
4
#https://www.codesdope.com/practice/python-printprintprint/ #1)Print anything you want on the screen. print("hello") # 2) Store three integers in x, y and z. Print their sum x=10 y=20 z=30 sum=x+y+z print(sum) #3) Store three integers in x, y and z. Print their product. x,y,z=10,20,30 print(x*y*z) #4) Check type of following: print(type("CodesDope")) print(type(15)) print(type(16.2)) print(type(9.33333333333333333333)) #5) Join two string using '+'. print('hi '+'you') #6) Store two values in x and y and swap them. x,y=10,5 x,y=y,x print(x,y) """ 7) Create a class named 'Rectangle' with two data members- length and breadth and a method to claculate the area which is 'length*breadth'. The class has three constructors which are : 1 - having no parameter - values of both length and breadth are assigned zero. 2 - having two numbers as parameters - the two numbers are assigned as length and breadth respectively. 3 - having one number as parameter - both length and breadth are assigned that number. Now, create objects of the 'Rectangle' class having none, one and two parameters and print their areas. """ """ 8) """
true
bf794f5e450f517f9aa56012b18298c471d68999
Kapiszko/Learn-Python
/ex11.py
426
4.15625
4
print("How old are you?", end=' ') age = int(input("Please give your age ")) print("How tall are you?", end=' ') height = int(input("Please give your height ")) print("How much do you weigh?", end=' ') weight = int(input("Please give your weight ")) print (f"So, you're {age} old, {height} tall and {weight} heavy.") sum_of_measurements = age + height + weight print("The sum of your measurements is", sum_of_measurements)
true
fc41dcd6953857498946355e64e58b32429fcc45
YashMistry1406/Competitve_Coding-
/sde problems/Array/sort color.py
1,119
4.15625
4
# Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, # with the colors in the order red, white, and blue. # We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. # You must solve this problem without using the library's sort function. # Example 1: # Input: nums = [2,0,2,1,1,0] # Output: [0,0,1,1,2,2] # Example 2: # Input: nums = [2,0,1] # Output: [0,1,2] # Example 3: # Input: nums = [0] # Output: [0] # Example 4: # Input: nums = [1] # Output: [1] class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ lo=0 mid=0 hi= len(nums)-1 while mid <= hi: if nums[mid]==0: nums[lo],nums[mid]=nums[mid],nums[lo] lo+=1 mid+=1 elif nums[mid] == 1: mid+=1 else: nums[mid],nums[hi]=nums[hi],nums[mid] hi-=1 return nums
true
4a96f7c36e897f6af65eaa60077bd988d9b7e34b
serubirikenny/Shoppinlist2db
/shop.py
1,043
4.125
4
class ShoppingList(object): """class to represent a shopping list and CRUD methods""" def __init__(self, name): self.name = name self.items = {} def add_item(self, an_item): if an_item.name in self.items: self.items[an_item.name] += an_item.quantity else: self.items[an_item.name] = an_item.quantity def remove_item(self, name): if name not in self.items: print 'Item not on shopping list.' else: if self.items[name] > 1:#reduce the item numbers by 1 if there's more than 1 self.items[name] -= 1 elif self.items[name] == 0 or self.items[name] == 1:#else remove the item from the list entirely del self.items[name] def show_list(self): print self.items return self.items class Item(object): """class to represent items on a shopping list""" def __init__(self, name, quantity=1): self.name = str(name) self.quantity = int(quantity)
true
12682f41edb0a57e5774e5404b11b7a72c1698a8
aarushikool/CrypKool
/OTP.py
2,228
4.3125
4
from random import randint import matplotlib.pyplot as plt #string alphabet is declared here to convert ALPHABET into numerical values #ALPHABET[0] is a blank space ALPHABET = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ' def encrypt(text, key): text= text.upper() cipher_text = '' for index, char in enumerate(text): key_index = key[index] char_index = ALPHABET.find(char) cipher_text += ALPHABET[(char_index + key_index) % len(ALPHABET)] return cipher_text def decrypt(msg, key): plain = '' for index, char in enumerate(msg): key_index = key[index] char_index = ALPHABET.find(char) plain += ALPHABET[(char_index - key_index) % len(ALPHABET)] return plain def random_sequence(text): #we store the random values in a list random_sequence = [] #generating as many random values as the number of characters in the plain_text #size of the key = size of the plain_text for rand in range(len(plain_text)): random_sequence.append(randint(0,len(ALPHABET))) return random_sequence def frequency_analysis(plain_text): #the text is case insensitive plain_text = plain_text.upper #we will be using a dictionary to store letter frequencies letter_frequencies= {} #initialize the dictionary for letter in ALPHABET: letter_frequencies[letter] = 0 #let's consider the text we want to analyse for letter in plain_text: #we keep incrementing the occurence of the given letter if letter in ALPHABET: letter_frequencies[letter] += 1 return letter_frequencies #histogram of letter_frquencies def plot_distribution(frequencies): centers = range(len(ALPHABET)) plt.bar(centers, frequencies.values(), align='center', tick_label=frequencies.keys()) plt.xlim([0,len(ALPHABET)-1]) plt.show() if __name__ == "__main__": plain_text = 'HELLO I AM HERE BRO' key= random_sequence(plain_text) print("Original message is %s " % plain_text.upper()) cipher= encrypt(plain_text,key) print("Encrypted message is %s " % cipher) decrypted_text= decrypt(cipher,key) print("Decrypted message is %s " % decrypted_text) plot_distribution(frequency_analysis(cipher))
true
cc9caf4d73ee3d43b06d3698abc27888924ac923
garymorrissey/Programming-And-Scripting
/collatz.py
537
4.125
4
# Gary Morrissey, 11-02-2018 # The Collatz Conjecture program i = int(input("Please enter any integer:")) # Prompts you to choose a number, with the next term being obtained from the previous term while i > 1: if i % 2 == 0: i = i / 2 # If the previous term is even, the next term is one half the previous term print(i) else: i = (3 * i) + 1 # Otherwise, the next term is 3 times the previous term plus 1 print(i) # The conjecture is that no matter what value of n, the sequence will always reach 1
true
2b2bdc77c6e116371e56d5df4bb7699bc2dff31a
AmaanHUB/IntroPython
/variables_types/python_variables.py
847
4.34375
4
# How can we create a variable? # variable_name = value # creating a variable called name to store user name name = "Amaan" # declaring a String variable # creating a variable called age to store user age age = 23 # Integer # creating a variable called hourly_wage to store user hourly_wage hourly_wage = 15 # Integer # creating a variable called travel_allowance to store user travel_allowance travel_allowance = 3.5 # Float # # # # Types of variables in Python: # # String, int, float, boolean # print(travel_allowance) print(age) print(hourly_wage) # How can we take user data? # We can use a method called input() to get data from user # getting user input with the input() method name = input("Please enter your name: ") print(name) # How can we find out the type of variable? # type() method tells us the data type print(type(age))
true
19387eba9e667955c01c4fe19571af19b890c1d8
clowe88/Code_practicePy
/simple_cipher.py
277
4.15625
4
phrase = input("Enter a word or phrase to be encrypted: ") phrase_arr = [] finished_phrase = "" for i in phrase: phrase_arr.append(i) for x in phrase_arr: num = ord(x) cipher = chr(num + 12) finished_phrase += cipher print (finished_phrase)
true
087bc5cc5c04f905117e7950cfd64b1b927a01f9
manasmishracse/Selenium_WebDriver_With_Python
/PythonTesting/Demo Code/ReadFile.py
305
4.1875
4
# Reading a File Line by Line in Python and reverse it in o/p. lines = [] rev = "" file = open('File_Demo.txt', 'r') lines = file.readlines() print("{}{}".format("Content in File is ", lines)) for i in lines: rev = i + rev print("{}{}".format("Reversed Content of the File is:", rev)) file.close()
true
a7e708c106dc18cdd1b222f807dc6225cb2a2347
satyam-seth-learnings/machine_learning
/Machine Learning using Python(NIELIT Lucknow)/My Code/Assignments/Assignment-3(Day-6)/4.Circle.py
428
4.25
4
# Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle. class Circle: def __init__(self,r): self.radius=r def area(self): return 3.14*self.radius**2 def perimeter(self): return 2*3.14*self.radius c1=Circle(10) print(f'Radius: {c1.radius}') print(f'Area: {c1.area()}') print(f'Perimeter: {c1.perimeter()}')
true
5aa478055b9109df4e9b32ddf801473d80399148
satyam-seth-learnings/machine_learning
/Machine Learning using Python(NIELIT Lucknow)/My Code/Assignments/Assignment-2(Day-4)/8.Find cube of all numbers of list and find minimum element and maximum element from resultant list.py
309
4.28125
4
# Using lambda and map calculate the cube of all numbers of a list and find minimum element and maximum element from the resultant list. l=[1,2,6,4,8,9,10] cubes=list(map(lambda x: x**3,l)) print(f'Cube of all numbers: {cubes}') print(f'Minimum element: {min(cubes)}') print(f'Maximum element: {max(cubes)}')
true
0afc2bd9622c2a0a32a3c369733d6df66d8284ce
roycrippen4/python_school
/Assignments/triangle.py
928
4.625
5
# Python Homework 1 - Triangles sides and angles # Roy Crippen # ENG 101 # Due 11/18/2019 # The goal of this code is to take three sides of a triangle from a user and to compute the angles of said triangle. from math import degrees from math import acos # First I will receive the sides of the triangle from the user side_a = int(input('What is side a? ')) side_b = int(input('What is side b? ')) side_c = int(input('What is side c? ')) # Then I will compute the angles of the triangle. ang_a = degrees(acos((side_b**2 + side_c**2 - side_a**2) / (2 * side_b * side_c))) ang_b = degrees(acos((side_c**2 + side_a**2 - side_b**2) / (2 * side_c * side_a))) ang_c = 180 - ang_a - ang_b # Then I print the results print('\nThe sides of the triangle are ' + str(side_a) + ', ' + str(side_b) + ', and ' + str(side_c)+'.') print('The angles (in degrees) of the triangle are ' + str(ang_a) + ', ' + str(ang_b) + ', and ' + str(ang_c)+'.')
true
6b47c5254cee29f96045124913f14fee0f53b3c8
lazumbra/Educative-Data-Structures-in-Python-An-Interview-Refresher
/LinkedList/Doubly Linked Lists/main.py
1,673
4.125
4
from LinkedList import LinkedList from Node import Node def delete(lst, value): deleted = False if lst.is_empty(): print("List is Empty") return deleted current_node = lst.get_head() if current_node.data is value: # Point head to the next element of the first element lst.headNode = current_node.next_element # Point the next element of the first element to None current_node.next_element.previous_element = None deleted = True # Both links have been changed. print(str(current_node.data) + " Deleted!") return deleted # Traversing/Searching for node to Delete while current_node: if value is current_node.data: if current_node.next_element: # Link the next node and the previous node to each other prev_node = current_node.previous_element next_node = current_node.next_element prev_node.next_element = next_node next_node.previous_element = prev_node # previous node pointer was maintained in Singly Linked List else: current_node.previous_element.next_element = None deleted = True break # previousNode = tempNode was used in Singly Linked List current_node = current_node.next_element if deleted is False: print(str(value) + " is not in the List!") else: print(str(value) + " Deleted!") return deleted lst = LinkedList() for i in range(11): lst.insert_at_head(i) lst.print_list() delete(lst, 5) lst.print_list() delete(lst, 0) lst.print_list()
true
51f497fa15c6f77934f98cf1595b66cb7a455ae7
charleycodes/hb-code-challenges
/concatenate-lists-2-13.py
872
4.3125
4
# Whiteboard Easier # Concepts Lists def concat_lists(list1, list2): """Combine lists. >>> concat_lists([1, 2], [3, 4]) [1, 2, 3, 4] >>> concat_lists([], [1, 2]) [1, 2] >>> concat_lists([1, 2], []) [1, 2] >>> concat_lists([], []) [] """ # If we didn't put these on sep lines, (just returned list1.extend(list2)), # the function would have returned None. # Also, if we'd used append instead, for test1, we would have gotten: # [1, 2, [3, 4]] list1.extend(list2) return list1 ##################################################################### # END OF ASSESSMENT: You can ignore everything below. if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED. GOOD WORK!" print
true
afaf0b4d56ec34e86b518d0b0f05a5b31c19e9dc
XiaoA/python-ds
/33_sum_range/sum_range.py
1,279
4.125
4
def sum_range(nums, start=0, end=None): """Return sum of numbers from start...end. - start: where to start (if not provided, start at list start) - end: where to stop (include this index) (if not provided, go through end) >>> nums = [1, 2, 3, 4] >>> sum_range(nums) 10 >>> sum_range(nums, 1) 9 >>> sum_range(nums, end=2) 6 >>> sum_range(nums, 1, 3) 9 If end is after end of list, just go to end of list: >>> sum_range(nums, 1, 99) 9 """ """My first thought was to use a `reduce` function. But even when Imported the library, I had issues. # return functools.reduce(nums) # I learned that the built-in `Sum` function would probably perform better. # Ref: https://docs.python.org/3/library/functions.html#sum # https://realpython.com/python-reduce-function/#comparing-reduce-and-accumulate # The SB implementation first checks for cases where there is no 'end', and returns the sum of the entire list, before slicing the start/end indices: """ if end is None: end = len(nums) return sum(nums[start:end + 1]) # When might the `reduce` function be a better approach? I'll need to look into that more.
true
2a5576f2f7f10af9f2f23ad68f7270d85e9ef6e3
Chaser/PythonHardWay
/Ex27/Ex27_MemorizingLogic.py
2,805
4.34375
4
def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word def print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) print word def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explantion \n\t\twhere there is none. """ print "--------------" print poem print "--------------" five = 10 - 2 + 3 - 5 print "This should be five: %s" % five def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 #NOT Routines print "NOT Routines\n" print not(False) #True print not(True) #False print "-------------------------\n" print "OR Routines\n" print True or False #True print True or True #True print False or True #True print "-------------------------\n" print "AND Routines\n" print True and False #False print True and True #True print False and True #True print False and False #False print "-------------------------\n" print "NOT OR Routines\n" print not(True or False) #False print not(True or True) #False print not(False or True) #False print not(False or False) #True print "-------------------------\n" print "NOT AND Routines\n" print not(True and False) #True print not(True and True) #False print not(False and True) #True print not(False and False) #True print "-------------------------\n" print "!= Routines\n" print (1 != 0) #True print (1 != 1) #False print (0 != 1) #True print (0 != 0) #False print "-------------------------\n" print "== Routines\n" print (1 == 0) #False print (1 == 1) #True print (0 == 1) #False print (0 == 0) #True
true
45fd466c0cfd03262a9baad12133103943aa88c6
sanket-k/Assignment_py
/python-files/Question 3.py
2,008
4.4375
4
# coding: utf-8 # ### Question 3 # ### Note: problem similar to Question 2 # Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The # element value in the i-th row and j-th column of the array should be i*j. # # Note: i=0,1.., X-1; j=0,1,¡ Y-1. # # #### Example # # Suppose the following inputs are given to the program: # # 3,5 # # Then, the output of the program should be: # # [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] # ### Version 1 # In[4]: #define function to display matrix by accepting variables def displayMatrix(x,y): dim_array = [[0 for j in range(y)] for i in range(x)] # define array for i in range(x): # use recurvise loop to reach entered numbers for j in range(y): dim_array[i][j] = i * j # allocate array by multiplying the row and columns return(dim_array) # return array # In[5]: x = int(input("Input the number of rows : ")) # input the number of rows y = int(input("Input the number of columns : ")) # input number of columns print("the 2-Dimensional array is : {}". format(displayMatrix(x,y))) # display the array # ### Verision 2 # In[3]: row_num = int(input("Input number of rows: ")) # input rows col_num = int(input("Input number of columns: ")) # input columns multi_list = [[0 for col in range(col_num)] for row in range(row_num)] # allocate array for row in range(row_num): # recursive loop to reach entered numbers for col in range(col_num): multi_list[row][col]= row*col # allocate array by multiplying the row and columns print("the 2-Dimensional array is : {}".format(multi_list)) # display the array
true
ab4216252416679138e20fa13c9abdb37f7c73cc
KalinHar/OOP-Python-SoftUni
/workshop/hash_table.py
2,142
4.21875
4
class HashTable: """"The HashTable should have an attribute called array of type: list, where all the values will be stored. Upon initialization the default length of the array should be 4. After each addition of an element if the HashTable gets too populated, double the length of the array and re-add the existing data. You are not allowed to inherit any classes. Feel free to implement your own functionality (and unit tests) or to write the methods by yourself.""" def __init__(self): self.array = [None] * 2 def extend_array(self): new_array = [None for _ in range(len(self.array) * 2)] for kvp in self.items(): k, v = kvp new_array[self.hash(k)] = (k, v) self.array = new_array def hash(self, key: str): # a function that should figure out where to store the key - value pair total = 0 for i in range(len(key)): total += ord(key[i]) * (7**i) return total % len(self.array) def add(self, key: str, value: any): # adds a new key - value pair using the hash function if self.array[self.hash(key)] != None: # check for collision and extend array if it self.extend_array() self.add(key, value) self.array[self.hash(key)] = (key, value) def get_value(self, key: str): # returns the value corresponding to the given key return self.array[self.hash(key)][1] def get_pair(self, key: str): # returns the kvp corresponding to the given key return self.array[self.hash(key)] def items(self): return [kvp for kvp in self.array if kvp] # additional "magic" methods, that will make the code in the example work correctrly h = HashTable() h.add("weer", 1) h.add("wer", 2) h.add("er", 3) h.add("we", 4) h.add("wee", 5) h.add("seeer", 6) h.add("ersa", 7) h.add("wed", 8) h.add("wcee", 9) print(h.items()) # we have -> 9 elements => len array must be 8+1 = 16 print(len(h.array)) # but len = 32=2**5 => 1 unexpected collision was happened and 4 expected print(h.get_value("er")) print(h.get_pair("wcee"))
true
a352cb58f7c04e49769d48edab362c55e03a2142
karslio/PYCODERS
/Assignments-04-functions/11-equal_reverse.py
242
4.25
4
def equal_reverse(): word = input('enter a word') newString = word[::-1] if word == newString: return True else: return False print(equal_reverse()) # Ex: madam, tacocat, utrecht # Result: True, True, False
true
55aa5c2b12663d078a37ff58edcda05416d69f04
madisonstewart2018/quiz1
/main 6.py
1,184
4.46875
4
#this function uses the variables matrix and vector. def matVec(matrix, vector): ''' The function takes in a matrix with a vector, and for each element in one row multiplies by each number in the vector and then adds them together. Function returns a new vector. ''' new_x = [] for i in range(len(matrix)): #i.e. in range(3) so (0, 1, 2) product = 0 for j in range(len(vector)): #i.e. in range(3) so (0, 1, 2) product += matrix[i][j] * vector[j] #the product is then the prodcut (0) + matrix of i(outer range(3)) and j(inner range(3)) times the vector of j(outer range(3)). The computer goes through and multiplies all of this together. new_x.append(product) #adds the prodcut found above to the end of new_x. So it puts the answer(product) in the brackets of new_x. return new_x #this is the testing variables. testmatrix01 = [[1, 2, 3], [3, 4, 5], [6, 7, 8]] testmatrix02 = [1] testmatrix03 = 'this is a test' testvector01 = [1, 2, 3] testvector02 = [[1, 2, 3], [3, 4, 5], [5, 6 ,7]] testvector03 = 5 print(matVec(testmatrix01, testvector01)) #print(matVec(testmatrix02, testvector02)) #print(matVec(testmatrix03, testvector03))
true
081346e448fc60eec12caf9bab5aca15080bb962
BrianClark1/Python-for-Everybody-Specialization
/Chapter 11/11.2.py
827
4.21875
4
#Looking inside of a file, Extracting numbers and summing them name = input("Enter file:") #Prompt User to input the file if len(name) < 1 : name = "RegexRealSum.txt" #Allows user to simply press enter to open specific file handle = open(name) #assigns the file to a variable name inp = handle.read() #Reads the entire file, newlines and all and puts it into a single string import re #To use regular expressions in your program you must import the librARY getnum = re.findall('[0-9]+', inp) #Looks for integers using finaall and regular expressions from the string getnumint = list(map(int, getnum)) #Map function interates through the list converting each string to an integer sum = 0 for thing in getnumint: #Simple definite loop to sum the parts of the list together sum = sum + thing print(sum) #Print Result
true
f9ddc7d5c1236760550c5d868536c748d1769e88
nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available
/completed Tutorials/bubbleSort.py
706
4.28125
4
#The main difference between bubble sort and insertion sort is that #bubble sort performs sorting by checking the neighboring data elements and swapping them if they are in wrong order #while insertion sort performs sorting by transferring one element to a partially sorted array at a time. #BUBBLE SORT myList = [15,24,62,53,25,12,51] maxIndex = 6 #remember its maxIndex not max number of elements print('This is the unsorted list ' + str(myList)) n = maxIndex for i in range(maxIndex): for j in range (n): if (myList[j] > myList[j+1]): temp = myList[j] myList[j] = myList[j+1] myList[j+1] = temp n-=1 print('This is the sorted list ' + str(myList))
true
b87526548062f13ae7e10e90185550b9c896cee5
nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available
/completed Tutorials/global, local, nonlocal scope variables.py
1,113
4.59375
5
#The nonlocal keyword is used to work with variables inside nested functions, #where the variable should not belong to the inner function. #Use the keyword nonlocal to declare that the variable is not local. #Example 01 (with nonlocal) def myfunc01(): x = "John" #x is 'John' def myfunc02(): nonlocal x #this refers to the previous x x = "hello" #and now has become 'hello' myfunc02() return x #hence this will be 'hello' print(myfunc01()) #Example02 (without nonlocal) def myfunc1(): x = "John" #this will be 'John' def myfunc2(): x = "hello" #this doesn't refer to the previous x, its a new x myfunc2() return x print(myfunc1()) #Example03 (global scope) global a a = 10 def hi(): a = 52 print(a) #52 output hi() print(a) #10 output #Example 04 (local scope) s = 10 #these are by default made global def myfucn(): b = 7 #variables inside a function are said to be local print(b) # displays 7 print(s) # displays 10 myfucn() print(b) # displays that b is not defined since its local to the function myfunc()
true
ee9e7af06d173872648edb0c4ae4ce925981a930
saketborse/Blink-to-Roll-Dice-with-Eye-Detection
/diceroll.py
648
4.15625
4
import random def dice(): # range of the values of a dice min_val = 1 max_val = 6 # to loop the rolling through user input roll_again = "yes" # loop while roll_again == "yes" or roll_again == "y": #print("Rolling The Dices...") #print("The Values are :") # generating and printing 1st random integer from 1 to 6 #print(random.randint(min_val, max_val)) # generating and printing 2nd random integer from 1 to 6 #print(random.randint(min_val, max_val)) roll_again = "no" out = str(random.randint(min_val, max_val)) return out
true
56bfcf0cd7d2ffcca129085aa597ec7d19ca1b22
aandr26/Learning_Python
/Coursera/Week3/Week3b/Projects/format.py
1,239
4.21875
4
# Testing template for format function in "Stopwatch - The game" ################################################### # Student should add code for the format function here def format(t): ''' A = minutes, B = tens of seconds, C = seconds > tens of seconds D = remaining tens of seconds. A:BC:D ''' A = ((t // 10) // 60) #print ("This is A " + str(A)) B = (((t // 10) % 60) // 10) #print ("This is B " + str(B)) C = (((t // 10) % 60) % 10) #print ("This is C " + str(C)) D = ((t // 1) % 60) % 10 #print ("This is D " + str(D)) return (str(A) + ":" + str(B) + str(C)+ "." + str(D)) ################################################### # Test code for the format function # Note that function should always return a string with # six characters print (format(0)) print (format(7)) print (format(17)) print (format(60)) print (format(63)) print (format(214)) print (format(599)) print (format(600)) print (format(602)) print (format(667)) print (format(1325)) print (format(4567)) print (format(5999)) ################################################### # Output from test #0:00.0 #0:00.7 #0:01.7 #0:06.0 #0:06.3 #0:21.4 #0:59.9 #1:00.0 #1:00.2 #1:06.7 #2:12.5 #7:36.7 #9:59.9
true
20b6edc6c257810f00377bc18c4fb0c4d5fe7d3a
aandr26/Learning_Python
/Coursera/Week3/Week3b/Exercises/expanding_cricle.py
865
4.125
4
# Expanding circle by timer ################################################### # Student should add code where relevant to the following. import simplegui WIDTH = 200 HEIGHT = 200 radius = 1 # Timer handler def tick(): global radius global WIDTH radius += 2 # Draw handler def draw(canvas): global WIDTH global HEIGHT global radius if radius <= (WIDTH/2): canvas.draw_circle([WIDTH/2, HEIGHT/2], radius, 2, "Red") elif radius >= (WIDTH/2): timer.stop() canvas.draw_circle([WIDTH/2, HEIGHT/2], radius, 2, "Red") canvas.draw_text("It's too big ya dingus!", [WIDTH/8, HEIGHT/2], 18 ,"Red") # Create frame and timer frame = simplegui.create_frame("Circle", WIDTH, HEIGHT) frame.set_draw_handler(draw) timer = simplegui.create_timer(100, tick) # Start timer frame.start() timer.start()
true
1da99068500ac43445324a856ac14ff1f7e1c626
rebel47/PythonInOneVideoByCodeWithHarry
/chapter2solutions.py
886
4.28125
4
# To add two numbers # a = int(input("Enter the first number: \n")) # b = int(input("Enter the second number: \n")) # print("Sum of first and second number is:",a+b) # To find the remainder # a = int(input("Enter the number whose remainder you want to know: \n")) # print("The reaminder of the given number is:", a%2) # Check type of variable of assigned using input function # a = input("Enter your anything you want to: \n") # print(a) # print(type(a)) # To find whether a is greater than b or not # a = 34 # b = 80 # print(a>b) # To find the average of the two number given by the users # a = int(input("Enter the first number")) # b = int(input("Enter the second number")) # avg = (a+b)/2 # print("Average of two number is:", avg) # To find the square of the number given by the user a = int(input("Enter the number: \n")) a *= a print("Square of the given number is:", a)
true
a608c36a28981eb16358dfb74e1414d1b028aacb
rebel47/PythonInOneVideoByCodeWithHarry
/chapter3solutions.py
829
4.40625
4
# # Print user name with Good afternoon message # name = input("Enter your name:\n") # print("Good afternoon", name) # #Print the given name by adding user name # name = input("Enter the Candidate Name:\n") # date = input("Enter the Date:\n") # letter = '''Dear <|NAME|>, # You are selected!! # Date: <|DATE|>''' # letter = letter.replace("<|NAME|>", name) # letter = letter.replace("<|DATE|>", date) # print(letter) # # WAP to detect double spaces in a string and replace them with single spaces # story = "hello my name is Ayaz Alam and today I am going to learn Python" # doubleSpaces = story.find(" ") # print(doubleSpaces) # print(story.count(" ")) # print(story.replace(" ", " ")) # Format the given text by using escape sequence letter = '''Dear Harry, \n\tThis Python course is nice. \nThanks! ''' print(letter)
true
52deb61b876f65ec65d06c4285f7e34db66ccdec
arushss/Python_Task
/Task01.py
2,516
4.5
4
# Create three variables in a single line and assign different values to them and make sure their data types are different. # Like one is int, another one is float and the last one is a string. x, y, z = 10, 20.5, "Consultadd" print ("x is: ", x) print ("y is: ", y) print ("z is: ", z) # Create a variable of value type complex and swap it with another variable whose value is an integer. cmplx = 20+5j x, cmplx = cmplx, x print("Values after swapping are:") print("x is: ", x) print("Cmplex variable is: ", cmplx) # Swap two numbers using the third variable as the result name and do the same task without using any third variable. print("x and y will be swapped with third variable called name") name = x x = y y = name print ("x and y value after swapping is: ", x, y) print("swapping x and y again without using third variable") x,y = y,x print("x and y value after swapping without third variable is: ", x, y) # Write a program to print the value given by the user by using both Python 2.x and Python 3.x Version. print("Enter any number from keyboard") val = input() print("value you have entered is: ", val) # this is printing the value using python 3.x version print("printing value for 2.x version is going to give us an error because currently I am working on version 3.x but the below line is commented for that purpose") # print "value of x in version 2.x is", val # Write a program to complete the task given below: # Ask the user to enter any 2 numbers in between 1-10 and add both of them to another variable call z. # Use z for adding 30 into it and print the final result by using variable results. print("enter two numbers one by one with values between 1 and 10") a = int(input()) b = int(input()) z = a + b results = z + 30 print("The final value is: ", results) # Write a program to check the data type of the entered values. HINT: Printed output should say - The input value data type is: int/float/string/etc print("enter anything so that its data type can be checked") val2 = eval(input ()) print("The data type of entered value is: ", type(val2)) # If one data type value is assigned to ‘a’ variable and then a different data type value is assigned to ‘a’ again. Will it change the value. If Yes then Why? # yes the value will be changed because that's why the variable is used for. # It means we have an access to the memory which can store the data of any type and # python is smart enough to change the data type of that variable depending upon the value stored in it.
true
2f60538072b1e817495b6a4df3036e4a06c72713
BoLindJensen/Reminder
/Python_Code/Snippets/Files/MoreFiles/Open.py
1,513
4.125
4
''' The function open() opens a file. file: path to file (required) mode: read/write/append, binary/text encoding: text encoding eg. utf-8. It is a good idea to always specify this, as you never know what other file systems use as their default Modes: 'r' Read 'w' Write 'x' eXclusive creation, fails if the file already exists. 'a' Append to the file if it exists. 'b' Binary mode 't' Text mode (Default) '+' open a disk file for updating(reading and writing) 'U' Universal new lines mode(legasy code) check: http://docs.python.org/3/library/codecs.html#standard-encodings ''' import sys print(sys.getdefaultencoding()) my_filename = "text.txt" # Make the file f = open(my_filename , mode='wt', encoding ='utf-8') #print(help(f)) # Write something into the file f.write("This is a long message,") f.write(" that continues. \n") f.write("Now it ends.") f.close() #print(f) # Open a file g = open(my_filename, mode= 'rt', encoding= 'utf-8') # Read 16 chars of the file print(g.read(16)) # Read everything from last read print(g.read()) print(g.read()) # no more information in file. print(g.seek(0)) # return cartridge to 0 print(g.readline()) print(g.readline()) print(g.seek(0)) # return cartridge to 0 print(g.readlines()) # Give a list g.close() # and we are done with the file # append to a file. h = open(my_filename, mode= 'at', encoding= 'utf-8') h.writelines( ['\n' 'Added lines \n' 'Remember the newlines character, ' 'if you need it \n' '...']) h.close()
true
ec4d7456fbfaa7bef8bbe1244174b7c984ffd999
BoLindJensen/Reminder
/Python_Code/Snippets/Lists/List_Comprehension.py
225
4.59375
5
# https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions # L3 returns all elements of L1 not in L2. L1 = [1,2,6,8] L2 = [2,3,5,8] L3 = [x for x in L1 if x not in L2] print(L3) #L3 will contain [1, 6].
true
570d466855d3abeb761c3bb07e1f53628b2df264
BoLindJensen/Reminder
/Python_Code/Snippets/Lists/List_Comprehension2.py
950
4.34375
4
''' Python Comprehension works on list[], set{}, dictionaries{key:value} List Comprehension style is Declarative and Functional it is readable, expressive, and effective. [ expr(item) for item in items ] [ expr(item) for item in iterable ] [ expr(item) for item in iterable if predicate(item) ] ''' words = "What is this list comprehension i hear so much about, what can it help me with?" words_list = words.split() # This List comprehension print([len(word) for word in words_list]) # Is the same as this foreach loop. word_lengths = [] for word in words_list: word_lengths.append(len(word)) print(word_lengths) from math import sqrt def is_prime(x): if x < 2: return False for i in range(2,int(sqrt(x)) +1): if x % i == 0: return False return True print([x for x in range(101)]) print("Using is_prime() function as optional filter clause") print([x for x in range(101) if is_prime(x)])
true
d31d9c60357120583f0fb35784016b5d561aef81
sgttwld/tensorflow-2-simple-examples
/1b_gradientdescent_gradient.py
831
4.15625
4
""" Example of gradient descent to find the minimum of a function using tensorflow 2.1 with explicit gradient calculation that allows further processing Author: Sebastian Gottwald Project: https://github.com/sgttwld/tensorflow-2.0-simple-examples """ import tensorflow as tf import numpy as np import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' optimizer = tf.keras.optimizers.SGD(learning_rate=.05) x = tf.Variable(tf.random.normal(shape=(), mean=2.0, stddev=0.5)) f = lambda: (x**2-2)**2 def opt(f,x): with tf.GradientTape() as g: y = f() grad = g.gradient(y, x) ## here we could do some gradient processing ## grad = ... optimizer.apply_gradients(zip([grad], [x])) print('init','x =',x.numpy(), 'f(x) =',f().numpy()) for n in range(10): opt(f,x) print('ep',n,'x =',x.numpy(), 'f(x) =',f().numpy())
true
9ca4f40c2b05a7da51e640000c6a37ca88bf91a8
suvratjain18/CAP930Autum
/23AugPractical.py
1,078
4.59375
5
# What Is Sets #collection of well defined things or elements #or # Unorderd collection of distinct hashable elements #In First Create a set s={1,2,3} print(s) print(type(s)) t={'M','K','R'} print(t) print(type(t)) # How you can declare Empty Set using below here # empty_set=set() # it will convert list to string below example set_from_list=set([1,2,1,4,3]) basket={"apple","orange","apple","pear","banana"} len(basket) # Output is 4 Because it detects only distinct ones orange in basket #check membership functions for fruit in basket: print(fruit,end='/') a=set('abracadabra') b=set('alacazam') print(a) print(b) a-b # means common between two sets a is not showing # Output above command a-b {'d', 'b', 'r'} >>> a|b # It means union # Output of both sets {'l', 'z', 'r', 'b', 'a', 'd', 'c', 'm'} a&b # letters in both a and b a^b # letters in a or b but not both (a-b U b-a) a=set('missippi') # its Output is in sets {'m','i','s','p'} a.add('r') # its add in a set a.remove('r') # its remove r in the set a.pop() # it removes the set value from the first
true
661fe7a34a439278c3830a9b13f4b5f6b8d0521e
AnatoliKosarev/Python-beginner-course--Teclado-
/filesPython/fileImports/user_interactions/myfile.py
1,138
4.21875
4
print(__name__) """ The file that we run always has a __name__ variable with a value of "__main__". That is simply how Python tells us that we ran that file. Running code only in script mode Sometimes we want to include some code in a file, but we only want that code to run if we executed that file directly—and not if we imported the file. Since we know that __name__ must be equal to "__main__" for a file to have been run, we can use an if statement. We could type this in myfile.py: """ def get_user_age(): return int(input("Enter your age: ")) if __name__ == "__main__": get_user_age() """ That could allow us to run myfile.py and see if the get_user_age() function works. That is one of the key use cases of this construct: to help us see whether the stuff in a file works when we normally don't want it to run. Another use case is for files which you don't normally run yourself. Sometimes you may write a file that is for use by another program, for example. Using this construct would allow you to run your file for testing, while not affecting its functionality when it's imported by another program. """
true
b0410a2b46b734f18da31834065151d53cd37a41
AnatoliKosarev/Python-beginner-course--Teclado-
/advancedPythonDevelopment/itertoolsCombinatoricIterators.py
2,369
4.84375
5
# permutations """ permutations is concerned with finding all of the possible orderings for a given collection of items. For example, if we have the string "ABC", permutations will find all of the ways we can reorder the letters in this string, so that each order is unique. """ from itertools import permutations p_1 = permutations("ABC") print(*p_1) # ('A', 'B', 'C') ('A', 'C', 'B') ('B', 'A', 'C') ('B', 'C', 'A') # ('C', 'A', 'B') ('C', 'B', 'A') """ By default, permutations returns different orderings for the entire collection, but we can use the optional r parameter to limit the function to finding shorter permutations. """ p_2 = permutations("ABC", r=2) # ('A', 'B') ('A', 'C') ('B', 'A') ('B', 'C') ('C', 'A') ('C', 'B') """ Providing an r value greater than the length of the collection passed into permutations will yield an empty permutations object. """ p_3 = permutations("ABC", r=4) print(*p_3) # # combinations """ combinations returns an iterable object containing unique combinations of elements from a provided collection. Note that combinations isn't concerned with the order of elements, so combinations will treat ('A', 'B') as being identical to ('B', 'A') in its results. The length of the resulting combinations is controlled by the r parameter once again, but in the case of combinations, this argument is mandatory. """ from itertools import combinations c_1 = combinations("ABC", r=2) # ('A', 'B') ('A', 'C') ('B', 'C') c_2 = combinations("ABC", r=3) # ('A', 'B', 'C') """ It is possible to get duplicate elements back from combinations, but only if the provided iterable contains multiple instances of a given element. (1, 2, 3, 1), for example. """ c_3 = combinations((1, 2, 3, 1), r=2) # (1, 2) (1, 3) (1, 1) (2, 3) (2, 1) (3, 1) """ In this case (1, 2) and (2, 1) are not simply the same elements in a different order, the 1s are in fact different elements in the original collection. """ """ It's possible to include instances where an item is paired with itself using the combinations_with_replacement function. It works just like combinations, but will also match every element to itself. """ from itertools import combinations, combinations_with_replacement c_4 = combinations((1, 2, 3), r=2) # (1, 2) (1, 3) (2, 3) c_5 = combinations_with_replacement((1, 2, 3), r=2) # (1, 1) (1, 2) (1, 3) (2, 2) (2, 3) (3, 3)
true
3814a7116033ae2935d0ef09c8d7fae42f29c027
AnatoliKosarev/Python-beginner-course--Teclado-
/advancedPythonDevelopment/namedTuple.py
524
4.1875
4
from collections import namedtuple Student = namedtuple("Student", ["name", "age", "faculty"]) names = ["John", "Steve", "Mary"] ages = [19, 20, 18] faculties = ["Politics", "Economics", "Engineering"] students = [ Student(*student_data) for student_data in zip(names, ages, faculties) ] print(students) oldest_student = max(students, key=lambda student: student.age) # In the code above, we've set a custom key for max so that it compares our tuples based on the age element in each tuple print(oldest_student)
true
bb7ba363b2297d7d57b85e3c9b2cd9ce71147235
AnatoliKosarev/Python-beginner-course--Teclado-
/pythonFundamentals/zipFunction.py
2,299
4.65625
5
""" Much like range, zip is lazy, which means it only calculates the next value when we request it. We therefore can't print it directly, but we can convert it to something like a list if we want to see the output """ from itertools import zip_longest student_ids = (112343, 134555, 113826, 124888) names = ("mary", "Richard", "Noah", "KATE") print(*zip(student_ids, names)) student_dict = dict(zip(student_ids, names)) print(student_dict) student_dict2 = dict(zip(names, student_ids)) print(student_dict2) student_dict3 = list(zip(student_ids, names, [1, 2, 3, 4, 5])) # value "5" is ignored because student_ids, names have only 4 elements, to avoid this - zip_longest should be used print(student_dict3) pet_owners = ["Paul", "Andrea", "Marta"] pets = ["Fluffy", "Bubbles", "Captain Catsworth"] for owner, pet in zip(pet_owners, pets): print(f"{owner} owns {pet}.") movie_titles = [ "Forrest Gump", "Howl's Moving Castle", "No Country for Old Men" ] movie_directors = [ "Robert Zemeckis", "Hayao Miyazaki", "Joel and Ethan Coen" ] movies = list(zip(movie_titles, movie_directors)) # clears after the first loop if not converted to list, dict or tuple - list(zip(movie_titles, movie_directors)) for title, director in movies: print(f"{title} by {director}.") movies_list = list(movies) print(f"There are {len(movies_list)} movies in the collection.") print(f"These are our movies: {movies_list}.") """ unzip = *zipped_collection Using the * operator, we can break up a zip object, or really any collection of collections. For example, we might have something like this: """ zipped = [("John", 26), ("Anne", 31), ("Peter", 29)] # We can use the * operator in conjunction with zip to split this back into names and ages: names, ages = zip(*zipped) print(names) # ("John", "Anne", "Peter") print(ages) # (26, 31, 29) """ _____________________________________________________ zip_longest when we use zip, zip will stop combining our iterables as soon as one of them runs out of elements. If the other iterables are longer, we just throw those excess items away. """ l_1 = [1, 2, 3] l_2 = [1, 2] combinated = list(zip(l_1, l_2)) print(combinated) # [(1, 1), (2, 2)] combinated2 = list(zip_longest(l_1, l_2, fillvalue="_")) print(combinated2) # [(1, 1), (2, 2), (3, '_')]
true
36c9c7f2a4f0f955a46fd85c4116897bfbf61143
AnatoliKosarev/Python-beginner-course--Teclado-
/pythonFundamentals/input.py
239
4.15625
4
my_name = "Bob" your_name = input("Enter your name: ") # always returns string print(f"Hello, {your_name}. My name is {my_name}") print() age = int(input("enter your age: ")) months = age * 12 print(f"you have lived for {months} months")
true
b012c287ee491ed19617ebc9ec1b5d82b89e3d10
AnatoliKosarev/Python-beginner-course--Teclado-
/pythonFundamentals/listComprehension.py
2,079
4.53125
5
# can be used with lists, tuples, sets, dictionaries numbers = [0, 1, 2, 3, 4] doubled_numbers1 = [] for number in numbers: doubled_numbers1.append(number * 2) print(doubled_numbers1) # same can be done with list comprehension which is much shorter doubled_numbers2 = [number2 * 2 for number2 in numbers] print(doubled_numbers2) doubled_numbers3 = [number3 * 2 for number3 in range(10)] print(doubled_numbers3) # we can reuse the base list numbers = [number * 2 for number in numbers] print(numbers) friend_ages = [22, 35, 31, 27] age_strings = [f"My friend is {age} years old" for age in friend_ages] print(age_strings) friend = input("Enter your friend's name: ") names = ["Rolf", "Phil", "Vito"] friends_lower = [name.lower() for name in names] if friend.lower() in friends_lower: print(f"{friend.title()} is one of your friends.") names = ("mary", "Richard", "Noah", "KATE") ages = (36, 21, 40, 28) people = [(name.title(), age) for name, age in zip(names, ages)] print(people) # List comprehensions also allow for more than one for clause # We can use this to find all the possible combinations of dice rolls for two dice, for example: roll_combinations = [(d1, d2) for d1 in range(1, 7) for d2 in range(1, 7)] # for для d1 - внешний цикл, для d2 - внутренний print(roll_combinations) # dictionary comprehension student_ids = (112343, 134555, 113826, 124888) names = ("mary", "Richard", "Noah", "KATE") students = {} for student_id, name in zip(student_ids, names): student = {student_id: name.title()} students.update(student) print(students) students2 = { student_id: name.title() # the value we want to add to the new collection for student_id, name in zip(student_ids, names) # a loop definition which determines where the original values are coming from } print(students2) students3 = { student_ids[i]: names[i].title() # the value we want to add to the new collection for i in range(len(student_ids)) # a loop definition which determines where the original values are coming from } print(students3)
true
af12948c9b1f6161862ae5079d03bf8d3595e44e
jsdiuf/leetcode
/src/Powerful Integers.py
1,611
4.1875
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2019/1/6 12:06 Given two non-negative integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0. Return a list of all powerful integers that have value less than or equal to bound. You may return the answer in any order. In your answer, each value should occur at most once. Example 1: Input: x = 2, y = 3, bound = 10 Output: [2,3,4,5,7,9,10] Explanation: 2 = 2^0 + 3^0 3 = 2^1 + 3^0 4 = 2^0 + 3^1 5 = 2^1 + 3^1 7 = 2^2 + 3^1 9 = 2^3 + 3^0 10 = 2^0 + 3^2 Example 2: Input: x = 3, y = 5, bound = 15 Output: [2,4,6,8,10,14] Note: 1 <= x <= 100 1 <= y <= 100 0 <= bound <= 10^6 """ import math class Solution: def powerfulIntegers(self, x, y, bound): """ :type x: int :type y: int :type bound: int :rtype: List[int] """ if x == 1 and y == 1: return [2] if bound >= 2 else [] if x == 1: jtop = int(math.log(bound - 1, y)) return [1 + y ** j for j in range(jtop+1)] if y == 1: itop = int(math.log(bound - 1, x)) return [1 + x ** i for i in range(itop+1)] ans = set() itop = int(math.log(bound - 1, x)) jtop = int(math.log(bound - 1, y)) for i in range(itop+1): for j in range(jtop+1): t = x ** i + y ** j if t <= bound: ans.add(t) else: break return list(ans) s = Solution() print(s.powerfulIntegers(1, 2, 100))
true
c167226fbfec1a0ecbf43cfcda87b6e51317e656
jsdiuf/leetcode
/src/N-ary Tree Preorder Traversal.py
835
4.15625
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-10-23 9:19 Given an n-ary tree, return the preorder traversal of its nodes' values. For example, given a 3-ary tree: Return its preorder traversal as: [1,3,5,6,2,4]. Note: Recursive solution is trivial, could you do it iteratively? """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ res = [] def helper(node): if node: res.append(node.val) if res.children: for n in node.children: helper(n) helper(root) return res
true
80c0e24423aa62f932ec85bb6c172dfac5c9244b
jsdiuf/leetcode
/src/Valid Parentheses.py
2,026
4.125
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-8-3 9:47 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true """ class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ map = {"(": -3, "{": -2, "[": -1, "]": 1, "}": 2, ")": 3} if s == "": return True if len(s) % 2 != 0: return False stack = [] for e in s: n = len(stack) # not empty if map[e] < 0: stack.append(e) continue if n > 0 and map[stack[n - 1]] + map[e] == 0: stack.pop() continue return False return len(stack) == 0 def isValid2(self, s): """ ([)] """ stack = [] for c in s: if c == '(': stack.append(')') elif c == '{': stack.append('}') elif c == '[': stack.append(']') elif len(stack) == 0 or stack.pop() != c: return False return len(stack) == 0 def isValid3(self, s): """这也行!!!!! :type s: str :rtype: bool """ n = len(s) if n == 0: return True if n % 2 != 0: return False while '()' in s or '{}' in s or '[]' in s: s = s.replace('{}', '').replace('()', '').replace('[]', '') return s == '' s = Solution() print(s.isValid("{{}[()][]}"))
true
40d26a6f9730deb24c97e2793f492213daac4437
jsdiuf/leetcode
/src/Sort Array By Parity II.py
1,137
4.1875
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-10-14 9:32 Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return any answer array that satisfies this condition. Example 1: Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Note: 2 <= A.length <= 20000 A.length % 2 == 0 0 <= A[i] <= 1000 """ class Solution: def sortArrayByParityII(self, A): """ :type A: List[int] :rtype: List[int] """ odd = [] # 奇数 even = [] # 偶数 for i in range(len(A)): if A[i] & 1 == 0: odd.append(A[i]) else: even.append(A[i]) ans = [] for i in range(len(odd)): ans.append(odd[i]) ans.append(even[i]) return ans return [(odd[i],even[i]) for i in range(len(odd))] s = Solution() print(s.sortArrayByParityII([4, 2, 5, 7]))
true
15def978d14ace9dc60ae954f9c18cb1184acff7
sauerseb/Week-Two-Assignment
/program3.py
439
4.34375
4
# __author__ = Evan Sauers (sauerseb) # CIS-125-82A # program3.py # # This program prompts the user for a distance measured in kilometers, converts it to miles, and prints out the results. # K= kilometers # M= miles # Ask user for a distance in kilometers # Convert to miles # (K * .62) K = eval(input("Please enter a distance in kilometers: ")) M = (K * .621371192) print("The distance" , K, " in kilometers is equal to " , M, "miles")
true
3381cbb4e997978ffa139b47868fdb282a00a7db
langestefan/pyluhn
/luhn/luhn.py
1,094
4.25
4
"""Calculate checksum digit from any given number using Luhn algorithm.""" def create_luhn_checksum(number): """ Generates luhn checksum from any given integer number. :param number: Number input. Any integer number. :return: Calculated checksum digit """ str_number = str(number) n_digits = len(str_number) parity = n_digits % 2 sum_n = 0 # Loop over digits, start at most right hand point for index in range(n_digits, 0, -1): digit = int(str_number[index - 1]) if parity == index % 2: digit += digit if digit > 9: digit -= 9 sum_n += digit return (sum_n * 9) % 10 def verify_checksum(number_plus_cs): """ Verify a given number that includes a Luhn checksum digit. :param number_plus_cs: A number + appended checksum digit. :return: True if verification was successful, false if not. """ number = str(number_plus_cs)[:-1] checksum = number_plus_cs % 10 if create_luhn_checksum(number) is not checksum: return False else: return True
true
c0c74fe14d6ff278ee0bc0396d298cf903aa505f
kingsleyndiewo/codex-pythonium
/simple_caesar_cipher.py
806
4.40625
4
# A simple Caesar cipher # Author: Kingsley Robertovich # Caesar cipher is a type of substitution cipher in which each letter in the plaintext is # 'shifted' a certain number of places down the alphabet. In this example we use the ASCII # character set as our alphabet def encipher(clearText, offset = 5): cipherText = '' for c in clearText: s = ord(c) + offset cipherText += chr(s) return cipherText def decipher(ciphertext, offset = 5): clearText = '' for c in cipherText: s = ord(c) - offset clearText += chr(s) return clearText if __name__ == '__main__': # get some input clearText = input("Please enter a message to encipher: ") cipherText = encipher(clearText) print(cipherText) newClear = decipher(cipherText) print(newClear)
true
d4cabe574a786147dba2fbb9cee912e24a4a120d
adam-barnett/LeetCode
/unique-paths-ii.py
1,689
4.125
4
""" Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the middle of a 3x3 grid as illustrated below. [[0,0,0], [0,1,0], [0,0,0]] The total number of unique paths is 2. Note: m and n will be at most 100. Problem found here: http://oj.leetcode.com/problems/unique-paths-ii/ """ """ I solve the problem in place on the input grid, switching all of the values of the obstacles from 1 to -1 so they can be appropriately ignored. """ class Solution: # @param grid_obs, a list of lists of integers # @return an integer def uniquePathsWithObstacles(self, grid_obs): if not grid_obs or not grid_obs[0]: return 0 if grid_obs[0][0] == 1: return 0 for i in xrange(len(grid_obs)): for j in xrange(len(grid_obs[i])): if i == 0 and j == 0: grid_obs[i][j] = 1 elif grid_obs[i][j] == 1: grid_obs[i][j] = -1 else: if i: grid_obs[i][j] += max(grid_obs[i-1][j], 0) if j: grid_obs[i][j] += max(grid_obs[i][j-1], 0) return max(grid_obs[-1][-1], 0) #test sol = Solution() test_cases = [ ([[0]],1), ([[1]],0), ([[0,1]],0), ([[0,0,0],[0,1,0],[0,0,0]],2)] for (case, expected) in test_cases: print '\nFor the grid:', case, ' there are:', expected, 'routes' print 'our system finds:', sol.uniquePathsWithObstacles(case), print 'routes'
true
71a1e30327e58b46a8851048359e520621d8f088
miaoranren/calculator-2-exercise
/calculator.py
1,411
4.375
4
"""A prefix-notation calculator. Using the arithmetic.py file from Calculator Part 1, create the calculator program yourself in this file. """ from arithmetic import * while True: response = input("> ") tokens = response.split(' ') if tokens[0] == 'q': print("You will exit!") break elif len(tokens) < 2: print("Not enough inputs") continue operator = tokens[0] num1 = tokens[1] #This is the case with only two index , we default num2 as None. if len(tokens) < 3: num2 = None else: num2 = tokens[2] result = None if not num1.isdigit() or num2.isdigit() : print("There are not numbers!") break elif operator == "+": result = add(float(num1),float(num2)) elif operator == "-": result = subtract(float(num1),float(num2)) elif operator == "*": result = multiply(float(num1),float(num2)) elif operator == "/": result = divide(float(num1),float(num2)) elif operator == "square": result = square(float(num1)) elif operator == "cube": result = cube(float(num1)) elif operator == "pow": result = power(float(num1),float(num2)) elif operator == "mod": result = mod(float(num1),float(num2)) else: print('Please enter two integers!') print(result)
true
e8860d7c2095fa654b7e6ed28f9a60ce73931491
ptg251294/DailyCodingProblems
/ParanthesesImbalance.py
801
4.3125
4
# This problem was asked by Google. # # Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make # the string valid (i.e. each open parenthesis is eventually closed). # # For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, # since we must remove all of them. def count_invalid_parentheses(input_string): count = 0 invalid_count = input_string.find('(') for index in range(invalid_count, len(input_string)): if input_string[index] == '(': count += 1 else: count -= 1 return abs(count) + invalid_count if __name__ == '__main__': given_string = '(((((()(((' answer = count_invalid_parentheses(given_string) print(answer)
true
c56e83834fe1e889bd985dd43b7d9d62976554d2
ptg251294/DailyCodingProblems
/One2OneCharMapping.py
770
4.125
4
# This problem was asked by Bloomberg. # # Determine whether there exists a one-to-one character mapping from one string s1 to another s2. # # For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d. # # Given s1 = foo and s2 = bar, return false since the o cannot map to two characters. def mapping(): dictionary = {} for i in range(len(str1)): if str1[i] in dictionary and str2[i] != dictionary.get(str1[i]): return False else: dictionary[str1[i]] = str2[i] print('mapping------------>', dictionary) return True if __name__ == '__main__': str1 = 'abc' str2 = 'bcd' print(mapping() if len(str1) == len(str2) and len(str1) > 0 and len(str2) > 0 else False)
true
1a4c2d8a5ff279c6b64d15c8f91670a2f83f956c
Giuco/data-structures-and-algorithms
/course-1-algorithmic-toolbox/week-1/1-max-pairwise-product/max_pairwise_product.py
796
4.15625
4
# python3 from typing import List def max_pairwise_product_original(numbers: List[int]) -> int: n = len(numbers) max_product = 0 for first in range(n): for second in range(first + 1, n): max_product = max(max_product, numbers[first] * numbers[second]) return max_product def max_pairwise_product(numbers: List[int]) -> int: biggest = float("-inf") biggest_2 = float("-inf") for number in numbers: if number >= biggest: biggest_2 = biggest biggest = number elif number >= biggest_2: biggest_2 = number return biggest_2 * biggest if __name__ == '__main__': input_n = int(input()) input_numbers = [int(x) for x in input().split()] print(max_pairwise_product(input_numbers))
true
03e1f167ce7bf0212b7556e2bb5ef2615ada7488
longm89/Python_practice
/513_find_bottom_left_tree_value.py
1,010
4.125
4
""" Given the root of a binary tree, return the leftmost value in the last row of the tree. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: """ We will use BFS to go level by level We travel from right to left and save the value of the last node in the tree The time complexity is O(number of nodes) """ left_most_value = None queue = [root] first_pos = 0 while first_pos < len(queue): current_node = queue[first_pos] left_most_value = current_node.val first_pos += 1 if current_node.right: queue.append(current_node.right) if current_node.left: queue.append(current_node.left) return left_most_value
true
a18b926704febe19ac9cd70081b09b3ea583fc98
ppysjp93/Effective-Computation-in-Physics
/Functions/lambdas.py
852
4.4375
4
# a simple lambda lambda x: x**2 # a lambda that is called after it is defined (lambda x, y=10: 2*x +y)(42) # just because it isi anonymous doesn't mean we can't give it a name! f = lambda: [x**2 for x in range(10)] print(f()) # a lambda as a dict value d = {'null': lambda *args, **kwargs: None} # lambda as a keyword argument f in another function def func(vals, f=lambda x: sum(x)/len(x)): f(vals) # a lambda as a keyword argument in a function call func([6, 28, 496, 8128], lambda data: sum([x**2 for x in data])) # lambda's are often used when sorting containers. We can adapt the sorted # built-in function so that there is a 'key-function' which is applied to # each element in the list. The sorting then occurs on the return value of # the 'key-function' nums = [8128, 6, 496, 28] sorted(nums) sorted(nums, key=lambda x: x%13)
true
5c01549c5e88fef47d466803ace0862a8f2331c2
ppysjp93/Effective-Computation-in-Physics
/Functions/generators.py
1,482
4.4375
4
def countdown(): yield 3 yield 2 yield 1 yield 'Blast off!' # generator g = countdown() next(g) x = next(g) print(x) y, z = next(g), next(g) print(z) for t in countdown(): if isinstance(t, int): message = "T-" + str(t) else: message = t print(message) # A more complex example could be creating a generator that finds the # the square of a range of values up to n and adds one to each one. def square_plus_1(n): for x in range(n): x2 = x * x yield x2 + 1 for sp1 in square_plus_1(10): print(sp1) # This is a good example of abstraction that has been used to tidy the # complexities of the function away. # PALINDROME GENERATOR # You can create a palindrom generator that makes use of two sub generators # the first yields all the values forwards and the second yields all the values # backwards. # This is the generic definition of the sub generator def yield_all(x): for i in x: yield i # paindrom using 'yield from' semantics which is more concise def palindromise(x): yield from yield_all(x) # yields forwards yield from yield_all(x[::-1]) # yields backwards for letter in palindromise("hello"): print(letter, end = "") # The above is equivalent to this full expansion: def palindromize_explicit(x): for i in x: yield i for i in x[::-1]: yield i print("\n") for letter in palindromize_explicit("olleh"): print(letter, end = "")
true
2c7926ba3280dbee2c3bb85dd16100a607c5374a
SDSS-Computing-Studies/004-booleans-ssm-0123
/task1.py
602
4.5
4
#! python3 """ Have the user input a number. Determine if the number is larger than 100 If it is, the output should read "The number is larger than 100" (2 points) Inputs: number Outputs: "The number is larger than 100" "The number is smaller than 100" "The number is 100" Example: Enter a number: 100 The number is 100 Enter a number: 102 The number is larger than 100 """ num = input("Give me a number") num = float(num) if num > 100 : print("This number is larger than 100") elif num == 100 : print("This number is 100") elif num < 100 : print("This number is smaller than 100")
true
02b0aeebab04235c4ebd3f1944e059e6faf581d2
kayartaya-vinod/2019_04_PYTHON_NXP
/examples/ex08.py
708
4.21875
4
''' More loop examples: Accept two numbers and print all primes between them ''' from ex07 import is_prime from ex06 import line def print_primes(start=1, end=100): while start <= end: if is_prime(start): print(start, end=', ') start += 1 print() line() # this function re-writes (overwrites/overrides) the above function definition def print_primes(start=1, end=100): for n in range(start, end+1): if is_prime(n): print(n, end=', ') print() line('*') def main(): print_primes() print_primes(50) print_primes(end=50) print_primes(start=50) print_primes(200, 500) print_primes(end=200, start=50) if __name__=='__main__': main()
true
058a01fa70d67c4322fa03dcb7b7ba1bfbf2d5b8
gabrielriqu3ti/GUI_Tkinter
/src/grid.py
381
4.15625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 13 22:24:18 2020 @author: gabri """ from tkinter import * root = Tk() # Creating Label Widget myLabel1 = Label(root, text = "Hello World!") myLabel2 = Label(root, text = "My name is Gabriel H Riqueti") # Shoving it onto the screen myLabel1.grid(row = 0, column = 0) myLabel2.grid(row = 1, column = 0) root.mainloop()
true
8117eed08dbe2803db65510843a217ad1602808e
yhoang/rdm
/IRI/20170619_IRI.py
2,620
4.3125
4
#!/usr/bin/python3.5 ### printing methods # two ways to print in Python name = 'Florence' age = 73 print('%s is %d years old' % (name, age)) # common amongst many programming languages print('{} is {} years old'.format(name, age)) # perhaps more consistent with stardard Python syntax ### dictionary shopping_dict = {'item-0': 'bread', 'item-1': 'potatoes', 'item-2': 'eggs', 'item-3': 'flour', 'item-4': 'rubber duck', 'item-5': 'pizza', 'item-6': 'milk'} # different ways to iterate through each key/value and print it for key in shopping_dict: print(key) print(shopping_dict[key]) for key, value in shopping_dict.items(): print(key,value) for i in shopping_dict.keys(): print(i) for i in shopping_dict.values(): print(i) ### input method temperature = int(input()) ### Check if a variable or data type for example, a list (my_list) exists (not empty) my_list=() if 'my_list' in globals(): print("my_list exists in globals") if 'my_list' in locals(): print("my_list exists in locals") ### lists/array handling shopping = ['bread', 'potatoes', 'ggs', 'flour', 'rubber duck', 'pizza', 'milk'] extrashopping = ['cheese', 'flour', 'eggs', 'spaghetti', 'sausages', 'bread'] # Combining lists all_items = shopping + extrashopping # and then remove redundancy using set() unique_items = set(all_items) # or combining it right away without adding doubles # slower though! (3times slower?) for i in extrashopping: if i not in shopping: shopping.append(i) ### performance measurement import timeit start = timeit.timeit() end = timeit.timeit() print (end - start) ### read/write example with python3+ def read_each_line_of_each_file(pathname): # name of path with multiple files with open(pathname+"/receptor_proteins.csv",'w') as csv_out: for files in os.listdir(pathname): if files.endswith(".csv"): csv_out.write("%s: \n" % files) with open(pathname+"/"+files,'r') as csv_files: for entry in csv_files: if ('receptor') in entry.lower(): csv_out.write("%s\t%s\n" % (entry.split("\t")[0],entry.split("\t")[3])) pathname = 'demo_folder' # name of path with multiple files read_each_line_of_each_file(pathname) with open(pathname+"/receptor_proteins.csv",'r') as new_csv: for entry in new_csv: print(entry) ### module sys allows you to pipe elements to code # call in bash python script.py element1 element2 element3 # in script: import sys var = [] for i in sys.argv: var.append(i)
true
fe7219d3dcbcb122404675c79678ec2aa46fec85
pascalmcme/myprogramming
/week5/lists.py
392
4.25
4
list = ["a","b","c"] #changeable and orderable collection tuple = (2,3) # not changeable print(type(list)) print(len(tuple)) list.append(99) print(list) newlist = list + [1] print(newlist) lista = [1,2,'a',True] # different data types in list print(lista[0]) print(lista[1:]) # 1 to end print(lista[::-1]) print(lista[::2]) #note we start counting at 0 x = lista.pop(0) print(x)
true
88044fba92673eae63292c65aa63c804fc4fb041
ridersw/Karumanchi---Algorithms
/selectionSort.py
448
4.125
4
def selectionSort(arr): size = len(elements) for swi in range(len(elements)-1): minIndex = swi for swj in range(minIndex+1, size): if elements[swj] < elements[minIndex]: minIndex = swj if swi != minIndex: elements[swi], elements[minIndex] = elements[minIndex], elements[swi] if __name__ == "__main__": elements = [78, 12, 15, 8, 61, 53, 23, 27] selectionSort(elements) print("Sorted Array: ", elements)
true
e60d1d29e10422a69b0b867be7f849f4030e51fa
baishuai/leetcode
/algorithms/p151/151.py
300
4.125
4
# Given an input string, reverse the string word by word. # For example, # Given s = "the sky is blue", # return "blue is sky the". class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ return ' '.join(reversed(s.split()))
true
181f19fec56913372b5aa480dfea3e5d3c4c91b8
senseiakhanye/pythontraining
/section5/ifelseif.py
246
4.21875
4
isFound = True if (isFound): print("Is found") else: print("Is not found") #else if for python is different num = 2 if (num == 1): print("Number is one") elif (num == 2): print("Number if two") else: print("Number is three")
true
baca925b539e5fcc04be482c5fc8b27a6ff355eb
johnstinson99/introduction_to_python
/course materials/b05_matplotlib/d_sankey/sankey_example_1_defaults.py
1,070
4.34375
4
"""Demonstrate the Sankey class by producing three basic diagrams. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey # Example 1 -- Mostly defaults # This demonstrates how to create a simple diagram by implicitly calling the # Sankey.add() method and by appending finish() to the call to the class. # flows: # positive flow goes into the main stream. # negative flow comes out of the main stream. # orientations: # 0 = horizontal # 1 = vertical upwards # -1 = vertical downwards Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10], labels=['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th'], orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish() plt.title("The default settings produce a diagram like this.") # Notice: # 1. Axes weren't provided when Sankey() was instantiated, so they were # created automatically. # 2. The scale argument wasn't necessary since the data was already # normalized. # 3. By default, the lengths of the paths are justified. plt.show()
true
1fc9ba256d1201e878b76e6d9419d162d0e9cd59
anuragpatilc/anu
/TAsk9_Rouletle_wheel_colors.py
992
4.375
4
# Program to decides the colour of the roulette wheel colour # Ask the user to select the packet between 0 to 36 packet = int(input('Enter the packet to tell the colour of that packet: ')) if packet < 0 or packet > 36: print('Please enter the number between 0 to 36') else: if packet == 0: print('Your selected packet GREEN') elif packet < 11: if packet % 2 == 0: print('Your selected packet BLACK') else: print('Your selected packet RED') elif packet < 19: if packet % 2 == 0: print('Your selected packet RED') else: print('Your selected packet BLACK') elif packet < 29: if packet % 2 == 0: print('Your selected packet BLACK') else: print('Your selected packet RED') else: if packet % 2 == 0: print('Your selected packet RED') else: print('Your selected packet BLACK')
true
83ccf65950e90bd1cf095c29e5b1c61b1d7a75d9
zeus911/sre
/leetcode/Search-for-a-Range.py
1,062
4.15625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'liuhui' ''' Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. ''' class Solution: def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ temp, l = 0, -1 for i in range(len(nums)): if nums[i] == target and temp == 0: temp = 1 l = i elif nums[i] == target and temp != 0: temp += 1 else: pass if l != -1: return [l, l+temp-1] else: return [-1, -1] if __name__ == '__main__': nums = [5, 7, 7, 8, 8, 10] solut = Solution() res = solut.searchRange(nums, 8) print(res)
true
1dfd1b6ceeaaa4e18804ebdf96697fff2e494a25
mimichen226/GirlsWhoCode_SIP2018
/Python/Libraries/DONE_rock_paper_scissors.py
562
4.1875
4
########### Code for Rock Paper Scissors ############ import random gestures = ["scissors", "rock", "paper"] computer = random.choice(gestures) human = input("Rock, paper, scissors, SHOOT: ") human = human.lower().lstrip().rstrip() print("Computer chooses {}".format(computer.upper())) if computer == human: print("TIE") elif (computer == "scissors" and human == "paper") or (computer == "paper" and human == "rock") or (computer == "rock" and human == "scissors"): print("You lost. Go computers. ") else: print("You win! Down with computers. ")
true
bff09661d3f94c924370978ec58eba596f184bcc
penelopy/interview_prep
/Basic_Algorithms/reverse_string.py
389
4.3125
4
""" Reverse a string""" def reverse_string(stringy): reversed_list = [] #strings are immutable, must convert to list and reverse reversed_list.extend(stringy) for i in range(len(reversed_list)/2): reversed_list[i], reversed_list[-1 - i] = reversed_list[-1 -i], reversed_list[i] print "".join(reversed_list) string1 = "cat in the hat" reverse_string(string1)
true
6507cb3071727a87c6c7309f92e7530b74fcc5a2
penelopy/interview_prep
/Trees_and_Graphs/tree_practice_file.py
1,262
4.25
4
"""NOTES AND PRACTICE FILE Ex. Binary Tree 1 / \ 2 3 Ex. Binary Search Tree 2 / \ 1 3 A binary search is performed on sorted data. With binary trees you use them to quickly look up numbers and compare them. They have quick insertion and lookup. """ class BinarySearchTree: def __init__(self, value): self.value = value self.left = None self.right = None def get_right(self): return self.right def set_right(self, node): self.right = node def get_left(self): return self.left def set_left(self, node): self.left = node def set_value(self, number): self.value = number def depth_first_traversal(self, node): """ DFT, recursive""" print node.value, if node.left: depth_first_traversal(node.left) if node.right: depth_first_traversal(node.right) def breath_first_traversal(self, node): if not node: return None else: queue = [node] while len(queue) > 0: current = queue.pop(0) print current.value, if current.left: queue.append(current.left) if current.right: queue.append(current.right)
true
2ee39e37dec9a9c5df1f70683a5a01d2a6935f09
ak14249/Python
/map_function.py
2,336
4.40625
4
print("Que: Write a map function that adds plus 5 to each item in the list.\n") lst1=[10, 20, 30, 40, 50, 60] lst2=list(map(lambda x:x+5,lst1)) print(lst2) print("\n=========================================================\n") print("Que: Write a map function that returns the squares of the items in the list.\n") lst1=[10, 20, 30, 40, 50, 60] lst2=list(map(lambda x:x*x,lst1)) print(lst2) print("\n=========================================================\n") print("Que: Write a map function that adds Hello, in front of each item in the list.\n") lst1=["Jane", "Lee", "Will", "Brie"] lst2=list(map(lambda x:"Hello, "+x,lst1)) print(lst2) print("\n=========================================================\n") print("Que: Using map() function and len() function create a list that's consisted of lengths of each element in the first list.\n") lst1=["Alpine", "Avalanche", "Powder", "Snowflake", "Summit"] lst2=list(map(lambda x:len(x),lst1)) print(lst2) print("\n=========================================================\n") print("Que: Using map() function and lambda add each elements of two lists together. Use a lambda with two arguments.\n") lst1=[100, 200, 300, 400, 500] lst2=[1,10,100,1000,10000] lst3=list(map(lambda x,y:x+y,lst1,lst2)) print(lst3) print("\n=========================================================\n") print("Que: Using map() function and lambda and count() function create a list which consists of the number of occurence of letter: a.\n") lst1=["Alaska", "Alabama", "Arizona", "Arkansas", "Colorado", "Montana", "Nevada"] lst2=list(map(lambda x:x.count("a"),lst1)) print(lst2) print("\n=========================================================\n") print("Que: Using map() function and lambda and count() function create a list consisted of the number of occurence of both letters: A and a.\n") lst1=["Alaska", "Alabama", "Arizona", "Arkansas", "Colorado", "Montana", "Nevada"] lst2=list(map(lambda x:x.lower().count("a"),lst1)) print(lst2) print("\n=========================================================\n") print("Que: Using map() function, first return a new list with absolute values of existing list. Then for ans_1, find the total sum of the new list's elements.\n") lst=[99.3890,-3.5, 5, -0.7123, -9, -0.003] new_lst=list(map(abs,lst)) ans_1=sum(new_lst) print(ans_1)
true
6098028a07d94854e273ca763d3ff1f566ea6c4d
karthikrk1/python_utils
/primeSieve.py
1,330
4.34375
4
#!/bin/python3 ''' This is an implementation of the sieve of eratosthenes. It is created for n=10^6 (Default Value). To use this in the program, please import this program as import primeSieve and call the default buildSieve method Author: Karthik Ramakrishnan ''' def buildSieve(N=1000000): ''' This function is an implementation of the sieve of eratosthenes. The function creates a boolean array of size N and marks the prime numbers as True. This is an utility function that creates a boolean array for the sieve and sets up the prime numbers. Args: N - The upper bound until which we need to set up the sieve. Return: isPrime - The boolean array with all the prime numbers set as True. The remaining values are made False. ''' N+=1 # This is to make sure we have the N inclusive in the array and not getting it lost due to 0-based indexing of Python lists isPrime = [True] * N # Initializing the isPrime list with all True values. isPrime[0] = isPrime[1] = False # Since 0 and 1 are considered Neither Prime nor composite. So we make them False. for (ind, num) in enumerate(isPrime): if num: for no in range(ind*ind, N, ind): # This is used to mark the factors as not Prime. isPrime[no] = False return isPrime
true
af8e0ab5c3cabbda9b75721c81492e285345c9d3
brianhoang7/6a
/find_median.py
940
4.28125
4
# Author: Brian Hoang # Date: 11/06/2019 # Description: function that takes list as parameter and finds the median of that list #function takes list as parameter def find_median(my_list): #sorts list from least to greatest my_list.sort() #distinguishes even number of items in list if len(my_list) % 2 == 0: #finding the smallest number of the second half of the list num1 = my_list[int(len(my_list)/2)] #finding the largest number of the first half of the list num2 = my_list[int(len(my_list)/2 - 1)] #adding the two numbers up and dividing by 2 to return the median sum1 = num1 + num2 return sum1/2 #finds the number in the center of the list to return as the median for lists with odd number of objects elif len(my_list) % 2 != 0: num1 = my_list[round(len(my_list)/2)] return num1 #my_list = [4,5,3,7,8,3,1,12,13] #print(find_median(my_list))
true
bbacdc29ca3d75eeaee34e1d9800e57b390bd83c
pastcyber/Tuplesweek4
/main.py
917
4.1875
4
value = (5, 4, 2000, 2.51, 8, 9, 151) def menu(): global value option = '' while(option != 6): print('*** Tuple example ***') print('1. Print Tuple ***') print('2. Loop over tuple') print('3. Copy Tuple') print('4. Convert to list') print('5. Sort Tuple') print('6. Exit ***') option = int(input('Please enter option: ')) if(option == 1): print(value) elif(option == 2): continue elif(option == 3): start = int(input('Enter start of range: ')) end = int(input('Enter start of range: ')) newtuple = value[start:end] print(newtuple) elif(option == 4): templist = list(value) templist.append(100) value = tuple(templist) print(value) elif(option == 5): templist = list(value) templist = sorted(value)# reverse = True (descending) value = tuple(templist) print(value)
true
70f84fb61188d4a12f42bc5ab4e90f190dde764b
YOOY/leetcode_notes
/problem/check_if_number_is_a_sum_of_powers_of_three.py
292
4.15625
4
# check if n can be formed by 3**0 + 3**1 + ... + 3**n # if any r equals to 2 it means we need 2 * (3 ** n) which should be false def checkPowersOfThree(n): while n > 1: n, r = divmod(n, 3) if r == 2: return False return True print(checkPowersOfThree(21))
true
07815b759c627172f59ac80c7bc403f6b9b48a90
Aditi-Billore/leetcode_may_challenge
/Week2/trie.py
2,258
4.1875
4
# Implementation of trie, prefix tree that stores string keys in tree. It is used for information retrieval. # class TrieNode: def __init__(self): self.children = [None] *26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, letter): # return index value of character to be assigned in array return ord(letter) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) # if current character is not present if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] # mark last node as leaf pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord def startsWith(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None def main(): keys = ["the","a","there","anaswe","any","by","their"] output = ["Not present in trie","Present in trie"] # Trie object t = Trie() # Construct trie for key in keys: t.insert(key) # Search for different keys print("{} --{}-- {}".format("the","search",output[t.search("the")])) print("{} --{}-- {}".format("these","search",output[t.search("these")])) print("{} --{}-- {}".format("their","search",output[t.search("their")])) print("{} --{}-- {}".format("thaw","startsWith",output[t.startsWith("th")])) print("{} --{}-- {}".format("anyw","startsWith",output[t.startsWith("anyw")])) if __name__ == "__main__": main()
true
239d29e78ee6f68d72bcda0a08f25d62ee223b7d
ellezv/data_structures
/src/trie_tree.py
2,588
4.1875
4
"""Implementation of a Trie tree.""" class TrieTree(object): """.""" def __init__(self): """Instantiate a Trie tree.""" self._root = {} self._size = 0 def insert(self, iter): """Insert a string in the trie tree.""" if type(iter) is str: if not self.contains(iter): self._size += 1 start = self._root for letter in iter: start.setdefault(letter, {}) start = start[letter] start["$"] = {} return raise TypeError("Please enter a string.") def contains(self, value): """Will return True if the string is in the trie, False if not.""" if type(value) is str: start = self._root for letter in value: try: start = start[letter] except KeyError: return False if "$" in start.keys(): return True return False def size(self): """Return the size of the Trie tree. O if empty.""" return self._size def remove(self, value): """Will remove the given string from the trie.""" if type(value) is str: current_letter = self._root for letter in value: try: current_letter = current_letter[letter] except KeyError: break if "$" in current_letter.keys(): del(current_letter['$']) if len(current_letter.keys()): return for letter in value[::-1]: current_letter = letter if current_letter is {}: del current_letter else: break raise KeyError("Cannot remove a word that is not in the Trie.") def traversal(self, string): """Depth first traversal.""" if type(string) is str: dict_cur = self._root for letter in string: try: dict_cur = dict_cur[letter] except KeyError: break for letter in dict_cur.keys(): if letter != '$': yield letter for item in self.traversal(string + letter): yield item if __name__ == '__main__': tt = TrieTree() words = ['otter', 'other', 'apple', 'apps', 'tea', 'teabag', 'teapot'] for i in words: tt.insert(i)
true
20e60f62e4865b7a1beb1cdd67330159ebbba35c
LesterZ819/PythonProTips
/PythonBasics/Lists/CreatingLists.py
534
4.15625
4
#You can create a list of values by putting them in [brackets] and assigning them a variable. #For example: varialble = [item1, item2, item3, item4] #lists can contain any time of value, or multiple value types #Example list containing floats or real numbers. float = [1.25, 15.99, 21.33] #Example of a list containing int or integer numbers. int = [1, 2, 3, 4] #Example of a list containing str or strings. str = ["a", "b", "c"] #Example of a list containing bool or boolean values. bool = [True, False, True, True]
true
9f13a8c2f6f5d0f9095da83f175c15a51108096c
LukeBecker15/learn-arcade-work
/Lab 06 - Text Adventure/lab_06.py
2,656
4.15625
4
class Room: def __init__(self, description, north, south, east, west): self.description = description self.north = north self.south = south self.east = east self.west = west def main(): room_list = [] room = Room("You are in the entrance to the Clue house.\nThe path leads north.", 2, None, None, None) room_list.append(room) room = Room("You are in the billiard room.\nThe path leads north and east.", 4, None, 2, None) room_list.append(room) room = Room("You are in the ballroom.\nThe path leads north, south, east, and west.", 5, 0, 3, 1) room_list.append(room) room = Room("You are in the kitchen.\nThe path leads north and west.", 6, None, None, 2) room_list.append(room) room = Room("You are in the library.\nThe path leads south and east.", None, 1, 5, None) room_list.append(room) room = Room("You are in the study.\nThe path leads south, east, and west.", None, 2, 6, 4) room_list.append(room) room = Room("You are in the dining room.\nThe path leads south and west.", None, 3, None, 5) room_list.append(room) current_room = 0 done = False while done == False: print() print(room_list[current_room].description) next_room = input("What direction do you want to move? ") if next_room.title() == "N" or next_room.title() == "North": next_room = room_list[current_room].north if next_room == None: print() print("You can't go this way.") else: current_room = next_room elif next_room.title() == "S" or next_room.title() == "South": next_room = room_list[current_room].south if next_room == None: print() print("You can't go this way.") else: current_room = next_room elif next_room.title() == "E" or next_room.title() == "East": next_room = room_list[current_room].east if next_room == None: print() print("You can't go this way.") else: current_room = next_room elif next_room.title() == "W" or next_room.title() == "West": next_room = room_list[current_room].west if next_room == None: print() print("You can't go this way.") else: current_room = next_room elif next_room.title() == "Q" or next_room.title() == "Quit": done = True print() print("The game is over.") main()
true
183d3360519f1935140cefd8830662d0f168e6ae
DhirajAmbure/MachineLearningProjects
/PythonPracticePrograms/factorialOfNumber.py
1,225
4.28125
4
import math as m def findfact(number): if number == 1: return number elif number != 0: return number * findfact(number - 1) number = int(input("Enter number to find Factorial: ")) if number < 0: print("factorial can not be found for negative numbers") elif number ==0: print("Factorial of 0 is 1") else: print("Factorial of {} is {}".format(number,findfact(number))) print("Factorial of {} using function from math package is {}".format(number,m.factorial(number))) # def findFact(number): # if(number==0 | number==1): # return 1 # elif (number > 1): # return number * findFact(number-1) # # varFact = int(input("Please Enter the number to find Factorial")) # fact = 0 # if(varFact < 0): # print("Please enter +ve number to find factorial") # else: # print("factorial of {} is {}".format(varFact,findFact(varFact))) # """Using while loop""" def factUsingWhile(number): """To find the factorial of given parameter""" factr = 1 while(number>0): factr *= number number -= 1 return factr factr_vari = int(input("Enter the number: ")) print(factUsingWhile(factr_vari))
true
18a845aa39833a9b137bd19759c543a8a77054b6
Ladydiana/LearnPython
/ListComprehensions.py
959
4.15625
4
# -*- coding: utf-8 -*- """ LIST COMPREHENSIONS """ #capitalized_cities = [city.title() for city in cities] squares = [x**2 for x in range(9) if x % 2 == 0] print(squares) #If you would like to add else, you have to move the conditionals to the beginning of the listcomp squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)] print(squares) """ QUIZ - Extract First Names """ names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"] first_names = [name.split()[0].lower() for name in names] print(first_names) """ QUIZ - Multiples of Three """ count = 0 multiples_3 = [x * 3 for x in range(1, 21)] print(multiples_3) """ QUIZ - Filter Names by Scores """ scores = { "Rick Sanchez": 70, "Morty Smith": 35, "Summer Smith": 82, "Jerry Smith": 23, "Beth Smith": 98 } passed = passed = [name for name, score in scores.items() if score >= 65] print(passed)
true
e5f63dd75eadec1499cb15037c3b4623ace06b76
abhi472/Pluralsight
/Chapter5/classes.py
1,035
4.1875
4
students = [] class Student: school_name = "Sumermal Jain Public School" # this is similar to a static variable but unlike java we do not need to have a static class for static variables we # can have a class instance just like school_name for static call of it def __init__(self, name, student_id = 112): self.name = name # self is an equivalent of this self.student_id = student_id # both self.name and self.student are member variables known as instance variables in python students.append(self) def __str__(self): # overriding return "student : " + self.name def get_school_name(self): return self.school_name # mark = Student("mark") # print(mark) # # print(Student.school_name) # # Student.school_name = "wowo" # # print(Student.school_name) # # print(mark.get_school_name()) # as expected the school_name will have the same value across all class objects
true
62eadc4c3eb829a71a0a2fd24282da4a2c8f3232
abhi472/Pluralsight
/Chapter3/rangeLoop.py
444
4.375
4
x = 0 for index in range(10): # here range creates a list of size 10(argument that has been passed) x += 10 print("The value of X is {0}".format(x)) for index in range(5, 10): # two args mean list start from 5 and goes till 9 x += 10 print("The value of X is {0}".format(x)) for index in range(5, 10, 2): # three args mean list start from 5 and increments two till 9 x += 10 print("The value of X is {0}".format(x))
true
80b8be8ba4fabddfcffaf7d8a69039c83679938f
JubindraKc/python_assignment_dec15
/#4_firstname_lastname_split.py
503
4.28125
4
def full_name(): print("your first name is ", first_name) print("your last name is ", last_name) choice = input("will you include your middle name? y/n\n") name = input("please enter your full name separated with whitespace\n") if choice == 'y': first_name, last_name, middle_name = name.split(" ") full_name() print('your middle name is ', middle_name) elif choice == 'n': first_name, last_name = name.split(" ") full_name() else: print("error")
true
48d8c9acfbbe437a075f8850b40559cc5a7d52d7
simonechen/PythonStartUp
/ex1.py
407
4.1875
4
# print("Hello World!") # print("Hello Again") # print("I like typing this.") # print("This is fun.") # print("Yay! Pringting.") # print("I'd much rather you 'not'.") print('I "said" do not touch this.') # ' "" ' print("I'm back.") # Terminate print("-how to make my script print only one of the lines?") print("-one way is to put a `#` character at the beginning of every line not supposed to be printed")
true
57629ce5b3adbfeb89b532c2b2af3b4977815c26
queeniekwan/mis3640
/session13/set_demo.py
540
4.3125
4
def unique_letters(word): unique_letters = [] for letter in word: if letter not in unique_letters: unique_letters.append(letter) return unique_letters print(unique_letters('bookkeeper')) # set is a function and type that returns unique elements in an item word = 'bookkeeper' s = set(word) print(s, type(s)) s.add('a') print(s) # intersection between two sets s1 = {1, 2, 3} s2 = {2, 3, 4} print(s1 & s2) #intersection print(s1 | s2) #union print(s1.difference(s2)) #what's in s1 that s2 doesn't have
true
4babb313798da7167ba3ffbf63c6ce25ee2528c5
sayaliupasani1/Learning_Python
/basic_codes/list1.py
899
4.15625
4
fruits = ["Mango", "Apple", "Banana", "Chickoo", "Custard Apple", "Strawberry"] vegetables = ["Carrots", "Spinach", "Onion", "Kale", "Potato", "Capsicum", "Lettuce"] print (type(fruits)) print(fruits) #fruits.extend(vegetables) #print(fruits) #fruits.extend(vegetables[1]) print (fruits) fruits.extend(vegetables[1:3]) print (fruits) fruits.append("Garlic") print (fruits) fruits.insert(1,"Baby Spinach") print (fruits) fruits.remove("Baby Spinach") print(fruits) fruits.clear() print(fruits) vegetables.append("Onion") print(vegetables) vegetables.remove("Onion") print(vegetables) vegetables.remove("Onion") print(vegetables) vegetables.pop() print(vegetables.index("Kale")) print(vegetables.count("kale")) lucky_nums=[8,5,9,0,3,2,6] print(lucky_nums) lucky_nums.sort() print(lucky_nums) lucky_nums.reverse() print(lucky_nums) lucky_nums2= lucky_nums.copy() print(lucky_nums) print(lucky_nums2)
true
7693ec8848f94f4375fa79e2d216744c71d4f56f
michaelpeng/anagramsgalore
/anagramlist.py
1,251
4.3125
4
""" Given a list of strings, tell which items are anagrams in the list, which ones are not ["scare", "sharp", "acres", "cares", "ho", "bob", "shoes", "harps", "oh"] return list of lists, each list grouping anagrams together """ """ Function to check two strings are anagrams of each other 'scare' 'acres' True """ def anagrammer(string1, string2): this_dict = {} for letter in string1: if letter not in this_dict: this_dict[letter] = 1 else: this_dict[letter] += 1 for letter in string2: if letter not in this_dict: return False else: this_dict[letter] -= 1 for key, value in this_dict.iteritems(): if value != 0: return False return True def anagramlist(this_list): anagram_dict = {} while len(this_list) != 0: item = this_list[0] if item not in anagram_dict: anagram_dict[item] = [this_list.pop(this_list.index(item))] for word in list(this_list): if anagrammer(item, word): anagram_dict[item].append(this_list.pop(this_list.index(word))) else: this_list.remove(item) return_list = [] for key, value in anagram_dict.iteritems(): return_list.append(value) print return_list this_list = ["scare", "sharp", "acres", "cares", "ho", "bob", "shoes", "harps", "oh"] anagramlist(this_list)
true
9d6eaa66b5e3e24818e50cadbbbba75e76a5ca73
ramlingamahesh/python_programs
/conditionsandloops/Sumof_NaturalNumbers.py
615
4.21875
4
num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate un till zero while (num > 0): sum += num num -= 1 print("The sum is", sum) # 2 Python Program - Find Sum of Natural Numbers print("Enter '0' for exit."); num = int(input("Upto which number ? ")); if num == 0: exit(); elif num < 1: print("Kindly try to enter a positive number..exiting.."); else: sum = 0; while num > 0: sum += num; num -= 1; print("Sum = ", sum);
true