blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
559b25244991703f4f70032df9516bd4b28048b7
elminson/hackerrank
/find-pair-of-numbers/solution.py
794
4.21875
4
# Input: A list / array with integers. For example: # [3, 4, 1, 2, 9] # Returns: # Nothing. However, this function will print out # a pair of numbers that adds up to 10. For example, # 1, 9. If no such pair is found, it should print # "There is no pair that adds up to 10.". def pair10(given_list): a = [] a.append(given_list[0]) found = 0 for i in given_list: number = 10-i if number in a: print(number,",", i) found = 1 break #remove this line if you want to print all pairs found else: a.append(i) if(found==0): print("There is no pair that adds up to 10.") #run solution print(""" Which pair adds up to 10? (Should print 1, 9) [3, 4, 1, 2, 9] """) pair10([3, 4, 1, 2, 9])
true
fc930865974fb10e85e4793868954262a736c3b9
morrrrr/CryptoMasters
/11_Diffie-Hellman_key_agree.py
1,804
4.15625
4
import math from sympy import nextprime # UTILS def exponentiation_by_squaring(base, exponent) : res = 1 while exponent > 0 : if exponent & 1 == 1: res = (res * base) exponent = (exponent - 1) // 2 base = (base * base) else: exponent = exponent // 2 base = (base * base) return res def non_trivial_divisors(n): divs = [] for i in range(2,int(math.sqrt(n))+1): if n%i == 0: divs.append(i) divs.append(int(n/i)) return list(set(divs)) def is_generating_element(g, N): result = True for div in non_trivial_divisors(N-1): if(pow(g,div) % N == 1): result = False break return result def generating_element(mod): for i in range(2, mod): if is_generating_element(i, mod): return i # EXAMPLE AND DESCRIPTION """ Diffie-Hellman key exchange is a method of securely exchanging cryptographic keys over a public channel. The simplest and the original implementation of the protocol uses the multiplicative group of integers modulo p, where p is prime, and g is a primitive root modulo p. """ """alice and bob choose a public prime number and its primitive root""" p = nextprime(1000) g = generating_element(p) """alice picks a random private u, computes ya = g^u and sends it to bob""" u = 17 ya = exponentiation_by_squaring(g, u) """bob picks a random private v, computes yb = g^v and sends it to alice""" v = 28 yb = exponentiation_by_squaring(g, v) """both compute the common secret key""" ka = exponentiation_by_squaring(yb, u) kb = exponentiation_by_squaring(ya, v) print("Alice and Bob secret keys match ", ka == kb) print("The secret common key is ", ka)
true
c86cda934adc71beb1e3a8e94b3e17e4f59e10f9
prathap442/python-basica
/if_method.py
409
4.125
4
num1 = 100 num2 = 100 if num1 > num2: print('the num1 is greater than num2') elif(num2 > num1): print('the num2 is greater than num1') else: print('the num1 is equal to num2') # and operator usage # if (num1 > num2) and (num2 > num1): # print('num1 can\'t predict what kind you are') # elif(num1 > num2) # print('num1 is greater than num2') # elif(num1 < num2) # print('num1 is less than num2')
false
e62a10bb91d6210ac2cbce790ec2a995d867c4e2
mtholder/eebprogramming
/lec2pythonbasics/factor.py
991
4.28125
4
#!/usr/bin/env python import sys if len(sys.argv) != 2: sys.exit(sys.argv[0] + ": Expecting one command line argument -- the integer to factor into primes") n = int(sys.argv[1]) if n < 1: sys.exit(sys.argv[0] + "Expecting a positive integer") if n == 1: print 1 sys.exit(0) def get_smallest_prime_factor(x): "Returns the smallest integer that is a factor of `x` or `None`" for i in range(2, x): if (x % i) == 0: return i return None def factor_into_primes(x): "Returns a list of prime numbers that are factors of `x`" current = x primes = [] while True: y = get_smallest_prime_factor(current) if y is None: break primes.append(y) current = current/y primes.append(current) return primes p = factor_into_primes(n) #convert to string. p_str = [] product = 1 for el in p: p_str.append(str(el)) product = product * el assert product == n print " ".join(p_str)
true
e4ba425daaa585b36e16ce7d12bd071e4843e9e4
shiningPanther/Project-Euler
/Problem2.py
1,118
4.15625
4
''' Problem 2: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''' # Recursive function to create the Fibonacci numbers up to a certain limit and also keeps score of the sum of even-valued numbers def createFibonacci(x, y, limit): # This global declaration is necessary to make python understand where to find the variable sumFibo global sumFibo newNumber = x + y if newNumber % 2 == 0: sumFibo += newNumber if newNumber < limit: fibonacciNumbers.append(newNumber) createFibonacci(fibonacciNumbers[-1], fibonacciNumbers[-2], limit) # Define the first numbers for the recursive function fibonacciNumbers = [1, 2] # The sum of the Fibonacci numbers already starts at 2 for the first two terms sumFibo = 2 limit = 4e6 createFibonacci(1,2,limit) print('Fibonacci numbers:', fibonacciNumbers) print('Sum of even Fibonacci numbers:', sumFibo)
true
f4c33344856ee099cca55c02b9c4bec38dfd841f
st-pauls-school/python
/5th/turtles-intro/turtle-intro.py
1,674
4.4375
4
#the turtle library import turtle # run (F5) this file # type one of the function names from the shell # note that if you close the turtle window, you will need to re-run this # to make new functions, copy the simple() function and replace the text in between the comments to do # the different new movements def simple(): # create the screen for the turtle to exist in ts = turtle.getscreen() # create a turtle, assign to a variable a = turtle.getturtle() # code below here moves the turtle around # move the turtle around, left and right use degrees, forward # (and backwards) are approximately pixels # at the beginning the turtle points to the right, in middle of the screen a.forward(50) # turn 90 degrees left, so it now points up a.left(90) # go forward (i.e. up) a.forward(30) # turn left again, so now pointing to the left a.left(90) # go back, i.e. to the right a.backward(100) # code above here moves the turtle around # loop around - hit control-c to exit the function back to the shell ts.mainloop() def triangle(): ts = turtle.getscreen() a = turtle.Turtle() a.forward(80) a.left(120) a.forward(80) a.left(120) a.forward(80) a.left(120) ts.mainloop() def triangle2(): ts = turtle.getscreen() a = turtle.getturtle() ts.bgcolor("lightblue") ts.title("Playground") a.color("hotpink") a.pensize(5) a.forward(80) a.left(120) a.forward(80) a.left(120) a.forward(80) a.left(120) ts.mainloop()
true
e5b991906748f48551b8036f7fdb10b4b98b03e4
yuhan1212/coding_practice
/coding_practice_private/binary_tree_traversal/depth_first/postorder.py
1,274
4.1875
4
# Construct Node class class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None # Construct BinaryTree class class BinaryTree(object): def __init__(self, root): self.root = Node(root) # Instanciate a tree: tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) tree.root.right.left = Node(6) tree.root.right.right = Node(7) # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 # / \ / \ # N N N N # Read and process each data in the Node of a BinaryTree, # by postorder (left, right, root) def postorder_recursion(root): ''' function name: postorder_recursion parameters: tree.root, read in a binary tree's root return: string, the postorder of this binary tree ''' if not root: return '' if root.value and not root.left and not root.right: return str(root.value)+" - " traversal = '' traversal += postorder_recursion(root.left) traversal += postorder_recursion(root.right) traversal += str(root.value)+" - " return traversal print(postorder_recursion(tree.root))
true
9aac2cf63015eaea8939a87c23f6e213176a261d
yuhan1212/coding_practice
/coding_practice_private/binary_tree_traversal/breadth_first/levelorder.py
1,576
4.125
4
# Construct Node class class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None # Construct BinaryTree class class BinaryTree(object): def __init__(self, root): self.root = Node(root) # Instanciate a tree: tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) tree.root.right.left = Node(6) tree.root.right.right = Node(7) # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 # / \ / \ # N N N N # Read and process each data in the Node of a BinaryTree, # by levelorder. def levelorder_recursion(root): ''' function name: levelorder_recursion parameters: root, read in a binary tree's root return: string, the postorder of this binary tree ''' if not root: return "" current_level = [root] next_level = [] traversal = "" for i in current_level: traversal += str(i.value) + " - " if i.left: next_level += [i.left] if i.right: next_level += [i.right] while next_level != []: current_level = next_level next_level = [] for i in current_level: traversal += str(i.value) + " - " if i.left: next_level += [i.left] if i.right: next_level += [i.right] return traversal print(levelorder_recursion(tree.root))
true
d9ed648b9f57c03cbe17743590720fb0213c3f2b
brucekkk/python_scripts
/txt_operate.py
1,053
4.28125
4
# -*- coding: utf-8 -*- ''' Created on 2019.11.19 @author: BMA this is a script to modify txt file, including replace one word and delete some column. Notice that if we give 1 to the delete column,it means printing first column, 2 means printing first and second columns, etc. ''' file_path = '10-1.txt' # change file name with open(file_path) as file_object: lines = file_object.readlines() contexts = '' for line in lines: contexts += line class Txt(): #this is a class for modify txt file def __init__(self,word): #initialize self.word = word def change_one_word(self): #this is a function to replace the word return contexts.replace('python',self.word) def delete_some_column(self,column): #this is a function to remove some column column_list = [ i.strip().split(' ')[:column] for i in lines ] column_out = '\n'.join([' '.join(i) for i in column_list]) return column_out new_file = Txt('c') #print(new_file.change_one_word()) file_out = new_file.delete_some_column(3) with open('output.txt','w') as f: f.write(file_out)
true
97b815570d2524c5ecd78a8d52ebc18276a45f97
mingyyy/crash_course
/week2/martes/7-5.py
637
4.125
4
''' 7-5. Movie Tickets: A movie theater charges different ticket prices depending on a person’s age . If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15 . Write a loop in which you ask users their age, and then tell them the cost of their movie ticket . ''' flag = True while flag: a = int(input("What's your age: ")) if a < 0: flag = False elif a < 3: print("The movie is FREE for you!") elif 3 <= a <= 12: print("The movie ticket is $10.") else: print("The ticket costs you $15.")
true
be43bcf5880b9f59cbddfa6052de53120aaef7cc
mingyyy/crash_course
/week1/ChangingGuestList.py
1,149
4.40625
4
''' 3-5. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a new set of invitations . You’ll have to think of someone else to invite . • Start with your program from Exercise 3-4 . Add a print statement at the end of your program stating the name of the guest who can’t make it . • Modify your list, replacing the name of the guest who can’t make it with the name of the new person you are inviting. • Print a second set of invitation messages, one for each person who is still in your list . ''' from week1.GuestList import guests x="" for i in guests: x += i +" " print(f"{x}can't make it to the dinner.") newlist = guests[-2:] newlist.insert(0, "Michael Jordan") # for i in newlist: # print(f"Dear {i}, It would be my honor to have you for dinner tonight." # f"\n\t Address: Jalan Nuyh Kuning 04\n\t Friday 7PM") ''' 3-9. Dinner Guests: Working with one of the programs from Exercises 3-4 through 3-7 (page 46), use len() to print a message indicating the number of people you are inviting to dinner . ''' print(f"{len(newlist)} guests are invited.")
true
d46f4f18129728b15fa6a391e17344a459898628
mingyyy/crash_course
/week2/viernes/class_9_6.py
857
4.53125
5
''' 9-6. Ice Cream Stand: An ice cream stand is a specific kind of restaurant . Write a class called IceCreamStand that inherits from the Restaurant class you wrote in Exercise 9-1 (page 166) or Exercise 9-4 (page 171) . Either version of the class will work; just pick the one you like better . Add an attribute called flavors that stores a list of ice cream flavors . Write a method that displays these flavors . Create an instance of IceCreamStand, and call this method . ''' from class_9_1 import Restaurant class IceCreamStand(Restaurant): flavors = ["chocolate", "durian", "cherry", "strawberry", "mint", "coffee"] def __str__(self): l = "" for i in self.flavors: l += (i+ " ") return f"There are {len(self.flavors)} flavors in {self.name} shop: " + l ics = IceCreamStand("poppy", "icecream") print(ics)
true
655652ddbc5ff290cbb0a1fe70aaf06d8bcbd2c0
mingyyy/crash_course
/week2/viernes/class_9_8.py
981
4.3125
4
''' 9-8. Privileges: Write a separate Privileges class . The class should have one attribute, privileges, that stores a list of strings as described in Exercise 9-7 . Move the show_privileges() method to this class . Make a Privileges instance as an attribute in the Admin class . Create a new instance of Admin and use your method to show its privileges . ''' from class_9_3 import User from class_9_7 import Admin class Privileges(): privileges = ["can add post", "can delete post", "can ban user", "can block user", "can delete user", "can add user"] def show_privileges(self): l = "" for i in self.privileges: l += ("- " + i + "\n") return f"There are {len(self.privileges)} attributes for Admins: \n" + l class Admin(User): p = Privileges() def display(self): return f"{self.first_name.title()} has some privileges.\n" + self.p.show_privileges() print(Admin("martin", "python").display())
true
73700d1140b8d8e53f91a673248435bde5f65007
mingyyy/crash_course
/week2/jueves/class_9_3.py
1,033
4.59375
5
''' 9-3. Users: Make a class called User . Create two attributes called first_name and last_name, and then create several other attributes that are typically stored in a user profile . Make a method called describe_user() that prints a summary of the user’s information . Make another method called greet_user() that prints a personalized greeting to the user . Create several instances representing different users, and call both methods for each user . ''' class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def describe_user(self): return f"User's full name is {self.last_name.upper()} {self.first_name.capitalize()}" def greet_user(self): print(f"{self.first_name.capitalize()}, welcome!") user1 = User("Michael", "Jordan") user2 = User("Freddy", "cocoonkid") user3 = User("Rob", "Lub") print(user1.describe_user()) print(user2.describe_user()) print(user3.describe_user()) user2.greet_user() user3.greet_user()
true
7617579a48dabff19c4bc3ddb7e7e7822db5ff03
mingyyy/crash_course
/week2/miercoles/8-3.py
555
4.59375
5
''' 8-3. T-Shirt: Write a function called make_shirt() that accepts a size and the text of a message that should be printed on the shirt . The function should print a sentence summarizing the size of the shirt and the message printed on it . Call the function once using positional arguments to make a shirt . Call the function a second time using keyword arguments . ''' def make_shirt(size, text): print(f"The shirt is in size {size}. \nIt says:'{text}' on it. ") make_shirt("XL", "Tét Chagè!") make_shirt(size="S", text="What a wonderful day!")
true
c0a2fbaebf0efe9c0eae3dea677264bd759e6b91
mingyyy/crash_course
/week1/GuestList.py
472
4.21875
4
''' 3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who would you invite? Make a list that includes at least three people you’d like to invite to dinner . Then use your list to print a message to each person, inviting them to dinner . ''' guests = ["Buddha", "Guassian", "Poisson"] for i in guests: print(f"Dear {i}, It would be my honor to have you for dinner tonight." f"\n\t Address: Jalan Nuyh Kuning 04\n\t Friday 7PM")
true
8ea04f8f0537d507c15511a4a103f8b1a2fbf6f1
mingyyy/crash_course
/week3/lunes/chap10_10.py
1,169
4.125
4
''' 10-10. Common Words: Visit Project Gutenberg (http://gutenberg.org/ ) and find a few texts you’d like to analyze . Download the text files for these works, or copy the raw text from your browser into a text file on your computer . You can use the count() method to find out how many times a word or phrase appears in a string . For example, the following code counts the number of times 'row' appears in a string: $ line = "Row, row, row your boat" >>> line.count('row') 2 $ line.lower().count('row') 3 Notice that converting the string to lowercase using lower() catches all appearances of the word you’re looking for, regardless of how it’s formatted . Write a program that reads the files you found at Project Gutenberg and determines how many times the word 'the' appears in each text . ''' from os import listdir mypath = "/Users/Ming/Documents/CodingNomads/2019_crashcourse/week3/lunes" for i in listdir(mypath): if i[:2] == "gp": n = 0 book = "" filename = i with open(i, "r") as f: book = f.read() n = book.lower().count('the') print(f"There are {n} 'the' in text file '{i}'.")
true
de8d56410cc1457009f7edd91f8880af8dacbc2b
mingyyy/crash_course
/week2/miercoles/8-9.py
314
4.15625
4
''' 8-9. Magicians: Make a list of magician’s names . Pass the list to a function called show_magicians(), which prints the name of each magician in the list . ''' def show_magicians(l): rs = " " for i in l: rs += (i + " ") return rs print(show_magicians(["Martin", "Melissa", "Michael"]))
false
3f0d2e755d26bc66570fb3fd1d2076d61982229e
Illugi317/forritun
/mimir/assignment2/3.py
518
4.1875
4
''' Write a program that reads in 3 integers and prints out the minimum of the three. ''' num1 = int(input("First number: ")) # Do not change this line num2 = int(input("Second number: ")) # Do not change this line num3 = int(input("Third number: ")) # Do not change this line # Fill in the missing code below if num1 < num2 and num1 < num3: min_int = num1 elif num2 < num1 and num2 < num3: min_int = num2 else: min_int = num3 print("The minimum is: ", min_int) # Do not change this line
true
29fce86b38d0a1d2e25c61a7b388ecd7cc2d9ed0
Illugi317/forritun
/mimir/13/1.py
1,241
4.21875
4
'''Write a program that asks for a name and a phone number from the user and stores the two in a dictionary as key-value pair. The program then asks if the user wants to enter more data (More data (y/n)? ) and depending on user choice, either asks for another name-number pair or exits. Finally, it stores the dictionary <key, values> pairs in a list of tuples and prints a sorted version of the list. Note: If a name is already in the dictionary, the old value should be overwritten. Example: Name: pranshu Number: 517-244-2426 More data (y/n)? y Name: rich Number: 517-842-5425 More data (y/n)? y Name: alireza Number: 517-432-5224 More data (y/n)? n [('alireza', '517-432-5224'), ('pranshu', '517-244-2426'), ('rich', '517-842-5425')]''' def add_to_dict(my_dict: dict, name: str, number: str): my_dict[name] = number def print_dict(my_dict) -> list: new_list = [] for key, value in sorted(my_dict.items()): new_list.append((key,value)) return new_list my_dict = dict() while True: name = input('Name: ') number = input('Number: ') add_to_dict(my_dict,name,number) more = input('More data (y/n)? ') if more == 'y': continue if more == 'n': print(print_dict(my_dict))
true
19271efb3151367a8411a66d29fa72376a7b5ba9
Illugi317/forritun
/mimir/10/2.py
890
4.1875
4
''' Write a program that makes a list of the unique letters in an input sentence. That is, if the letter "x" is used twice in a sentence, it shouild only appear once in your list. Neither punctuation nor white space should appear in your list. The letters should appear in your list in the order they appear in the input sentence. Example input/output: Input a sentence: this is, a sentence. Unique letters: ['t', 'h', 'i', 's', 'a', 'e', 'n', 'c'] Hint: import string https://docs.python.org/3.8/library/string.html ''' import string # Implement a function here def uni(sentence: str): listi = [] for char in sentence: if char not in listi and char.isalpha(): listi.append(char) return listi # Main starts here sentence = input("Input a sentence: ") # Call the function here unique_letters = uni(sentence) print("Unique letters:", unique_letters)
true
ed5273b38d45704cd164f2fafd939e8e57264a66
Illugi317/forritun
/mimir/17/2.py
1,432
4.125
4
''' 2. Sentence 5 points possible Implement a class called Sentence that has a constructor that takes a string, representing the sentence, as input. The class should have the following methods: get_first_word(): returns the first word as a string get_all_words(): returns all words in a list. replace(index, new_word): Changes a word at a particular index to new_word. For example, if the sentence is "I'm going back", then replace(2, "home") results in "I'm going home". If the index is not valid, the method does not do anything. Example use of class: sent = Sentence('This is a test') print(sent.get_first_word()) print(sent.get_all_words()) sent.replace(3, "must") print(sent.get_all_words()) Output: This ['This', 'is', 'a', 'test'] ['This', 'is', 'a', 'must'] ''' class Sentence: def __init__(self,words)-> None: self.words = words.split() def get_first_word(self): return str(self.words[0]) def get_all_words(self): return self.words def replace(self,index,word_to_replace_with): try: self.words[index] = word_to_replace_with except IndexError: pass def __str__(self) -> str: return str(self.my_value) if __name__ == '__main__': sent = Sentence('This is a test') print(sent.get_first_word()) print(sent.get_all_words()) sent.replace(3, "must") #print(sent.get_all_words())
true
0d5a143820fe0c434b581faadfafa31ff9fe4e3b
Illugi317/forritun
/mimir/assignment3/3.py
364
4.125
4
''' Write a program using a while statement, that given a series of numbers as input, adds them up until the input is 10 and then prints the total. Do not add the final 10. ''' summ = 0 while True: num = int(input("Input an int: ")) # You can copy this line but not change it if num == 10: break summ += num print(summ)
true
dcc6bf25956533d61c25830783d07cefd4c83090
Illugi317/forritun
/mimir/assignment1/3.py
330
4.15625
4
''' Write a program that: Takes an integer n as input Adds n doubled to n tripled and prints out the result Examples: If the input is 2, the result is 10 If the input is 3, the result is 15 If the input is 4, the result is 20 ''' n_str = int(input('Input n: ')) print(n_str*2 + n_str*3)
true
2bf3b0acc2f35b2c7df93af116c8c8722336d1e1
Illugi317/forritun
/mimir/assignment1/5.py
551
4.46875
4
''' BMI is a number calculated from a person's weight and height. The formula for BMI is: weight / height2 where weight is in kilograms and heights is in meters Write a program that prompts for weight in kilograms and height in centimeters and outputs the BMI. ''' weight_str = input("Weight (kg): ") # do not change this line height_str = input("Height (cm): ") # do not change this line weight = float(weight_str) height = float(height_str) / 100 bmi = weight / height**2 print("BMI is: ", bmi) # do not change this line
true
66321184d6f6c1a8d910920b83bc7968f22d0695
Illugi317/forritun
/mimir/assignment4+/2.py
1,849
4.6875
5
''' Let's attempt to draw a sine wave using the print() statement. Sine waves are usually drawn horizontally (left to right) but the print() statement creates output that is ordered from top to bottom. We'll therefore draw our wave vertically. Our program shall accept two arguments: number_of_cycles - which controls how many waves should be drawn number_of_lines - which controls how many lines are used to print the waves Python has a built in math.sin() function that we will leverage. To calculate its input, we will consider the lines to be numbered from 0 and onwards. The distance in radians is then given by: radians_per_line = number_of_cycles * 2 * math.pi / number_of_lines radians = line_number * radians_per_line math.sin(radians) will return a number between -1.0 and 1.0 inclusive. We are going to linearly transform the sine value to a number between 0 and 40 (inclusive) and round that number to figure out how many "X" characters to print. Here are a few examples: Sine value Number of X characters to print -1.0 0 0.0 20 1.0 40 0.8414709848078965 37 ''' # Don't change the following lines import math number_of_cycles = float(input("Number of cycles: ")) number_of_lines = int(input("Stretched over how many lines? ")) radians_per_line = number_of_cycles * 2 * math.pi / number_of_lines # ...now fill in the rest for i in range(number_of_lines): radians = i * radians_per_line sin = math.sin(radians) # output = output_start + ((output_end - output_start) / (input_end - input_start)) * (input - input_start) output = 0 + ((40 - 0) / (1.0 - -1.0)) * (sin - -1.0) for x in range(round(output)): print("X", end="") print()
true
33b46891082bf7233f853dfc38d160b03cccce69
Illugi317/forritun
/mimir/12/3.py
1,140
4.4375
4
''' This program builds a wordlist out of all of the words found in an input file and prints all of the unique words found in the file in alphabetical order. Remove punctuations using 'string.punctuation' and 'strip()' before adding words to the wordlist. Make your program readable! Example input file test.txt: the test file! another line in the test file. third, is this a good test? Input/Output: Enter filename: test.txt ['a', 'another', 'file', 'good', 'in', 'is', 'line', 'test', 'the', 'third', 'this'] ''' import re,string def open_file(filename): try: return open(filename,'r') except: return None new_string = string.punctuation new_new_string = new_string.replace("-","") regex = re.compile('[%s]' % re.escape(new_new_string)) def re(word): return regex.sub('',word) word_list = [] filename = input("Enter filename: ") file_object = open_file(filename) for line in file_object: for char in line.split(): word_list.append(char) new_word_list = [] for word in word_list: new_word_list.append(re(word)) new_word_list = list(dict.fromkeys(new_word_list)) print(sorted(new_word_list))
true
e3c862ed88c6d2c707f8f09d6658758ba7863ce5
Pixelsavvy72/PythonProblems
/coin toss.py
930
4.125
4
import random count = 0 heads = 0 tails = 0 headsInARow = 0 tailsInARow = 0 most = 0 least = 0 prompt = "Enter a number > " print "How many times would you like to flip the coin?" times = int(raw_input(prompt)) while count < times: flip = random.randrange(1,3,1) if flip == 1: heads += 1 headsInARow += 1 tailsInARow = 0 if headsInARow > most: most = headsInARow if least == 0: least = most if least > headsInARow: least = headsInARow else: tails += 1 tailsInARow += 1 headsInARow = 0 if tailsInARow > most: most = tailsInARow if least == 0: least = most if least > tailsInARow: least = tailsInARow count += 1 print "Heads: %s" %heads print "Tails: %s" %tails print "Most in a row was %s" %most print "Least in a row was %s" %least
false
50ba6f395942e3da9f0e75658894b09b5eccc03f
ms-shakil/Data-Structure
/Binary_Tree.py
2,765
4.125
4
class Node: def __init__(self,data): self.data = data self.left = None self.right = None def __repr__(self): return repr(self.data) def add_left(self,value): self.left = value def add_right(self,value): self.right = value def Tree(): two =Node(2) nine =Node(9) seven = Node(7) two.add_left(seven) two.add_right(nine) one =Node(1) six =Node(6) seven.add_left(one) seven.add_right(six) five = Node(5) ten = Node(10) six.add_left(five) six.add_right(ten) eight =Node(8) three =Node(3) four = Node(4) nine.add_right(eight) eight.add_left(three) eight.add_right(four) return two def Pre_order(node): print(node.data) if node.left is not None: Pre_order(node.left) if node.right is not None: Pre_order(node.right) def Post_Order(node): if node.left is not None: Post_Order(node.left) if node.right: Post_Order(node.right) print(node.data) def In_Order(node): if node.left : In_Order(node.left) print(node) if node.right: In_Order(node.right) if __name__ == "__main__": root = Tree() Pre_order(root) print("space") Post_Order(root) print("No space") In_Order(root) #### Another Binary Tree Programme ! class Queue: def __init__(self): self.arr =[] def Enqueue(self,data): self.arr.append(data) def Dequeue(self): return self.arr.pop(0) def is_empty(self): if self.arr ==[]: return True return False class TreeNode: def __init__(self,data = None): self.data= data self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None def insert(self,value): if self.root is None: self.root = TreeNode(value) else: nodes = Queue() nodes.Enqueue(self.root) while True: chacking_node = nodes.Dequeue() if chacking_node.left is None: chacking_node.left = TreeNode(value) return elif chacking_node.right is None: chacking_node.right = TreeNode(value) return else: nodes.Enqueue(chacking_node.left) nodes.Enqueue(chacking_node.right) my_tree = BinaryTree() my_tree.insert("a") my_tree.insert("b") my_tree.insert("c") my_tree.insert("d")
false
2f1aff649c38537c56124dd7b9c3d712f6f232ce
spencerhhall/phone-codes
/convert.py
1,058
4.15625
4
# Dictionary containing the number associated with each part of the alphabet ASSOCIATIONS = {"abc": 2, "def": 3, "ghi": 4, "jkl": 5,"mno": 6,"pqrs": 7,"tuv": 8, "wxyz": 9} # wordlist: array that contains all words from the wordlist that are the desired length def convertToNumbers(wordlist): combos = {} for word in wordlist: combo = "" # Iterates through each letter in the word and checks if it is part of any dict keys # (it should be 100% of the time) and then concatenates the associated value to the # combination for letter in word: # Shoutout StackOverflow for this tasty line number = [val for key, val in ASSOCIATIONS.items() if letter in key] combo += str(number[0]) # combo += number[0] # Combination is complete, now to add to dict if not already recorded or the frequency # of the combo is increased by 1 if combo in combos: # Increases frequency by 1 combos[combo] += 1 else: combos[combo] = 1 # combos is a dictionary containing all x length number combinations and their # frequency return combos
true
b6d1f075e6a8af8cdc5e2186079b992100edae66
howinator/CS303E
/6-31.py
1,602
4.25
4
def main(): import time time = time.time() year, month, days, hours, minutes, seconds = convert_seconds(time) print ("Current date and time is ", month, " ", days, ", ", year, hours, ":", minutes, ":", seconds) def convert_seconds (time): secondsInYear = 365 * 24 * 60 * 60 numYears = time // secondsInYear time -= time * numYears numYears += 1970 if time < 2678400: month = "January" time -= 2678400 elif (time < 5097600): month = "February" time -= 5097600 elif (time < 7776000): month = "March" time -= 7776000 elif (time < 10368000): time -= 10368000 month = "April" elif (time < 13046400): time -= 13046400 month = "May" elif (time < 15638400): time -= 15638400 month = "June" elif (time < 18316800): time -= 18316800 month = "July" elif (time < 20995200): time -= 20995200 month = "August" elif (time < 23587200): time -= 23587200 month = "September" elif (time < 26265600): time -= 26265600 month = "October" elif (time < 28857600): time -= 28857600 month = "November" elif (time < 31536000): time -= 31536000 month = "December" numDays = time // (24 * 60 * 60) time -= numDays * (24 * 60 * 60) numHours = time // (60 * 60) time -= numHours * 60 * 60 numMinutes = time // 60 time -= numMinutes * 60 return numYears, month, numDays, numHours, numMinutes, time main()
false
b36d2bbf9bc1c219b9d6191eb912b13012a227bb
samirsaravia/Python_101
/Bootcamp_2020/challenges/question_2.py
251
4.125
4
""" Question 2 Write python code that will create a dictionary containing key, value pairs that represent the first 12 values of the fibonacci sequence """ s = 35 a = 0 b = 1 d = dict() for i in range(s + 1): d[i] = a a, b = b, a + b print(d)
true
056ca0c2bd5d5f3a6ff11e9fbf28b6f8445f1a8c
samirsaravia/Python_101
/Bootcamp_2020/files_and_functions/challenges/3.py
335
4.3125
4
""" Question 3 Write a function to calculate a to the power of b. If b is not given its default value should be 2.Call it power """ def power(a, b=2): """ :return: returns the power of a**b. by default b is 2 """ return a ** b print(f'4 to the power of 3 gives {power(4,3)}') print(f'Inputting 4 gives {power(4)}')
true
a2ed12a50b06d55b03f368e100582a7e1a242dc1
rezende-marcus/Pythonteste
/aula08.py
263
4.15625
4
import emoji #from math import sqrt, floor #import math #num = int(input('Digite um número: ')) #raiz = sqrt(num) #raiz = math.sqrt(num) #print('A raiz de {} é igual a {:.2f}'.format(num, raiz)) #print('A raiz de {} é igual a {:.2f}'.format(num, floor(raiz)))
false
bec2a04cf084a5bfb87db165cc6c1b16a8ff0369
Smoow/MIT-UNICAMP-IPL-2021
/solutions/p2_1.py
994
4.1875
4
def square(x): """ Calculate the square of a number. Args: x [int, float]: numerical argument to be squared. Returns: Square of x. """ return x ** 2 def fourth_power(x): """ Calculate the fourth power of a number. Args: x [int, float]: numerical argument to be exponentiated. Returns: Fourth power of x. """ return square(square(x)) def perfect_square(x): """ Checks whether x is a perfect square. May fail for significantly large non-square integer inputs. Args: x [int, float]: nonnegative numerical argument to check. Returns: bool representing whether x is a perfect square """ if x < 0: raise ValueError("Input must be positive") sqrt = x ** 0.5 # se x é um quadrado perfeito, sua raiz já é um inteiro, então truncar # sqrt com int() leva ao mesmo número e a diferença é zero return (sqrt - int(sqrt)) == 0
false
e15b9185e9c602cda06553aa7dc9aca671acdf6f
PythonStudy/CorePython
/Exercise/Chapter8/8_4_PrimeNumbers.py
861
4.5
4
#coding=utf-8 """ Prime Numbers. We presented some code in this chapter to determine a number’s largest factor or if it is prime. Turn this code into a Boolean function called isprime() such that the input is a single value, and the result returned is True if the number is prime and False otherwise. """ def isprime(int_num): result = True if int_num <=0 or not isinstance(int_num,int): #print("Please give a int number bigger than 0") raise Exception("Please give a int number bigger than 0") if int_num == 1 or int_num == 2: return True for factor in range(2,int_num//2+1): if (int_num % factor == 0): result = False return result assert isprime(2) == True assert isprime(1) == True assert isprime(3) == True assert isprime(6) == False assert isprime(12) == False
true
e14d8667012aa8a66efe76bcff3b2a459633a2b2
PythonStudy/CorePython
/Exercise/Chapter8/8_7_PefectNumber.py
1,193
4.125
4
#coding = 'utf-8' #Exercise 8.7 """ Perfect Numbers. A perfect number is one whose factors (except itself) sum to itself. For example, the factors of 6 are 1, 2, 3, and 6. Since 1 + 2 + 3 is 6, it (6) is considered a perfect number. Write a function called isperfect() which takes a single integer input and outputs 1 if the number is perfect and 0 otherwise. """ def isperfect(int_num): factor_sum = 0 factors = [] for factor in range(1,int_num//2 +1): #print(factor) if int_num % factor == 0: factors.append(factor) factor_sum += factor #print('factors are ',factors) #print('factor_sum is ',factor_sum) #print('int number is : ',int_num) if factor_sum == int_num: return 1 else: return 0 def find_isperfect(int_num = 100): perfect_nums = [] for number in range(1,int_num): if isperfect(number) == 1: perfect_nums.append(number) return perfect_nums isperfect_nums = find_isperfect(100) print("perfect numbers in range are ") print(isperfect_nums) assert isperfect(6) == 1 assert isperfect(18) == 0 assert isperfect(28) == 1
true
6764bb9e4f541c46872550d6f60f04b3c4c8c141
KHungeberg/Python-introcourse
/C4Assignment4E (2).py
1,008
4.125
4
# Assignment 4E: Bacteria growth: import numpy as np import math as ma # Write a program that simulates the bacteria growth hour by hour and stops when the number of bacteria exceeds # some fixed number, N. Your program must return the time t at which the population first exceeds N. Even # though the actual number of bacteria is really a whole number (integer) your program must work with nt as a # decimal number (real), i.e., you should not round the numbers # The number of bacteria at n+1 is best approximated by the formula: # n(t+1)=(1+alpha*(1-n(t)/K))*nt # In function we'll have 4 inputs: #a0=Number of bacteria at t=0 #alpha=out population growth coefficient. #K=capacity(maximal number of bacteria possible) #N=Final pupulationsize def bacteriaGrowth(n0,alpha,K,N): tN = n0 t = 0 while tN < N: tN = (1+alpha*(1-tN/K))*tN t = t+1 return t print(bacteriaGrowth(100.0, 0.4, 1000.0, 500.0))
true
80f5f93884735da50dcf50c2438a400a2f387974
KHungeberg/Python-introcourse
/C3Assignment3C.py
701
4.1875
4
#ASSIGNMENT 3C # Write a function that takes as input two unit vectors v1 and v2 representing two lines, and computes the acute # angle between the lines measured in radians. # First we import math and numpy import math as m import numpy as np # The formula for calculating the angle between 2 unitvectors is arrccos of the dot product of the vectors. # We define out function as such: def acuteAngle(v1,v2): if m.acos(np.dot(v1,v2))>(m.pi/2): theta = m.pi - m.acos(np.dot(v1,v2)) else: theta = m.acos(np.dot(v1,v2)) return theta print(acuteAngle(np.array([(-4.0)/5.0,3.0/5.0]),np.array([(20.0)/(29.0),(21.0)/(29.0)]))) #Test of function.
true
e77faccfbf6c28f62145b4a70414217f7ca9a873
jamiebrynes7/advent-of-code-2017
/day_3/challenge1.py
1,037
4.125
4
import sys import math def main(): # Get input arguments. try: target_square = int(sys.argv[1]) except IndexError: print("Usage: python challenge1.py <target_square>") exit(1) # Get the closest perfect odd square root (defines dimensions of the square) closest_perfect_square_root = math.ceil(math.sqrt(target_square)) closest_perfect_square_root += 1 if closest_perfect_square_root % 2 == 0 else 0 # Will always be on the outside of the square. Need to find out where. edge = int((closest_perfect_square_root ** 2 - target_square) / closest_perfect_square_root) # Edge of 0 means bottom, 1 means left, 2 means top, etc... distance_along_edge = closest_perfect_square_root ** 2 - target_square - edge * closest_perfect_square_root result = int(closest_perfect_square_root / 2) + int(closest_perfect_square_root / 2) - distance_along_edge print("The answer is: " + str(result)) if __name__ == "__main__": main()
true
de22af72c9b8d49040639b5e4c05c78ef9b15a9e
rohitraghavan/D05
/HW05_ex09_01.py
674
4.15625
4
#!/usr/bin/env python3 # HW05_ex09_01.py # Write a program that reads words.txt and prints only the # words with more than 20 characters (not counting whitespace). ############################################################################## # Imports # Body def read_check_words(): """This method reads a file and prints words > 20 chars""" try: words_file = open("words.txt") except: print("Something went wrong") return for line in words_file: word = line.strip() if len(word) > 20: print(word) ############################################################################## def main(): read_check_words() if __name__ == '__main__': main()
true
62aac78ddb481d0a40391b4eaeeb1e0a894531c5
kazenski-dev/01_ling_progr_cesusc
/N1_exercicio_02.py
1,976
4.46875
4
""" Crie um classe Funcionário com os atributos nome, idade e salário. Deve ter um método aumenta_salario. Crie duas subclasses da classe funcionário, programador e analista, implementando o método nas duas subclasses. Para o programador some ao atributo salário mais 20 e ao analista some ao salário mais 30, mostrando na tela o valor. Depois disso, crie uma classe de testes instanciando os objetos programador e analista e chame o método aumenta_salario de cada um.(2,0) """ class Funcionario: def __init__(self, nome, idade, salario): self.nome = nome self.idade = idade self.salario = salario self.aumento = 0 def aumenta_salario(self): self.salario = self.salario + self.aumento class Programador(Funcionario): def __init__(self, nome, idade, salario): Funcionario.__init__(self, nome, idade, salario) self.aumento = 20 class Analista(Funcionario): def __init__(self, nome, idade, salario): Funcionario.__init__(self, nome, idade, salario) self.aumento = 30 class Teste(Funcionario): def __init__(self, nome, idade, salario): Funcionario.__init__(self, nome, idade, salario) self.aumento = 90 pessoa_dev = Programador("Eduardo kazenski", 29, 1500) print("Funcionario: {0}".format(pessoa_dev.nome)) print("Salario normal: {0}".format(pessoa_dev.salario)) pessoa_dev.aumenta_salario() print("Salario com acrecimo: {0}".format(pessoa_dev.salario)) pessoa_analyst = Analista("Lucicreide", 30, 2500) print("Funcionario: {0}".format(pessoa_analyst.nome)) print("Salario normal: {0}".format(pessoa_analyst.salario)) pessoa_analyst.aumenta_salario() print("Salario com acrecimo: {0}".format(pessoa_analyst.salario)) bckp_teste = Teste("pessoa cadastrada", 1, 1) print("Funcionario: {0}".format(bckp_teste.nome)) print("Salario normal: {0}".format(bckp_teste.salario)) pessoa_analyst.aumenta_salario() print("Salario com acrecimo: {0}".format(bckp_teste.salario))
false
0af43e944a3d5ac7680c69af69908361c95f545b
philipesko/LearningPython14
/Lesson1/CompareStringToString.py
491
4.125
4
def compareStr (a, b): if type(a) is str and type(b) is str: print(0) if a == b: print(1) elif len(a) > len(b) and not a == b: print(2) elif b == 'learn' and not a == b: print(3) else: print("This is not string!") print('------') compareStr('test', 'learn') compareStr(int(12), int(123)) compareStr('test', 'test') compareStr('kokoko', '12б') compareStr(13, 14)
false
21bd0fa289fe626e6d52a6328225af89bbac7217
tomvangoethem/toledo
/03_find_triplets/find_triplets.py
1,285
4.125
4
""" Write a program that takes a list of integer numbers as input. Determine the number of sets of 3 items from the list, that sum to 0. E.g. if the list = [5, -2, 4 , -8, 3], then there is one such triplet: 5 + (-8) + 3 = 0. For larger lists, the number of triplets probably will be much higher. If the list would contain a value more than once, count a triplet for each item with this value. E.g. the list [5, -2, 4, 3, -8, 3] will have two triplets: 5 + 3 + (-8) = 0 (with value 3 from position 3) and 5 + (-8) + 3 = 0 (with value 3 from the last position in the list) What is the time complexity of your algorithm? Suppose your algorithm works in time T(n) = a*n^b, then you can easily derive that T(2n)/T(n) = 2^b. Measure T(n) and T(2n) for some value of n, and use these measurements to estimate the exponent b for your algorithm. """ def find_triplets(seq): return 0 assert find_triplets([]) == 0 # At least 3 items required assert find_triplets([3,-3]) == 0 # At least 3 items required assert find_triplets([1, -1, 0]) == 1 # Trivial case assert find_triplets([2, -1, -1]) == 1 # Trivial case assert find_triplets([5, -2, 4 , -8, 3]) == 1 assert find_triplets([3, -2, 2, 0, -1, -5]) == 3 assert find_triplets([4, -2, 0, 2, -1, -2, -1, -4, 3, -6, 5, -9]) == 13
true
5f7582dc194423187d59d370056439e6c1ebfd3a
Jhonatanpasos/Introprogramacion
/Talleres/Tallercondicionales2.py
1,331
4.25
4
#--------------------------------Ejercicios condicionales---------------------------------# #1. Dados dos numeros, determine si son iguales o cual es el mayor #2. Pida la edad del usuario y muestre en pantalla la siguiente información: # - Si tiene menos de 18 años diga que es menor de edad # - Desde 18 hasta 25 es joven # - Desde 26 hasta 60 es adulto # - Mayor a 60 es adulto mayor #3. Escriba un programa que pida el año actual y un año cualquiera, y que escriba cuantos # años han pasado desde ese año, o cuantos años falta para llegar a ese año #4. Escriba un programa que pida una distancia en cm y escriba esa distancia en km, m y cm #Ejercicio 2 print ("#"*20, "¿Eres joven, adulto o adulto mayor?", "#"*20) #-----constantes----- Bienvenida = "¡Bienvenido! vamos a mirar si eres joven o adulto" Mensajeresultado = "De acuerdo a los datos ingresados, tu eres un {}" PreguntaEdad = "Ingrese su edad : " #-----Codigo de entrada----- print (Bienvenida) edad = int (input (PreguntaEdad)) if (edad < 18): print (Mensajeresultado.format ("menor de edad")) elif (edad >= 18 and edad <= 25): print (Mensajeresultado.format ("adulto joven")) elif (edad >= 26 and edad <= 60): print (Mensajeresultado.format ("adulto")) else : print (Mensajeresultado.format ("adulto mayor"))
false
6ab1c7ca59e057eb8468408324a67ea728ed1e8e
Jhonatanpasos/Introprogramacion
/Clases/Operaciones.py
817
4.25
4
#Le otorgamos un valor a las variables numeroA = 87 numeroB = 83 #Realizamos una suma entre las variables sumar = numeroA + numeroB print ("el resutado de la suma es", sumar) print (f"la suma dio {sumar} exitosamente") #Realizamos una resta entre las variables restar = numeroA - numeroB print ("el resutado de la resta es", restar) #Realizamos una multiplicación entre las variables multiplicar =numeroA * numeroB print ("el resultado de la multiplicación es", multiplicar) #Realizamos una división entre variables dividir = numeroA / numeroB print ("el resultado de la división es", dividir) #Elevamos una variable a otra variable exponente = numeroA**numeroB print ("el resultado de la elevación al exponente es", exponente) #Usamos print para mostrar en pantalla los resultados de las operaciones realizadas
false
22909c205fde49807b154925facd55aee51edc55
MCHARNETT/Simple-Projects
/fibonacci.py
618
4.5
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 26 11:07:59 2017 @author: harne """ import sys def fibonacciSeries(n): ''' n is the range of values that the program will calculate the series up to. returns a list of the fibbonaci numbers in that range. ''' fibbonaci_numbers = [1, 1] for i in range(n): if i>1: fibbonaci_numbers.append(fibbonaci_numbers[i-1]+fibbonaci_numbers[i-2]) return fibbonaci_numbers result = int(input("enter the value you want to calculate the fibbonacci sequence up to: ")) print (fibonacciSeries(result))
true
1539fb30613474a6a14579b40bca98431b3cab79
YeashineTu/HelloWord
/game.py
859
4.21875
4
#!/usr/bin/python #-*- coding utf-8 -*- #date:20171011 #author:tyx #==== 点球小游戏 ==== def isRight(value,list): if value not in direction: print('Your direction is not right,input again') return False else: return True def isEqual(value1,value2): if(value1==value2[0]): print("sorry,you lost the score") return True else: print("Congratulations!") return False import random score_me=0 score_computer=0 isTrue=False i=1 direction=['left','middle','right'] while(i<=3): com_direc=random.sample(direction,1) print("###Round %d"%i) print("Please input your direction,'left','middle'or'right' ") my_dirc=input() while(isTrue==False): isTrue=isRight(my_dirc,direction) if isEqual(my_dirc,com_direc): score_computer +=1 else: score_me +=1 i+=1 print('my score is :%d'%score_me) print("computer's score is:%d"%score_computer)
true
dd104ea65ffd608e4d34783422e77e3aab2caf5b
lostarray/LeetCode
/027_Remove_Element.py
1,127
4.15625
4
# Given an array and a value, remove all instances of that value in place and return the new length. # # Do not allocate extra space for another array, you must do this in place with constant memory. # # The order of elements can be changed. It doesn't matter what you leave beyond the new length. # # Example: # Given input array nums = [3,2,2,3], val = 3 # # Your function should return length = 2, with the first two elements of nums being 2. # # Hint: # # Try two pointers. # Did you use the property of "the order of elements can be changed"? # What happens when the elements to remove are rare? # # Tags: Array, Two Pointers class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ length = len(nums) i = 0 while i < length: while nums[i] == val and length > i: length -= 1 nums[i] = nums[length] i += 1 return length if __name__ == '__main__': nums = [4, 5] print Solution().removeElement(nums, 5) print nums
true
71b64e10176d739cd899624a4ece18d2369a4053
Aehlius/CS-UY_1134
/HW/HW4/ia913_hw4_q4.py
1,154
4.28125
4
import BST_complete def create_chain_bst(n): # this function creates a degenerate tree with all right children from 1 to n chain_tree = BST_complete.BST() for i in range(n): # since the loop will insert larger values as it continues, all children will be right chain_tree.insert(i+1) return chain_tree def add_items(bst, low, high): # this recursive function will add items in an order as to create a balanced tree mid = int((low+high)/2) if high <= low: bst.insert(mid) else: bst.insert(mid) add_items(bst, low, mid-1) add_items(bst, mid+1, high) def create_complete_bst(n): # this function will create a balanced tree in range from 1 to n bst = BST_complete.BST() add_items(bst, 1, n) return bst """ The complexity for both algorithms is O(n), since the insert function will insert every value from 1 to n only once, and perform a constant amount of work in order to find the location of each item I.e. every recursive call performs a constant amount of work and there are a total of n recursive calls Therefore, work is O(n) in both functions """
true
283214a2ea9b857cf20e782d328d9ae32baee10a
JasperMi/python_learning
/test/chapter_04/test2.py
447
4.40625
4
# range(1,6):生成1-5的数字 for value in range(1, 6): print(value) # list():将其中的值转换为列表 numbers = list(range(1, 6)) print(numbers) # 生成1-10之间的偶数 even_numbers = list(range(2, 11, 2)) print(even_numbers) numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] # 获得数字列表中的最大值 print(max(numbers)) # 获得数字列表中的最小值 print(min(numbers)) # 获得数字列表的和 print(sum(numbers))
false
04ec80a89fb31219728371330989b67900b00977
JasperMi/python_learning
/chapter_04/pizzas.py
416
4.21875
4
pizzas = ['seafood pizza', 'cheese pizza', 'beef pizza'] # 创建副本 friends_pizzas = pizzas[:] pizzas.append('chicken pizza') friends_pizzas.append('corn pizza') # for pizza in pizzas: # print("I like " + pizza) print("My favorite pizzas are:") for pizza in pizzas: print(pizza) print("\nMy friends favorite pizzas are:") for pizza in friends_pizzas: print(pizza) # print("I really love pizza!")
true
511c7189863776d385c52fdb088c37d1555a87fc
sushmita-2001/Python-p2p-programming-classes
/calc.py
685
4.4375
4
print('Welcome to the calculator world!!') print('Please type the math operation you want to complete') print("+ for addition \n - for subraction \n * for multiplication \n / for division \n ** for power \n % for modulus") num1 = int(input('Enter the first number: ')) num2 = int(input('Enter the second number: ')) operator = input('Which operator do you want to use?: ') if operator == '+': print(num1 + num2) elif operator == '-': print(num1 - num2) elif operator == '*': print(num1 * num2) elif operator == '/': print(num1 / num2) elif operator == '**': print(num1 ** num2) elif operator == '%': print(num1 % num2)
true
e0a8234f3f2c1eb5e0c20c24f561971ad4d701e7
nakinnubis/abiola_akinnubi_test
/QuestionIsOverlapProgram python version/isoverlap.py
1,267
4.25
4
import sys #this lambda converts string to float since python does not have decimal tofloat = lambda x:float(x) #this converts inputs to array but calls the tofloat method on each inputs def InputToArray(inpt): values = [] listvalue = inpt.split(',') for inp in listvalue: values.append(tofloat(inp)) if(len(values) > 1 and len(values) < 3): return values else: return None #lambda that takes two arguements one for x4 and x1 for comparing values #the other takes two arguments as well to compare x3 and x2 RightIsLessThanLeft = lambda x4,x1:x4 < x1 RightIsGreaterThanLeft = lambda x3,x2:x3 > x2 def main(): input1 = input("Enter the value of x1,x2 by separating the input with a comma: ") input2 = input("Enter the value of x3,x4 by separating the input with a comma: ") firstcoordinate = InputToArray(input1) secondcoordinate = InputToArray(input2) if(firstcoordinate != None and secondcoordinate != None): if (RightIsLessThanLeft(secondcoordinate[1], firstcoordinate[0]) or RightIsGreaterThanLeft(secondcoordinate[0], firstcoordinate[1])): print("LINES DOES NOT OVERLAP") else: print("LINES DOES OVERLAP") if __name__ == "__main__": main()
true
c721ff8e28c36253644f4893cf75f6a69e0040ed
prafful/python_jan_2020
/32_threads.py
818
4.25
4
""" thread as smallest unit of execution! multithreading thread module (depreceated) (python 3+ has _thread to support backward compatibility!) threading module """ import _thread import time def callMeForEachThread(threadName, delay): counter = 0 while counter<=5: print(threadName," " , "Current Counter:", counter) time.sleep(delay) counter+=1 print(threadName, " Time: ", time.time()) # function being called by main thread! #callMeForEachThread("Thread 1", 1) _thread.start_new_thread(callMeForEachThread, ("Thread 1", 1)) _thread.start_new_thread(callMeForEachThread, ("Thread 2", 2)) _thread.start_new_thread(callMeForEachThread, ("Thread 3", 3)) _thread.start_new_thread(callMeForEachThread, ("Thread 4", 4)) input() #fuoco
true
42c32fe289ab0c5534b4332592cd6e88371e05a6
prafful/python_jan_2020
/22_oops_class.py
960
4.28125
4
''' class instance attributes class attributes self __init__ ''' #create custom class in python class Vehicle: vehicleCount = 0 #constructor def __init__(self, color, vtype): print("I am in constructor!") self.color = color self.vtype = vtype Vehicle.vehicleCount += 1 def selectVehicle(self): print("{0:-^30}".format("Vehicle Info")) print("Vehicle Color: ", self.color) print("Vehicle Type: ", self.vtype) myVehicle1 = Vehicle('Red', 'SUV') myVehicle2 = Vehicle('Black', 'Sedan') myVehicle3 = Vehicle('Purple', 'MUV') print("Count of vehicle instances: ", Vehicle.vehicleCount) myVehicle1.selectVehicle() myVehicle2.selectVehicle() myVehicle3.selectVehicle() class Shop: def __init__(self, name, no): self.name = name self.no = no print("I am in Shop constructor!") myShop = Shop("Pyarelal Sweets", 444) print(myShop.name) print(myShop.no)
true
81b05a94802aba0c980133a86297c4fccfedaae8
junjiegithub/hello_world
/brother_wu_19/test/3test.py
1,404
4.28125
4
''' 函数的定义: 1,具备某一功能的代码段 2.可以重复使用 函数的定义语法: def 函数名称(): 函数体(实现功能的代码段) 注意:函数体的缩进 函数的调用 调用语法 没有参数: 函数名称() 有函数: 函数名称(实参值) 丰富你的函数-返回值 语法: :return[变量] def 函数的名称(参数): 函数体(实现功能的代码段) :return 变量(没有变量,返回None) 1.返回值可以是任何类型的变量 2.返回值也可以是表达式 3,可以返回一个/多个变量,可以用逗号隔开或者元祖 4,函数体执行过程中,遇到return意味着函数调用结束 5.函数中没有return关键字,默认返回None 6.使用较多,返回的值可以用来传递给其他函数 ''' # # def san(): # print("遮风挡雨遮阳") # # san() # san() def get_money_from_ATM(bank_id,passwd,money): #验证你的银行卡是否有效,是否有余额 #检测:密码是否正确 #取款 金额 是否< 你的存款 #以上符合的情况下,吐出人民币给你,完了再吐出你的银行卡 print("******") print(bank_id,passwd,money) return bank_id,money icbc_card_id ="1111111111" passwd="123456" money=2000 ccc,mon=get_money_from_ATM(icbc_card_id,passwd,money) print(ccc,money)
false
5c6f3e64420a0c773c93c7e3c7711544a52a3c76
yeazin/python-test-tutorial-folder
/csv input tutorial/reading csv.py
496
4.21875
4
#reading CSV file import csv with open('csvfile.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') dates=[] colors=[] for row in readCSV: ''' print('') print(row[0],row[1],row[2],row[3]) ''' color=row[3] date=[0] dates.append(date) colors.append(color) print(dates) print(colors) askcolor=input('what color do u want to know the date of?:') coldex= colors.index(askcolor.lower()) thedate = dates[coldex] print('the date of ',askcolor,'is',thedate)
true
ac563df061b4ac6abd833d73f5bcfa66cd06851a
ngirmachew/data-structures-algorithms-1
/CtCI/Ch.1 - Arrays & Strings/1.6string_compression.py
769
4.28125
4
def string_compression(input_string): # takes care of upper and lower case -> all to lower # example: given aabcccccaaa shoud return -> a2b1c5a3 input_string = input_string.lower() count = 1 # string that is used to store the compressed string compressed_str = "" for i in range(len(input_string) - 1): if input_string[i] == input_string[i + 1]: count += 1 else: compressed_str += input_string[i] + str(count) count = 1 print(i) print(input_string[i]) print(count) compressed_str += input_string[i] + str(count) if len(compressed_str) >= len(input_string): return input_string else: return compressed_str print(string_compression('aabcccccaaa'))
true
72f459eb7ab8ac7a7cd719077e51f6e404b08eae
CristianMoraS/Metodos_Ordenamiento_Python
/Métodos de Ordenamiento/Algoritmos - Metodos/QuickSort.py
2,784
4.1875
4
import random # Importamos la clase random para los datos randomicos. import time # Se importa la clase time, para saber el tiempo de ejecucion del programa. # El siguiente es el método de ordenamiento QuickSort, acepta como parametro una lista (array), la cual es la # Traduccion de nuestros datos, almacenados por comas en un archivo. def QuickSort(lista): # Las siguientes 3 listas, se utilizan para recorrer este arreglo y realizar las comparaciones. izquierda = [] centro = [] derecha = [] # El siguiente condicional depende si nuestro arreglo contiene elementos. if len(lista) > 1: # La variable "pivote" se inicializa en el primer dato del array, y se utiliza para tener de ejemplo # ese dato, para compararlo con los demas, hasta hallar uno menor, igual o mayor: """ 1. Si el dato es menor se convertira en el nuevo pivote- 2. Si el dato es igual, se coloca despues del pivote. 3. Si el dato es mayor, debe ir despues del pivote. """ pivote = lista[0] for i in lista: # Este ciclo for, recorre el array. # los siguiente condicionales realizan las comparaciones con respecto a nuestro pivote, con respecto # a los demas elementos que componen el array. if i < pivote: izquierda.append(i) elif i == pivote: centro.append(i) elif i > pivote: derecha.append(i) #print(izquierda+["-"]+centro+["-"]+derecha) return QuickSort(izquierda)+centro+QuickSort(derecha) else: return lista #Escribe numeros en un archivo llamado "Ejemplo.txt" File = open("Ejemplo.txt", "w") for i in range(100): # Se utiliza el ciclo for, para llenar el archivo con los datos randomicos # y separados por comas. File.write( str(random.randint(1,1000)) + "," ) # La función Write se utiliza para escribir sobre el archivo, # teniendo en cuenta que estan separados por comas. File.close() # La función Close, se utiliza para cerrar el archivo sobre el cual se esta escribiendo. # Leer y sumar los numeros del archivo "Ejemplo.txt" fr = open("Ejemplo.txt", "r") for line in fr: # El ciclo for en este caso, se utiliza para leer los datos y las lineas del archivo. files = line.split(",") # El Método Split se encarga de leer solamente los datos, que no sean comas (,). tam = len(files)-1 # Len sirve para obtener la longitud. # Impreción de los arreglos ordenados y no ordenados. print ("No Ordenado \n") print(files) print ("Ordenado \n") print(QuickSort(files)) hms = time.time() # La siguiente linea expresa el tiempo de ejecucion print((time.time()) - hms) fr.close()
false
26d65ef77f47517779fe29dfed53ddeb883f4841
manupachauri1023/manupachauri1023
/manu leap year.py
309
4.1875
4
year = int(input("enter the year") if year%4==0 and year % 100 !=0: print("it is a leap year") elif year % 100 ==0: print("it is not leap year") elif year % 400 ==0: print("it is a leap year") else: print("it is not a leap year)
false
3efb6832abc42063722faa7e3fe006e06978abbf
mollyocr/learningpython
/practicepython/exercise6.py
1,057
4.46875
4
### 2018-10-29 mollyocr #### practicepython.org exercise 6: string lists ## Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) string_to_eval = input("Hi! Enter a string. I'll tell you if it's a palidrome or not. ") #### Yo, you don't have to cast a str because input is always a string. string_to_eval = string_to_eval.replace(" ", "") #### list[start, stop, step] will build you a sublist. # string_backwards = string_to_eval[::-1] # # if string_to_eval == string_backwards: # print (f"\"{string_to_eval}\" is a palindrome!") # else: # print (f"\"{string_to_eval}\" is not a palindrome!") #### You can condense it tho: if string_to_eval == string_to_eval[::-1]: print (f"\"{string_to_eval}\" is a palindrome!") else: print (f"\"{string_to_eval}\" is not a palindrome!") #### DONE: This only works for palindromes that are words, not phrases with spaces. Fix that! How do you erase spaces? #### Print lines aren't pretty anymore.
true
75d3fed54c68a294785a43e57f068d2bee765c5c
mollyocr/learningpython
/practicepython/exercise4.py
1,340
4.4375
4
#### 2018-10-25 mollyocr #### practicepython.org exercise 4: divisors ## Create a program that asks the user for a number and then prints out a list of all the divisors of that number. (A divisor is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.) number_to_eval = int(input("Hi! Enter a number, and then I'll tell you all of its divisors. ")) #### Good job, yo, for casting that input up front. ##### 1. take number_to_eval & create a list using range function of all of the integers between 0 and number_to_eval... plus the number_to_eval itself eval_range = range(1, number_to_eval+1) # print (list(eval_range)) #### A number is a divisor of itself so the +1 is necessary to include number_to_eval in the range. Is there a more elegant way to do this? #### Similarly, need to exclude 0 from the range or you'll get a "ZeroDivisionError: integer division or modulo by zero" error. ##### 2. you'll need some for and if statements, and another list to put things in # divisor_list = [] # # for item in eval_range: # if number_to_eval % item == 0: # divisor_list.append(item) # # print (divisor_list) #### OR you can just print it. Cleaner but not as portable maybe?-- for item in eval_range: if number_to_eval % item == 0: print (item)
true
73f3882babca313f137eff0892e8ef9ebc41bf2a
imushir/qxp_python_class_july_2019
/QuickxpertPython-master/13042019/class/example_scdnd.py
2,058
4.3125
4
class Employee: """ This Employee class """ company_name = "Quickxpert" # class variable def __init__(self): """ This is constructor of class Employee. Initializes the attribute values. :returns: None :rtype: None :author: Qxpert """ # Instance variables self.employee_name = "" self.employee_age = "" self.employee_dob = "" self.employee_department = "" def set_employee_details(self, emply_nm, emply_age, emply_dob, emply_dprt): """ This function will set the employee details. :param emply_nm: contains the employee's name :type emply_nm: string :param emply_age: contains the employee's age :type: string :param emply_dob: contains the employee's dob :type: string :param emply_dprt: contains the employee's dprt :type: string :returns: None :rtype: None :author: Qxprt """ self.employee_name = emply_nm self.employee_age = emply_age self.employee_dob = emply_dob self.employee_department = emply_dprt def get_employee_details(self): """ This function will print the employee details :returns: employee details :rtype: string :author: Qxprt """ print("Employee Name {}\nEmployee Age {}\nEmployee Date of Birth {}\n" \ "Employee Department {}".format(self.employee_name, self.employee_age, \ self.employee_dob, self.employee_department)) if __name__ == "__main__": name = input("Enter employee name : ") age = input("Enter employee age : ") dob = input("Enter employee dob : ") department = input("Enter the employee department : ") emply_one_obj = Employee() emply_two_obj= Employee() emply_thr_obj = Employee() emply_one_obj.set_employee_details(name, age, dob, department) emply_one_obj.get_employee_details()
true
e7f673bf317a07788ef32be89ed6f81f3669b9e4
hsingh08/Python-Programming
/Source Codes/Lecture 1 Excersies/areaof circle.py
224
4.125
4
import math num1String = input('Please enter the radius of the circle: ') Radius = int(num1String) AOC=math.pi*Radius*Radius CF=2*math.pi*Radius print ("Area of the Circle is",AOC) print ("Circumference of the Circle is",CF)
true
b66153a0db603adce890f8d50bd248b01bf5fc00
aditp928/cyber-secruitiy-
/4-OldFiles/Unit03-Python/2/Activities/02-Ins_IntroToDictionaries/dictionaries.py
1,260
4.625
5
# Creating a dictionary by setting a variable equal to "keys" and "values" contained within curly brackets pet = { # A key is a string while the value can be any data type "name": "Misty", "breed": "Mutt", "age": 12 } print(pet) # A single value can be collected by referencing the dictionary and then using the key as the index print(pet["name"]) # The value of a key can also be changed by setting it equal to a new value pet["age"] = 13 print(pet["age"]) # The del() function can be used to remove a key/value pair from a dictionary del(pet["breed"]) print(pet) # .keys() can be used to collect a list of the keys in a dictionary print(pet.keys()) # .values() can be used to collect a list of the values in a dictionary print(pet.values()) # A list of dictionaries petList = [ { "name": "Misty", "breed": "Mutt", "age": 12 }, { "name": "Pixel", "breed": "Beagle", "age": 2 }, { "name": "Rockington", "breed": "Igneous", "age": 200000 } ] # Looping through the list to then print out the values in the dictionary for pet in petList: print(pet["name"] + " is a " + pet["breed"] + " that is " + str(pet["age"]) + " years old")
true
9b5f0f216ed287ff1e2267aa856958a9ae7fa303
aditp928/cyber-secruitiy-
/1-Lesson-Plans/Unit03-Python/4-Review/Activities/11-Par_Inventory/Unsolved/inventory_collector.py
574
4.5
4
# TODO: Create an empty dictionary, called inventory # TODO: Ask the user how many items they have in their inventory # TODO: Use `range` and `for` to loop over each number up to the inventory number # TODO: Inside the loop, prompt the user for the name of an item in their inventory ("What's the item? ") # TODO: Then, prompt the user for the price of that item ("How much does it cost? ") # TODO: Finally, put the item into the dictionary as the key, and associate it with its price # TODO: Outside of the loop, use `items` to print: "The price of <ITEM> is $<PRICE>."
true
ab2f60bce0d8db79d03bb4b9c9d9816c05ecd5ff
aditp928/cyber-secruitiy-
/1-Lesson-Plans/Unit03-Python/2/Activities/07-Stu_FirstFunctions/Solved/Length.py
221
4.21875
4
# function to get the length of an item def length(item): count = 0 for i in item: count = count + 1 return count print(length("hello")) print(length("goodbye")) print(length(["hello", "goodbye"]))
true
3b15c02306cdef261e92a40b878fdacec5c135b2
aditp928/cyber-secruitiy-
/4-OldFiles/Unit03-Python/2/Activities/08-Ins_WritingFiles/WriteFile.py
819
4.34375
4
# Not only can Python read files, it can also write to files as well # The open() function is used once more but now "w" is used instead of "r" diary_file = open("MyPersonalDiary.txt", "w") parts_of_entry = ["Dear Diary,", "\n", "Today I learned how to write text into files using Python!", " ", "It was pretty great."] # Text is written into files one string at a time. Because of this, it is usually a good idea to combine all of the text into a single string before writing it all at once. full_text = "" for part in parts_of_entry: # The += operator takes the original value of the variable and adds the following value to it full_text += part print(full_text) # The .write() function is then used to push the text into the external file diary_file.write(full_text)
true
516293e2fd7545225d84ff047c0bb3a0c86668e3
aditp928/cyber-secruitiy-
/4-OldFiles/Unit03-Python/1/Activities/06-Ins_ForLoops/ForLoops.py
1,044
4.4375
4
hobbies = ["Rock Climbing", "Bug Collecting", "Cooking", "Knitting", "Writing"] weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] # Looping through the values in a list for hobby in hobbies: print(hobby) print("-------------") # It is possible to loop through the length of a list numerically too for x in range(len(hobbies)): print(x) # You can also use this to loop through the index of a list print(hobbies[x]) # This also means that you can loop through two or more lists at once print(weekdays[x]) print("-------------") # It is possible to loop through a range of numbers as well # The first number in range() is the starting value while the second is the number to loop up to for x in range(2, 5): print(x) print("-------------") # Nested for loops can also be used to loop through lists of differing lengths users_info = [ ["Jacob", "Password123"], ["Ronessa", "AGreatPasscode"], ["Eric", "PassPassPass"] ] for user in users_info: for info in user: print(info)
true
6fa93041b3158f07fd1ae5ac7a55cc3af2838e84
MargoshKKa/roman_numbers_converter
/main.py
1,039
4.28125
4
from converters.to_roman_converter import arabic_to_roman from converters.to_arabic_converter import roman_to_arabic def menu(): value = '' while value != 'e': value = input(''' What do you want to do? e - exit the program r - convert roman to arabic a - convert arabic to roman ''') try: if value == 'r': roman_case() elif value == 'a': arabic_case() elif value == 'e': break else: continue except ValueError as err: print(f''' Invalid input! {err.args[0]}''') def roman_case(): roman = input("Enter roman number: ") transformed_number = roman_to_arabic(roman) print(f'Arabic value: {transformed_number}') def arabic_case(): number = input("Enter arabic number: ") transformed_number = arabic_to_roman(int(number)) print(f'Roman value: {transformed_number}') def main(): menu() if __name__ == '__main__': main()
false
853baa71b9e872547c8bd04cc6186da5dd62c3f9
UmarAlam27/Python_beginner_learning_
/faulty calc by nikhil.py
1,592
4.3125
4
#Exercise #Design a calculator which will correctly solve all the problems except.. #..the following ones # 45 * 3 = 555, 56 + 9 = 77, 56/6=4 # ...Your program should take operator and the two numbers as input from user and return the result # making a faulty calculator while(True): print ("Enter rrthe First no.\n") var1 = int (input()) print ("Enterrr the Second no.\n") var2 = int (input()) operator=input("Enter the , Available Operations: + , - , * , / , ** , %\n") if (max(var1, var2) == 45 and min(var1, var2) == 3 and operator == "*"): print("Result:", "555") elif (max(var1, var2) == 56 and min(var1, var2) == 9 and operator == "+"): print("Result:", "77") elif (var1== 56 and var2 == 6 and operator == "/"): print("Result:", "4") else: if (operator == "+"): print("Result:", var1 + var2) elif (operator == "-"): print("Result:", var1 - var2) elif (operator == "*"): print("Result:", var1 * var2) elif (operator == "/"): print("Result:", var1 / var2) elif (operator=="**"): print("Result:", var1 ** var2) elif(operator=="%"): print("Result:", var1 % var2) if((input("Do you want to continue calculating? If yes type 'Y' else type 'N' \n")).capitalize() =='Y'): continue else: print("Thank You for using the Calculator") break # created by aditya
true
407511e14db6518f72240a8143a94ba7bdf1984a
unalenes1/python
/class3.py
586
4.21875
4
#Overloading / Aşırı Yükleme #Vektor Adında Sınıfımızı Oluşturuyoruz class Vector: def __init__(self,a,b): # Yapıcı Fonksiyonumuzu Oluşturuyoruz self.a = a #a değerlerimizi eşleştiriyoruz self.b = b #b değerlerimizi Eşleştiriyoruz def __str__(self): #__str__ Sınıfımıza a ya bu cevabı ver diyoruz return 'Vector (%d , %d)' %(self.a , self.b) def __add__(self,c): #Aşırı Yüklemeye C parametresini gönderiyoruz return Vector(self.a+c.a,self.b+c.b) v1 = Vector(5,20) v2 = Vector (5,2) print(v1+v2)
false
ab2d511cd408d4bc7cf645a9088a9fc095ca89ae
SatishEddhu/Deep-Analytics
/Python Basics/dictionary.py
712
4.28125
4
# Dictionary is a mutable object map1 = {"key1":10, "key2":20, "key3":30} type(map1) # dict print map1 map1.keys() # Two ways of getting values from map map1.get("key3") map1["key3"] # modifying map has a concise syntax map1["key4"] = 70 # adding new key map1["key2"] = 90 # can also modify values of existing keys # No error thrown print map1.get("key7") # 'None' is output instead of NULL; # "None' is a special keyword type(map1.get("key7")) # NoneType # Error is thrown map1["key7"] # throws KeyError # Iterate through map for x in map1.keys(): print x, map1.get(x) for x in map1.iteritems(): print x, type(x) # type(X) is a tuple type(map1.iteritems()) # dictionary-itemiterator
true
874e299ee655dcfa3163d9dbcc186dc6fe0f8ce6
dougbarrows/pfb2019_dougs_files
/problem_sets/Python_02/p2_11.py
351
4.46875
4
#!/usr/bin/env python3 number = 50 if number > 0: print("positive") if number < 50: print(" and less than 50") if number % 2 == 0: print("and it is even") else: print("and it is odd") if number > 50: if number % 3 == 0: print("is larger than 50 and divisible by3..!") elif number < 0: print("negative") else: print("its zero")
false
ba19426155017d3320c68bb3682c0a11f12bb0f6
FarazMannan/Roulette
/Roulett.py
1,546
4.375
4
# random number gen. import random # intro to the game print("") # adding and subrtacting system # bank bank = 500 # asking the player to enter one of 3 color choices (input) keep_gambling = True while keep_gambling == True: color_selected = input("What color would you like to pick? ") color_selected = color_selected.lower() # the different color choices in a compiled list color = [ "green", "red", "black", ] # random number generator random_number = random.randint(0,2) color_the_ball_lands_on = color[random_number] # printing the random number generator, what the program says the correct # color is if color_selected == color_the_ball_lands_on: winner_winner_chicken_dinner = True else: winner_winner_chicken_dinner = False if winner_winner_chicken_dinner == True: print("You win!") else: print("You lost!") # need to add a bank # subtracting and adding the balance off of wins # and loses if winner_winner_chicken_dinner == True: bank = bank + 50 else: bank = bank - 50 dollars_in_pocket = str(bank) print("Dollars in Pocket: $" + dollars_in_pocket) if bank <= 0: keep_gambling = False print("You have lost all of your money. Goodbye") elif bank >= 1000: keep_gambling = False print("Know when to hold em, know when to fold em, know when to walk away...") print("Congrats on walking away with $1,000!")
true
90ccf10cb639c66df875fa03cbba2aa42d10fab4
mparab01/Python_Assignment
/Assignment1.py
1,409
4.40625
4
# coding: utf-8 # Q. Print only the words that start with s in this sentence # In[1]: s = 'Print only the words that start with s in this sentence' # In[2]: for i in s.split(): if i[0]=='s': print i # Q. Use range to print all even numbers from 0 to 10 # In[4]: l = range(0,11,2) print l # Q. Use list comprehension to create a list of numbers between 1 to 50 that are divisible by 3 # In[6]: l2 = [i for i in range(1,51)if i%3==0] print l2 # Go through the string below and if the length of a word is even print "even!" # In[7]: st = 'Print every word in this sentence that has an even number of letters' for i in st.split(): if len(i)%2==0: print i # Q. Write a program that prints the integer from 1 to 100. But for multiple of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For the numbers which are multiples of both three and five print "FizzBuzz" # In[ ]: for i in range(1, 101): if (i%5==0) and (i%3==0): print "FizzBuzz" elif (i%3==0): print "Fizz" elif (i%5==0): print "Buzz" else: print i # Q. Use list Comprehension to create a list of the first letters of every letters of every word in the string below: # In[10]: st = 'Create a list of the first letter of every word in this string' # In[12]: l2 = [s[0] for s in st.split()] print l2 # In[ ]:
true
8c995a9cf354f361d5acd4f424b2feb1f02688f6
moni310/function_Questions
/3_or_5_sum.py
257
4.15625
4
def limit(parameter): n=num sum=0 while 0<n: number=int(input("enter the number")) if number%3==0 or number%5==0: sum=sum+number n=n-1 print(sum) num=int(input("enter the number")) limit( num)
true
9f29a197c7637ee528024896ba3ddf0c417148ca
moni310/function_Questions
/string_length.py
350
4.125
4
def string_function(name,name1): if len(name)>len(name1): print(name,"name length is more than name1") elif len(name)<len(name1): print(name1,"name1 length is more than name") else: print("name1 and name is equal") name=input("enter the any alpha") name1=input("enter the any alpha") string_function(name,name1)
true
54deb48c6c2f13d940817f8a3d8cca0656b32e0b
tylercrosse/DATASCI400
/lab/01-03/L02-2-ListDict.py
1,897
4.40625
4
""" # UW Data Science # Please run code snippets one at a time to understand what is happening. # Snippet blocks are sectioned off with a line of #################### """ # DataStructures (built-in, multi-dimensional) # Documentation on lists and other data structures # https://docs.python.org/3/tutorial/datastructures.html #################### list #################### City = ['USA', 704] # List can have mixed types type(City) #################### City.append('Seattle') City #################### City[1] #################### # Equal-length lists in a list create a rectangular strucure Name = ['Seattle', 'San Jose', 'San Jose', 'La Paz', 'La Paz'] Country = ['USA', 'USA', 'Costa Rica', 'Mexico', 'Bolivia'] Population = [704, 1030, 333, 265, 757] Cities = [Name, Country, Population] Cities #################### Cities[2][3] #################### CityNamesByCountry = {'USA':['Seattle', 'San Jose'], 'Costa Rica':'San Jose', 'Mexico':'Oaxaca'} type(CityNamesByCountry) # dict #################### CityNamesByCountry #################### CityNamesByCountry['USA'] #################### CityNamesByCountry['Mexico'] = 'La Paz' CityNamesByCountry['Bolivia'] = 'La Paz' CityNamesByCountry #################### list(CityNamesByCountry.keys()) #################### list(CityNamesByCountry.values()) #################### list(CityNamesByCountry.items()) #################### 'CostaRica' in CityNamesByCountry #################### 'Costa Rica' in CityNamesByCountry #################### 'LaPaz' in CityNamesByCountry.values() #################### 'La Paz' in CityNamesByCountry.values() #################### CountryByCityNames = {'Seattle':'USA', 'San Jose':['USA', 'Costa Rica'], 'La Paz':['Bolivia', 'Mexico']} CountryByCityNames #################### # Verify that the same information is here Cities
true
83d3f06d181c8b3ab1e0f3d9ab961eb4b730a3ce
tylercrosse/DATASCI400
/lab/04/L04-B-1-DataTypes.py
1,536
4.21875
4
""" # UW Data Science # Please run code snippets one at a time to understand what is happening. # Snippet blocks are sectioned off with a line of #################### """ """ Data Types """ # Create an integer x = 7 # Determine the data type of x type(x) ################# # Add 3 to x x + 3 ################# # Create a float x = 7.0 # Determine the data type of x type(x) ################# # Add 3 to x x + 3.0 ################# # Add a float, an integer, and a Boolean 7 + 3.0 + True ################# # Create a string x = "a" # Determine the data type of x type(x) ################# # Add b to x x + "b" ################ # Try to add 3 to a string x + 3 ################ # Create a string x = "7" # Determine the data type of x type(x) ################ # If we try to add 3 to x, we will get an error x + 3 # Add "3" to x x + "3" ################ import numpy as np # Create an array of integers x = np.array([5, -7, 1, 1, 99]) # Determine the data type of x type(x) ################ # Find out the data type for the elements in the array x.dtype.name ################ # If we can add 3 to this array. x + 3 ################ # Create an array of strings x = np.array(["abc", "", " ", "?", "7"]) # Determine the data type of x type(x) # Find out the data type for the elements in the array x.dtype.name ################ # If we try to add 3 to this array of strings we will get a TypeError. x + 3 #################
true
7c551f2f830d950126c1095262818ddc1e0d51c5
tylercrosse/DATASCI400
/assignments/TylerCrosse-L04-NumericData.py
1,629
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Lesson 04 Assignment Create a new Python script that includes the following for your Milestone 2 data set: - Import statements - Load your dataset - Assign reasonable column names, the data set description - Median imputation of the missing numeric values - Outlier replacement if applicable - Histogram of a numeric variable. Use plt.show() after each histogram - Create a scatterplot. Use plt.show() after the scatterplot - Determine the standard deviation of all numeric variables. Use print() for each standard deviation - Comments explaining the code blocks - Summary comment block on how the numeric variables have been treated: which ones had outliers, required imputation, distribution, removal of rows/columns. """ import pandas as pd import matplotlib.pyplot as plt url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data' Adult = pd.read_csv(url, header=None) Adult.columns = ['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income'] # Histogram of a numeric variable. Use plt.show() after each histogram age = Adult.age age.hist() plt.show() # Print the standard deviation for each numeric variable print(Adult.std()) """ There didn't appear to be any data that was missing or an outlier as a result of the collection methods. Both 'capital-gain' and 'capital-loss' had a lot of rows of zeros and a fairly large range of values but that seems to be intentional and accurate. """
true
8c692414bfd4ca0d1af8c086e8944b552c27cedf
JnthnTrn/my-first-python-project
/Set.py
972
4.1875
4
# names = {"tyler", "jacky", "ramiro", "kingsley"} # print("jacky" in names) #names[0] makes no sense #looping through set with a for loop #for name in names: #elements in sets cannot be changed #Changing a list #names = ["tyler", "jacky", "ramiro", "kingsley"] # names[2] = "jordan" #adding new elements to a set: set.add(element), or set.update(1st) #.add adds only one, whereas update can add multiple # names.add("jordan") # names_to_add = ("andrew", "jonathan", "george") # names.update(names_to_add) #removing items from a set # names.remove("kingsley") # names.remove("andrew") #gives us an error # name.discard("andrew") #does nothing even though it doesn't exist # names.clear() #set unions # names1 = {"tyler", "jacky", "ryan", "ramiro", "kingsley"} # names2 = {"tyler", "jacky", "andrew", "george", "angelo"} # names_union = names1.union(names2) # names_intersection = names1.intersection(names2) # print(names_union) # print(names_intersection)
true
25c6fa624f1b915e388b49beafff4add2d5a8421
Nadineioes/compsci-jmss-2016
/tests/t1/sum2.py
322
4.125
4
# copy the code from sum1.py into this file, THEN: # change your program so it keeps reading numbers until it gets a -1, then prints the sum of all numbers read numbers = [] num = 0 while num != -1: num = input('number: ') num = int(num) if num != -1: numbers.append(num) sum = sum(numbers) print(sum)
true
dbf2b0caf4936965364dfbc0892131978aafe05f
Niloy009/Python-Learning
/hello_you.py
421
4.34375
4
# ask user name name = input("What is your name?: ") #ask user age age = input("What is your age?: ") #ask user city city = input("Where do you live in?: ") #ask user what they enjoy? love = input("What do you love to do?: ") #create output string = "Your name is {} and you are {} years old. You are from {} & you love {}." output = string.format(name,age,city,love) #Print the output to screen print(output)
true
cca31d36b2890feea13506a2d934a0fd68162c63
xaviercallens/convex-optimization
/tools.py
684
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Some tools. """ __version__ = "0.1" __author__ = "Nasser Benabderrazik" def give_available_values(ls): """ Give the available values in ls as: "value1 or value2 or value3 ...". This is used for printing the available values for string variables in a function. Parameters ---------- ls: list (String) List Returns ------- s: String """ n = len(ls) if n > 1: s = "'{}' or '{}'" + " or '{}'"*(n-2) s = s.format(*[value for value in ls]) else: s = ls[0] return s if __name__ == '__main__': print(give_available_values(["newtonLS", "dampedNewton"]))
true
c463cec2b899361c5b989619e50d81831be29989
ml5803/Data-Structures-and-Algorithms
/Data Lecture/9-27-RecursionContinued.py
1,846
4.375
4
''' start assumption with WHEN CALLING ''' def count_up3(start,end): if start == end: print(start) else: count_up3(start,(start+end)//2) count_up3((start+end)//2+1,end) # when calling countdown on a smaller range # it would print the numbers in that range in a decreasing order def count_down(start,end): if start == end: print(end) else: print(end) count_down(start,end-1) # when calling count_up_and_down on a smaller range # it would print the numbers in that range in an increasing order followed by decreasing order def count_up_and_down(start,end): if(start==end): print(end) else: print(start) count_up_and_down(start+1,end) print(start) def factorial(n): if(n==1): return 1 else: return n * factorial(n-1) # When calling sum_list with a list shorter than lst, it would return sum of all elements in that list def sum_list(lst): if len(lst)==1: return lst[0] else: return lst[0] + sum_list(lst[1:]) # Can use indicies to make this Theta(n). ''' When adding recursion trees, you add local cost of each call. Recursive calls mutiple times increase the asymptotic runtime. ''' # Theta(n) def power1(x, n): if (n == 1): return x else: rest = power1(x, n - 1) return x * rest # Theta(n) def power2(x, n): if (n == 1): return x else: rest1 = power2(x, n // 2) rest2 = power2(x, n // 2) if (n % 2 == 1): return x * rest1 * rest2 else: return rest1 * rest2 # Theta(logn) def power3(x, n): if (n == 1): return x else: rest = power3(x, n // 2) if (n % 2 == 0): return rest * rest else: return x * rest * rest
true
5b0c8fc9f82e9e39c9ee7a1d6f9ee9687aea3281
filmote/PythonLessons
/Week2_4.py
956
4.125
4
import turtle def polygon(aTurtle, sides, length): counter = 0 angle = 360 / sides while counter < sides: aTurtle.right(angle) aTurtle.forward(length) counter = counter + 1 # ------------------------------------------------- # set up our shapes # triangle = { "name": "Triangle", "numberOfSides": 3, "length": 120 } small_square = { "name": "Square", "numberOfSides": 4, "length": 70 } big_square = { "name": "Square", "numberOfSides": 4, "length": 150 } pentagon = { "name": "Pentagon", "numberOfSides": 5, "length": 60 } shapes = [triangle, small_square, big_square, pentagon] # ------------------------------------------------- # draw our shapes # window = turtle.Screen() window.bgcolor("black") terry = turtle.Turtle() terry.shape("turtle") terry.color("red") for shape in shapes: polygon(terry, sides = shape["numberOfSides"], length = shape["length"]) window.exitonclick()
true
eb43e22f2e3e59fa6bf239b47ea852b4534cdf8e
FictionDk/python-repo
/tensor-note/tensor1.14/tensor_1_1.py
1,540
4.1875
4
# -*- coding: utf-8 -*- import sys import turtle # 列表 def list_test(): a = [1,2,3,4,5,6,7] b = ["张三","李四","王五"] c = [1,3,4,"4","5",b] print(a) print(b) # 列表名[起:止] -- 前闭后开区间 print(c[0:2]) # 列表名[起:止:步长] -- 步长有方向 print(a[4:1:-2]) print(a[6::-2]) # 从倒数第二个开始 print(a[-2::-2]) # 元组,一旦定义不能改变 def tuple_test(): f = (1,2,3) print(f[1]) # 字典 def dict_test(): dic = {1:"123","name":"张三","height":180} print(dic[1]) print(dic["name"]) dic["age"] = 18 print(dic["age"]) def if_test(): age = input("请输入你的年龄 \n") if int(age) > 18: print("你成年了!") else: print("你还未成年!") def for_test(): h = ["a","b","c","d"] for i in h: print(i) for j in h: print(j) def while_test(): x,y = 1,2 while True: x = x + 1 y = y + 1 print(x,",",y) if x > 5 or y > 5: break pass def turtle_test(): t = turtle.Pen() t.forward(100) t.left(90) t.forward(100) t.left(90) def turtle_for_test(): t = turtle.Pen() for i in range(0,4): t.forward(100) t.left(90) def main(): print(sys.stdout.encoding) # list_test() # tuple_test() # dict_test() # if_test() # for_test() # while_test() # turtle_test() turtle_for_test() pass if __name__ == "__main__": main()
false
3dbfe7a30074d70668da454332320e22e1747026
bebee4java/pytest
/test/org/py/test/functiontest.py
1,705
4.15625
4
#!/usr/bin/python3 def changeint(a): a = 10 b = 2 changeint(b) print(b) # 结果是2 # 可写函数说明 def changeme(mylist): "修改传入的列表" mylist.append([1, 2, 3, 4]) print("函数内取值: ", mylist) return # 调用changeme函数 mylist = [10, 20, 30] changeme(mylist) print("函数外取值: ", mylist) # 可写函数说明 def printme(str): "打印任何传入的字符串" print(str) return # 调用printme函数 printme(str="菜鸟教程") # 可写函数说明 def printinfo(name, age=35): "打印任何传入的字符串" print("名字: ", name) print("年龄: ", age) return # 调用printinfo函数 printinfo(age=50, name="runoob") print("------------------------") printinfo(name="runoob") # 可写函数说明 def printinfo(arg1, *vartuple): "打印任何传入的参数" print("输出: ") print(arg1) for var in vartuple: print(var) return print('=============可变参数===================') # 调用printinfo 函数 printinfo(10) printinfo(70, 60, 50) print('=====================匿名函数=======================') # 可写函数说明 sum = lambda arg1, arg2: arg1 + arg2 # 调用sum函数 print("相加后的值为 : ", sum(10, 20)) print("相加后的值为 : ", sum(20, 20)) print('===================作用域===========================') total = 0 # 这是一个全局变量 # 可写函数说明 def sum(arg1, arg2): # 返回2个参数的和." total = arg1 + arg2 # total在这里是局部变量. print("函数内是局部变量 : ", total) return total # 调用sum函数 sum(10, 20) print("函数外是全局变量 : ", total) print(sum(10, 20))
false
e97520c28a8f47624740a39aec5aa01fa8857db7
JaydeepUniverse/python
/projects/gameBranchesAndFunctions.py
2,974
4.21875
4
from sys import exit def start(): print """ Welcome to my small, easy and fun game. There is a door to your right and left. Which one would you take ? Type right or left. """ next = raw_input("> ") if next == "left": bear_room() elif next == "right": evil_room() else: dead2("You're not playing correctly.") def bear_room(): print """ There is a bear here. The bear has a bunch of honey. The bear is standing on the door, how would you move it ? Type the ans. as below: 1. take honey 2. taunt bear 3. open door """ bear_moved = False while True: next = raw_input("> ") if next == "take honey": dead2("The bear would look at you and then slap at your face.") elif next == "taunt bear" and not bear_moved: print " " print "The bear has moved from the door, door is open and you can go through it now." print "You can now 'open door' or it's your choice still to 'taunt beer' but ready for consequences of it." print " " bear_moved = True elif next == "taunt bear" and bear_moved: dead2("Bear would going to chew your legs.") elif next == "open door" and bear_moved: gold_room() else: print " " print "I got no idea what that means." print " " def gold_room(): print " " print "This room is full of Gold. How may kg would you take ? Type 25 or 50" print " " next = raw_input("> ") if next == "25" or next == "50": nex1 = int(next) else: print " " print "You have to options only to type." print " " if next1 == 25: print " " print "Nice, you're not greedy, you win!" print " " exit(0) else: dead2("You greddy bastard!") def evil_room(): print """ Here you see great evil. To save yourself type, 1. flee 2. fight """ next = raw_input("> ") if next == "flee": print " " print "Good choice! You're still in the game." print " " start() elif next == "fight": dead2("Oh that's bad! You lost the game.") else: evil_room() def dead(why): print " " print why, "Good Job!" print " " exit(0) def dead2(why): print " " print why, "Bad Job!" print " " exit(0) start()
true
c95ff9f7a74cf4d9973f1e0f006a42840348539c
sminix/spongebob-meme
/spongebob.py
876
4.15625
4
''' Take input string and output it in the format of sarcastic spongebob meme Sam Minix 6/23/20 ''' import random lower = 'abcdefghijklmnopqrstuvwxyz' upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def spongebob(text): newText = '' #initialize new text choice = [True, False] #initialize choices for i in range(len(text)): #for each letter in text new = text[i] if new in lower: #if the new letter is lowercase, radomly make uppercase if random.choice(choice): #if the random choice is True new = upper[lower.index(new)] #change to upper case letter elif new in upper: #if uppercase, make lowercase new = lower[upper.index(new)] newText += new #add new letter to new text return newText
true
51d992a4447fd815d2241e74f33dd95da622ec1c
detcitty/100DaysOfCode
/challenges/kaggle/python-course/ex4.py
715
4.21875
4
def multi_word_search(doc_list, keywords): """ Takes list of documents (each document is a string) and a list of keywords. Returns a dictionary where each key is a keyword, and the value is a list of indices (from doc_list) of the documents containing that keyword >>> doc_list = ["The Learn Python Challenge Casino.", "They bought a car and a casino", "Casinoville"] >>> keywords = ['casino', 'they'] >>> multi_word_search(doc_list, keywords) {'casino': [0, 1], 'they': [1]} """ values = list(map(lambda x: word_search(doc_list, x), keywords)) Dict = {} for i, e in enumerate(keywords): Dict[e] = values[i] return(Dict) # Check your answer q3.check()
true
be0696e5dbdc94185fd09ec087f83d7787b2492c
detcitty/100DaysOfCode
/python/unfinshed/findTheVowels.py
559
4.3125
4
# https://www.codewars.com/kata/5680781b6b7c2be860000036/train/python ''' We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters). So given a string "super", we should return a list of [2, 4]. Some examples: Mmmm => [] Super => [2,4] Apple => [1,5] YoMama -> [1,2,4,6] NOTES Vowels in this context refers to: a e i o u y (including upper case) This is indexed from [1..n] (not zero indexed!) ''' import regex as re def vowel_indices(word): # your code here pass
true
48bf51edf36127d6023eb16353cea66bd56e4159
detcitty/100DaysOfCode
/python/unfinshed/tribonacci_sequence.py
2,370
4.53125
5
# https://www.codewars.com/kata/556deca17c58da83c00002db/train/python ''' Well met with Fibonacci bigger brother, AKA Tribonacci. As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :( So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence: [1, 1 ,1, 3, 5, 9, 17, 31, ...] But what if we started with [0, 0, 1] as a signature? As starting with [0, 1] instead of [1, 1] basically shifts the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get: [0, 0, 1, 1, 2, 4, 7, 13, 24, ...] Well, you may have guessed it by now, but to be clear: you need to create a fibonacci function that given a signature array/list, returns the first n elements - signature included of the so seeded sequence. Signature will always contain 3 numbers; n will always be a non-negative number; if n == 0, then return an empty array (except in C return NULL) and be ready for anything else which is not clearly specified ;) If you enjoyed this kata more advanced and generalized version of it can be found in the Xbonacci kata [Personal thanks to Professor Jim Fowler on Coursera for his awesome classes that I really recommend to any math enthusiast and for showing me this mathematical curiosity too with his usual contagious passion :)] ''' def tribonacci(signature, n): # your code here # what does this do? # How will this work? changing_list = signature count = 0 if (n > 0): if n == 1: changing_list = [changing_list[0]] elif n == 2: changing_list = [changing_list[0], changing_list[1]] elif n == 3: changing_list = [changing_list[0], changing_list[1], changing_list[2]] else: while count < n - 3: new_value = changing_list[-1] + \ changing_list[-2] + changing_list[-3] changing_list.append(new_value) count += 1 else: changing_list = [] return(changing_list)
true
27f2a03e8e37e000028b5e8a556dfa15156198a8
Programmer0000/python-studying
/mypython/first.py
576
4.3125
4
''' 第一部分,代码的输入输出以及算式运算 ''' # name = input("please input your name ") # print("your name is", name) # please input your name tomy # your name is tomy print('a', 'b', 'c') # 输出三个字母,分隔符默认为空格' ',结束符默认为换行符'\n' print('a', 'b', 'c', sep=',') # 将字母之间的分隔符改为','号 print('a', 'b', 'c', end=';') # 将换行符改为';' print('a', 'b', 'c') ''' a b c a,b,c a b c;a b c ''' # python可以直接将表达式进行计算 result = 3*5/2+4*2 print(result) print(2**4) ''' 15.5 '''
false
55cfcefef97312fa2cd309f8cdc071128ed4f478
yewei600/Python
/Crack the code interview/Minesweeper.py
846
4.21875
4
''' algorithm to place the bombs placing bombs: card shuffling algorithm? how to count number of boms neighboring a cell? when click on a blank cell, algorithm to expand other blank cells ''' import random class board: dim=7 numBombs=3 bombList=[None]*numBombs def __init__(self): print "let's play Minesweeper!" for i in range (0,self.dim): for j in range(0,self.dim): print "?", print #determine the location of bombs for i in range (0,self.numBombs): self.bombList[i]=random.randrange(0,self.dim*self.dim+1) print self.bombList[i] def is_bomb(self,num): # def makePlay(self,row,column): # if not isBomb()
true
9b9b89a566210fb165d1967f137a237f3817fa7e
yewei600/Python
/Crack the code interview/bit manipulation/pairwiseSwap.py
449
4.1875
4
def pairwiseSwap(num): #swap odd and even bits in an integer with as few instructions as possible tmp=0 num=bin(num) num=num[2:] num=list(num) if len(num)%2: num.insert(0,'0') print("before swapping: "), print num for i in range(0,len(num),2): tmp=num[i] num[i]=num[i+1] num[i+1]=tmp print(" after swapping: "), print num
true
3651d8f220a37e768a3ddd677a607c89035bed6f
yuxy000/PythonSyntax
/json/desc.py
1,305
4.1875
4
""" JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数: json.dumps(): 对数据进行编码。 json.loads(): 对数据进行解码。 在json的编解码过程中,python 的原始类型与json类型会相互转换,具体的转化对照如下: Python 编码为 JSON 类型转换对应表: Python JSON dict object list, tuple array str string int, float, int- & float-derived Enums number True true False false None null JSON 解码为 Python 类型转换对应表: JSON Python object dict array list string str number (int) int number (real) float true True false False null None """ import json data = { 'no': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com' } # 如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。 # 写入 JSON 数据 with open("../tmp/data.json", 'w') as f: json.dump(data, f) # 读取数据 with open('../tmp/data.json', 'r') as f: data1 = json.load(f) print(type(data1))
false
ee09a52cebcbbd5889a0f2a227672ac42e1c9cc3
DerryPlaysXd/learn-python-basics
/Python Files/01-variables.py
568
4.40625
4
""" Welcome to the first course of the Learn-Python-Basics project! Here you will learn how to create a new variable, print the variable out and do some basic math! """ # First of all let's create a variable: aVar = 3 # We can print aVar out with the following line: print(aVar) # We can also do some calculations using variables aVar = 3 # We need to define a second variable bVar = 2 resultVar = aVar + bVar # Once again we can print the result out 3+2 = 5, so the output will be 5 print(resultVar) """ This is the end of the course! Move on to another one! """
true