blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1950a6f8072e37f8cee0639e6119704b6830f663
hyunmin0317/PythonProgramming
/Final/실습 11-1.py
462
4.125
4
def longest(str1, str2, str3): longest = str1 if (len(longest) < len(str2)): longest = str2 if (len(longest) < len(str3)): longest = str3 return longest def shortest(str1, str2, str3): shortest = str1 if (len(shortest) > len(str2)): shortest = str2 if (len(shortest) > len(str3)): shortest = str3 return shortest print(longest("one", "second", "three")) print(shortest("one", "second", "three"))
true
fcb2b22c4d9d98f431e0273c6f3d7c9ede287d61
allenjcochran/google-python-class
/donuts.py
594
4.15625
4
#!/usr/bin/python -tt # Copyright 2010 Google Inc. import sys # Define a main() function that prints a little greeting. def main(): # Get the name from the command line, using 'World' as a fallback. if len(sys.argv) <= 9: name = sys.argv[1] print 'The number of donuts', sys.argv[1] if len(sys.argv) >= 9: name = sys.argv[1] print 'The number of donuts', 'many' else: name = 'I don\'t know how many donuts you are talking about' print 'How many Donuts\?', name # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
true
5a79feddc5c74ab87de37cdc931073df724d9580
aristotel-tuktuk/calculations
/exersice9.py
602
4.28125
4
#Задача «Часы - 3» #С начала суток часовая стрелка повернулась на угол в α градусов. Определите сколько полных часов, минут и секунд прошло с начала суток, то есть решите задачу, обратную задаче «Часы - 1». Запишите ответ в три переменные и выведите их на экран. a = float(input()) hours = int(a // 30) minutes = int(a % 30 * 2) seconds = int(a % 0.5 * 120) print(hours, minutes, seconds)
false
f845cdbfd7747be7760e489db65ec03763b61571
z-cntrl/Code
/math_quiz.py
1,311
4.21875
4
############################################################################### # Author: Chloe Weber # Date: 3/9/21 # Description A program that returns two series of numbers on separate lines #and asks the user to give the correct answer, if they pass it says one thing if they don't it says wrong ############################################################################### import random as r def random_number(digit): if digit == 2: num = r.randrange(10,100,1) return num if digit == 3: num = r.randrange(100, 1000, 1) return num def main(): fig_one = random_number(2) #Sending 2 across as digit, which returns as num = fig_one print(f'{fig_one: 5d}') fig_two = random_number(3) #Sending 3 to random_number as digit, returns as num which is = to fig_two print(f'+{fig_two: 3d}') #rewatchin 'passing arguments' lecture print('-----') ans = int(input('= ')) correct_answer = fig_one + fig_two if ans != correct_answer: print(f'Incorrect. The correct answer is {correct_answer}.') else: print('Correct -- Good Work!') # Write your mainline logic here ------------------------------------------ # Don't change this ----------------------------------------------------------- if __name__ == '__main__': main()
true
67172b7331ecbb92581019cd38ce9f93a2932bd0
geekcomputers/Python
/Python Program to Count the Number of Each Vowel.py
399
4.21875
4
# Program to count the number of each vowels # string of vowels vowels = 'aeiou' ip_str = 'Hello, have you tried our tutorial section yet?' # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels,0) # count the vowels for char in ip_str: if char in count: count[char] += 1 print(count)
true
b7875cc58eb8fa78a9f54ba2e33ea8a7b15ba235
geekcomputers/Python
/convert_time.py
783
4.21875
4
from __future__ import print_function # Created by sarathkaul on 12/11/19 def convert_time(input_str): # Checking if last two elements of time # is AM and first two elements are 12 if input_str[-2:] == "AM" and input_str[:2] == "12": return "00" + input_str[2:-2] # remove the AM elif input_str[-2:] == "AM": return input_str[:-2] # Checking if last two elements of time # is PM and first two elements are 12 elif input_str[-2:] == "PM" and input_str[:2] == "12": return input_str[:-2] else: # add 12 to hours and remove PM return str(int(input_str[:2]) + 12) + input_str[2:8] if __name__ == "__main__": input_time = input("Enter time you want to convert: ") print(convert_time(input_time))
true
c3073018d8e1ebc33a00651fb49b5d7578083621
geekcomputers/Python
/dice_rolling_simulator.py
2,305
4.28125
4
# Made on May 27th, 2017 # Made by SlimxShadyx # Editted by CaptMcTavish, June 17th, 2017 # Comments edits by SlimxShadyx, August 11th, 2017 # Dice Rolling Simulator import random try: input = raw_input except NameError: pass global user_exit_checker user_exit_checker = "exit" # Our start function (What the user will first see when starting the program) def start(): print("Welcome to dice rolling simulator: \nPress Enter to proceed") input(">") # Starting our result function (The dice picker function) result() # Our exit function (What the user will see when choosing to exit the program) def bye(): print("Thanks for using the Dice Rolling Simulator! Have a great day! =)") # Result function which is our dice chooser function def result(): # user_dice_chooser No idea how this got in here, thanks EroMonsterSanji. print("\r\nGreat! Begin by choosing a die! [6] [8] [12]?\r\n") user_dice_chooser = input(">") user_dice_chooser = int(user_dice_chooser) # Below is the references to our dice functions (Below), when the user chooses a dice. if user_dice_chooser == 6: dice6() elif user_dice_chooser == 8: dice8() elif user_dice_chooser == 12: dice12() # If the user doesn't choose an applicable option else: print("\r\nPlease choose one of the applicable options!\r\n") result() # Below are our dice functions. def dice6(): # Getting a random number between 1 and 6 and printing it. dice_6 = random.randint(1, 6) print("\r\nYou rolled a " + str(dice_6) + "!\r\n") user_exit_checker() def dice8(): dice_8 = random.randint(1, 8) print("\r\nYou rolled a " + str(dice_8) + "!") user_exit_checker() def dice12(): dice_12 = random.randint(1, 12) print("\r\nYou rolled a " + str(dice_12) + "!") user_exit_checker() def user_exit_checker(): # Checking if the user would like to roll another die, or to exit the program user_exit_checker_raw = input( "\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>" ) user_exit_checker = user_exit_checker_raw.lower() if user_exit_checker == "roll": start() else: bye() # Actually starting the program now. start()
true
3db22ee66217267ff7aee5ab7533be78f8feba46
geekcomputers/Python
/Sorting Algorithms/Bubble_sort.py
597
4.46875
4
def bubble_sort(Lists): for i in range(len(Lists)): for j in range(len(Lists) - 1): # We check whether the adjecent number is greater or not if Lists[j] > Lists[j + 1]: Lists[j], Lists[j + 1] = Lists[j + 1], Lists[j] # Lets the user enter values of an array and verify by himself/herself array = [] array_length = int( input("Enter the number of elements of array or enter the length of array") ) for i in range(array_length): value = int(input("Enter the value in the array")) array.append(value) bubble_sort(array) print(array)
true
4e622d0815174abd5e264e06b46e1036394d0feb
geekcomputers/Python
/equations.py
1,165
4.21875
4
### ##### ####### by @JymPatel ##### ### ### ##### edited by ... (editors can put their name and thanks for suggestion) :) ### # what we are going to do print("We can solve the below equations") print("1 Quadratic Equation") # ask what they want to solve sinput = input("What you would like to solve?") # for Qdc Eqn if sinput == "1": print("We will solve for equation 'a(x^2) + b(x) + c'") # value of a a = int(input("What is value of a?")) b = int(input("What is value of b?")) c = int(input("What is value of c?")) D = b ** 2 - 4 * a * c if D < 0: print("No real values of x satisfies your equation.") else: x1 = (-b + D) / (2 * a) x2 = (-b - D) / (2 * a) print("Roots for your equation are", x1, "&", x2) else: print("You have selected wrong option.") print("Select integer for your equation and run this code again") # end of code print("You can visit https://github.com/JymPatel/Python3-FirstEdition") # get NEW versions of equations.py at https://github.com/JymPatel/Python3-FirstEdition with more equations # EVEN YOU CAN CONTRIBUTE THEIR. EVERYONE IS WELCOMED THERE..
true
febd3ff6a2c454f07e650c9d374c1c7350e110dd
geekcomputers/Python
/Sorting Algorithms/Bubble_Sorting_Prog.py
376
4.125
4
def bubblesort(list): # Swap the elements to arrange in order for iter_num in range(len(list) - 1, 0, -1): for idx in range(iter_num): if list[idx] > list[idx + 1]: temp = list[idx] list[idx] = list[idx + 1] list[idx + 1] = temp list = [19, 2, 31, 45, 6, 11, 121, 27] bubblesort(list) print(list)
true
e1cc51f13d221a6a8dd45a829557b7622f701a84
geekcomputers/Python
/stack.py
1,268
4.40625
4
# Python program to reverse a string using stack # Function to create an empty stack. # It initializes size of stack as 0 def createStack(): stack = [] return stack # Function to determine the size of the stack def size(stack): return len(stack) # Stack is empty if the size is 0 def isEmpty(stack): if size(stack) == 0: return True # Function to add an item to stack . # It increases size by 1 def push(stack, item): stack.append(item) # Function to remove an item from stack. # It decreases size by 1 def pop(stack): if isEmpty(stack): return return stack.pop() # A stack based function to reverse a string def reverse(string): n = len(string) # Create a empty stack stack = createStack() # Push all characters of string to stack for i in range(0, n, 1): push(stack, string[i]) # Making the string empty since all # characters are saved in stack string = "" # Pop all characters of string and # put them back to string for i in range(0, n, 1): string += pop(stack) return string # Driver program to test above functions string = "GeeksQuiz" string = reverse(string) print("Reversed string is " + string) # This code is contributed by Yash
true
21060130b122055b47d8982a938143da7af62cbb
geekcomputers/Python
/Strings.py
579
4.125
4
String1 = "Welcome to Malya's World" print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'm a TechGeek" print("\nString with the use of Double Quotes: ") print(String1) # Creating a String # with triple Quotes String1 = '''I'm Malya and I live in a world of "TechGeeks"''' print("\nString with the use of Triple Quotes: ") print(String1) # Creating String with triple # Quotes allows multiple lines String1 = """Smile For Life""" print("\nCreating a multiline String: ") print(String1)
true
e7cb918f27de0433e10887a708fd1de5728f0669
geekcomputers/Python
/Sorting Algorithms/Counting Sort.py
868
4.1875
4
# Python program for counting sort def countingSort(array): size = len(array) output = [0] * size # Initialize count array count = [0] * 10 # Store the count of each elements in count array for i in range(0, size): count[array[i]] += 1 # Store the cummulative count for i in range(1, 10): count[i] += count[i - 1] # Find the index of each element of the original array in count array # place the elements in output array i = size - 1 while i >= 0: output[count[array[i]] - 1] = array[i] count[array[i]] -= 1 i -= 1 # Copy the sorted elements into original array for i in range(0, size): array[i] = output[i] data = [4, 2, 2, 8, 3, 3, 1] countingSort(data) print("Sorted Array in Ascending Order: ") print(data) # This code is contributed by mohd-mehraj.
true
4e3f5987f04b4635b06c4a759e95d2eaae9ec93b
geekcomputers/Python
/Python Program to Remove Punctuations from a String.py
371
4.46875
4
# define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said ---and went." # To take input from the user # my_str = input("Enter a string: ") # remove punctuation from the string no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char # display the unpunctuated string print(no_punct)
true
00777b77f62961eafe2cf703e7a58698081c6cfa
geekcomputers/Python
/FIND FACTORIAL OF A NUMBER.py
543
4.375
4
# Python program to find the factorial of a number provided by the user. def factorial(n): if n < 0: # factorial of number less than 0 is not possible return "Oops!Factorial Not Possible" elif n == 0: # 0! = 1; when n=0 it returns 1 to the function which is calling it previously. return 1 else: return n*factorial(n-1) #Recursive function. At every iteration "n" is getting reduced by 1 until the "n" is equal to 0. n = int(input("Enter a number: ")) # asks the user for input print(factorial(n)) # function call
true
8629524dde42cd04e96e48c7c4adf29635697383
geekcomputers/Python
/Sorting Algorithms/bubblesortpgm.py
1,698
4.21875
4
"""Bubble Sort Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Example: First Pass: ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. Second Pass: ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. Third Pass: ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )""" # Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): not_swap = True # Last i elements are already in place for j in range(0, n - i - 1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] not_swap = False if not_swap: break # Driver code to test above arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print("Sorted array is:") for i in range(len(arr)): print("%d" % arr[i]),
true
8e471f54b14459a37642a4212a0ec7882ab6178d
geekcomputers/Python
/tic_tak_toe.py
2,633
4.34375
4
# Tic-Tac-Toe Program using # random number in Python # importing all necessary libraries import numpy as np import random from time import sleep # Creates an empty board def create_board(): return np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) # Check for empty places on board def possibilities(board): l = [] for i in range(len(board)): for j in range(len(board)): if board[i][j] == 0: l.append((i, j)) return l # Select a random place for the player def random_place(board, player): selection = possibilities(board) current_loc = random.choice(selection) board[current_loc] = player return board # Checks whether the player has three # of their marks in a horizontal row def row_win(board, player): for x in range(len(board)): win = True for y in range(len(board)): if board[x, y] != player: win = False continue if win == True: return win return win # Checks whether the player has three # of their marks in a vertical row def col_win(board, player): for x in range(len(board)): win = True for y in range(len(board)): if board[y][x] != player: win = False continue if win == True: return win return win # Checks whether the player has three # of their marks in a diagonal row def diag_win(board, player): win = True y = 0 for x in range(len(board)): if board[x, x] != player: win = False if win: return win win = True if win: for x in range(len(board)): y = len(board) - 1 - x if board[x, y] != player: win = False return win # Evaluates whether there is # a winner or a tie def evaluate(board): winner = 0 for player in [1, 2]: if row_win(board, player) or col_win(board, player) or diag_win(board, player): winner = player if np.all(board != 0) and winner == 0: winner = -1 return winner # Main function to start the game def play_game(): board, winner, counter = create_board(), 0, 1 print(board) sleep(2) while winner == 0: for player in [1, 2]: board = random_place(board, player) print("Board after " + str(counter) + " move") print(board) sleep(2) counter += 1 winner = evaluate(board) if winner != 0: break return winner # Driver Code print("Winner is: " + str(play_game()))
true
769fa0fd8f58aebc0240d119bb4d9fa33494a2b1
geekcomputers/Python
/area_of_square.py
231
4.46875
4
# Returns the area of the square with given sides n = input("Enter the side of the square: ") # Side length should be given in input side = float(n) area = side * side # calculate area print("Area of the given square is ", area)
true
1c6f8e5af875995ac1032c02ed834183fcc729b2
oknashar/interview-preparation
/googlePY/OA/Minimum-Domino-Rotations-For-Equal-Row.py
1,492
4.21875
4
''' n a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i-th domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same. If it cannot be done, return -1. Example 1: Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. Example 2: Input: A = [3,5,1,2,3], B = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal. ''' def sol(A, B): mapA = {} mapB = {} for i in range(len(A)): if mapA.get(A[i]): mapA[A[i]].append(i) else: mapA[A[i]] = [i] if mapB.get(B[i]): mapB[B[i]].append(i) else: mapB[B[i]] = [i] for el in mapA: toAppend = mapB.get(el) or [] fullSet = set(mapA[el]+toAppend) if len(fullSet) == len(A): return min(len(fullSet-set(mapA[el])),len(fullSet-set(toAppend))) return -1 print(sol([2,1,2,4,2,2],[5,2,6,2,3,2])) print(sol([3,5,1,2,3],[3,6,3,3,4])) print(sol([1,1,1,1,1],[1,1,1,1,1]))
true
a402180485c6cc4ed6a2c90dd13d3e557fb40c42
CataHax/lab2-py
/ex6.py
561
4.1875
4
# input a phone number x = int(input("Enter a phone number:")) # Take the string consisting of the first three characters and surround it with "(" and ") ". This is the area code. # Concatenate the area code, the string consisting of the next three characters, a hyphen, and the string consisting # of the last four characters. This is the formatted number. xstr = str(x) l = len(xstr) x1 = xstr[0:3] x2 = xstr[3:6] x3 = xstr[len(xstr)-4:len(xstr)] print("(",x1,")",x2,"-",x3) # EITHER THIS WAY print("(%s)%s-%s" % (x1,x2,x3)) # OR THIS WAY (PREFERABLY)
true
7eb422927724b81ba278b2e3de74ae812675b64f
angjerden/oiler
/svpino/problem3.py
533
4.1875
4
__author__ = 'anders' # Problem 3 # # Write a function that computes the list of the first # 100 Fibonacci numbers. By definition, the first two # numbers in the Fibonacci sequence are 0 and 1, # and each subsequent number is the sum of the # previous two. As an example, here are the first # 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. def compute(f, nr): while len(f) <= nr: f.append(f[-2] + f[-1]) return f if __name__ == '__main__': fibonacci = [0, 1] print(str(compute(fibonacci, 100)))
true
d229f9c08525e14b2d117026b2db0965287087e2
Ace5584/Machine-Learning-Notes
/other-libraries/learning-numpy/Part 1/main.py
895
4.53125
5
#------------------------------------------# # This part of np is about inizilizing and # # understanding and seeing types of data # # sets and sizes # #------------------------------------------# import numpy as np #init with dtype specifies the data type # dtype='int16' # dtype='int32' # etc... a = np.array([1, 2, 3]) print(a) b = np.array([[10.2, 3, 34, 2], [2, 38, 20.0, 3]]) print(b) #get dimentions print(a.ndim) print(b.ndim) #Get shape print(a.shape) print(b.shape) #Get type print(a.dtype) print(b.dtype) #Get size print(a.itemsize) #itemsize is the size one item in the array print(b.itemsize) print(a.size) #size counts how many items are in the list print(b.size) #The total size in memory would be: print(a.size * a.itemsize) #This is the hard way by calculating it print(b.size * b.itemsize) #Easier way: print(a.nbytes) print(b.nbytes)
true
729277f45c38b9dfb4fd5def1302e29db7601b1f
Ace5584/Machine-Learning-Notes
/other-libraries/learn-pandas/part 2/main.py
1,229
4.21875
4
#-----------------------------# # Reading data, getting rows, # # columns, cells, headers, # # etc... And sorting # # /discribing data. And High # # Level description on data # #-----------------------------# import pandas as pd df = pd.read_csv('C:/src/learn-pandas/pandas code/pokemon_data.csv') # Reading headers print(df.columns) # Reading each column print(df['Name'][0:5]) # [0:5] stands for how many data you want to print with index form print(df.Name[0:5]) # Only words for one word # Reading each row print(df.iloc[1]) # iloc -> integer location print(df.iloc[1:4]) # Getting multiple rows with index numbers # Reading a specific location print(df.iloc[2, 1]) # Looping through rows and columns for index, row in df.iterrows(): # Iterate through each row #print(index, row) print(index, row['Name']) # With only names # Locate specific rows with specific data print(df.loc[df['Type 1'] == "Grass"]) # High level disription on data print(df.describe()) # Produces count, mean, std, min, 25%, 50%, 75%, and max for each row of data # Sorting data print(df.sort_values('Name', ascending=False)) print(df.sort_values(['Type 1', 'HP'], ascending=[0,1])) # Numbers represends true/false
true
2b88ed10b16d103e1154e3c4e812c09743b8b02c
AsoUrum/python_Assignment_1
/question-3.py
1,115
4.21875
4
""" Given a string of odd length 7, return the middle char of the word """ word = input("Please Enter an odd number word with characters greater that 7: ") wordlenght= int(len(word)) odd = wordlenght%2 while ( not(wordlenght >=7 and odd == 1)): print("invalid word length, or not an odd nunber characters. Try again") word = input("Please Enter an odd number word with characters greater that 7: ") wordlenght= int(len(word)) odd = wordlenght%2 start = (wordlenght//2)-1 end = start + 3 result = word[start:end] print("The 3 middle character to the word entered are ","{", result[0],"}","{",result[1],"}", "{", result[2],"}") """ word = input("Please Enter an odd number word with characters greater that 7: ") wordlenght= int(len(word)) odd = wordlenght%2 if wordlenght >6 and odd == 1: start = (wordlenght//2)-1 end = start + 3 result = word[start:end] print("The 3 middle character to the word entered are ","{", result[0],"}","{",result[1],"}", "{", result[2],"}") else : print("invalid word length, or not an odd nunber characters. Try again") """
true
44429416c832ab713f336bbc3c0f6fd48b4aacd9
anantvir/Leetcode-Problems
/Array_Manipulations/Search_2D_Matrix_II.py
1,016
4.25
4
"""Approach --> For each row of matrix, run a binary search through that row return True if element is found else False Complexity --> O(r*log(c)) where r = rows and c = columns""" """Better can be done by going through diagnols and searching the row and column chunks. Refer to https://leetcode.com/problems/search-a-2d-matrix-ii""" import math def BinarySearch(value,arr,start,end): while start <= end: mid = math.floor((start+end)/2) if arr[mid] == value: return True elif value < arr[mid]: end = mid - 1 else: start = mid + 1 return False def Search_2D_Matrix(value,m): for i in range(len(m)): start_idx = 0 end_idx = len(m[i])-1 array = m[i] if BinarySearch(value,array,start_idx,end_idx) == True: return True return False m =[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] print(Search_2D_Matrix(5,m))
true
06121543c410017a1403e8d454056a149375f64d
anantvir/Leetcode-Problems
/Practice_2/Reshape_the_Matrix.py
1,935
4.125
4
""" MAIN IDEA --> Approach 1: Use a queue. Traverse the original matrxi and put every element in the queue. Then traverse the new matrix and on th fly dequeue each element and assign it to the new matrix. Approach 2 : 2D matrix can be represented in memory as 1D array. Convert given matrix to 1 D array(temp) where each element of the matrix becomes M[i][j] = temp[n*i+j] where n = number of columns and i = index of row in original matrix and j = index of column in original matrix. So make a temp array then each element in the new Matrix M[p][q] = M[i//c][i%c] where i = each index of temp array. But actually we dont need to create the temp array in memory because we are not using the array element, just the indices ! which start from 0. So we can just keep a count variable instead which starts from 0. Now traverse the matrix to be created(given input r and c) and for each index in new matrix, the elemtn at that index is M_new[i][j] = M_old[count//c][count%c] where c = new number of columns to be expected in output matrix. Then set count ++. """ """--------------------------- Using a Queue ----------------------------""" from collections import deque class Solution(object): def matrixReshape(self, original_matrix, r, c): """ :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ r0 = len(original_matrix) c0 = len(original_matrix[0]) if r0*c0 != r*c: return original_matrix Q = deque() for i in range(r0): for j in range(c0): Q.append(original_matrix[i][j]) new_matrix = [[None for i in range(c)]for i in range(r)] for i in range(r): for j in range(c): new_matrix[i][j] = Q.popleft() return new_matrix M = [[1,2,3,4],[5,6,7,8]] M2 = [[1,2],[3,4]] s = Solution() print(s.matrixReshape(M2,1,4))
true
051f74548b371e7319a050f7df841f3a667a420b
Arjuna1513/Python_Practice_Programs
/AllAboutLists/ListComprehensionOfTuples.py
493
4.15625
4
"""for row in elements: for col in row: print(col, end='\t') print('\n') print(elements[0][0]) # u cannot try to view the tuple present in list if u try it will throw # "TypeError: 'generator' object is not subscriptable" error. tuple1=((1, 2), (3, 4)) print(tuple1[0][0])""" elements = [x for x in range(5)] print(elements) del elements[2] print(elements) #del elements print(elements) tuple1 = (1, 2, 3, 4, 5) del tuple[1] # tuple doesn't support deletion of items.
true
84f30546eab00b0932211886af2593954316b5f4
Arjuna1513/Python_Practice_Programs
/SwitchStatementInPython/SwitchEx1.py
760
4.46875
4
def intToMonth(argument): dict1 = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } return dict1.get(argument, "Invalid month") # Take the input integer from user option = int(input("Enter Integer input here>>>>")) if option < 0 or option > 12: print("Please enter the value greater than 0 and lesser than or equal to 12") else: month = intToMonth(option) print(month)
true
754d177ce3fbf35e1bcfdeeb4e1093a98403c22d
Arjuna1513/Python_Practice_Programs
/AllAboutLists/AllAboutMatrix.py
1,512
4.375
4
# create a matrix with nested lists using comprehensions """elements = [[x for x in range(4)]for row in range(4)] for row in elements: print(row)""" # Create a 4*4 matrix without using """elements = [] for row in range(4): inner_list = [] for col in range(4): inner_list.append(col) elements.append(inner_list) for row in elements: print(row)""" # Creating 4 * 4 deep nested matrix using comprehension: elements = [[[z for z in range(2)]for y in range(4)]for x in range(4)] for row in elements: print(row) # Creating 4 * 4 deep nested matrix without using comprehension: """elements = [] for x in range(4): inner_list = [] for y in range(4): deep_list = [] for z in range(2): deep_list.append(z) inner_list.append(deep_list) elements.append(inner_list) for row in elements: print(row)""" # Transpose of 3*4 matrix using Comprehension """elements = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] elements = [[row[i] for row in elements]for i in range(4)] for row in elements: print(row)""" # Transpose of 3*4 matrix without using Comprehension """elements = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] transposed_list = [] for x in range(4): inner_list = [] for row in elements: inner_list.append(row[x]) transposed_list.append(inner_list) for row in transposed_list: print(row)"""
false
9eb43f96d7ab6cf5c7696a60e24ce170bfc65a62
BROjohnny/Python-A-Z-and-BasicPrograms-
/05 For Loop/For Loop.py
363
4.25
4
print("this is normal for loop") for i in range(1,11): print(i) print("\nin this for loop print 1 to 10 numbers passing 3 by 3") for i in range(1,11 ,3): print(i) print("\nthis is how to print values of 2 list as nexted loop") adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj[1:]: for y in fruits[:2]: print(x, y)
true
8e699ea99af07d3c2c1dd445a0e62ce45b653526
azharul/misc_problems
/iterator.py
674
4.28125
4
#!/usr/bin/python #Write Interleaving Iterator class which takes a list of Iterators as input and iterates one element at a time from each iterator until they are all empty # interleaving iterators are also called Round Robin iterator from itertools import islice, cycle def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) print list(roundrobin(range(5),"hello")
true
a20b85284bbac100bcc5498c0cdadc069b7ab08e
azharul/misc_problems
/running_avg.py
387
4.15625
4
#!/usr/bin/python #Implement a class that can calculate the running average of a stream of input numbers up to a maximum of N numbers def running_avg(): temp=0 avg=0 C=1 n=int(raw_input("Enter maximum number of entries: ")) while C<=n: temp=int(raw_input("Enter number: ") avg = (avg*(C-1)+temp)/C C +=1 print avg if C==n: print "your count has ended" running_avg()
true
7652554adf1cf618049bc9c65a87d98d9f1265e2
olieysteinn/T-111-PROG_Assignment-5
/5+/stdev.py
1,085
4.1875
4
# You might need this to calculate a square root using math.sqrt import math num = int(input("Enter a number (-1 to exit) ")) num_sum, count, current_average, standard_deviation = 0, 0, 0, 0 # Loop until the user types in -1 while num != -1: num_sum += num count += 1 previous_average = current_average previous_standard_deviation = standard_deviation # Calculate the cumulative moving average and standard deviation current_average = previous_average + ((num - previous_average) / count) if count == 1: standard_deviation = math.sqrt(math.pow(num - current_average, 2) / count) else: standard_deviation = math.sqrt(((count * current_average) - previous_average) / count) print(round(standard_deviation, 2)) standard_deviation = (previous_standard_deviation + (num - previous_average) * (num - current_average)) / count # Print them out within the loop print("Average:", round(current_average, 2)) print("Standard deviation:", round(standard_deviation, 2)) num = int(input("Enter a number (-1 to exit) "))
true
7ca8718e57774256ab93fba3fb712a7814702885
BrichtaICS3U/assignment-2-logo-and-action-abblurs
/action.py
2,516
4.34375
4
# ICS3U # Assignment 2: Action # Abbey Jayne # adapted from http://www.101computing.net/getting-started-with-pygame/ # Import the pygame library and initialise the game engine # Don't forget to import your class import pygame import random #to randomize rain fall #Import Rain class from rain import Rain from rain import Cloud pygame.init() pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096) pygame.mixer.music.load('GoodMusic.mp3') pygame.mixer.music.play(0) #-1 means loops for ever, 0 means play just once) #https://www.youtube.com/watch?v=X2WH8mHJnhM # Define some colours # Colours are defined using RGB values BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (79, 184, 219) GREY = (196, 196, 196) # Set the screen size SCREENWIDTH = 640 SCREENHEIGHT = 427 # Open a new window # The window is defined as (width, height), measured in pixels size = (SCREENWIDTH, SCREENHEIGHT) screen = pygame.display.set_mode(size) pygame.display.set_caption("Recorder Animation") #Lists that will contain all rain / cloud sprites raindrops = pygame.sprite.Group() clouds = pygame.sprite.Group() # This loop will continue until the user exits the game carryOn = True # The clock will be used to control how fast the screen updates clock = pygame.time.Clock() background_image = pygame.image.load("background.png") #http://davidgmiller.typepad.com/lovelandmagazine/2014/01/montessori-school-holds-winter-performance.html #Making the rain drops for i in range(100): drop = Rain(BLUE, 3, 7) raindrops.add(drop) #Making the clouds for i in range(7): cloud = Cloud(GREY, 50, 35) clouds.add(cloud) #---------Main Program Loop---------- while carryOn: # --- Main event loop --- for event in pygame.event.get(): if event.type == pygame.QUIT: # Player clicked close button carryOn = False if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: #Player clicked space bar carryOn = False screen.blit(background_image, [0, 0]) #Rainfall for rain in raindrops: rain.fall() #Clouds moving for cloud in clouds: cloud.move() raindrops.draw(screen) raindrops.update() clouds.draw(screen) clouds.update() # Update the screen with queued shapes pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) # Once the main program loop is exited, stop the game engine pygame.quit()
true
8dfd38dec0914cef8448966127acbd9335f54fcc
dipoesan/100daysofpythoncode
/Day 4/Day4 - Project.py
1,664
4.15625
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' options = [rock, paper, scissors] computers_option = random.randint(0, 2) # print (y) choice = int(input("What do you choose? Type 0 for rock, 1 for paper or 2 for scissors.")) if choice == 0: print(options[0]) if computers_option == 0: print("Computer chose:\n " + options[0]) print("It is a draw") if computers_option == 1: print("Computer chose:\n " + options[1]) print("You lose") if computers_option == 2: print("Computer chose:\n " + options[2]) print("You won") if choice == 1: print(options[1]) if computers_option == 0: print("Computer chose:\n " + options[0]) print("You won") if computers_option == 1: print("Computer chose:\n " + options[1]) print("It is a draw") if computers_option == 2: print("Computer chose:\n " + options[2]) print("You lose") if choice == 2: print(options[2]) if computers_option == 0: print("Computer chose:\n " + options[0]) print("You lose") if computers_option == 1: print("Computer chose:\n " + options[1]) print("You won") if computers_option == 2: print("Computer chose:\n " + options[2]) print("It is a draw") else: print("You did not make the right selection. Please start again.")
false
14e7df85bc8c7c45d46c4e17e250e064e531cdb5
oldtree61/practise
/python_work/chapter4/numbers_range.py
1,018
4.375
4
print("\n打印1-5的数:") for value in range(1,6): print(value) print("\n创建一个1-8数字的列表:") numbers=list(range(1,9)) print(numbers) print("\n打印1-10中的偶数:") even_numbers=list(range(2,11,2)) print(even_numbers) print("\n创建1-10的平方的列表:") squares=[] for value in range(1,11): square=value**2 squares.append(square) print(squares) #以下代码也可行 squares=[] for value in range(1,11): squares.append(value**2) print(squares) digits=list(range(1,11)) print(digits) digits=[1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(min(digits)) print(max(digits)) print(sum(digits)) print("\n创建1-10的平方的列表:") squares=[] for value in range(1,11): square=value**2 squares.append(square) print(squares) #以下代码也可行 squares=[] for value in range(1,11): squares.append(value**2) print(squares) #列表解析 print("以下是列表解析,用一行代码即可:") squares =[value**2 for value in range(1,11)] print(squares)
false
02d0f89834c36261a54f69ac9642aecde1820686
ODCenteno/python_100days
/day_5/adding_even.py
544
4.375
4
""" ## Adding Evens # Instructions You are going to write a program that calculates the sum of all the even numbers from 1 to 100. Thus, the first even number would be 2 and the last one is 100: i.e. 2 + 4 + 6 + 8 +10 ... + 98 + 100 Important, there should only be 1 print statement in your console output. It should just print the final total and not every step of the calculation. """ def calc_total_even(): total_even = sum(even for even in range(2, 101, 2)) print(total_even) if __name__ == '__main__': calc_total_even()
true
dc47e2438926ed734cfe8bfc875f98c54b93931f
ODCenteno/python_100days
/day_3/odd-even.py
445
4.125
4
""" Creat a program that evaluates if a nuber is odd or even """ def main(): number = int(input('Enter a number: ')) check_number(number) def check_number(number): if number % 2 == 0: print('It is even') else: print('It is odd') def get_number(): try: number = input('Enter a number: ') return number except: print('Only numbers please') if __name__ == '__main__': main()
true
0823c6903b13d15050468e5f575b3f5454b4482f
ODCenteno/python_100days
/day_3/leap_year.py
946
4.34375
4
""" Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February. The reason why we have leap years is really fascinating, this video does it more justice: https://www.youtube.com/watch?v=xX96xng7sAE This is how you work out whether if a particular year is a leap year. on every year that is evenly divisible by 4 **except** every year that is evenly divisible by 100 **unless** the year is also evenly divisible by 400 """ def main(): year = int(input('Enter a year to know if it is a leap year: ')) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print(f'Year {year} is leap.') else: print(f'Year {year} is Not leap.') else: print(f'Year {year} is leap.') else: print(f'Year {year} is Not leap.') if __name__ == '__main__': main()
true
9a3de3c338f34e59f13547358332e6880b4976e3
shivamvku/class_8000
/exption.py
1,540
4.15625
4
# Excption handling # Hnadling the inbult Excption # Use deine Excption # inbult Excption # =========================== # a = 1 # b = 0 # print(a/b) # Handling the exptions # try , except # try -------------> you write the actual code # whic you want execute # except -------< you write the handing of exptions raised from the try block # Single Excption handing # ============================ # try: # a = int(input('Enter a number --1\n')) # b = int(input('Enter a number --2\n')) # print(a/b) # except ZeroDivisionError: # print('Ther eis zero in denominator\n') # Multpile Excption handing # ================================= # try: # a = int(input('Enter a number --1\n')) # b = int(input('Enter a number --2\n')) # print(a/b) # except ValueError: # print('Chek your input\n') # except ZeroDivisionError: # print('Ther eis zero in denominator\n') # try: # a = int(input('Enter a number --1\n')) # b = int(input('Enter a number --2\n')) # print(a/b) # except (ZeroDivisionError,ValueError): # print('Check your inputs\n') # a = int(input('Enter a number --1\n')) # b = int(input('Enter a number --2\n')) # if a%b == 0: # print('even') # else -----> it get executed when there is no excption raised # finally ---- > it alwasys get executed try: a = int(input('Enter a number --1\n')) b = int(input('Enter a number --2\n')) print(a/b) except (ZeroDivisionError,ValueError): print('Check your inputs\n') else: print('The result is ',a/b) finally: print('The program ended\n')
false
8cc9eebb49164e47a43a9794cfa2f7e7b343ccc5
kumarnalinaksh21/Python-Practice
/Arrays/Anagram problem.py
886
4.4375
4
################ Question ###################################### # Construct an algorithm to check whether two words (or phrases) # are anagrams or not! # "An anagram is a word or phrase formed by rearranging the letters # of a different word or phrase, typically using all the original # letters exactly once" # For example: restful and fluster ################################################################ def check_anagram(var_string1, var_string2): if len(var_string1) != len(var_string2): print("False") else: var_list_1 = list(var_string1.casefold()) var_list_2 = list(var_string2.casefold()) if var_list_1.sort() == var_list_2.sort(): print("True") else: print("False") if __name__ == "__main__": var_string_1 = "Restful" var_string_2 = "Fluster" check_anagram(var_string_1, var_string_2)
true
52994bf2cd07e48f3cb3d0558fc9a3bb7232e164
sgupta304/amazon-401d1-python-sahil
/Modules/day_1/ReverseList.py
783
4.25
4
def reverse_list(input_list): new_list = [] for current_value in input_list[::-1]: new_list.append(current_value) return new_list if __name__ == '__main__': a = [1, 3, 4, 5, 6, 8] b = [89, 2354, 3546, 23, 10, -923, 823, -12] c = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 200, 201, 202, 203, 204, 205, 206, 207] d = [] e = [1] f = ["One", "Two", "Three", "Four", "Five"] print(reverse_list(a)) print(reverse_list(b)) print(reverse_list(c)) print(reverse_list(d)) print(reverse_list(e)) print(reverse_list(f))
false
4c38c820f8a25bc97d51a090ea756e3171ccee4a
beatrizmarinho/pythonalgoritmos
/Algoritmos_Python_Beatriz_Paudarco_Marinho/2_sacardinheiro.py
957
4.125
4
#2. Algoritmo para ir ao banco para sacar dinheiro (Imprimir a sequência para ir ao banco e sacar dinheiro) print('Dirija-se ao banco ou caixa eletrônico') print('Verifique se o caixa eletrônico aceita a bandeira do seu cartão') print('Insira o cartão com a parte frontal virada para cima no local indicado no caixa eletrônico') print('Digite sua senha') print('Retire o cartão quando a máquina solicitar') print('Selecione a opção "Saque" no menu principal') print('Selecione a quantia que gostaria de sacar') print('Pressione a tecla "Enter" ou "Confirma"') print('Aguarde a máquina processar a transação') print('Decida se quer ou não imprimir o comprovante pressionando o botão ou toque na tela nas opções "Sim" ou "Não"') print('Retire o dinheiro e o comprovante (caso solicitado) nos locais indicados') print('Decida de gostaria de realizar outra transação ou finalize a operação. Banco X agradece a preferência!')
false
e5ec47a5039806badaadec40915b0b6f35891ca1
Gerry84/Python-for-everybody
/3.2.py
323
4.125
4
#3.2 hours = input('Enter number of hours: ') rate = input('Enter rate: ') try: if int(hours)<40: pay = int(hours) * int(rate) print('Pay: ',pay) else: pay = 40 * int(rate) + (int(hours)-40) * 1.5 * int(rate) print('Pay: ',pay) except: print('Error, please enter numeric input')
true
b987e3dddbc09e5dd024519f65aef99e86c4982c
jinlygenius/basics
/algorithm/sortings/bubble_sort.py
789
4.40625
4
''' The algorithm works by comparing each item in the list with the item next to it, and swapping them if required. In other words, the largest element has bubbled to the top of the array. The algorithm repeats this process until it makes a pass all the way through the list without swapping any items. O(n2) algorithms ''' from utils.my_decorators import timeit @timeit def bubble_sort(data): for i in range(len(data)): # import pdb; pdb.set_trace() for index, value in enumerate(data[:len(data) - i:]): # cannot use -i because i will = 0 # import pdb; pdb.set_trace() if index == 0: continue if value < data[index - 1]: data[index], data[index - 1] = data[index - 1], data[index] return data
true
7147808fe49335f259327f4e34ef241bf5c659d4
bdanziger/euler
/MainReflexivePosition.py
876
4.3125
4
#!/usr/bin/python from ReflexivePosition import ReflexivePosition if __name__ == "__main__": reflPosn = ReflexivePosition() # These are examples from the problem statement itself print 'reflexive position of 1, should equal 1 : ', reflPosn.f(1) == 1 print 'reflexive position of 5, should equal 81 : ', reflPosn.f(5) == 81 print 'reflexive position of 12, should equal 271 : ', reflPosn.f(12) == 271 print 'reflexive position of 7780, should equal 111111365 : ', reflPosn.f(7780) == 111111365 # This is the sum of reflexive positions of the function 3^k when k goes from 1 to 13. It also shows the sums along the way total = 0 for k in range (1, 14): total += reflPosn.f(3 ** k) print 'sum of reflexive positions of 3^k 1<=k<=13, after k = ', k, ', total = ', total
false
33914f9635d83148c350deb7113785c0310fa5b8
Samundar9525/datastructure-codes
/basic data structure using python/merge sory.py
1,031
4.21875
4
def mergesort(a,lb,ub): if(lb<ub): mid=int((ub+lb)/2) mergesort(a,lb,mid) mergesort(a,mid+1,ub) merge(a, lb, mid, ub) def merge(a,lb,mid,ub): i=lb j=mid+1 k=lb while(i<=mid and j<=ub): if(a[i]<=a[j]): b[k]=a[i] i=i+1 else: b[k]=a[j] j=j+1 k=k+1 if(i>mid): while(j<=ub): b[k] = a[j] j=j+1 k=k+1 else: while(i<=mid): b[k]=a[i] k = k+1 i = i+1 for i in range (lb,k): a[i]=b[i] #here instead of takin input from user we created a list having ome data element: a=[3,8,5,2,4,1] b = [0] * 6 #this will fix the size of the array ans set the default value 0 in it print(f"The data before sorting is : {a}") print("sorting initiated...........") lb=0 ub=len(a)-1 print("\n") #function is called here mergesort(a,lb,ub) print(f"The sorted data is : {a}")
true
35619e6f8455e1704c1533c6da6fd812d3b15437
Samundar9525/datastructure-codes
/basic data structure using python/inheritance_hierarchy.py
911
4.125
4
class detail: def __init__(self): self.name=input("enter your name : ") self.age=input("enter your age : ") self.address=input("enter your address : ") # the below classes have same parent that is detail class student(detail): def printstuddent(self): print("student data : ",self.__dict__) class teacher(detail): def printteacher(self): print("teacher data : ",self.__dict__) class employee(detail): def printemployee(self): print("employee data : ",self.__dict__) print(" select option : \n 1.student \n 2.teacher \n 3.employee ") choice=int(input("enter your choice to insert the data")) if (choice==1): obj=student() obj.printstuddent() elif(choice==2): obj = teacher() obj.printteacher() elif(choice==3): obj = employee() obj.printemployee() else: print("invalid choice")
false
735532a52ce1d141dd4ce9fb14d77df6d73ad02f
mkanenobu/til
/python/iterater.py
257
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- arr = ["One", "Two", "Three", "Four", "Five"] for i in arr: print(i) # with index for i, v in enumerate(arr): print(i, v) # with index starts 3 for i, v in enumerate(arr, start=3): print(i, v)
false
91a79e69b06427b9e7e89f00987b73bea84ba479
xavinavarro/di
/Tema 1/Ejercicios 1/Ejercicio1.py
682
4.28125
4
#1.Suponga que dos variables, valores varA y varB, están asignados, ya sean números o cadenas. #Escribir una pieza de código Python que imprime uno de los siguientes mensajes: #"Cadena involucrada", si bien varA o varB son cadenas #"Grande" si varA es mayor que varB #"Igual" si varA es igual a varB #"Más pequeño" si varA es menor que varB #Escribir el código asumiendo varA y varB ya están definidos #!/usr/bin/env python varA = 11 varB = 11 if type (varA) == int and type (varB) == int: if varA < varB: print ("Mas pequeño") elif varA == varB: print ("Igual") else: print ("Grande") if type (varA) == str or type (varB) == str: print ("Cadena involucrada")
false
df59777a5c92502633e414d1e9a3443c6d82f6c3
ajaykumars/PythonWorks
/contents/basics/conditional_statements.py
356
4.25
4
a = 2; b = 1; if a > b: print("a with value ({}) is greater than b with value ({})".format(a, b)) elif a < b : print("a with value ({}) is lesser than b with value ({})".format(a, b)) else : print ("a is equal to b") print ("foo" if a < b else "bar") name = "John" if name in ["John", "Rick"]: print("Your name is either John or Rick.")
false
07c862160943278a5de8323013e59f0fdb21c401
MarwanBit/Tri-1-Procedural-Programming-2019-2020
/notes_and_lectures/september_17_notes.py
291
4.21875
4
from sys import argv #To print anything from the command line type python file_name things_to_print #argv is everything in a list which contains all the arguments typed into the command line print('My name is {} and I have just run.'.format(argv[1])) print(argv) for i in argv: print(i)
true
ecf4e75654dc0992c0a3bffca551e358cf1f0c8c
zyp19/leetcode1
/树/二叉树/617.合并二叉树.py
2,820
4.28125
4
"""617.合并二叉树(双树 无辅助函数 先序/后序遍历 改变树(给树的节点赋值) 所以要把返回值付给节点) 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为NULL 的节点将直接作为新二叉树 的节点。 注意: 合并必须从两个树的根节点开始。 """ """ 双树+先序遍历 且是调整整棵树的题目,最后返回根节点,那么调用左右子树的函数的时候一定是返回左子树和右子树,因为要给左右子树赋值,所以一定要有返回值才行 相似的题还有226,但是226虽然也是需要调整一棵树,但是其关键在于交换子树,所以不存在给左右子树赋值的问题,所以就先序遍历不用返回值。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right """ 注意这种做法是错误的,我这样做的初衷是想要改变树,但是root1为空的情况下,第25行是不成立的,所以说会报错 """ class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: # 这里可以精简一下前面的判断条件 if not root1: root1 = root2 if not root2: root1 = root1 # if not root1 and not root2: # return root1 # if not root1 and root2: # return root2 # elif not root2 and root1: # return root1 elif root1 and root2: root1.val = root1.val + root2.val self.mergeTrees(root1.left,root2.left) self.mergeTrees(root1.right,root2.right) return root1 """ 正确做法:先给根节点赋值(递归前面的部分),再给左右子树赋值(左右子树先序遍历)! """ class Solution1: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: if not root1: return root2 if not root2: return root1 if root1 and root2: root1.val = root1.val + root2.val # return root1 #思考:这一句话为什么不加?傻了吧?加了这一句符合if的时候不就直接返回了吗。。。就不会执行下面的递归了 root1.left = self.mergeTrees(root1.left,root2.left) root1.right = self.mergeTrees(root1.right,root2.right) return root1 s = Solution1() t1 = TreeNode(1,TreeNode(3,TreeNode(5)),TreeNode(2)) t2 = TreeNode(2,TreeNode(1,None,TreeNode(4)),TreeNode(3,None,TreeNode(7))) s.mergeTrees(t1,t2)
false
2c256a558ce2df7fc89352686c581275357a8341
zyp19/leetcode1
/暑期实习-大厂笔面试/广联达/new.py
805
4.28125
4
""" 小明得到一个只包含大小写英文字母的字符串s,下标从1开始计算。现在他希望得到这个字符串下标的一个奇怪的集合。这个奇怪的集合需要满足的条件是: 1. 集合中的任意下标i对应的字母s[i]必须是小写字母 (islower()) 2. 对于集合中的任意两个下标i、j,对于任意数字k,i<=k<=j,有s[k]是小写字母() 3. 集合中的下标对应的字母是两两不同的(去除重复) 4. 集合中的数字尽可能的多(废话) 帮助小明计算这个集合最多可以有多少下标(个)。 aaBBBabBaAb 2 """ def function(s): out_list = set() for i in range(len(s)): if s[i].islower(): out_list.add(s[i]) return len(out_list) result = function("aabbcc") print(result)
false
860b79b412ae9b1f46a4741c5d5b5788a6096827
DVaughn20/Hello_Github
/HelloGit.py
809
4.1875
4
# comment print("Hello World!") a = 6 b = 4 print(a+b) #how to make a list myList = [1, 2, 3] #how to access elements of a list print(myList[1]) d = 2 while d < 20: print(d) d += 2 #how to create a function def sumFunction(a,b): return a + b print(sumFunction(2, 20)) print("hello world") #dictionary #lookup{} #three datatypes at input #float someFloat = float(input("Enter a float: ")) print("You entered float: " + str(someFloat)) print(f"you entered float: {someFloat}" ) #string phrase = input ("Enter a String: ") print("you said " + phrase) print(f"you said {phrase}") #int someInt = float(input("Enter an int: ")) print("You entered int: " + str(someInt)) print(f"you entered int: {someInt}" ) print(f"Do Python inline, like this: {someFloat} * {someInt} = {someFloat} * {someInt}")
false
bf6488379b198483e9e6320afd34a5e6e1197736
barbaracalderon/curso-de-python3-do-curso-em-video
/mundo_2/desafio058.py
707
4.1875
4
# Melhor o jogo do DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10. # Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos # palpites foram necessŕios para vencer. import random num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] num_escolhido = random.choice(num) num_usuario = int(input('Escolha um número entre 0 e 10: ')) contador = 0 while num_usuario != num_escolhido: print('Ainda não foi. Vamos de novo!') num_usuario = int(input('Escolha um número entre 0 e 10: ')) contador += 1 print('Parabéns! Você acertou o número que eu pensei: {}\nPara isso, você tentou {} vezes. Nessa última, você acertou!'.format(num_escolhido, contador))
false
bbcba2257b6ee963afabd047f75015873584cc0f
barbaracalderon/curso-de-python3-do-curso-em-video
/mundo_3/desafio072.py
935
4.25
4
# Crie um programa que tenha uma tupla totalmente preenchida # com uma contagem por extenso, de zero até vinte. # Seu programa deverá ler um número pelo teclado (entre 0 e 20) # e mostrá-lo por extenso. print('================== [NÚMERO POR EXTENSO] ==================') while True: valor = int(input('Digite um valor entre 0 e 20: ')) while valor < 0 or valor > 20: valor = int(input('Valor inválido. Digite um valor entre 0 e 20: ')) tupla = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte') print(f'Você digitou {valor} e seu nome por extenso é {tupla[valor]}.') continuar = str(input('Deseja continuar? [S/N]: ')).strip().upper()[0] if continuar == 'N': print('Saindo do programa. Volte sempre!') break
false
0910b16f66bc177698949c08b917715afeea7a1e
barbaracalderon/curso-de-python3-do-curso-em-video
/mundo_1/desafio028.py
489
4.1875
4
# Escreva um programa que faça o computador "pensar" em um número # inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual # foi o número escolhido pelo computador. # O programa deverá escrever na tela se o usuário venceu ou perdeu. import random num = [0, 1, 2, 3, 4, 5] num_escolhido = random.choice(num) num_usuario = int(input('Escolha um número entre 0 e 5: ')) if num_usuario == num_escolhido: print('Parabéns! Você venceu!') else: print('Você perdeu.')
false
bdeed10d1581d552c32bee5a61bfb3a2ec09e14f
barbaracalderon/curso-de-python3-do-curso-em-video
/mundo_3/desafio086.py
1,414
4.4375
4
# Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores # lidos pelo teclado. No final, mostre a matriz na tela com a formatação correta. print('=============== [MATRIZ 3x3] ===============') print('Vamos começar inserindo os dados para a sua matriz.') linha1 = [] linha2 = [] linha3 = [] matriz = [] cont = 1 while cont < 10: while cont < 4: valor = int(input(f'Digite o {cont}ª valor: ')) linha1.append(valor) cont += 1 while cont < 7: valor = int(input(f'Digite o {cont}ª valor: ')) linha2.append(valor) cont += 1 while cont < 10: valor = int(input(f'Digite o {cont}ª valor: ')) linha3.append(valor) cont += 1 matriz.append(linha1) matriz.append(linha2) matriz.append(linha3) print('===========================================') for e in matriz[0]: print(f'[{e:^5}]', end=' ') print() for f in matriz[1]: print(f'[{f:^5}]', end=' ') print() for g in matriz[2]: print(f'[{g:^5}]', end=' ') ''' Uma outra forma de realizar esse exercício, mostrada pelo prof. Guanabara, é a seguinte: matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'Digite um valor para [{l}], [{c}]: ')) print('=-' * 30) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5]', end='') print() '''
false
638e8272ff01d1e47ab5666997158d0c0347a973
barbaracalderon/curso-de-python3-do-curso-em-video
/mundo_2/desafio071.py
1,178
4.15625
4
# Crie um programa que simule o funcionamento de um caixa eletrônico. No início, # pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa # vai informar quantas cédulas de cada valor serão entregues. # OBS.: Considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. print('=============== [BANCO SKINA - CAIXA ELETRÔNICO] ==============') print('Bem-vindo ao Caixa Eletrônico do Banco Skina! Estamos na sua Conta Corrente.') print('Temos as seguintes cédulas disponíveis: R$50,00; R$20,00; R$10,00 e R$1,00') valor = int(input('Digite o valor a ser sacado: R$ ')) total = valor cedula = 50 total_cedula = 0 while True: if total >= cedula: # A ideia é diminuir o valor da cédula do valor total, um por vez até não dar mais total -= cedula total_cedula += 1 else: print(f'Total de {total_cedula} cédulas de R$ {cedula}') if cedula == 50: cedula = 20 elif cedula == 20: cedula = 10 elif cedula == 10: cedula = 1 total_cedula = 0 if total == 0: break print('=' * 63) print('Volte sempre! O Banco Skina agradece.')
false
5f3bee2cef980df68e3f410ac31ab02d8650948b
barbaracalderon/curso-de-python3-do-curso-em-video
/mundo_3/desafio093.py
1,195
4.21875
4
# Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do # jogador e quantas partidas ele jogou. Depois, vai ler a quantidade de gols feitos em cada partida. # No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos no campeonato. print('======= [PLACAR DO JOGADOR] =========') dados = {} dados["Jogador"] = str(input('Nome do jogador: ')) dados["Partidas"] = int(input('Número de partidas jogadas: ')) gols = [] soma = 0 for g in range(0, dados["Partidas"]): gol = int(input(f'Gols na partida {g+1}: ')) gols.append(gol) dados["Gols"] = gols[:] dados["Total de Gols"] = sum(gols) print('=========== RELATÓRIO =============') print('<< DICIONÁRIO >> ==================') print(dados) print('<< CAMPOS >> ======================') for k, v in dados.items(): print(f'O campo {k} tem valor {v}') print('<< RESUMO DA PARTIDA >> ===========') print(f'O jogador {dados["Jogador"]} jogou {dados["Partidas"]} partidas!') for a in range(0, dados["Partidas"]): print(f'Na partida {a+1} fez {dados["Gols"][a]} gols') print('<< TODOS OS DADOS >> =============') for k, v in dados.items(): print(f'{k}: {v}')
false
58bdf06ff88233bba8882492f79797c52673fc48
bholanathyadav/PythonPractice
/ArmstrongNum.py
326
4.375
4
# A program to find if a number is an Armstrong number dt. 12th Feb 2019 num = int(input("Enter a number of your choice: ")) a = str(num) b = len(a) arm = 0 for i in a: c = int(i) arm += c**b if num == arm: print("Yes, it is an Armstrong number") else: print("No, it is not an Armstrong number")
true
d5408ff4086dea692e02b4aab8b05f37db65b4a2
bholanathyadav/PythonPractice
/greatestof3numbers.py
547
4.34375
4
# program to print largest of three numbers print('enter three numbers') a = int(input("Enter first number: ")) b = int(input('Enter second number: ')) c = int(input('enter third number: ')) if a > b: if a > c: print(str(a) + ' is the greatest number') elif c > a: print(str(c) + ' is the greatest number') elif b > c: print(str(b) + ' is the greatest number') else: print(str(c) + ' is the greatest number') # end of program
false
17e39068a7dd9896ef88b26b48326bddfa406c1b
afan12/Python
/assign6.py
1,796
4.15625
4
class Rectangle(object): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w #width of rectangle self.h = h #height of rectangle def area(self): return self.width * self.height def __str__(self): return('Rectangle(' + str(self.x) + ',' + str(self.y) + ',' + str(self.w) + ',' + str(self.h)+')') def right(self): return self.x + self.w def bottom(self): return self.y + self.h def size(self): return self.w,self.h def position(self): return self.x,self.y def area(self): return self.w * self.h def expand(self, offset): return('Rectangle(' + str(self.x-offset) + ',' + str(self.y-offset) + ',' + str(self.w+2*offset) + ',' + str(self.h+2*offset)+')') def contains_point(self, x, y): return(x >= self.x and x <= self.x + self.w and y >= self.y and y <= self.y + self.h) r2 = Rectangle(5, 10, 50, 100) print(r2) r3 = Rectangle(3,5,10,20) r3.right() print(r3.right()) r4 = Rectangle(12,10,72,35) r4.right() print(r4.right()) r5 = Rectangle(5, 7, 10, 6) r5.bottom() print(r5.bottom()) r5.y+=12 r5.bottom() print(r5.bottom()) r6 = Rectangle(1,2,3,4) r6.size() print(r6.size()) r6.position() print(r6.position()) r6.area() print(r6.area()) r = Rectangle(30,40,100,110) print(r) r1 = r.expand(offset = 3) print (r1) print (r) print (r.expand(-5)) r = Rectangle(30, 40, 100, 110) print(r.contains_point(50,50)) print(r.contains_point(30,40)) print(r.contains_point(130, 150)) print(r.contains_point(131, 50)) print(r.contains_point(0,0))
false
1905da90cdac22726e72508af744585c3e209bcb
HanchengZhao/Leetcode-exercise
/348. Design Tic-Tac-Toe/TicTacToe.py
2,024
4.3125
4
class TicTacToe(object): ''' The key observation is that in order to win Tic-Tac-Toe you must have the entire row or column. Thus, we don't need to keep track of an entire n^2 board. We only need to keep a count for each row and column. If at any time a row or column matches the size of the board then that player has won. To keep track of which player, I add one for Player1 and -1 for Player2. There are two additional variables to keep track of the count of the diagonals. Each time a player places a piece we just need to check the count of that row, column, diagonal and anti-diagonal. ''' def __init__(self, n): """ Initialize your data structure here. :type n: int """ self.size = n self.row = [0] * n self.col = [0] * n self.diagonal = 0 self.reverseDiagonal = 0 def move(self, row, col, player): """ Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Player 2 wins. :type row: int :type col: int :type player: int :rtype: int """ toAdd = 1 if player == 1 else -1 self.row[row] += toAdd self.col[col] += toAdd if row == col: self.diagonal += toAdd if row + col == self.size - 1: self.reverseDiagonal += toAdd size = self.size if (abs(self.row[row]) == size or abs(self.col[col]) == size or abs(self.diagonal) == size or abs(self.reverseDiagonal) == size): # a player wins return player return 0 # Your TicTacToe object will be instantiated and called as such: # obj = TicTacToe(n) # param_1 = obj.move(row,col,player)
true
aa2252d4f9c95e56e5ddc17cf92a43da198d9edb
HanchengZhao/Leetcode-exercise
/332. Reconstruct Itinerary/findItinerary.py
1,711
4.1875
4
from collections import defaultdict class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: self.trips = defaultdict(list) self.path = ["JFK"] for t in sorted(tickets): self.trips[t[0]].append(t[1]) # backtrack to see if the city would be the good choice # otherwise append it back to try other cities # the first path it returns will be the lowerst in lexical order def dfs(city): if len(self.path) == len(tickets) + 1: return self.path nxtTrips = sorted(self.trips[city]) for nxt in nxtTrips: self.trips[city].remove(nxt) self.path.append(nxt) worked = dfs(nxt) if worked: return worked self.trips[city].append(nxt) self.path.pop() return dfs("JFK") ''' Follow up question: What if the initial origin is not given? How would you find out the initial origin? Conditions for a directed graph: A directed graph has an eulerian circuit if and only if it is connected and each vertex has the same in-degree as out-degree. In this case we can choose any node as the start node. A directed graph has an eulerian trail if and only if it is connected and each vertex except 2 have the same in-degree as out-degree, and one of those 2 vertices has out-degree with one greater than in-degree (this is the start node), and the other vertex has in-degree with one greater than out-degree (this is the end node). What is the time complexity? O(Vlog(V) + E), V for nubmer of cities, E for number of tickets What is the space complexity? '''
true
823288aa85bfdf950884bbcca1bc99a0b1e4582c
darylhjd/ctci
/trees_and_graphs/validate_bst.py
601
4.15625
4
from tree import * def validate_bst(root: BTNode, mi, ma): """Validate whether a binary tree is a binary search tree.""" # Solution: O(n) time for going through each node, O(logn) for recursive calling. # Base case. If the root is None, return True. if root is None: return True # We check if current node satisfies bounds. The current node's value # must be equal to or more than mi, and less than ma. if not mi <= root.data < ma: return False else: return validate_bst(root.left, mi, root.data) and validate_bst(root.right, root.data, ma)
true
762be873f4c493a6197c3e5dc253a2318abba79f
darylhjd/ctci
/arrays_and_strings/palindrome_permutation.py
1,048
4.1875
4
from collections import defaultdict def palindrome_permutation(string: str): """Check if the given string is a permutation of a palindrome.""" # Solution: O(n) time for creating the counter, and O(n) auxiliary space (worst case each letter is different), # where n is the length of the string. # We use the property of a palindrome that for even length strings, # all letters will occur an even number of times, while for a odd length string, # there can only be one letter that occurs an odd number of times. # Sanitise string string = ''.join(string.lower().replace(" ", "")) counter = defaultdict(int) for letter in string: counter[letter] += 1 if len(string) % 2: has_odd = False for letter, count in counter.items(): if count % 2 and has_odd: return False elif count % 2: has_odd = True else: for letter, count in counter.items(): if count % 2: return False return True
true
f6ef3687038017c3294e205b513dceb469a31061
darylhjd/ctci
/trees_and_graphs/route_between_nodes.py
1,206
4.34375
4
def route_between_nodes(n1, n2): """Find out whether there is a route between n1 and n2.""" # Solution: O(k^(b/2)) time and space, k is the average number of neighbour nodes for each node, # b is the breadth of the search. # Use a queue to do BFS through n1's and n2's neighbours. n1_search = set() n1_search.add(n1) n1_store = set() n2_search = set() n2_search.add(n2) n2_store = set() while len(n1_search) != 0 and len(n2_search) != 0: # Loop through all nodes in n1 to search, and store their neighbours in a temp buffer for node in n1_search: if node in n2_search: return True for n in node.neighbours: n1_store.add(n) # Replace n1_search with the nodes in n1_store and empty n1_store. n1_search = n1_store n1_store = set() # Do the same thing for n2 nodes. for node in n2_search: if node in n1_search: return True for n in node.neighbours: n2_store.add(n) # Replace n2_search with the nodes in n2_store and empty n2_store. n2_search = n2_store n2_store = set()
true
53e18ee0f709e16c46c02f6abce1b276a1532715
BinXu-UW/basic-pythoncode
/Xu_pa2/sphere.py
432
4.25
4
# Programmer: Bin Xu # Class: Cpts 111 Section 01 # Programming Assignment: Project 02 # Filename: sphere.py # Date Created: 02/01/01 # Description: A program that calculates the volume and surface area of a sphere from its radius import math def main(): r= input ("Enter the radius: ") V = (4.0/3.0)*math.pi*(r**3) A = 4.0*math.pi*(r**2) print "Volume:",V print "Surface area:",A main()
true
046fa4c3c7c35156ad8f3a7bce5d45ed67180384
johntiger1/LinkedList
/python_approaches/hackerrank.py
758
4.25
4
""" Reverse a linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method. """ def Reverse(head): # base case: if head is None: return head # a couple of solutions: # connect each one as it "comes" prev = None curr = head next = head.next while (curr is not None): curr.next = prev prev=curr curr = next if next is None: return prev next = next.next # at the end, curr is None return prev
true
70af260ff5eaa180da241e2d920b5d05b66080c7
AmandaRH07/Entra21_Python
/01-Exercicios/Aula001/Ex2.py
1,265
4.15625
4
#--- Exercício 2 - Variáveis #--- Crie um menu para um sistema de cadastro de funcionários #--- O menu deve ser impresso com a função format() #--- As opções devem ser variáveis do tipo inteiro #--- As descrições das opções serão: #--- Cadastrar funcionário #--- Listar funcionários #--- Editar funcionário #--- Deletar funcionário #--- Sair #--- Além das opções o menu deve conter um cabeçalho e um rodapé #--- Entre o cabeçalho e o menu e entre o menu e o rodapé deverá ter espaçamento de 3 linhas #--- Deve ser utilizado os caracteres especiais de quebra de linha e de tabulação opcao = int(input(""" SISTEMA DE CADASTRO DE FUNCIONARIO\n\n\n {} - Cadastrar Funcionário {} - Listar Funcinários {} - Editar Funcionário {} - Deletar Funcionário {} - Sair\n\n\n Escolha uma opção: """.format(1,2,3,4,5))) if opcao == 1: print("A opção escolhida foi 'Cadastrar funcionário'") elif opcao == 2: print("A opção escolhida foi 'Listar funcionários'") elif opcao == 3: print("A opção escolhida foi 'Editar funcionário'") elif opcao == 4: print("A opção escolhida foi 'Deletar funcionário'") elif opcao == 5: print("A opção escolhida foi 'Sair'") else: pass
false
d9d1dea3c9e6ac436cda29f42bf73f3a4b2c6180
J0NATHANsimmons/Lab9
/lab9-70pt.py
641
4.28125
4
############################################ # # # 70pt # # # ############################################ # Create a celcius to fahrenheit calculator. # Multiply by 9, then divide by 5, then add 32 to calculate your answer. # TODO: # Ask user for Celcius temperature to convert # Accept user input # Calculate fahrenheit # Output answer print "Celius to Farenheit calculator!" print "Type your Celcius tempurature :" userInput = int(raw_input()) *9 /5 +32 print "Your Farenheit tempurature is " + str(userInput) + "!"
true
f3a7a06249cd77f91b8a7f99298713530f3c65de
tamirverthim/programmers-introduction-to-mathematics
/secret-sharing/interpolate.py
959
4.1875
4
from polynomial import Polynomial from polynomial import ZERO def single_term(points, i): """Return one term of an interpolated polynomial. Arguments: - points: a list of (float, float) - i: an integer indexing a specific point """ theTerm = Polynomial([1.]) xi, yi = points[i] for j, p in enumerate(points): if j == i: continue xj = p[0] theTerm = theTerm * Polynomial([-xj / (xi - xj), 1.0 / (xi - xj)]) return theTerm * Polynomial([yi]) def interpolate(points): """Return the unique degree n polynomial passing through the given n+1 points.""" if len(points) == 0: raise ValueError('Must provide at least one point.') x_values = [p[0] for p in points] if len(set(x_values)) < len(x_values): raise ValueError('Not all x values are distinct.') terms = [single_term(points, i) for i in range(0, len(points))] return sum(terms, ZERO)
true
e9d0e0e4fb445c4909ed9eaa5586e7c710972136
woody-connell/dc-classwork
/week01/2-Tuesday/preLectureNotes/strings.py
1,277
4.1875
4
###################### Strings ###################### print("I am a string.") print('I am a string too.') print('I\'m a string and I have to escape my single quote.') print("I'm a string and I have a single quote.") print(""" I am a string and I can span multiple lines! """) ####################### Concatentating Strings ###################### print('abc' + 'def') # Escape Characters print('I am one line.\nI am another line') print('I am one line.\bI went back one space') print('I am one line.\tI horizontal spacing') print('I am one line.\nI new line') print('I am one line.\n\vI new line with vertical spacing') ####################### Integers and Floats ###################### print(5) # integer print(5.6) # float # mixed type will be converted to a float print(8 + 1.0) # result 9.0 print(8.0 / 3) # you get 2.666666 # Calculating with Python print(20 + 3650) print(8 * 3.57) print(5 + 30 * 20) # Use parentheses to control the order of operations print(((5 + 30) * 20) / 10) print(5 + 30 * 20 / 10) ####################### More Arithmetic ###################### print(5 // 2 ) # division w/o decimal print(5 % 2 ) # modulus/remainder print(5 ** 3 ) # exponentiation
true
205bce3d1c430dcc3f9ede8caf9ba6ed5ba969cd
Novandev/interview_prep_python
/algorithms/recursion/factorials.py
297
4.1875
4
""" Factorials are defined as a nuber n in the follwing sequence down to 1 n! = n *(n-1) *(n-2) * (n-3)........ n = 1 """ def factorial_recursive(val): if val < 2: return 1 return(val * factorial_recursive(val -1)) if __name__ == "__main__": print(factorial_recursive(5))
false
6fe44847e3a913e8ae5738987ad1b2caa7a876f0
Novandev/interview_prep_python
/algorithms/dynamic_programming/fibonnacci_dynamic.py
977
4.25
4
""" Dynamic programming and Memoization """ def fibonacci_dynamic(n): ''' This function displayes the proper use of memoization ''' pass def fibonacci_recursion(n): ''' SO recursion is usually a place to start with this kinda stuff The problem is that it builds a tree so larger values end up being intractable fib(7) ={ 6{ 5:{ 4 3" } 4:{ 2 3 } } 5:{ } } This means that it tends to repeat steps, so we'll need to cut down on that This is 2^n so fibonacci_recursion(50) == 2^50 YIKES ''' print(n-1, n-2) # Base case if n <= 2: return 1 return fibonacci_recursion( n - 1) + fibonacci_recursion( n- 2) if __name__ == "__main__": print(fibonacci_recursion(7))
true
d12c833768b687418f8584ec406678bf820b75a3
yuehu9/Deep-Learning-From-Scratch
/5_DL_regularization/data_utils.py
2,632
4.59375
5
import numpy as np import matplotlib.pyplot as plt import sklearn.datasets def plot_decision_boundary(model, X, y): '''The function for plotting the decision function takes as arguments an anonymous function used to generate the predicted labels, and applies the function to the training data. plot_decision_boundary(lambda x: clf.predict(x), train_X, C) The function calls the predict method from the class LogisticRegressionCV that implements logistic regression in scikit-learn. --------------------------------------------------------------- predict(X)[source] Predict class labels for samples in X. Parameters: X : {array-like, sparse matrix}, shape = [n_samples, n_features] Samples. Returns: C : array, shape = [n_samples] Predicted class label per sample. --------------------------------------------------------------- In order to use the same function for plotting the decision boundary for your neural network model, you need a function for predicting the labels. Because of the matrix dimensions, you need a separate function that takes as input the training examples using a matrix of shape (m,n) and outputs the labels as a 1-d array. For example, you can implement a function: predict_plot(parameters,X) where paramaters are the weights and biases of the neural network model and X is the training data size of shape (m,n). Then, you can plot the boundary using plot_decision_boundary(lambda x: predict_plot(parameters, x), train_X, C) ''' # Set min and max values and give it some padding x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1 y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1 h = 0.01 # Generate a grid of points with distance h between them xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the function value for the whole grid Z = model(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # Plot the contour and training examples plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) plt.ylabel('x2') plt.xlabel('x1') plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) plt.show() # Load 2D data from sklearn def load_moons(plot = True): # Generate the data N = 200 X, Y = sklearn.datasets.make_moons(n_samples=N, noise=.3) X, Y = X.T, Y.reshape(1, Y.shape[0]) # For plotting colors C = np.ravel(Y) # Visualize the data if plot: plt.scatter(X[0, :], X[1, :], c=C, s=40, cmap=plt.cm.Spectral); return X, Y
true
38cc6bb0b6716e277aa148a6f30801d8c61f1fbd
meharrahim/python-small-projects-for-beginners
/Dice-Rolling-Simulator.py
547
4.34375
4
from random import randint # set min and max values of die min=1 max=6 # set a variable roll-again to repeat rolling roll_again = 'yes' # set a number of dice number_dice = 1 while roll_again == "yes": # integer input to number_dice number_dice = int(input("Input the number of dice you want to roll")) print("Rolling the dices...") print("The values are....") while number_dice > 0: print(randint(min, max)) number_dice= number_dice - 1 roll_again = input("Roll the dices again?(yes/no)")
true
c8f8e84ed588434b2e985e0d50c71f16870f5470
M11h3w/cspp10
/unit2/mstewart_simplecalc.py
512
4.15625
4
c = input("Enter a three digit equation such as 3+5: ") num1 = int(c[0]) op = c[1] num2 = int(c[2]) if op == "+": num3 = num1 + num2 print("The result is {}.".format(num3)) elif op == "-": num3 = num1 - num2 print("The result is {}.".format(num3)) elif op == "*": num3 = num1 * num2 print("The result is {}.".format(num3)) elif op == "/": num3 = num1 / num2 print("The result is {}.".format(num3)) elif op == "%": num3 = num1 % num2 print("The result is {}.".format(num3))
false
b60aa59e037e5c8c119bc5b56284cda9f298672a
acbarker19/PHY299-Class-Assignments
/Notes/notes_string.py
2,569
4.46875
4
print("Strings") print("'abc''cdf' = " + 'abc''cdf') print("'abc' + 'cdf' = " + 'abc' + 'cdf') print("'abc' * 3 = " + 'abc' * 3) print("str(4*2) = " + str(4*2)) print('Quotes within quotes: I said to her, "but why is the tomato blue?"') """ \t tab \n new line \r carriage return \' single quote \" double quote """ print("\r\nBackslash Commands") print("a\\tbcd\\nefg\\\"hij\\' = a\tbcd\nefg\"hij\'") # can use triple quotes to print strings on multiple lines print("\r\nStrings Across Multiple Lines") text = """Test Message with Triple Double Quotes""" print(text) print("\r\nSlicing and Indexing") s = "abcdefg" print("s = " + s) print("s[0]: " + s[0]) print("s[3]: " + s[3]) print("s[-1]: " + s[-1]) print("s[1:4]: " + s[1:4]) print("s[0:6:2]: " + s[0:6:2]) print("s[::-1]: " + s[::-1]) print("\r\nSlicing and Indexing Example") s = "I'm a little teapot" print(s) print(s[:12]) print(s[-3:] + s[:5]) print(s[:-7:-1]) print(s.replace("little", "big")) print("\r\nSwitching to Uppercase and Stripping a String") s = "+-a line from a text fileGGG" # strip removes characters from the beginning and end until it reaches a character not in parenthesis s2 = s.strip("+-G") s2 = s2.title() s2 = s2.replace("A Line", "An Awesome Line") print("s = " + s) print("s with stripping, title, and replace commands = " + s2) print("\r\nInsert Data into a String") person = "Mrs. White" place = "kitchen" weapon = "knife" sentence = "The murder was done by {0} in the {1} with the {2}.".format(person, place, weapon) print(sentence) # {0:.3f} includes 3 digits after the decimal in the 0th place of the string # {0:.2g} includes 2 digits total # {0:.2E} includes 2 digits after the decimal and switches the rest to exponential format score = 5.6789 sentence = "The restaraunt had a rating of {0:.3f}".format(score) print(sentence) sentence = "The restaraunt had a rating of {0:.2g}".format(score) print(sentence) sentence = "The restaraunt had a rating of {0:.2E}".format(score) print(sentence) print("\r\nQ2.3.2 - Is a String a Palindrome?") word = "racecar" print("Is " + word + " a palindrome?") print(word[::-1] == word) word = "hello" print("Is " + word + " a palindrome?") print(word[::-1] == word) print("\r\nP2.3.1 - Is a Nucleotide Sequence a Palindrome with its Pair?") s = "TGGATCCA" # replace nucleotide with pair s2 = s.replace("T", "a") s2 = s2.replace("A", "t") s2 = s2.replace("C", "g") s2 = s2.replace("G", "c") # return all to uppercase s2 = s2.upper() print("Is " + s + "'s pair a palindrome to the original?") print(s[::-1] == s2)
false
243d207ae4003988a9903e96d000fd14c4517de2
UjuAyoku/Pycharm-Projects
/Fizz Buzz.py
665
4.25
4
# Exercise 2 """ Write a function called fizz_buzz that takes a number. If the number is divisible by 3, it should return “Fizz”. If it is divisible by 5, it should return “Buzz”. If it is divisible by both 3 and 5, it should return “FizzBuzz”. Otherwise, it should return the same number. """ def fizz_buzz(number): try: if number % 3 == 0 and number % 5 == 0: return 'FizzBuzz' elif number % 3 == 0: return 'Fizz' elif number % 5 == 0: return 'Buzz' else: return number except TypeError: print('Incorrect input. Enter a number.')
true
ea92c718d609bdd40848ae003152a491c426e464
migzpogi/gitgud
/lessons/lambdas.py
539
4.15625
4
# Lambdas # https://www.w3schools.com/python/python_lambda.asp # Date: Sep 20, 2018 # Lambda is a small anonymous function # Can take any number of arguments, but can only have 1 expression # Syntax: lambda arguments : expression x = lambda a : a + 10 print(x(10)) y = lambda a, b, c : print('Your arguments are: {}, {} and {}'.format(a, b, c)) y('Migz', 1, ['Estrella', 24]) # Why use lambda functions? def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(11)) print(mytripler(11))
true
b385a60bb675f46e9958466e9889f949e6105746
skrishna1978/CodingChallenge-February-2019-
/2.26.2019 | stringShortener.py
2,144
4.28125
4
#2.26.2019 - shashi #program that take a sentence to shortens it to a given length. def stringShorten(sentence, maxLength, connector): #function starts here if not sentence or maxLength<=0: #error check return "Invalid" if maxLength >= len(sentence): #if sentence length matches required length return sentence #return original sentence. no change. #if length required matches connector length + 1 #or if connector length > maxLength # return sentence from start to maxLength. As in, the first maxLength characters in sentence. if maxLength == len(connector) + 1 or len(connector) > maxLength: return sentence[:maxLength] #if none of the above are true, then we shrink the sentence. #logic here is: #maxLength - length of connector = gives us how much is left to use for the sentence. #that value needs to be divided so that first half and last half can share it. shortenLength = maxLength - len(connector) #first we figure out how much sentence to use. shortenedSentence = sentence[:int(shortenLength/2)] #first half of the sentence based on length shortenedSentence += connector #add the connector pattern next #second half starts at the end of the sentence and adds it with remainder of dividing length by 2. #maxLength - (firtHalf + connector length) = second half length. shortenedSentence += sentence[-(int(shortenLength/2) + (shortenLength % 2)):] #second half of the sentence based on remaining length return shortenedSentence #return final version of the shortened sentence. #testing the function sentence = "The quick brown fox jumps over the lazy dog" print(stringShorten(sentence, 24,"...")) #where max length is < total sentence length. Shortened version returned. print(stringShorten(sentence,812,"...")) #where max length is > total sentence length. Sentence returned as is. print(stringShorten(sentence,0,"...")) #where max length is 0. Invalid returned.
true
2f039c4e309858e33c3ea424a3bf1dd924ea55d5
abhishekRamesh8/BestEnlist-Python-Internship-Repo
/Day 9/task5.py
205
4.15625
4
# Write a Python program to count the even numbers in a given list of integers lst = list(range(1, int(input('Enter the length of list: ')) + 1)) print(list(map(lambda x: (x % 2 == 0), lst)).count(True))
true
704bbf30ea723f79cff973a7ec86374065507139
abhishekRamesh8/BestEnlist-Python-Internship-Repo
/Day 3/task3.py
219
4.125
4
# Write a Python program to map two lists into a dictionary hdr_table = ["Name", "ID", "Lecture", "Grade"] record = ["R. Abhishek", "21101", "Programming", "A"] dt_student = dict(zip(hdr_table, record)) print(dt_student)
false
a04e047efca1bd88e177f26800d21c8b9d9f4a16
aneels3/Algorithm
/Dijktra.py
1,171
4.21875
4
# Dijktra's shortest path algorithm. Prints the path from source to target. def dijkstra(adj, source, target): INF = ((1<<63) - 1)//2 pred = { x:x for x in adj } dist = { x:INF for x in adj } dist[source] = 0 PQ = [] heapq.heappush(PQ, [dist[source], source]) while(PQ): u = heapq.heappop(PQ) # u is a tuple [u_dist, u_id] u_dist = u[0] u_id = u[1] if u_dist == dist[u_id]: #if u_id == target: # break for v in adj[u_id]: v_id = v[0] w_uv = v[1] if dist[u_id] + w_uv < dist[v_id]: dist[v_id] = dist[u_id] + w_uv heapq.heappush(PQ, [dist[v_id], v_id]) pred[v_id] = u_id if dist[target]==INF: stdout.write("There is no path between " + source + " and " + target) else: st = [] node = target while(True): st.append(str(node)) if(node==pred[node]): break node = pred[node] path = st[::-1] stdout.write("The shortest path is: " + " ".join(path))
false
65baf64dac7679aa5a58ba8b8208c83dd6d0af42
aneels3/Algorithm
/rightrotate.py
771
4.4375
4
# Python program to right rotate a list by n def rightRotate(lists, num): output_list = [] # Will add values from n to the new list for item in range(len(lists) - num, len(lists)): output_list.append(lists[item]) # Will add the values before # n to the end of new list for item in range(0, len(lists) - num): output_list.append(lists[item]) return output_list # Driver Code if __name__ == "__main__": list1 = [] # number of elemetns as input n = int(input("Enter number of elements : ")) # iterating till the range for i in range(0, n): ele = int(input()) list1.append(ele) print(list1) k = int(input("Enter the number of positions you want to shift:")) print(rightRotate(list1, k))
true
456071573ce391e95cc068aeb67896c450e816e9
wallacex19/python
/6-erros e exeções/erros e exceções.py
450
4.125
4
# try e except: o codigo q pode causar uma exceção é colocado no bloco try, e o tratamento da exceção é implementado no bloco except. def string(n="1"): try: a = "1" + n except: print("parâmetro invalido, uma exceção ocorreu") raise Exception("Mês Inválido") # força o erro e mostra uma mensagem. sem raise o programa continua finally: print("finally sempre será executado") string(1)
false
62b860e2af43f957f954a2fd6150e4110f35df65
JPCLima/DataCamp-Python-2020
/Data Scientist with Python- Track/Data Manipulation with pandas/3. Slicing and indexing/1_explicit_index.py
1,350
4.40625
4
# Setting & removing indexes # Look at temperatures print(temperatures) # Index temperatures by city temperatures_ind = temperatures.set_index("city") # Look at temperatures_ind print(temperatures_ind) # Reset the index, keeping its contents print(temperatures_ind.reset_index()) # Reset the index, dropping its contents print(temperatures_ind.reset_index(drop=True)) # Subsetting with .loc[] # Make a list of cities to subset on cities = ["Moscow", "Saint Petersburg"] # Subset temperatures using square brackets print(temperatures[temperatures["city"].isin(cities)]) # Subset temperatures_ind using .loc[] print(temperatures_ind.loc[cities]) # Setting multi-level indexes # Index temperatures by country & city temperatures_ind = temperatures.set_index(["country", "city"]) # List of tuples: Brazil, Rio De Janeiro & Pakistan, Lahore rows_to_keep = [("Brazil", "Rio De Janeiro"), ("Pakistan", "Lahore")] # Subset for rows to keep print(temperatures_ind.loc[rows_to_keep]) # Sorting by index values # Sort temperatures_ind by index values print(temperatures_ind.sort_index()) # Sort temperatures_ind by index values at the city level print(temperatures_ind.sort_index(level=["city"])) # Sort temperatures_ind by country then descending city print(temperatures_ind.sort_index( level=["country", "city"], ascending=[True, False]))
true
2ef08c80e252f319589b657f2047ad243c142e7d
Jadoon83/PythonMVA
/21_FUnctionInPython.py
1,630
4.21875
4
# in Python, we have to define a function before we can use it. # def keyword is used to define a function followed by th neme of the function # and then the parameters # The main() function is called at the bottom def main(): fileName = "CountryList.csv" myList = ["C", "Python", "Java", "C++", "NodeJS", "JavaScript"] printListSL (myList) printList (myList) print() value = printFile(fileName) printFileLineByLine(fileName) print(value) print("-----------\nWell it works") return # Function to print the contents of a file def printFile(fileName): print ("Priting the contents of a file:\n") myFile = open(fileName, mode="r") fileData = myFile.read() print(fileData) print("--------------\n") myFile.close() return # Function to print the contents of a file line by line # You can notice a line gap because this function will print '\n' as well def printFileLineByLine(fileName): print ("Priting the contents of a file line by line:\n") myFile = open(fileName, mode="r") for lines in myFile: print(lines) myFile.close() return # Function to print a list in a single line def printListSL (list): print("Printing the list item in a line...\n") for items in list: print(items + " ", end="") print("\n") return # Function to print a list line by line def printList (list): print("Printing the list items...\n") for items in list: print(items) print("\n") return # Calling the main() function main() # There was no need of the main function but it makes the code a bit clean
true
266152f584f608a390fef38aa0e919069ddade50
Jadoon83/PythonMVA
/13_MoreOnForLoop.py
321
4.3125
4
for numbers in range (5): print (numbers) # More on range print() for numbers in range (1, 6): print (numbers) # Another kid of loop, more like foreach loop print() for nums in [1, 2, 3, 4, 5]: print(nums) # Few more exampples print() for num in [22, "Ashok", "Python", 22.4, 12, "C"]: print (num)
true
ea85cbb1fa92b0680049a57083d42ac72e4b4ad0
ajauhri/playground
/coin_change.py
1,104
4.375
4
#! /usr/bin/env python """ Usage: coin_change [options] Prints the minimum number of change using the input denominations. Options: -d, --provide a list of denominations. For example: coin_change 1 2 3 """ from sys import argv, exit def main(): if not len(argv[1:]) > 1 and not argv[1] == "-d": print ("Please enter denominations.") exit() denominations_available = [ int(i) for i in argv[2:] ] value = input('Enter value (cents 0 - 99):') coin_change(value, denominations_available) def coin_change(n, denominations): change_combinations = [] change = dict((k,[]) for k in range(0,n+1)) change[0] = [0] change_combinations.insert(0,0) for i in range(1,n+1): change_combinations.insert(i,99999999999) for denomination in denominations: if i >= denomination and (1 + change_combinations[i - denomination]) < change_combinations[i]: change_combinations[i] = 1 + change_combinations[i - denomination] print change_combinations[n] if __name__ == "__main__": main()
true
356973f79a45356f24c1621bc90fbc78ef447dd3
ShahzainAhmed/InvertedStar
/InvertedStar.py
236
4.53125
5
# Program to create Inverted Star pattern. # Taking input from the user. n=int(input("Enter number of rows: ")) # Using for loop with range. for i in range (n,0,-1): # Using print statement. print((n-i) * ' ' + i * '*')
true
4dca9e32ce5f63e6e395d05762cedfa248539aaf
akshah/pyPrep
/sortAlgos/merge_sort.py
807
4.125
4
#!/usr/bin/python def merge(leftA, rightA): results=[] li=0 ri=0 while li<len(leftA) and ri<len(rightA): if leftA[li]<rightA[ri]: results.append(leftA[li]) li+=1 else: results.append(rightA[ri]) ri += 1 while li<len(leftA): results.append(leftA[li]) li+=1 while ri<len(rightA): results.append(rightA[ri]) ri+=1 return results def merge_sort(array): if len(array)<2: return array mid=len(array)//2 leftArray=merge_sort(array[:mid]) rightArray=merge_sort(array[mid:]) results=merge(leftArray,rightArray) return results if __name__=="__main__": arr=[1,3,5,2,5,6,2,3,4,5,6] print(arr) sortedArr=merge_sort(arr) print(sortedArr)
false
08bba9009b19e7e99c2842843f0ac21c772c2cc3
maxmyth01/unit4
/stringUnion.py
422
4.21875
4
#Max Low #10-20-17 #stringUnion.py takes two words and then prints out all the apering letter each letter only once def stringUnion(word1, word2): letters = '' for ch in word1: if ch not in letters: letters = letters + ch for ch in word2: if ch not in letters: letters = letters + ch return(letters) print(stringUnion('mississippi','pennsylvania'))
true
89e11189a2ebf3072cfa0936b72421b20d555fad
stambla/google_prep
/anagram.py~
418
4.3125
4
#! usr/bin/env python """ 1.4 Write method which to decide if two strings are anagram or not. """ str_1 = input("Please input first word:") str_2 = input("Please input second word:") def check_anagram(str_1, str_2): temp = str_1[::-1] if temp == str_2: print "%s is angaram of %s" % (str_1, str_2) else: print "Hard luck!!! %s is not angaram of %s" % (str_1, str_2) check_anagram(str_1, str_2)
true
25a5fb2ae9f7f82dbbd3cb65b5cbe53a8c815ce3
humanoiddess13/be-fullstack-TDD
/find_min.py
1,780
4.25
4
def get_min(a, b): """ Return minimal number among a and b. """ return a if a < b else b def get_min_without_arguments(): """ Raise TypeError exception with message. """ raise TypeError('You must have at least 1 argument.') def get_min_with_one_argument(x): """ Return that value. """ return x def get_min_with_many_arguments(*args): """ Return smallest number among numbers in args. """ min_number = None for i in args: min_number = i if min_number is None or i < min_number else min_number return min_number def get_min_with_one_or_more_arguments(first, *args): """ Return smallest number among first and numbers in args. """ min_number = None for i in (first,) + args: min_number = i if min_number is None or i < min_number else min_number return min_number def get_min_bounded(*args, low, high): """ Return smallest number among numbers in args bounded by low & high. """ min_number = None for i in args: min_number = i if low < i < high and (min_number is None or i < min_number) else min_number return min_number def make_min(*, low, high): """ Return inner function object which takes at least one argument and return smallest number amount it's arguments, but if the smallest number is lower than the 'low' which given as required argument the inner function has to return it. """ def inner(first, *args): min_number = None for i in (first,)+args: min_number = i if low < i < high and (min_number is None or i < min_number) else min_number return min_number if min_number >= low else low return inner
true
20a8fb484e4a78e0d96f6194aad171509df41d49
reenadangi/python
/python_stack/Algos/LinkedList/mergesort.py
773
4.125
4
def mergeSort(arr): # find mid if len(arr)>1: # find middle mid=len(arr)//2 left=arr[:mid] right=arr[mid:] mergeSort(left) mergeSort(right) i=j=k=0 while i<len(left) and j<len(right): if left[i]<=right[j]: arr[k]=left[i] i+=1 k+=1 else: arr[k]=right[j] j+=1 k+=1 while i<len(left): arr[k]=left[i] i+=1 k+=1 while j<len(right): arr[k]=right[j] j+=1 k+=1 return arr else: return arr print(mergeSort([3,5,6,22,3,1,0,-1]))
false
e5b3d7887ee279cf11c24f184b292dfa54e13de1
reenadangi/python
/python_stack/Algos/list_comprehension/list.py
1,147
4.15625
4
nums=[1,2,3,4,5,6] my_list=[] # for i in nums: # my_list.append(i) # print (my_list) # 1. First example my_list=[i for i in nums] print(my_list) # 2. I want n*n for each in nums my_list=[] my_list=[i*i for i in nums] print(my_list) # 3. I want i for each in mums if i is even my_list=[] my_list=[i for i in nums if i%2==0] print(my_list) # 4. NESTED FOR LOOPS I want (letter,num) pair for each letter in ('abcd') and each num in(0123) my_list=[] # for letter in 'abcd': # for num in range(4): # # tuple of letter and num # my_list.append((letter,num)) # print(my_list) my_list=[(letter,num)for letter in 'abcd' for num in range(4) ] print(my_list) # 5. Dict my_list=[] names=['Bruce','clark','Peter','Logan'] heros=['batman','superman','spiderman','wolverine'] # for name,hero in zip(names,heros): # my_list[name]=hero # print (my_list) # if name is not clark my_list={name:hero for name,hero in zip(names,heros) if name!='clark'} print(my_list) # 6. Set compriherntion - all unique nums=[1,2,3,3,3,1,4,5,6] # my_set=set() # for i in nums: # my_set.add(i) # print(my_set) my_set={i for i in nums} print(my_set)
false