blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3a138f569de9b1e4d5e2227e1ee290489eb5883c
emir-naiz/first_git_lesson
/Courses/1 month/4 week/day 1/Задача №5 setify number.py
353
4.125
4
def setify(number_list): number_list.sort() empty_list = [] for number in empty_list: if number not in empty_list: empty_list.append(number) return empty_list print(setify(1,2,3,3,4,4,6,6,5,5)) print(set(([1,2,3,3,4,4,6,6,5,5]))) # при помощи set можно удалить дублирующие цифры
false
2355ee5a02dcbc66d33649b618d1c57e356e9ada
jamj2000/Programming-Classes
/Math You Will Actually Use/Week6_Sympy.py
725
4.3125
4
' "pip install sympy" before you do any of this ' import sympy # import the calculator with variable buttons :) from sympy import Symbol # -------------------------- first, solve the simple equation 2*x=2 x = Symbol('x') # create a "symoblic variable" x equation = 2*x - 2 # define the equation 2*x = 2 solution = sympy.solve(equation, x) # solve for x print(solution) # print the list of all solutions # -------------------------- next, lets do the equation of a circle y = Symbol('y') equation = x**2 + y**2 - 1**2 # x**2 + y**2 = r**2 where r =1 solution = sympy.solve(equation, y) # solve for y print(solution) # notice how one is the TOP half of the circle # and the other in the list is the BOTTOM half
true
0b6dae16fec055ad0eccb3d651b02f5643540e81
jamj2000/Programming-Classes
/Intro To Python/semester1/Week10_Challenge0.py
1,798
4.34375
4
''' This is a deep dive into FUNCTIONS What is a function? A function is a bunch of commands bundled into a group How do you write a function? Look below! CHALLENGES: (in order of HEAT = difficulty) Siberian Winter: Change the link of the Philly function Canada in Spring: Make the link an input to Philly, not a constant Spring in California: Convert Antonia's inputs to named inputs Summer in California: Write a new function which adds two numbers Rocket Engine: Convert these functions into a CLASS ''' import webbrowser def Franko(): print('Hello from Franko, the simple function') def Philly(): print('Hello from Philly, the funky phunction') print('You see, you can do a lot of stuff in one function') print('Like taking the square root of 1,245 to the power of pi!') import math sqrt1245_pi = math.sqrt(1245)**math.pi print('Which is exactly... ', sqrt1245_pi) print('You can even do fun stuff in here... Check this out...') webbrowser.open('http://www.jonnyhyman.com') def Antonia(argument1, argument2, TheyDontAllNeedToSayArgumentThough): print('Hello from Antonia, the fun function with fun inputs') print('These are my arguments:') print(argument1) print(argument2) print(TheyDontAllNeedToSayArgumentThough) webbrowser.open('https://media.giphy.com/media/R8n7YlPHe34dy/giphy.gif') def Kevin(named_argument = 'Wut', other_one = 'Hah', herp = 'derp' ): print('Hello from Kevin the function with NAMED inputs...') print('My inputs were...', named_argument, other_one, herp) #input(" ----> Notice how none of the functions run until you call them" # " //// [ENTER] to continue") print('_______________') # some space to be able to read easier Antonia()
true
d3f6517aeea44395a9796ee175fc8ef0dcaacaa1
csmdoficial/aulas-python
/curso/venv/bin/exercicios/desafio 033.py
537
4.15625
4
"""faça um programa qu leia três números e mostre qual é o menor e o maior """ a = float(input("Digite um numero:")) b = float(input("Digite outro numero:")) c = float(input('Digite o ultimo numero:')) #verificando quem é o menor menor = a if b < a and b < c: menor = b if c < a and c < b: menor = c #verificando quem é o maior maior = a if b > a and b > c: maior = b if c > a and c > b: maior = c print('O menor valor digitado foi {:.0f}'.format(menor)) print('O maior valor digitado foi {:.0f}'.format(maior))
false
e543c991e7ad17b2a657274bb1a5483636fc0d4f
csmdoficial/aulas-python
/curso/venv/bin/exercicios/desafio 025.py
265
4.15625
4
"""crie um programa que leia o nome de uma pessoa e diga se ela tem 'silva' no nome""" nome = str(input('Digite um nome:')).upper().strip() print('SILVA'in nome) n = str(input('Digite um nume:')).upper().strip() print('Seu nome tem Silva? {}'.format('SILVA' in n))
false
6fb1b7fff352717f4654ee2f38548c0fff13cfb7
iulyaav/coursework
/stanford-algo-courses/matrix_multiplication.py
1,177
4.25
4
def matrix_add(X, Y): pass def matrix_multiply(X, Y): """ Let X = | A B | and Y = | E F | | C D | | G H | We have the products: P1 = A(F-H) P2 = (A+B)H P3 = (C+D)E P4 = D(G-E) P5 = (A+D)(E+H) P6 = (B-D)(G+H) P7 = (A-C)(E+F) Claim: X * Y = | (P5 + P4) - P2 + P6 P1 + P2 | | P3 + P4 (P1 + P5) - (P3 + P7) | Nb - This only supports matrice of nxn where n is even """ if len(X) == len(Y) == 2: return [ [X[0][0]*Y[0][0] + X[0][1]*Y[1][0], X[0][0]*Y[0][1] + X[0][1]*Y[1][1]], [X[1][0]*Y[0][0] + X[1][1]*Y[1][0], X[1][0]*Y[0][1] + X[1][1]*Y[1][1]] ] def print_matrix(n): tmp = [] for i in range(n): # print("{} row:".format(i+1)) tmp.append([int(x) for x in input().split(' ')]) return tmp if __name__ == "__main__": print("Let's multiply matrices of n=") n = int(input()) print("Let's write the first matrix") first = print_matrix(n) print("Let's write the second matrix") second = print_matrix(n) print(matrix_multiply(first, second))
false
ad291e7fa25471945efc95465a4589cd89a44e7a
mihir-liverpool/RockPaperScissor
/rockpaperscissor.py
841
4.125
4
import random while True: moves = ['rock', 'paper', 'scissor'] player_wins = ['paperrock', 'scissorpaper', 'rockscissor'] player_move = input('please choose between rock paper or scissor: ') computer_move = random.choice(moves) if player_move not in moves: print('please choose an option between rock paper and scissor') elif computer_move == player_move: print ('your move was ', player_move) print ('computers move was', computer_move) print('That is a draw, please try again') elif player_move+computer_move in player_wins: print('your move was ', player_move) print('computers move was', computer_move) print('you win') else: print('your move was ', player_move) print('computers move was', computer_move) print('you lose')
true
1dbd6a073c1fbdae4bdc435d7a678e49e8709ab3
sombra721/Python-Exercises
/Regular Expression_ex.py
1,503
4.125
4
''' The script will detect if the regular expression pattern is contained in the files in the directory and it's sub-directory. Suppose the directory structure is shown as below: test |---sub1 | |---1.txt (contains) | |---2.txt (does not contain) | |---3.txt (contains) |---sub2 | |---1.txt (contains) | |---2.txt (contains) | |---3.txt (contains) |---sub3 |---|---sub3-1 The result will be: {"sub1": 2, "sub2": 3,"sub3": 0,"sub3\sub3-1": 0} Running the script with the two arguments: 1. Tha path to be traversal. 2. Ragular Expression pattern. e.g.: python re_traversal.py C:/test ("^[a-zA-Z]+_TESTResult.*") ''' import sys import os import re import pylab def draw_graph(result): names = result.keys() counts = result.values() pylab.xticks(range(len(names)), names) pylab.plot(range(len(names)), counts, "b") pylab.show() def main(argv): result = {} for path, subdirs, files in os.walk(argv[1]): for subdir in subdirs: result[os.path.join(path, subdir)[len(argv[1])+1:]] = 0 for name in files: if re.search(argv[2], open(os.path.join(path, name), 'r').read()): result[os.path.join(path, name)[len(argv[1])+1:-len(name)]] = result.get(os.path.join(path, name)[len(argv[1])+1:-len(name)], 0) + 1 if result: print result else: print "No match detected." draw_graph(result) if __name__ == '__main__': main(sys.argv)
true
8ae7109db20182e8e0367a39c03fa9e4dd04dba5
ryanthemanr0x/Python
/Giraffe/Lists.py
561
4.25
4
# Working with lists # Lists can include integers and boolean # friends = ["Kevin", 2, False] friends = ["Kevin", "Karen", "Jim"] print(friends) # Using index friends = ["Kevin", "Karen", "Jim"] # 0 1/-2 2/-1 print(friends[0]) print(friends[2]) print(friends[-1]) print(friends[-2]) print(friends[1:]) friends1 = ["Kevin", "Karen", "Jim", "Oscar", "Toby"] # 0 1 2 3 4 # Will grab all the elements upto, but not including last element print(friends1[1:4]) friends[1] = "Mike" print(friends[1])
true
6b82f94e0a3149bcb55199f4d3d3d860732aa475
ryanthemanr0x/Python
/Giraffe/if_statements.py
631
4.40625
4
# If Statements is_male = False is_tall = False if is_male or is_tall: print("You are a male or tall or both") else: print("You are neither male nor tall") is_male1 = True is_tall1 = True if is_male1 and is_tall1: print("You are a tall male") else: print("You are either not male or tall or both") is_male2 = True is_tall2 = False if is_male2 and is_tall2: print("You are a tall male") elif is_male2 and not(is_tall2): print("You are a short male") elif not(is_male2) and is_tall2: print("You are not a male and are tall") else: print("You are either not male or tall or both")
true
a97dadaf6560e38dafc3078ce3bbc4a849c66431
kiyotd/study-py
/src/6_asterisk/ex1.py
606
4.1875
4
list_ = [0, 1, 2, 3, 4] tuple_ = (0, 1, 2, 3, 4) print(list_) # [0, 1, 2, 3, 4] print(tuple_) # (0, 1, 2, 3, 4) # * # unpack 展開する print(*list_) # 0 1 2 3 4 print(*tuple_) # 0 1 2 3 4 # ** # 辞書などをキーワード引数として渡すことができる my_dict = {"sep": " / "} print(1, 2, 3, **my_dict) # 1 / 2 / 3 print(1, 2, 3, sep=" / ") # と同じ # 関数を定義するとき # 与えられた実引数はタプルにまとめられる def sum_func(*nums): total_ = 0 for num in nums: total_ += num return total_ print(sum_func(1, 2, 3, 4, 5)) # 15
false
2d259320a70264f55f837a84741a5a1b2abe6fd5
xhweek/learnpy
/.idea/ly-01.py
525
4.21875
4
#循环打印 #print('* ' * 5) """ for i in range(0,4): for j in range(0,5): print("* ",end=" ") print() """ for i in range(4): for j in range(5): #print(i,"-===========",j) if i == 0 or i == 3 or j == 0 or j == 4: print("* ",end = " ") else: print(" ",end = " ") print("") for i in range(5): for j in range(i+1): if i == 4 or j == 0 or j == i: print("* ",end=" ") else: print(" ",end = " ") print()
false
9e0a944f2100cab01f4e4cad3921c8786998681b
ikramsalim/DataCamp
/02-intermediate-python/4-loops/loop-over-lists-of-lists.py
446
4.25
4
"""Write a for loop that goes through each sublist of house and prints out the x is y sqm, where x is the name of the room and y is the area of the room.""" # house list of lists house = [["hallway", 11.25], ["kitchen", 18.0], ["living room", 20.0], ["bedroom", 10.75], ["bathroom", 9.50]] # Build a for loop from scratch for room, area in (house): print("the " + str(room) + " is " + str(area) + " sqm")
true
dcf1b439aa3db2947653f9197e961d4969f92095
ycayir/python-for-everybody
/course2/week5/ex_09_05.py
782
4.25
4
# Exercise 5: This program records the domain name (instead of the # address) where the message was sent from instead of who the mail came # from (i.e., the whole email address). At the end of the program, print # out the contents of your dictionary. # python schoolcount.py # # Enter a file name: mbox-short.txt # {'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7, # 'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8} handle = open('../../files/mbox-short.txt') counts = dict() for line in handle: line = line.strip() if not line.startswith('From'): continue words = line.split() if len(words) < 2: continue email = words[1] emailParts = email.split('@') domain = emailParts[1] counts[domain] = counts.get(domain, 0) + 1 print(counts)
true
16d0cc5afda917ebc335553cc6d338014b19f87b
aflyk/hello
/pystart/lesson1/l1t2.py
467
4.4375
4
""" Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. """ user_time = int(input("Введите кол-во секунд: ")) user_time = user_time % (60*60*24) print(f"{user_time // 3600}:{(user_time % 3600) // 60}:{(user_time % 3600) % 60 } ")
false
254210227b8c1c1ce4ddca88fb6a889a1c0e7c47
aflyk/hello
/pystart/lesson6/l6t2.py
1,224
4.3125
4
""" Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу: длина*ширина*масса асфальта для покрытия одного кв метра дороги асфальтом, толщиной в 1 см*число см толщины полотна. Проверить работу метода. Например: 20м*5000м*25кг*5см = 12500 т """ class Road: def __init__(self, lenght, width): self._lenght = lenght self._width = width def asf(self, weight=25, depth=5): return f"{(self._lenght * self._width * weight * depth)/1000} т" if __name__ == "__main__": small_road = Road(20, 5000) print(small_road.asf())
false
c3c1bf04376f728f6470a055e56c878ceec2d3b3
mjdall/leet
/spiral_matrix.py
2,106
4.1875
4
def spiral_order(self, matrix): """ Returns the spiral order of the input matrix. I.e. [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] becomes [1, 2, 3, 6, 9, 8, 7, 4, 5]. :type matrix: List[List[int]] :rtype: List[int] """ if not matrix or matrix is None: return [] output = [] # holds the limits for when we change axis direction curr_x_lim = len(matrix[0]) curr_y_lim = len(matrix) # holds the total number of entries in the array # as well as the number of total hops we need to do total_hops = curr_x_lim * curr_y_lim # the current directions we are travelling in the array # if x_direction is not 0 then y_direction will be 0, vice versa x_direction = 1 y_direction = 0 # the total number of steps we need to take in the current direction steps_in_direction = curr_x_lim # keep going until we've traversed each node x, y = 0, 0 while total_hops != 0: # append the current spot in the matrix output.append(matrix[y][x]) # increment variables keeping track of position steps_in_direction -= 1 total_hops -= 1 # we're done travelling in this direction if steps_in_direction == 0: # if we were travelling in x direction if x_direction: # y direction follows what x direction just was y_direction = x_direction # set x dir to zero x_direction = 0 # the next time we traverse in x direction, we dont go as far curr_x_lim -= 1 # set the number of steps we're expecting to take next steps_in_direction = curr_y_lim - 1 else: # x direction changes direction to y x_direction = -y_direction y_direction = 0 curr_y_lim -= 1 steps_in_direction = curr_x_lim # get the next spot in the array x += x_direction y += y_direction return output
true
3dd6609f9805f7c8bbf9949b56584a2c044475a3
mjdall/leet
/count_elements.py
668
4.28125
4
def count_elements(arr): """ Given an integer array arr, count element x such that x + 1 is also in arr. If there're duplicates in arr, count them seperately. :type arr: List[int] :rtype: int """ if arr is None or len(arr) == 0: return 0 found_numbers = {} for num in arr: found_numbers.setdefault(num, 0) found_numbers[num] += 1 nums_in_arr = found_numbers.keys() total_count = 0 for num in nums_in_arr: if num + 1 in found_numbers: total_count += found_numbers[num] return total_count
true
334da6ffae18a403cc33ae03c1600238a6a45ddd
denemorhun/Python-Problems
/Hackerrank/Strings/MatchParanthesis-easy.py
1,891
4.40625
4
# Python3 code to Check for balanced parentheses in an expression # EASY ''' Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true Solution: # position 0 -> [] # position 1 -> [] # position 2 -> () Use a stack to push all left paranthesis to open list. If the item equals the value in both open and closed lists, pop it. If we finish with an empty stack, paranthesis are balanced. ''' def isValid(input) -> bool: # convert string into a list input = list(input) # code: 0, 1, 2 open_list = ["[","{","("] close_list = ["]","}",")"] # No paranthesis means matching case if list is None: return True stack = [] # scroll through each char and add open paranthesis to the stack. for i in input: if i in open_list: stack.append(i) elif i in close_list: # get the paranthesis code: 0, 1, 2 code = close_list.index(i) if len(stack) > 0 and open_list[code] == stack[len(stack)-1]: stack.pop() # If all left paranthesis have been removed from stack we've found all the matches if len(stack) == 0: return True else: return False if __name__ == '__main__': input = ["khkjhkjhj", "#@#$@#$@", "()", "((([[[{}]]])))", ")(", "((]]", ""] for i in input: result = isValid(i) print("All paranthesis are matching.", i if result else "Mismatch", i)
true
bb708c316a2f7041f23c61036ff825153ad424a2
denemorhun/Python-Problems
/Grokking the Python Interview/Data Structures/Stacks and Queues/q_using_stack.py
1,149
4.21875
4
from typing import Deque from stack import MyStack # Push Function => stack.push(int) //Inserts the element at top # Pop Function => stack.pop() //Removes and returns the element at top # Top/Peek Function => stack.get_top() //Returns top element # Helper Functions => stack.is_empty() & stack.isFull() //returns boolean class NewQueue: def __init__(self): self.main_stack = MyStack() # Write your code here # Inserts Element in the Queue def enqueue(self, value): self.main_stack.push(value) return True # Removes Element From Queue def dequeue(self): # Write your code here temp_stack = MyStack() while not self.main_stack.size() == 1: temp_stack.push(self.main_stack.pop()) popped_item = self.main_stack.pop() while not temp_stack.is_empty(): self.main_stack.push(temp_stack.pop()) return popped_item def __str__(self): return str(self.main_stack) nq = NewQueue() nq.enqueue(1) nq.enqueue(2) nq.enqueue(3) nq.enqueue(4) nq.enqueue(5) val = nq.dequeue() print(nq) print(val)
true
a34383ee463d3c9749caf0e52c10e3e114fe02a7
denemorhun/Python-Problems
/AlgoExperts/LinkedList/remove_duplicates_from_linked_list.py
1,693
4.15625
4
''' A Node object has an integer data field, , and a Node instance pointer, , pointing to another node (i.e.: the next node in a list). A removeDuplicates function is declared in your editor, which takes a pointer to the node of a linked list as a parameter. Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list. Note: The pointer may be null, indicating that the list is empty. Be sure to reset your pointer when performing deletions to avoid breaking the list. Input Format Constraints The data elements of the linked list argument will always be in non-decreasing order. Your removeDuplicates function should return the head of the updated linked list. Sample Input 6 1 2 2 3 3 4 Sample Output 1 2 3 4 Explanation , and our non-decreasing list is . The values and both occur twice in the list , so we remove the two duplicate nodes. We then return our updated (ascending) list ''' # This is an input class. Do not edit. class LinkedList: def __init__(self, value): self.value = value self.next = None # Even though this class says linkedlist, it's actually Node def removeDuplicatesFromLinkedList(linkedList): # actually this is the head node currentNode = linkedList print("Starting with head node") while currentNode is not None: nextNode = currentNode.next print(currentNode.value) # if next node is equal to current node's value repeat loop while nextNode is not None and nextNode.value == currentNode.value: print('duplicate') nextNode = nextNode.next currentNode.next = nextNode currentNode = currentNode.next return linkedList
true
07bab891b92ca248e39056da104d2a9afdff953c
denemorhun/Python-Problems
/Hackerrank/Arrays/validate_pattern.py
1,708
4.34375
4
'''Validate Pattern from array 1 to array b Given a string sequence of words and a string sequence pattern, return true if the sequence of words matches the pattern otherwise false. Definition of match: A word that is substituted for a variable must always follow that substitution. For example, if "f" is substituted as "monkey" then any time we see another "f" then it must match "monkey" and any time we see "monkey" again it must match "f". Examples input: "ant dog cat dog", "a d c d" output: true This is true because every variable maps to exactly one word and vice verse. a -> ant d -> dog c -> cat d -> dog input: "ant dog cat dog", "a d c e" output: false This is false because if we substitute "d" as "dog" then you can not also have "e" be substituted as "dog". a -> ant d, e -> dog (Both d and e can't both map to dog so false) c -> cat input: "monkey dog eel eel", "e f c c" output: true This is true because every variable maps to exactly one word and vice verse. e -> monkey f -> dog c -> eel ''' def is_it_a_pattern(arr, patt): # matching_values dictionary mv = {} #isPattern = True if len(arr) != len(patt): return False for i in range(len(arr)): if arr[i] not in mv.keys(): mv[arr[i]] = patt[i] else: if mv[arr[i]] != patt[i]: return False return True if __name__ == '__main__': color1 = ["red", "green", "green"] patterns1 = ["a", "b", "b", "d"] print( "True" if is_it_a_pattern(color1, patterns1) else "False") color2 = ["blue", "green", "blue", "blue"] patterns2 = ["blue", "b", "c", "c"] print( "True" if is_it_a_pattern(color2, patterns2) else "False")
true
7ff5903c490ef8c34099db9252ec42918f2e850b
tcano2003/ucsc-python-for-programmers
/code/lab_03_Functions/lab03_5(3)_TC.py
1,028
4.46875
4
#!/usr/bin/env python3 """This is a function that returns heads or tails like the flip of a coin""" import random def FlipCoin(): if random.randrange(0, 2) == 0: return ("tails") return ("heads") def GetHeads(target): """Flips coins until it gets target heads in a row.""" heads = count = 0 while heads < target: count += 1 if FlipCoin() == 'heads': heads += 1 # print("heads") test code to show when heads occurs else: # 'tails' heads = 0 # print("tails") test code to show when tails occurs return count def GetAverage(number_of_experiments, target): """Calls GetHeads(target) that number_of_experiments times and reports the average.""" total = 0 for n in range(number_of_experiments): total += GetHeads(target) print ("Averaging %d experiments, it took %.1f coin flips to get %d in a row." % (number_of_experiments, total/number_of_experiments, target)) GetAverage(100, 3)
true
3b1315a4ffacc91f29a75daa3993a1cb2aab4133
tcano2003/ucsc-python-for-programmers
/code/lab_03_Functions/lab03_6(3).py
2,442
4.46875
4
#!/usr/bin/env python3 """Introspect the random module, and particularly the randrange() function it provides. Use this module to write a "Flashcard" function. Your function should ask the user: What is 9 times 3 where 9 and 3 are any numbers from 0 to 12, randomly chosen. If the user gets the answer right, your function should print "Right!" and then return a 1. If the answer is wrong, print "Almost, the right answer is 27" and return a 0. Write a function called TestAndScore(n) that calls your Flashcard function n times and prints the percentage of right answers like this, "Score is 90". It also returns this percentage. Make another function called GiveFeedback(p) that receives a percentage, 0 - 100. If p is 100 it prints "Perfect!", if it's 90-99 it prints "Excellent", 80-89 prints "Very good", 70-79 prints "Good enough", and <= 69, "You need more practice". Test all that in your program, calling TestAndScore(10) and then pass the returned value into GiveFeedback(). Make a new function called "Praise" that takes no arguments. It prints one of (at least) 5 phrases of Praise, chosen randomly. It might print, "Right On!", or "Good work!", for example. Call this Praise() function from your Flashcard() function whenever your user gets the answer right. """ import random def FlashCard(): n1 = random.randrange(13) n2 = random.randrange(13) answer = n1 * n2 print ("What is %d times %d? " % (n1, n2)) while True: try: response = int(input()) except ValueError: print ("%d times %d is a number. What number? " % ( n1, n2)) continue if response == answer: print ("Right!", Praise()) return 1 print ("Almost, the right answer is %d." % answer) return 0 def GiveFeedback(p): if p == 100: print ('Perfect!') elif p >= 90: print ('Excellent') elif p >= 80: print ('Very good') elif p >= 70: print ('Good enough') else: print ('You need more practice') def Praise(): pats = ("That's great!", "You're right!", "Good work!", "Right On!", "Superb!") print (random.choice(pats)) def TestAndScore(n): score = 0 for time in range(n): score += FlashCard() score = int(100.0 * score/n) print ("Score is %d." % score) return score GiveFeedback(TestAndScore(10))
true
008fa26d54dc77f783b3b60f5e2f85c83535a3fd
tcano2003/ucsc-python-for-programmers
/code/lab_14_Magic/circle_defpy3.py
1,823
4.1875
4
#!/usr/bin/env python3 """A Circle class, acheived by overriding __getitem__ which provides the behavior for indexing, i.e., []. This also provides the correct cyclical behavior whenever an iterator is used, i.e., for, enumerate() and sorted(). reversed() needs __reversed__ defined. """ #need to have def __getitem__(<<obj>> , <<3>>): in order to call obj[3], otherwise will fail class Circle: def __init__(self, data, times): #want to prevent infinite results with a circle class """Put the 'data' in a circle that goes around 'times' times.""" self.data = data self.times = times def __getitem__(self, i): #i is index given by the caller """circle[i] --> Circle.__getitem__(circle, i).""" l_self = len(self) if i >= self.times * l_self: raise IndexError ("Circle object goes around %d times" % (self.times)) #raise IndexError return self.data[i % l_self] # return answer def __len__(self): return len(self.data) #given the len() of the data def main(): circle = Circle("around", 3) print ("Works with circle[i], for i > len(circle) too:") for i in range(3 * len(circle) + 1): try: print ("circle[%2d] = %s" % (i, circle[i])) except IndexError as e: print(e) break print ("Works with sorted:") print (sorted(circle)) print ("Works for loops:") small_circle = Circle("XO", 2) for i, elementi in enumerate(small_circle): print ("small_circle[%d] = %s" % (i, elementi)) print ("Works for nested loops:") for i, elementi in enumerate(small_circle): for j, elementj in enumerate(small_circle): print ("%3d:%3d -> %s%s" % (i, j, elementi, elementj)) if __name__ == '__main__': main()
true
32ecb9b4cfe42fc63007e72ac3c8778fa8121ad5
huang-zp/pyoffer
/my_queue.py
646
4.125
4
class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.stack_in = [] self.stack_out = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.stack_in.append(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ if not self.stack_out: while self.stack_in: self.stack_out.append(self.stack_in.pop()) return self.stack_out.pop() else: return self.stack_out.pop()
true
aee36a7523ad8fc3de06ef7b047aff60fa3ab0d6
ADmcbryde/Collatz
/Python/recursive/coll.py
2,842
4.25
4
# CSC330 # Assignment 3 - Collatz Conjecture # # Author: Devin McBryde # # # def collatzStep(a): counter = 0 if (a == 1): return counter elif ( (a%2) == 1) : counter = collatzStep(a*3+1) else: counter = collatzStep(a/2) counter = counter + 1 return counter #The program is programmed as a function since local references are faster # than global variable references and speeds up the inner while loop def collatz(): #stores the top ten highest values and the steps to 1 # and initializes the array to zeroes maxValues = [[0 for x in range(2)]for y in range(10)] #stores the top ten highest values and the steps to 1 minVal = 0 col = long(0) #initialize x for the loop x = 2 #Main loop that goes through all values between 2 and 5000000000 # Top value has the L suffix since literals are interpreted as integers # This is a while loop instead since range(x) would produce an # array that would take over 20-40 gigabytes to store, depending # on if the array would store 4 or 8 byte integers. This can # also be solved by using xrange() instead, which uses iterators # instead, but its behavior is less well understood while(x < 1000000): alreadyexists = False #reset the next two values for the new number #col holds the value of the iterated number col = x #count tracks the number of iterations total count = 0 count = collatzStep(col) #Here we avoid having a value with a duplicate number of steps using the boolean flag #Need to add loop #Here we check if the count is larger than the smallest count recorded and add if it is for z in range(10): if (count == maxValues[z][0]): alreadyexists = True if (count > maxValues[minVal][0] and not(alreadyexists)): #here we replace the value of the smallest count for y in range(10): if(y == minVal): maxValues[y][0] = count maxValues[y][1] = x #we now reset the minVal to look for the new lowest count value minVal = 0 #search for the smallest count size in maxValues for y in range(10): if(maxValues[y][0] < maxValues[minVal][0]): minVal = y #increment x for the while loop to go to the next x += 1 #Now we perform a basic selection sort on the step count before printing for i in range(0,9): minValue = maxValues[i][0]; minColNum = maxValues[i][1]; minLocale = i; for j in range(i+1,10): if(minValue < maxValues[j][0]): minValue = maxValues[j][0]; minColNum = maxValues[j][1]; minLocale = j; tempVal = maxValues[i][0]; tempNum = maxValues[i][1]; maxValues[i][0] = minValue; maxValues[minLocale][0] = tempVal; maxValues[i][1] = minColNum; maxValues[minLocale][1] = tempNum; #print the maxValues array for i in range(10): print "Value: " , maxValues[i][1] , " Steps Taken: " , maxValues[i][0] collatz()
true
0d075a750c9745eb97a2577db4b7c7cf2407d903
ergarrity/coding-challenges
/missing-number/missing.py
1,009
4.21875
4
"""Given a list of numbers 1...max_num, find which one is missing in a list.""" def missing_number(nums, max_num): """Given a list of numbers 1...max_num, find which one is missing. *nums*: list of numbers 1..[max_num]; exactly one digit will be missing. *max_num*: Largest potential number in list >>> missing_number([7, 3, 2, 4, 5, 6, 1, 9, 10], 10) 8 """ nums_dict = {} # Creates keys for all possible numbers in list and sets all values to False for i in range(max_num): nums_dict[i+1] = False # Iterates over nums and changes value to True for each num key for num in nums: nums_dict[num] = True # Iterates over nums_dict and returns key with false value (this will be # missing number) for key in nums_dict: if nums_dict[key] == False: return key if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASS. NICELY DONE!\n")
true
8717208247c2d4f9eb24522c1b54ec33ce41789c
kwozz48/Test_Projects
/is_num_prime.py
613
4.1875
4
#Asks the user for a number and determines if the number is prime or not number_list = [] def get_integer(number = 'Please enter a number: '): return int(input(number)) def is_number_prime(): user_num = get_integer() number_list = list(range(2, user_num)) print (number_list) i = 0 a = 0 while i < user_num - 2: if user_num % number_list[i] == 0: a += 1 i += 1 else: i += 1 if a > 0: print ('The number is not prime') else: print ('The number is prime') return () answer = is_number_prime()
true
7b84faec3e2daad6d731610e6d4967f1e3859537
yucheno8/newPython6.0
/Day01/p_07输出和格式字符串一起使用.py
479
4.125
4
''' 格式 化字符串并输出 ''' # 占位符形式的字符串 # 1 a = 10 print('现在要打印一个数字,值是 %d' % a) # 2 print('name: %s age: %d' % ('Tom', 12)) # 占位符的常用 格式 print('%d' % 1) print('%5d' % 1) print('%05d' % 1) print('%-5d' % 1) print('%3d' % 12345) print('%.2f' % 3.1415926) print('%.3f' % 1) # f-string name = 'Tom' age = 11 print(f'name: {name} age:{age} score: {99}') s = f'name: {name} age:{age} score: {99}' print(s)
false
3c47b56deda38352aa8cd571d65a29c76d40827e
BRTytan/Unipexercicios
/IPE/Listas/ex04-04.py
330
4.15625
4
""" Exercicio 04-04:Escreva um programa que mostre os números de 1 até um numero digitado pelo usuário, mas, apenas os números impares. """ ################################################################################################### n1 = int(input("Digite um número: ")) x = 1 while x <= n1: print(x) x += 2
false
f04b4b2d639091ef6d2a21bf0a40604936664cc4
BRTytan/Unipexercicios
/IPE/inicias/ex01-02.py
382
4.34375
4
"""Exercicio 02: Resolva as expressões matematicas manualmente no caderno, apos, converta as seguintes expressões matematicas para que possam ser calculadas usando o interpretador python(confirmando o resultado encontrado)""" a = (10+20)*30 b = (4 ** 2) / 30 c = (9**4+2) * (6-1) print('Resultado de A é: {} \nResultado de B é: {:.2f} \nResultado de C é: {}'.format(a, b, c))
false
0eb55829a0aee6d7136f91550e89b9bb738f4e73
Scertskrt/Ch.08_Lists_Strings
/8.1_Months.py
722
4.40625
4
''' MONTHS PROGRAM -------------- Write a user-input statement where a user enters a month number 1-13. Using the starting string below in your program, print the three month abbreviation for the month number that the user enters. Keep repeating this until the user enters 13 to quit. Once the user quits, print "Goodbye!" months = "JanFebMarAprMayJunJulAugSepOctNovDec" ''' done = False month = int(input("Please pick a month(1-12) or quit ")) months = "JanFebMarAprMayJunJulAugSepOctNovDec" while done == False: if month > 12 or month < 1: print("Goodbye!") done = True break end = month*3 print(months[end-3:end]) month = int(input("Please pick a month(1-12) or quit(13) "))
true
539fadb2fc145e48a70950cd77d804d77c9cec07
roachaar/Python-Projects
/national debt length.py
1,937
4.5
4
############################################################################## # Computer Project #1: National Debt # # Algorithm # prompt for national debt and denomination of currency # user inputs the above # program does simple arithmetic to calculate two pieces of information # 1: national debt as a height in miles of stacked currency # 2: this height compared to the distance between the earth and moon # lastly, the program displays these values to the user ############################################################################## national_debt_str = input('Enter the national debt: ') #user inputs his or her\ #nation's national debt denomination_str = input('Enter a denomination of currency: ') #user\ #inputs a chosen denomination of the same currency as the national debt is\ #given in national_debt_float = float(national_debt_str) #we identify these as the values\ #in which they are meant to be denomination_int = int(denomination_str) #again BILL_HEIGHT=.0043 #in inches INCHES_PER_FOOT= 12 #inches per foot FEET_PER_MILE=5280 #feet per mile AVG_DISTANCE_BETWEEN_EARTH_AND_MOON=238857 #in miles height_of_national_debt_float = (national_debt_float/denomination_int)*\ (BILL_HEIGHT)/(INCHES_PER_FOOT)/(FEET_PER_MILE) #we use dimensional analysis to\ #get the height in miles compared_to_moon_float= (national_debt_float/denomination_int)*(BILL_HEIGHT)/\ (INCHES_PER_FOOT)/(FEET_PER_MILE)/(AVG_DISTANCE_BETWEEN_EARTH_AND_MOON) #same\ #thing here, only we now divide by the distance between the earth and the moon print('The height of your national debt in miles of your chosen denomination of\ currency is:',height_of_national_debt_float) print('The ratio of this height and the distance between the earth and the moon\ is:' ,compared_to_moon_float) #these 2 values are printed for the user to see
true
3597d031334cadd8da79740431f5941c2adb38c5
BeryJAY/Day4_challenge
/power/power.py
531
4.34375
4
def power(a,b): #checking data type if not((isinstance(a,int) or isinstance(a,float)) and isinstance(b,int)): return "invalid input" #The condition is such that if b is equal to 1, b is returned if(b==1): return(a) #If b is not equal to 1, a is multiplied with the power function and called recursively with arguments as the base and power minus 1 if(b!=1): return(a*power(a,b-1)) #the final result is then output if __name__ == '__main__': print("Result:",power(2,5))
true
511d35743234e26a4a93653af24ee132b3a62a7a
AntoanStefanov/Code-With-Mosh
/Classes/1- Classes.py
1,465
4.6875
5
# Defining a list of numbers numbers = [1, 2] # we learned that when we use the dot notation, we get access to all methods in list objects. # Every list object in Python has these methods. # numbers. # Wouldn't that be nice if we could create an object like shopping_cart and this object would have methods # like this: # shopping_cart.add() # shopping_cart.remove() # shopping_cart.get_total() # Another example: # Would be nice if we could have a point object with methods. # point.draw() # point.move() # point.get_distance() * between point x and point y # Here come classes # A class is a blueprint for creating new objects. # Throughout the course you have heard the term class. # For example: let's define a variable and set it to integer and print it's type x = 1 print(type(x)) # We see a class of int # So in Python we have a class called int for creating integers. Similarly, we have classes for creating booleans, # lists, dictionaries and so on. # EVERY OBJECT WE HAVE IN PYTHON IS CREATED USING A CLASS WHICH IS A BLUEPRINT FOR CREATING OBJECTS OF THAT TYPE. # # In this section you're going to learn how to create custom classes like customer, shopping_cart, point and so on. # Before that let's define a few terms. # 1. Class: blueprint for creating new objects # 2. Object: instance of a class # Example: # Class: Human (this class will define all the attributes of humans) then we could create objects # Objects: John, Mary, ...
true
a8f7dceb7daec1a665e215d9d99eeb620e73f398
AntoanStefanov/Code-With-Mosh
/Exceptions/7- Cost of Raising Exceptions.py
1,849
4.5
4
# As I explained in the last lecture, when writing your own functions, # prefer not to raise exceptions, because those exceptions come with a price. # That's gonna show you in this lecture. # From the timeit module import function called timeit # with this function we can calculate the execution time of some code. # This is how it works. Imagine you want to calculate the execution time of # this code. # We define a variable code1 and set it to string # This string should include our code so using triple quotes code # for multiple lines. One piece of code inside string with triple quotes from timeit import timeit code1 = ''' def calculate_xfactor(age): if age <= 0: raise ValueError('Age cannot be 0 or less.') return age / 10 try: calculate_xfactor(-1) except ValueError as error: pass ''' # Now we call timeit # - first arg = python code , second arg(keyword arg) = number of exectutions print('first code=', timeit(code1, number=10000)) # This function returns the exectution time of the code after 10 000 repetitions. # DIfferent approach ### 4 times faster code2 = ''' def calculate_xfactor(age): if age <= 0: None return age / 10 xfactor = calculate_xfactor(-1) if xfactor == None: pass ''' print('second code=', timeit(code2, number=10000)) # that's so because we execute the code 10 000 times # 1 time execution no difference # If you are building a simple application for a few users raising exceptions # in your functions is not going to have a bad impact on the performance of your app. # But if you are building application where performance and scaleability is important, # then it's better to raise exceptions when you really have to . # if you can handle the situation with a simple if statement, think twice for exceptions. # Raise exceptions if YOU REALLY HAVE TO !
true
1f7f8382c688f22fe10e8057185ce55307c90b1d
AntoanStefanov/Code-With-Mosh
/Exceptions/4- Cleaning Up.py
706
4.375
4
# There are times that we need to work with external resources like files, # network connections, databases and so on. Whenever we use these resources, # after, after we're done we need to release them. # For example: when you open a file, we should always close it after we're done, # otherwise another process or another program may not be able to open that file. try: file = open('name') age = int(input('Age: ')) xfactor = 10 / age except (ValueError, ZeroDivisionError): print('You didnt enter a valid age.') else: print("No exceptions were thorwn.") finally: # always executed clause with or without exception # and we use it to release external resources file.close()
true
91dc1d2f54c0cf7ad75ff9f9449b5c46051c4b4c
pedrolisboaa/pythonpro-pythonbirds
/exercicios/busca_linear.py
616
4.125
4
""" Crie um programa que recebe uma lista de inteiros e um valor que deve ser buscado. O programa deve retornar o índice onde o valor foi encontrado, ou -1, caso não encontre o valor. """ tamanho_lista = int(input('Digite o tamanho da sua lista:')) lista = [] for i in range(tamanho_lista): inserir_lista = int(input('Digite o número que deseja inserir na lista: ')) lista.append(inserir_lista) buscar_na_lista = int(input('Digite número que deseja buscar na lista: ')) if buscar_na_lista in lista: print(f'O {buscar_na_lista} está no range {lista.index(buscar_na_lista)}') else: print(-1)
false
a12230a5edc331e0989940c8ecd1243b9415aba9
daria-andrioaie/Fundamentals-Of-Programming
/a12-911-Andrioaie-Daria/main.py
2,983
4.46875
4
from random import randint from recursive import recursive_backtracking from iterative import iterative_backtracking def print_iterative_solutions(list_of_numbers): """ The function calls the function that solves the problem iteratively and then prints all the found solutions. :param list_of_numbers: the list of numbers for which we want to determine all the possibilities to insert between them the operators + and – such that by evaluating the expression the result is positive. """ list_of_solutions = iterative_backtracking(list_of_numbers) number_of_solutions = len(list_of_solutions) if number_of_solutions == 0: print('There are no solutions for the given set of numbers') else: for solution in list_of_solutions: print(solution) print(str(number_of_solutions) + ' SOLUTIONS: ') print('\n') print('\n') def print_recursive_solutions(list_of_numbers): """ The function calls the function that solves the problem recursively and then prints all the found solutions. :param list_of_numbers: the list of numbers for which we want to determine all the possibilities to insert between them the operators + and – such that by evaluating the expression the result is positive. """ list_of_solutions = [] recursive_backtracking(list_of_solutions, [], list_of_numbers) number_of_solutions = len(list_of_solutions) if number_of_solutions == 0: print('There are no solutions for the given set of numbers') else: for solution in list_of_solutions: print(solution) print(str(number_of_solutions) + ' SOLUTIONS: ') print('\n') print('\n') def initialise_numbers(number_of_elements): """ The function computes a random sequence of natural number. :param number_of_elements: the total number of elements in the sequence :return: the sequence of numbers, represented as a list """ list_of_numbers = [] for iteration in range(number_of_elements): natural_number = randint(1, 100) list_of_numbers.append(natural_number) return list_of_numbers def print_menu(): print('1. Solve recursively.') print('2. Solve iteratively') print('3. Exit.') print('\n') def start(): available_options = {'1': print_recursive_solutions, '2': print_iterative_solutions} number_of_elements = int(input('Enter a natural number greater than 9: ')) list_of_numbers = initialise_numbers(number_of_elements) not_finished = True while not_finished: print_menu() user_option = input('Enter option: ') if user_option in available_options: available_options[user_option](list_of_numbers) elif user_option == '3': not_finished = False else: print('Bad command') start()
true
41891f9a090ead7873bf5c006f423238a48f05db
daria-andrioaie/Fundamentals-Of-Programming
/a12-911-Andrioaie-Daria/iterative.py
2,158
4.5
4
from solution import is_solution, to_string def find_successor(partial_solution): """ The function finds the successor of the last element in the list. By "successor" of an element we mean the next element in the list [0, +, -]. :param partial_solution: array containing the current partial solution :return: True, if the last element has a successor, False, otherwise """ if partial_solution[-1] == 0: partial_solution[-1] = '+' return True elif partial_solution[-1] == '+': partial_solution[-1] = '-' return True return False def iterative_backtracking(list_of_numbers): """ The function uses the concept of backtracking to search the whole space of solutions, and keeps the found solutions in a list that will be returned. :param list_of_numbers: the list of numbers for which we want to determine all the possibilities to insert between them the operators + and – such that by evaluating the expression the result is positive. :return: the resulted solutions """ list_of_solutions = [] partial_solution = [0] while len(partial_solution): current_element_has_successor = find_successor(partial_solution) if current_element_has_successor: if is_solution(partial_solution, list_of_numbers): printable_solution = to_string(partial_solution, list_of_numbers) list_of_solutions.append(printable_solution) elif len(partial_solution) == len(list_of_numbers) - 1: # the solution array is full, but does not # represent a solution partial_solution.pop() else: partial_solution.append(0) # go to the next element in order to complete # the solution else: # go back with one step in the partial solution partial_solution.pop() return list_of_solutions
true
a43a94fda2b1a6ff937b0ab5df42f12fff90bde1
sal-7/OMIS485
/Python_chapter 4/A_temperature.py
1,206
4.125
4
""" /*************************************************************** OMIS 485 P120 - Ch4 Spring 2019 Programmer: Faisal Alharbi, Z-ID 1748509 Date Due:04/07/2018 Tutorials from Chapter 4 - Temperature Exercise. ***************************************************************/""" #!/usr/bin/env python3 import temperature as temp def display_menu (): print ("MENU") print ("1. Fah. to Cel.") print ("2. Cel. to Fah.") print () def convert_temp(): option = int (input ("Enter a menu option: ")) if option == 1: f = int (input ("Enter degrees Fahrenheit: ")) c = temp.to_celsius (f) c = round (c,2) print ("Degrees Celsius:", c) elif option == 2: c = int (input ("Enter degrees Celsius: ")) f = temp.to_fahrenheit (c) f = round (f, 2) print ("Degrees Fahrenheit:", f) else: print ("Enter a valid menu number") def main (): display_menu() again = "y" while again.lower() == "y": convert_temp() print () again = input ("Convert another temperature? (Y/N:) ") print ("See you!") if __name__ == "_main_": main() main()
false
48f7e3ee1d356eda254447e928321e6d7a8402c8
samsolariusleo/cpy5python
/practical02/q07_miles_to_kilometres.py
661
4.3125
4
# Filename: q07_miles_to_kilometres.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program that converts miles to kilometres and kilometres to miles # before printing the results # main # print headers print("{0:6s}".format("Miles") + "{0:11s}".format("Kilometres") + "{0:11s}".format("Kilometres") + "{0:6s}".format("Miles")) # define for loop for miles in range(1,11): convert_to_kilo = miles * 1.609 convert_to_miles = (miles + 3) * 5 / 1.609 print("{0:<6}".format(miles) + "{0:<11.3f}".format(convert_to_kilo) + "{0:<11}".format((miles + 3) * 5) + "{0:<6.3f}".format(convert_to_miles))
true
2e1e1897d6e0c4f92ee6815c9e1bb607dee10024
samsolariusleo/cpy5python
/practical02/q12_find_factors.py
562
4.4375
4
# Filename: q12_find_factors.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program that displays the smallest factors of an integer. # main # prompt for integer integer = int(input("Enter integer: ")) # define smallest factor factor = 2 # define a list list_of_factors = [] # find factors while factor < integer: while integer % factor != 0: factor = factor + 1 list_of_factors.append(factor) integer = integer//factor # return results print("The smallest factors are " + str(list_of_factors)[1:-1] + ".")
true
750d0ff689da9aa8aea56e2e9b248df47ed51057
samsolariusleo/cpy5python
/practical02/q05_find_month_days.py
956
4.625
5
# Filename: q05_find_month_days.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program that displays number of days in the month of a particular # year. # main # prompt for month month = int(input("Enter month: ")) # prompt for year year = int(input("Enter year: ")) # define list of months allmonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] # define list of days alldays = ["31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31", "29"] # check if month is feb # if month is feb, then check if year is leap year # if both are true, days is 29 # else, days are normal if month == 2 and year % 4 == 0: print(allmonths[month-1] + " " + str(year) + " has " + alldays[-1] + " days") else: print(allmonths[month-1] + " " + str(year) + " has " + alldays[month-1] + " days")
true
cce715b6938e2f5c16d6ee158ebfa7e15b4e0645
samsolariusleo/cpy5python
/practical02/q11_find_gcd.py
725
4.28125
4
# Filename: q11_find_gcd.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program to find the greatest common divisor of two integers. # main # prompt user for the two integers integer_one = int(input("Enter first integer: ")) integer_two = int(input("Enter second integer: ")) # find out which is the smaller of integer_one and integer_two if integer_one > integer_two: d = integer_two elif integer_one < integer_two: d = integer_one else: print("The greatest common divisor is " + str(integer_one) + ".") exit() # find greatest divisor while integer_one % d != 0 or integer_two % d != 0: d = d - 1 # return results print("The greatest common divisor is " + str(d) + ".")
true
8254638df080d0a3b76a0dddd42cf41e393dfed7
samsolariusleo/cpy5python
/practical01/q1_fahrenheit_to_celsius.py
453
4.28125
4
# Filename: q1_fahrenheit_to_celsius.py # Author: Gan Jing Ying # Created: 20130122 # Modified: 20130122 # Description: Program to convert a temperature reading from Fahrenheit to Celsius. #main # prompt to get temperature temperature = float(input("Enter temperature (Fahrenheit): ")) # calculate temperature in Celsius temperature = (5/9) * (temperature - 32) # display result print("Temperature in Celsius: {0:.2f}".format(temperature))
true
8e1570c6e03ec4817ab65fdba077df7bad1e97da
justintrudell/hootbot
/hootbot/helpers/request_helpers.py
490
4.46875
4
import itertools def grouper(iterable, n): """ Splits an iterable into groups of 'n'. :param iterable: The iterable to be split. :param n: The amount of items desired in each group. :return: Yields the input list as a new list, itself containing lists of 'n' items. """ """Splits a list into groups of three.""" it = iter(iterable) while True: chunk = tuple(itertools.islice(it, n)) if not chunk: return yield chunk
true
dfb6d90f75f7c2fbe370185856549fdf6c089927
gbaweja/consultadd_assignments
/assignment1/A1-6.py
654
4.1875
4
# Govinda Baweja # Assignment 1 # Date: 04-26-2019 # Nested if else statement i = 10 if (i == 10): # First if statement print ("\ni is 10") if (i < 15): print ("\ni is smaller than 15") # Nested - if statement # Will only be executed if statement above # it is true if (i < 12): print ("\ni is smaller than 12 too") else: print ("\ni is greater than 15") # Ladder if else Statement i = 20 if (i == 10): print ("\ni is 10") elif (i == 15): print ("\ni is 15") elif (i == 20): print ("\ni is 20") else: print ("\ni is not of my choice")
false
4182316191f1b325cb7640dd77c1acc023045c82
ZhbitEric/PythonLearning
/Python_work/_20ds_reference.py
310
4.1875
4
# 引用 shopList = ['apple', 'mango', 'carrot', 'banana'] myList = shopList del shopList[0] print(shopList) print(myList) # 这样的引用就没有指向同一个对象了 myList = shopList[:] # 切片操作,相当于循环复制拿元素出来 print(myList) del myList[0] print(shopList) print(myList)
false
73d37bf82e89c293e0e0fd86e99d74ec79b3b275
SRAH95/Rodrigo
/input_statement.py
1,748
4.15625
4
"""message = input("Tell me something, and I will repeat it back to you: ") print(message)""" ######################################################################################## '''name = input("Please enter your name: ") print("Hi, " + name.title() + "!")''' ######################################################################################## prompt = "If you tell us who you are, we can personalize the message you see." prompt += "\nWhat is your first name? " name = input(prompt) print("\nHello, " + name.title() + "!") ######################################################################################## '''age = input("How old are you? ") age = int(age) print(age >= 18) ''' ######################################################################################## '''height = input("How tall are you, in inches? ") height = int(height) if height >= 36: print("\nYou're tall enough to ride!") else: print("\nYou'll be able to ride when you're a little older.")''' ######################################################################################## """prompt = "\nEven or Odd number." prompt += "\nPlease, enter a number: " odd = input(prompt) odd = int(odd) if odd % 2 == 0: print("---> " + str(odd) + " is an even number.") else: print("---> " + str(odd) + " is an odd number.")""" ######################################################################################## """people = input("\nHow many people are going to dinner toningth?\n ") people = int(people) if people <= 8: print("There is an avilable table, wait for the waitress please") else: print("You have to wait for an avilable table, sorry")""" ########################################################################################
true
ba982e9794b3cbaaa034584cbb1f2017068f5ce5
Pranalihalageri/Python_Eduyear
/day5.py
516
4.125
4
1. list1 = [5, 20, 4, 45, 66, 93, 1] even_count, odd_count = 0, 0 # iterating each number in list for num in list1: # checking condition if num % 2 == 0: even_count += 1 else: odd_count += 1 print("Even numbers in the list: ", even_count) print("Odd numbers in the list: ", odd_count) 2. list1 = [10, 20, 4, 45, 99] # sorting the list list1.sort() # printing the last element print("Largest element is:", list1[-1]) print("minimum element is:", *list1[:1])
true
258d4ea28ffe6b9a85b2ecd34a34214ccb3a0682
FredericoVieira/listas-python-para-zumbis
/Lista 02/lista2ex5.py
433
4.15625
4
# -*- coding: utf-8 -*- num1 = int(raw_input('Digite o valor do primeiro inteiro: ')) num2 = int(raw_input('Digite o valor do segundo inteiro: ')) num3 = int(raw_input('Digite o valor do terceiro inteiro: ')) list = [num1, num2, num3] num_max = max(list) num_min = min(list) print('O maior número entre %d, %d, %d é %d') % (num1, num2, num3, num_max) print('O menor número entre %d, %d, %d é %d') % (num1, num2, num3, num_min)
false
b0398f9d1751611c505aa530849336dbb7f3ef00
Ran05/basic-python-course
/ferariza_randolfh_day4_act2.py
1,153
4.15625
4
''' 1 Write a word bank program 2 The program will ask to enter a word 3 The program will store the word in a list 4 The program will ask if the user wants to try again. The user will input Y/y if yes and N/n if no 5 If yes, refer to step 2. 6 If no, Display the total number of words and all the words that user entered. ''' <<<<<<< HEAD ======= 1 Write a word bank program 2 The program will ask to enter a word 3 The program will store the word in a list 4 The program will ask if the user wants to try again. The user will input Y/y if yes and N/n if no 5 If yes, refer to step 2. 6 If no, Display the total number of words and all the words that user entered. ''' >>>>>>> 4f0a6fb087d8f2ddb4b87fea98c0c42a7cbbfbc8 wordList = [] a = (str(input("Please Enter a word: "))) wordList.append(a) question = input("Do you want to add more words?: ") <<<<<<< HEAD if question == True: print(str(input("Please Enter a word: "))) else: wordList.append(a) ======= while question == "Y" or "Yes": print(a) if question == "N" or "no": break print(wordList) >>>>>>> 4f0a6fb087d8f2ddb4b87fea98c0c42a7cbbfbc8
true
92151c4a1ceca1910bd60785b2d5d030559cd241
niteshrawat1995/MyCodeBase
/python/concepts/classmethods.py
1,481
4.125
4
# Class methods are methods wich take class as an argument (by using decorators). # They can be used as alternate constructors. class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_emps += 1 def full_name(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = self.pay * self.raise_amount @classmethod def set_raise_amount(cls, amount): cls.raise_amount = amount @classmethod def from_string(cls, emp_str): first, last, pay = emp_str.split('-') # need to always return the cls(Employee) object. return cls(first, last, pay) @staticmethod def is_workday(day): if day.weekday() == 5 or day.weekday() == 6: return False else: return True emp_1 = Employee('Nitesh', 'Rawat', 20000) emp_2 = Employee('Vikas', 'Sharma', 30000) # Employee.set_raise_amount(1.05) # print(Employee.raise_amount) # print(emp_1.raise_amount) # print(emp_2.raise_amount) #emp_str_1 = 'John-Doe-70000' #emp_str_2 = 'Amy-Smith-70000' #emp_str_3 = 'Angier-Santos-000' emp_str_1 = Employee.from_string('John-Doe-70000') # print(emp_str_1.full_name()) import datetime my_date = datetime.date(2018, 5, 27) print(Employee.is_workday(my_date))
true
5f109dfef4214b33302401e473d9b115a65bffa5
niteshrawat1995/MyCodeBase
/python/concepts/getters&setters&deleters.py
1,284
4.15625
4
# getters,setters and deleters can be implemented in python using property decorators. # property decorators allows us to define a mehtod which we can access as an attribute. # @property is the pythonic way of creating getter and setter. class Employee(object): def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay # getter-like @property def email(self): print('getting email') return '{}.{}@company.com'.format(self.first, self.last) # getter-like @property def fullname(self): print('getting fullname') return '{} {}'.format(self.first, self.last) # setter-like @fullname.setter def fullname(self, name): print('setting fullname') first, last = name.split(' ') self.first = first self.last = last # deleter-like @fullname.deleter def fullname(self): prin('deleting fullname') self.first = None self.last = None print('Delete name!') emp1 = Employee('Nitesh', 'Rawat', '20000') # we now cannot set the attribute like this: #emp1.email = 'Nitesh.chopra@gmail.com' # To do the above task we need a setter print(emp1.fullname) # print(emp1.email) emp1.fullname = 'Time Tom' print(emp1.fullname)
true
95484e7fe8d71eaa0fbcd723b67eddeafd17f535
niteshrawat1995/MyCodeBase
/python/practise/DS/Doubly_LinkedList.py
937
4.34375
4
# Implementing doubly linked list: class Node(object): """Node will have data ,prev and next""" def __init__(self, data): self.data = data self.prev = None self.next = None class LinkedList(object): """Linked list will have head attribute.""" def __init__(self): self.head = None def append(self, data): # create new node: new_node = Node(data) # check if linked list is empty: if self.head is None: self.head = new_node.prev return while self.head.next != None: self.head = self.head.next self.head.next = new_node.prev new_node.prev = self.head def print_list(self): while self.head != None: print(str(self.head.data)) self.head = self.head.next dll = LinkedList() dll.append('A') dll.append('B') dll.append('C') dll.append('D') dll.print_list()
false
e78334b2ae75714172fad80bf81e8c76497f7cb5
scantea/hash-practice
/hash_practice/exercises.py
2,554
4.3125
4
def grouped_anagrams(strings): """ This method will return an array of arrays. Each subarray will have strings which are anagrams of each other Time Complexity: O(n) Space Complexity: O(1) """ freq_hash = {} for word in strings: key = ''.join(sorted(word)) if key not in freq_hash.keys(): freq_hash[key] = [] freq_hash[key].append(word) values_list = [] for value in freq_hash.values(): values_list.append(value) return values_list def top_k_frequent_elements(nums, k): """ This method will return the k most common elements In the case of a tie it will select the first occuring element. Time Complexity: O(n) Space Complexity: O(n) """ if nums == []: return nums freq_table = {} for num in nums: if num in freq_table: freq_table[num] += 1 else: freq_table[num] = 1 max_freq = 0 common_elemnts = [] for key, value in freq_table.items(): if freq_table[key] > max_freq: max_freq = freq_table[key] common_elemnts.append(key) elif freq_table[key] == max_freq: common_elemnts.append(key) return common_elemnts def valid_sudoku(table): """ This method will return the true if the table is still a valid sudoku table. Each element can either be a ".", or a digit 1-9 The same digit cannot appear twice or more in the same row, column or 3x3 subgrid Time Complexity: O(n)3 Space Complexity: O(n) """ for col in range(0, len(table)): column_hash = {} for square in table[col]: if square != ".": if square not in column_hash: column_hash[square] = 1 else: return False for row in range(3): for col in range(3): block_dict = {} block = [ table[3*row][3*col:3*col+3], # finding index in sudoku board table[3*row+1][3*col:3*col+3], table[3*row+2][3*col:3*col+3] ] for segment in block: for elem in segment: if elem != ".": if elem in block_dict: return False else: block_dict[elem] = 1 return True
true
5b119b5d6ee2dfeb455b174a2b2332de7cd7a6a7
sivaram143/python_practice
/conditions/ex_01.py
202
4.3125
4
#!/usr/bin/python # program to check whether a given no is even or ood num = input("Enter any number:") if num % 2 == 0: print("{0} is even".format(num)) else: print("{0} is odd".format(num))
true
de43dc0d3c246bfdd7a124e2942be5ebc717cb9d
sivaram143/python_practice
/operators/arithmetic.py
706
4.375
4
#!/usr/bin/python # Arithmetic Operators: +, -, *, /, %, **(exponent:power) num1 = input("Enter first number:") num2 = input("Enter second number:") print("************* Arithmetic Operators *************") print("Addition(+):{0}+{1}={2}".format(num1,num2,num1+num2)) if num1 > num2: res = num1 - num2 else: res = num2 - num1 print("Subtraction(-):{0}-{1}={2}".format(num1,num2,res)) print("Multiplication(*):{0}*{1}={2}".format(num1,num2,num1*num2)) if num2 == 0: res = "Infinity" else: res = num1 / num2 print("Division(/):{0}/{1}={2}".format(num1,num2,res)) print("Modulus(%):{0}%{1}={2}".format(num1,num2,res)) print("Exponential(**):{0}**{1}={2}".format(num1,num2,num1**num2))
false
fdc9e5dc5a169d1178cf3efa9e1f70a2f42576a1
rcoady/Programming-for-Everyone
/Class 1 - Getting Started with Python/Assignment4-6.py
982
4.375
4
# Assignment 4.6 # Write a program to prompt the user for hours and rate per hour using raw_input to # compute gross pay. Award time-and-a-half for the hourly rate for all hours worked # above 40 hours. Put the logic to do the computation of time-and-a-half in a function # called computepay() and use the function to do the computation. The function should # return a value. Use 45 hours and a rate of 10.50 per hour to test the program # (the pay should be 498.75). You should use raw_input to read a string and float() # to convert the string to a number. Do not worry about error checking the user input # unless you want to - you can assume the user types numbers properly. def computepay(h, r): if h > 40: overtime = h - 40 total = (40 * r) + ((overtime * r) * 1.5) else: total = (h * r) return total hrs = raw_input("Enter Hours:") hrs = float(hrs) rate = raw_input("Enter Rate:") rate = float(rate) p = computepay(hrs, rate) print p
true
e94e9bba980e60c3c6bbb96ef5c221a3852e9941
Shakleen/Problem-Solving-Codes
/Hacker Rank/Language Proficiency/Python/3. Strings/13. sWAP cASE.py
276
4.125
4
def swap_case(s): L = list(s) for pos in range(len(L)): if L[pos].isalpha: L[pos] = L[pos].lower() if L[pos].isupper() else L[pos].upper() return ''.join(L) if __name__ == '__main__': s = input() result = swap_case(s) print(result)
false
c3be60d54a88d10b85264b02689c43ffc9ec8b9e
Hr09/Python_code
/cicerciper.py
1,240
4.21875
4
message=input("Enter a message:") key=int(input("How many Charachters should we shift (1-26)")) secret_message="" for char in message: if char.isalpha(): char_code=ord(char) char_code+=key if char.isupper(): if char_code > ord('Z'): char_code-=26 elif char_code<ord('A'): char_code+=26 else: if char_code > ord('z'): char_code -= 26 elif char_code < ord('a'): char_code += 26 secret_message+=chr(char_code) else: secret_message +=char print("Encrypted:",secret_message) key=-key orig_message=" " for char in secret_message: if char.isalpha(): char_code=ord(char) char_code+=key if char.isupper(): if char_code > ord('Z'): char_code -= 26 elif char_code < ord('A'): char_code += 26 else: if char_code > ord('z'): char_code -= 26 elif char_code < ord('a'): char_code += 26 orig_message+=chr(char_code) else: orig_message+=char print("Decrypted :",orig_message)
false
57abcfd1f015392cec8b05af62fdf4a1ff06aa35
Luisarg03/Python_desktop
/Apuntes_youtube/operador_in.py
512
4.15625
4
print("Eleccion de asignaturas") print("Asignaturas disponibles: Bioquimica - Fisiologia - Salud mental") asignatura=input("Elige la asignatura: ") if asignatura in ("Bioquimica", "Fisiologia", "Salud mental"): print("La asignatura elegida es "+asignatura) else: print("La asignatura elegida no esta contemplada") #Python es case sensitive, para que tome las palabras como mayuscula o minuscula se usa: #lower() transforma la palabra en minusculas #upper() trasnforma la palabra en mayuscula
false
381467c9ac0ae671463340dee5d4b34297918d14
Luisarg03/Python_desktop
/Apuntes_youtube/practica_lista.py
1,537
4.3125
4
lista1=["maria", "luis", "natalia", "juan", "marcos", "pepe"]#el indice empieza contar desde el cero, ej "luis" seria posicion 2 indice 1 print([lista1]) print(lista1[2])#indico que solo quiero que aparezca el indice 2 print(lista1[-1])#el menos hace que el indice se cuente de derecha a izquierda, en este caso solo aparece el ultimo print(lista1[:3])#indico que solo se muestren los tres primeros indices, no hace falta por el "cero" print(lista1[2:])#empiezo desde el indice 2 en adelante hasta el final lista1.append("carlos")#agregar elemento a la lista, pero lo agrega al final de esta print([lista1]) lista1.insert(4,"pedro")#inserto el elemento en el indice que indico print(lista1[:]) lista1.extend(["fabio","lucas","leandro"])#permite agrerar varios elementos a la vez print(lista1[:]) print(lista1.index("lucas"))#indica en que indice se encuentra el elemento print("pepe" in lista1)#true o false, indice si el elemento esta o no dentro de la lista print("peponi" in lista1) lista2=["vaso", 456, 3.34, True, False, "camila"]#puedo enlistar distintos tipos de variable lista2.remove(True)#elimino un elemento de la lista indicando el nombre correspondiente print(lista2[:]) lista2.pop()#elimina el ultimo elemento de la lista print(lista2[:]) lista3=["cocina", "pokemon"] lista4=lista1+lista2+lista3#suma las listas, un concatenador es, pero crea una lista mayor por eso se usa otra variable print(lista4[:]) print(lista1[:]*2) #el multiplicador sirve de repetidor, repite la lista la veces que se indique
false
73b0b07826794a242dde684f94f946581c180949
Dszymczk/Practice_python_exercises
/06_string_lists.py
803
4.40625
4
# Program that checks whether a word given by user is palindrome def is_palindrome(word): return word == word[::-1] word = "kajak" # input("Give me some word please: ") reversed_word = [] for index in range(len(word) - 1, -1, -1): reversed_word.append(word[index]) palindrome = True for i in range(len(word)): if word[i] != reversed_word[i]: palindrome = False if palindrome: print("Word is palindrome") # string based program <- much faster way print("\n\nstring based program") reversed_word = word[::-1] print(reversed_word) if reversed_word == word: print("Word is palindrome") # Shorter code if word == word[::-1]: print("\n\nWord is palindrome") # Using function if is_palindrome(word): print("\n\n(3) Word is palindrome")
true
6fcd96b8c44668ccac3b4150d9b6c411b325bcc0
mm/adventofcode20
/day_1.py
2,436
4.375
4
"""AoC Challenge Day 1 Find the two entries, in a list of integers, that sum to 2020 https://adventofcode.com/2020/day/1 """ def find_entries_and_multiply(in_list, target): """Finds two entries in a list of integers that sum to a given target (also an integer), and then multiply those afterwards. """ two_numbers = None # We can use the idea of "complements" here. First, we'll start # an indices dict, which will have key = the number itself, and the # value equal to its index. indices = {} for i in range(0, len(in_list)): # Get the "complement" -- for this current value, what is the # extra value I need to add up to my target? complement = target - in_list[i] # e.g if in_list[i] = 1995, target = 2020, => complement = 25 # Does this value exist in my list? This is where the indices dict # comes in handy! if complement in indices: # Return the two numbers! two_numbers = (in_list[i], in_list[indices[complement]]) else: # Otherwise, add it to our indices list. It might match # up well with another number! indices[in_list[i]] = i if two_numbers: print(f"Two numbers found which add up to {target}: {two_numbers}") return two_numbers[0]*two_numbers[1] else: return None def find_three_entries_for_target(in_list, target): """Finds three integers which add up to a given target (also an integer), and multiply them afterwards. """ three_numbers = None # What we can do (sort of brute-force-y) is fix a number as we go through the # list, set a new target and then run the *two-integer* version of this problem # on the rest of the list. for i in range(0, len(in_list)): new_target = target - in_list[i] # Now, perform the two-integer solution on the *rest* of the list # (pretend this number isn't even there) two_number_product = find_entries_and_multiply(in_list[i+1:], new_target) if two_number_product: return in_list[i] * two_number_product def input_file_to_list(filepath): num_list = [] with open(filepath, 'r') as in_file: for line in in_file: num_list.append(int(line.strip())) return num_list in_numbers = input_file_to_list('inputs/day_1.txt') print(find_three_entries_for_target(in_numbers, 2020))
true
7252e716f0bb533d1a612728caf027276883e0ef
git4rajesh/python-learnings
/String_format/dict_format.py
800
4.5625
5
### String Substitution with a Dictionary using Format ### dict1 = { 'no_hats': 122, 'no_mats': 42 } print('Sam had {no_hats} hats and {no_mats} mats'.format(**dict1)) ### String Substitution with a List using Format ### list1 = ['a', 'b', 'c'] my_str = 'The first element is {}'.format(list1) print(my_str) ### List extraction my_str = 'The first element is {0}, the second element is {1} and third element is {2}'.format(*list1) print(my_str) ### String Substitution with a Tuple using Format ### tuple1 = ('one', 'second', 'third') my_str = 'The first element is {0}, the second element is {1} and third element is {2}'.format(*tuple1) print(my_str) ### String Substitution with a String variable using Format ### my_name = 'Rajesh' my_str = 'Hi {0}'.format(my_name) print(my_str)
true
79618644a020eaa269bc7995d650afed3043b411
ravitej5226/Algorithms
/backspace-string-compare.py
1,312
4.15625
4
# Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. # Example 1: # Input: S = "ab#c", T = "ad#c" # Output: true # Explanation: Both S and T become "ac". # Example 2: # Input: S = "ab##", T = "c#d#" # Output: true # Explanation: Both S and T become "". # Example 3: # Input: S = "a##c", T = "#a#c" # Output: true # Explanation: Both S and T become "c". # Example 4: # Input: S = "a#c", T = "b" # Output: false # Explanation: S becomes "c" while T becomes "b". # Note: # 1 <= S.length <= 200 # 1 <= T.length <= 200 # S and T only contain lowercase letters and '#' characters. class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ clean_S=[] clean_T=[] for i in range(len(S)): if(S[i]=='#'): clean_S.pop() if len(clean_S)>0 else '' else: clean_S.append(S[i]) for i in range(len(T)): if(T[i]=='#'): clean_T.pop() if len(clean_T)>0 else '' else: clean_T.append(T[i]) return "".join(clean_S)=="".join(clean_T) s=Solution() print(s.backspaceCompare("ab##","c#d#"))
true
08815d5371e53a75f10ec4d2b0b9bba1747a6fa6
ravitej5226/Algorithms
/zigzag-conversion.py
1,458
4.15625
4
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) # P A H N # A P L S I I G # Y I R # And then read line by line: "PAHNAPLSIIGYIR" # Write the code that will take a string and make this conversion given a number of rows: # string convert(string text, int nRows); # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ output=[]; if s=='': output='' return output if numRows==1: return s for i in range(0,numRows): start_index=i; alt=True; temp=0 if start_index<len(s): output.append(s[start_index]); else: break; while start_index<len(s): if temp>0: output.append(s[start_index]); if(alt): temp=2*(numRows-1-i); else: temp=2*(i); start_index=start_index+temp; alt=not alt; return ''.join(output) s=Solution(); print(s.convert('PAYPALISHIRING',3))
true
5fa0a0ab95042208eb2bef0dc47498c34056dda6
arthuroe/codewars
/6kyu/sort_the_odd.py
2,963
4.25
4
''' You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] ''' import sys def sort_array(source_array): print(source_array) # Traverse through all array elements for i in range(len(source_array)): if source_array[i] % 2 != 0: min_idx = i for j in range(i, len(source_array)): if source_array[j] % 2 != 0: if source_array[min_idx] > source_array[j]: min_idx = j else: continue # Swap the found minimum element with the first element source_array[i], source_array[min_idx] = source_array[min_idx], source_array[i] print(source_array) return source_array sort_array([64, 25, 12, 22, 11, 5, 8, 3]) print() sort_array([4, 25, 1, 2, 10, 7, 8, 3]) print() sort_array([5, 3, 1, 8, 0]) print() sort_array([5, 3, 2, 8, 1, 4]) print() sort_array([]) '''----other solutions----''' def sort_array(arr): odds = sorted((x for x in arr if x % 2 != 0), reverse=True) return [x if x % 2 == 0 else odds.pop() for x in arr] def sort_array(source_array): odds = iter(sorted(v for v in source_array if v % 2)) return [next(odds) if i % 2 else i for i in source_array] def sort_array(numbers): evens = [] odds = [] for a in numbers: if a % 2: odds.append(a) evens.append(None) else: evens.append(a) odds = iter(sorted(odds)) return [next(odds) if b is None else b for b in evens] from collections import deque def sort_array(array): odd = deque(sorted(x for x in array if x % 2)) return [odd.popleft() if x % 2 else x for x in array] def sort_array(source_array): return [] if len(source_array) == 0 else list(map(int, (','.join(['{}' if a % 2 else str(a) for a in source_array])).format(*list(sorted(a for a in source_array if a % 2 == 1))).split(','))) def sort_array(source_array): odd = sorted(list(filter(lambda x: x % 2, source_array))) l, c = [], 0 for i in source_array: if i in odd: l.append(odd[c]) c += 1 else: l.append(i) return l def sort_array(source_array): # retrieve the odd values sorted_array = sorted([value for value in source_array if value % 2 != 0]) # insert the even numbers in the original place for index, value in list(enumerate(source_array)): if value % 2 == 0: sorted_array.insert(index, value) return sorted_array ''' ----tests----- Test.assert_equals(sort_array([5, 3, 2, 8, 1, 4]), [1, 3, 2, 8, 5, 4]) Test.assert_equals(sort_array([5, 3, 1, 8, 0]), [1, 3, 5, 8, 0]) Test.assert_equals(sort_array([]),[]) '''
true
78576dc109ab336280899a740fbc2f3797563e52
bryansilva10/CSE310-Portfolio
/Language_Module-Python/Shopping-Cart_Dictionary/cart.py
1,423
4.21875
4
#var to hold dictionary shoppingCart = {} #print interface print(""" Shopping Options ---------------- 1: Add Item 2: Remove Item 3: View Cart 0: EXIT """) #prompt user and turn into integer option = int(input("Select an option: ")) #while user doesn't exit program while option != 0: if option == 1: #add item #prompt user for item and qty item = input("Enter an item: ") #if item already exists in cart if item in shoppingCart: print("Item already in cart") qty = int(input("Enter quantity: ")) #update qty shoppingCart[item] += qty #if it does not else: qty = int(input("Enter quantity: ")) #add qty to the item key shoppingCart[item] = qty elif option == 2: #remove item # prompt user for itme to be removed item = input("Enter an item: ") #remove it del (shoppingCart[item]) elif option == 3: #loop through items in cart for item in shoppingCart: #print each item print(item, ":", shoppingCart[item]) elif option != 0: #in case user enters invalid option print("Please enter a valid option") option = int(input("\n\nSelect an option: ")) #when loop breaks and exits else: print("You closed the program...")
true
9b72b3dd6d3aba0798f18f06ab37bdf0c39a339a
xu2243051/learngit
/ex30.py
858
4.125
4
#!/usr/bin/python #coding:utf-8 #================================================================ # Copyright (C) 2014 All rights reserved. # # 文件名称:ex30.py # 创 建 者:许培源 # 创建日期:2014年12月09日 # 描 述: # # 更新日志: # #================================================================ import sys reload(sys) sys.setdefaultencoding('utf8') people = 130 cars = 40 buses = 15 if cars > people: print "We should take the cars." elif cars < people: print "We should not take the cars." else: print "We can't decide." if buses > cars: print "That's too many buses." elif buses < cars: print "Maybe we could take the buses." else: print "We still can't decide." if people > buses: print "Alright, let's just take the buses." else: print "Fine, let's stay home then."
true
3c4cb233be63715f662d6f81f76feae91e51ac85
cupofteaandcake/CMEECourseWork
/Week2/Code/lc1.py
1,787
4.375
4
#!/usr/bin/env python3 """A series of list comprehensions and loops for creating sets based on the bird data provided""" __appname__ = 'lc1.py' __author__ = 'Talia Al-Mushadani (ta1915@ic.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code" birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) ## Conventional loop for creating list containing birds' latin names birds_latin = set() for species in birds: birds_latin.add(species[0]) #searches for and adds all of the first variables for each species, which is the latin name print(birds_latin) ## Conventional loop for creating list containing birds' common names birds_common = set() for species in birds: birds_common.add(species[1]) #searches for and adds all of the second variables for each species, which is the common name print(birds_common) ## Conventional loop for creating list containing birds' mean body masses birds_mean_body_mass = set() for species in birds: birds_mean_body_mass.add(species[2]) #searches for and adds all of the third variables for each species, which is the mean body mass print(birds_mean_body_mass) ## List comprehension for creating list containing birds' latin names birds_latin_lc = set([species[0] for species in birds]) print(birds_latin_lc) ## List comprehension for creating list containing birds' common names birds_common_lc = set([species[1] for species in birds]) print(birds_common_lc) ## List comprehension for creating list containing birds' mean body masses birds_mbm_lc = set([species[2] for species in birds]) print(birds_mbm_lc)
true
0b4d452a26c2b44684c2eae50ba622c56dd97f4f
kriti-ixix/python2batch
/python/Functions.py
614
4.125
4
''' Functions are of two types based on input: - Default - Parameterised Based on return type: - No return - Some value is returned ''' ''' #Function definition def addTwo(first, second): #first = int(input("Enter first number: ")) #second = int(input("Enter second number: ")) third = first + second print("The sum is: ", third) print("Addition!") #Function calling addTwo(5, 10) addTwo(30, 20) x = 40 y = 50 addTwo(x, y) ''' def addTwo(first, second): third = first + second return third x = addTwo(5, 10) y = addTwo(20, 30) print("The sums are ", x, " ", y)
true
2bbe8852b53fe5d099afbbd8a310704c04c0423b
mecosteas/Coding-Challenges
/count_words.py
1,260
4.375
4
""" Given a long text string, count the number of occurrences of each word. Ignore case. Assume the boundary of a word is whitespace - a " ", or a line break denoted by "\n". Ignore all punctuation, such as . , ~ ? !. Assume hyphens are part of a word - "two-year-old" and "two year old" are one word, and three different words, respectively. Return the word counts as a string formatted with line breaks, in alphanumeric order. Example: "I do not like green eggs and ham, I do not like them, Sam-I-Am" Output: i 2 do 2 not 2 like 2 green 1 eggs 1 and 1 ham 1 them 1 sam-i-am 1 Also Valid: and 1 do 2 eggs 1 green 1 ham 1 i 2 like 2 not 2 sam-i-am 1 them 1 """ def count_words(text): word_table = {} for word in text.split(): word = word.strip(".,~?!").lower() if word_table.get(word) == None: word_table[word] = 1 else: word_table[word] += 1 return '\n'.join(f'{word} {freq}' for word, freq in word_table.items()) text = "I do not like green eggs and ham, \nI do not like them, Sam-I-Am" # print(text) # text_arr = text.split() # print(text_arr) # text_arr = [word.strip(".,~?!").lower() for word in text_arr] # print(text_arr) # text = ''.join(text_arr) # print(text) print(count_words(text))
true
507e4a5ea9054c11509e8d6f678d74aa6c3f545e
sleepingsaint/DS-ALG
/DS/linkedList.py
2,724
4.21875
4
# defining stack element object class Element(object): def __init__(self, value): self.value = value self.next = None # defining stack object class Stack(object): def __init__(self, head=None): self.head = head # helper class functions # function to add elements def append(self, new_element): if self.head: current = self.head while current.next: current = current.next current.next = Element(new_element) else: self.head = Element(new_element) # function to see the position of the element def get_position_value(self, position): current = self.head counter = 1 if position < 1: return None else: while current and counter <= position: if counter == position: return current.value current = current.next counter += 1 return None # function to insert an element at an certain position # Inserting at position 3 means between the 2nd and 3rd elements def insert_element(self, index, new_element): if self.head: current = self.head counter = 1 if index == 1: e = Element(new_element) e.next, self.head = self.head, e elif index > 1: while current and counter < index - 1: current = current.next counter += 1 if not current: print('cannot insert the element') else: e = Element(new_element) e.next, current.next = current.next, e # function to delete an first node with given value def delete(self, value): if self.head: current = self.head previous = None while current.value != value and current.next: previous = current current = current.next if current.value == value: if previous: previous.next = current.next else: self.head = current.next else: return None # initializing the stack stck = Stack() # adding elements stck.append(1) stck.append(2) stck.append(3) # getting position # inserting element stck.insert_element(2, 4) stck.delete(3) print(stck.get_position_value(1)) print(stck.get_position_value(2)) print(stck.get_position_value(3)) print(stck.get_position_value(4)) stck.insert_element(500, 6) print(stck.get_position_value(1)) print(stck.get_position_value(2)) print(stck.get_position_value(3))
true
d5891584688ff83c60bf74fc7611c625f57b14db
Sukanyacse/Assignment_2
/assignment 2.py
254
4.1875
4
numbers=(1,2,3,4,5,6,7,8,9) count_even=1 count_odd=-1 for value in range(1,10): if(value%2==0): count_even=count_even+1 else: count_odd=count_odd+1 print("Number of even numbers:",count_even) print("Number of odd numbers:",count_odd)
true
92ff8e67eb22909831b10bfcdd1faedef658825e
Lauraparedesc/Algoritmos
/Actividades/ejercicios/exlambda.py
1,291
4.25
4
#Exponente n de un # dado exponente = lambda base = 0, exponente = 0 : base**exponente resultado = exponente (5,2) print (resultado) #string string = lambda cantidad = 0 : print ('♡'*cantidad) string (60) #maximo # listaEdades1 = [18,12,14,13,12,20] listaEdades2 = [19,47,75,14,12,22] lambdamaximos = lambda x = [], y = []: print (max(x),max(y)) lambdamaximos (listaEdades1, listaEdades2) #V o F par numeroPar = lambda par = 0 : par % 2 == 0 print(numeroPar(23)) print(numeroPar(12)) #V o F impar numeroImpar = lambda impar = 0 : impar % 2 != 0 print(numeroImpar(23)) print(numeroImpar(12)) #union 2 palabras unirP = lambda word1 , word2 : word1 + ' ' + word2 print (unirP('Soy','programador')) #saludo preguntaNombre = 'Ingrese su nombre por favor : ' nombre = input(preguntaNombre) saludar = lambda name = '' : print (f'Bienvenid@ {name}, disfruta el programa') saludar(nombre) #Letras palabraX = 'Blessed' lenPalabra = lambda palabra : len (palabra) print (lenPalabra(palabraX)) #¿? showLen = lambda funcion, palabra : print (funcion(palabra)) showLen(lenPalabra, palabraX) #Triangulo calcularAreaTriangulo = lambda base = 0, altura = 0: base*altura/2 print(calcularAreaTriangulo(5,8)) #IMC imc = lambda peso = 0, altura = 1: round(peso/altura**2,3) print (imc(48,1.58))
false
e644585b9b3a99f72e3ed4fc948ecb26ca0465f0
moheed/python
/languageFeatures/python_using_list_as_2d_array.py
1,976
4.5625
5
#NOTE: creating list with comprehension creates many #pecularities.. as python treats list with shallow copy... #for example arr=[0]*5 #=== with this method, python only creates one integer object with value 5 and #all indices point to same object. since all are zero initially it doesn't matter. arr[0]=5 #when we modify arr[0], it creates a new int object with val=5 and makes the zero-index point #new object. print(arr) #this works expected. #however, arr2=[[0]*5]*5 #expecting 5x5 matrix filled with zero print(arr2) arr2[0][0]=1 #expecting only 0,0 to be 1.. but o/p? print(arr2) #[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]] #HOW all elements of first column are changed... Weired??? #This is because list works in shallow way... as shown for arr(1-d array) #however, when we declare a 2-d arr, that means all indices in a given inner [](ie col) point to single integer object 0 #when we update by arr2[0][0]=x, what we are doing is, updating the first element of inner[](ie col) #since all row-indices for that col point to same object, it updates all first values of given col. """ Similarly, when we create a 2d array as “arr = [[0]*cols]*rows” we are essentially the extending the above analogy. 1. Only one integer object is created. 2. A single 1d list is created and all its indices point to the same int object in point 1. 3. Now, arr[0], arr[1], arr[2] …. arr[n-1] all point to the same list object above in point 2. The above setup can be visualized in the image below. One way to check this is using the ‘is’ operator which checks if the two operands refer to the same object. Best Practice: If you want to play with matrix run the LOOP and ensure all mxn objects are allocated.! # Using above second method to create a # 2D array rows, cols = (5, 5) arr=[] for i in range(cols): col = [] for j in range(rows): col.append(0) arr.append(col) print(arr) """
true
7cc37dc2b2888106efb3c2ee41d61bb86b511f5b
moluszysdominika/PSInt
/lab02/zad3.py
644
4.15625
4
# Zadanie 3 # Basic formatting text1 = "Dominika" text2 = "Moluszys" print("{1} {0}" .format(text1, text2)) # Value conversion class Data(object): def __str__(self): return "Dominika" def __repr__(self): return "Moluszys" print("{0!s} {0!r}" .format(Data())) # Padding and aligning strings print("{:>12}" .format("Dominika")) print("{:12}" .format("Moluszys")) print("{:_<10}" .format("Domix")) print("{:^11}" .format("Domix")) # Truncating long strings print("{:.15}" .format("konstantynopolitanczykowianeczka")) # Combining truncating and padding print("{:15.20}" .format("konstantynopolitanczykiewiczowna"))
false
92a753e7e633025170d55b3ebdb9f2487b3c4fa0
HayleyMills/Automate-the-Boring-Stuff-with-Python
/Ch6P1_TablePrinter.py
1,352
4.4375
4
##Write a function named printTable() that takes a list of lists of strings ##and displays it in a well-organized table with each column right-justified. ##Assume that all the inner lists will contain the same number of strings. ##For example, the value could look like this: ##tableData = [['apples', 'oranges', 'cherries', 'banana'], ## ['Alice', 'Bob', 'Carol', 'David'], ## ['dogs', 'cats', 'moose', 'goose']] ##Your printTable() function would print the following: ## ## apples Alice dogs ## oranges Bob cats ##cherries Carol moose ## banana David goose #def printTable(): #input is a list of strings #output is an orgniased table with each column rjust tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] rows = len(tableData) #number of lists cols = len(tableData[0]) #number of cols maxlength = 0 for i in range(0,(rows)): #loop for number of rows for x in tableData[i]: #loop for the each item in the row if maxlength < len(x): #find the max length of the words maxlength = len(x) for k in range(0, (cols)): for v in range(0, (rows)): print((tableData[v][k]).rjust(maxlength), end = ' ') print()
true
e317905dca19712d90a62f463a4f782bd22668e5
Ahmad-Magdy-Osman/IntroComputerScience
/Classes/bankaccount.py
1,195
4.15625
4
######################################################################## # # CS 150 - Worksheet #11 --- Problem #1 # Purpose: Practicing User-Defined Classes. # # Author: Ahmad M. Osman # Date: December 9, 2016 # # Filename: bankaccount.py # ######################################################################## class BankAccount: #Bank Account Class #Creating account and initiating balance value def __init__(self, balance=0): self.balance = balance #Returning the account's current balance value def getBalance(self): return self.balance #Setting the account's balance to the value of amount def setBalance(self, amount): self.balance = amount #Depositing the value of amount into the account's balance def deposit(self, amount): print("$%.2f will be deposited." %(amount)) self.balance += amount #Withdrawing the value of amount from the account if the balance is sufficient def withdraw(self, amount): if self.balance >= amount: print("$%.2f will be withdrawn." %(amount)) self.balance -= amount else: print("Insufficient funds") #Printing account balance def __str__(self): display = "Account Balance: " + ("$%.2f" %(self.balance)) return display
true
b19db0ac2fef12e825b63552fbd0b298fcb632ec
Ahmad-Magdy-Osman/IntroComputerScience
/Turtle/ex10.py
859
4.65625
5
###################################### # # CS150 - Interactive Python; Python Turtle Graphics Section, Exercise Chapter - Exercise 10 # Purpose: Drawing a clock with turtles # # Author: Ahmad M. Osman # Date: September 22, 2016 # # Filename: ex10.py # ##################################### #Importing turtle module import turtle #Initiating window canvas window = turtle.Screen() window.bgcolor("lightgreen") #Initiating clock turtle clock = turtle.Turtle() clock.shape("turtle") clock.color("blue") clock.hideturtle() clock.speed(0) clock.pensize(5) clock.pu() clock.setposition(0, 0) clock.stamp() #Drawing clock for i in range(12): clock.left(30) clock.forward(125) clock.pd() clock.forward(10) clock.pu() clock.forward(25) clock.stamp() clock.forward(-160) #Waiting for user to exit through clocking on the turtle program screen window.exitonclick()
true
bbcefac3f0243ed8df81ed8a4875626b78ab3ca4
iangraham20/cs108
/labs/10/driver.py
976
4.5
4
''' A driver program that creates a solar system turtle graphic. Created on Nov 10, 2016 Lab 10 Exercise 5 @author: Ian Christensen (igc2) ''' import turtle from solar_system import * window = turtle.Screen() window.setworldcoordinates(-1, -1, 1, 1) ian = turtle.Turtle() ss = Solar_System() ss.add_sun(Sun("SUN", 8.5, 1000, 5800)) ss.add_planet(Planet("EARTH", .475, 5000, 0.6, 'blue')) try: ss.add_planet( Planet(input('Please enter the name of the planet: '), float(input('Please enter the radius of the planet: ')), float(input('Please enter the mass of the planet: ')), float(input('Please enter the distance of the planet from the origin: ')), input('Please enter the color of the planet: '))) except ValueError as ve: print('ValueError occurred:', ve) except TypeError as te: print('TypeError occurred:', te) except: print('Unknown Error') #Keep the window open until it is clicked window.exitonclick()
true
0e75d78ea6d8540a5417a8014db80c0b84d32cc9
iangraham20/cs108
/projects/07/find_prefix.py
1,677
4.125
4
''' A program that finds the longest common prefix of two strings. October 25, 2016 Homework 7 Exercise 7.3 @author Ian Christensen (igc2) ''' # Create a function that receives two strings and returns the common prefix. def common_prefix(string_one, string_two): ''' A function that compares two strings, determines the common prefix and returns the result. ''' # Create necessary variables. prefix_results = '' character = 0 # Begin while loop to compare strings. while character <= (len(string_one) - 1) and character <= (len(string_two) - 1): # Begin if statement to compare the characters of the two strings. if string_one[character] == string_two[character]: # Add appropriate values to the variables. prefix_results += string_one[character] character += 1 # Once the prefix has been found exit the if statement. else: break # Return the results and exit the function. return prefix_results # Create a function that runs tests on the function named common_prefix. def test_common_prefix(): ''' A function that calls common_prefix, tests the results, and prints a boolean expressions. ''' assert(common_prefix('', '') == '') assert(common_prefix('abc123', '') == '') assert(common_prefix('abcDefg', 'abcdefg') == 'abc') assert(common_prefix('abcde5g', 'abcdefg') == 'abcde') assert(common_prefix('12345f7', '1234567') == '12345') test_common_prefix() # Create a user input for common_prefix. print(common_prefix(input('Please enter first string: '), input('Please enter second string: ')))
true
b3e1ca7c075544d30a3a7cbd65193871f62f7a64
iangraham20/cs108
/projects/12/polygon.py
881
4.25
4
''' Model a single polygon Created Fall 2016 homework12 @author Ian Christensen (igc2) ''' from help import * class Polygon: ''' This class represents a polygon object. ''' def __init__(self, x1 = 0, y1 = 0, x2 = 0, y2 = 50, x3 = 40, y3 = 30, x4 = 10, y4 = 30, color = '#0000FF'): ''' This is the Constructor method for the Polygon class. ''' self._x1 = x1 self._y1 = y1 self._x2 = x2 self._y2 = y2 self._x3 = x3 self._y3 = y3 self._x4 = x4 self._y4 = y4 self._color = color def render(self, canvas): ''' This render method allows the polygon object to be displayed on a screen. ''' canvas.create_polygon(self._x1, self._y1, self._x2, self._y2, self._x3, self._y3, self._x4, self._y4, fill = self._color, outline='black')
false
50b03235f4a71169e37f3ae57654b7a37bcb9d10
adamsjoe/keelePython
/Week 3/11_1.py
246
4.125
4
# Write a Python script to create and print a dictionary # where the keys are numbers between 1 and 15 (both included) and the values are cube of keys. # create dictonary theDict = {} for x in range(1, 16): theDict[x] = x**3 print(theDict)
true
86e3aa25fd4e4878ac12d7d839669eda99a6ea1c
adamsjoe/keelePython
/Week 1/ex3_4-scratchpad.py
964
4.125
4
def calc_wind_chill(temp, windSpeed): # check error conditions first # calc is only valid if temperature is less than 10 degrees if (temp > 10): print("ERROR: Ensure that temperature is less than or equal to 10 Celsius") exit() # cal is only valid if wind speed is above 4.8 if (windSpeed < 4.8): print("ERROR: Ensure that wind speed greater than 4.8 km/h") exit() # formula for windchill v = windSpeed**0.16 chillFactor = 13.12 + 0.6215 * temp - 11.37 * v + 0.3965 * temp * v return chillFactor def convertToKMH(mphSpeed): return mphSpeed * 1.609 # test values temperature = 5 windSpeed = convertToKMH(20) # call the fuction to calculate wind chill wind_chill = calc_wind_chill(temperature, windSpeed) # print a string out print("The wind chill factor is ", wind_chill, " Celsius") # print a pretty string out print("The wind chill factor is ", round(wind_chill, 2), " Celsius")
true
d3ab5cfe7bb1ff17169b2b600d21ac2d7fabbf70
adamsjoe/keelePython
/Week 8 Assignment/scratchpad.py
1,193
4.125
4
while not menu_option: menu_option = input("You must enter an option") def inputType(): global menu_option def typeCheck(): global menu_option try: float(menu_option) #First check for numeric. If this trips, program will move to except. if float(menu_option).is_integer() == True: #Checking if integer menu_option = 'an integer' else: menu_option = 'a float' #Note: n.0 is considered an integer, not float except: if len(menu_option) == 1: #Strictly speaking, this is not really required. if menu_option.isalpha() == True: menu_option = 'a letter' else: menu_option = 'a special character' else: inputLength = len(menu_option) if menu_option.isalpha() == True: menu_option = 'a character string of length ' + str(inputLength) elif menu_option.isalnum() == True: menu_option = 'an alphanumeric string of length ' + str(inputLength) else: menu_option = 'a string of length ' + str(inputLength) + ' with at least one special character'
true
4720925e6b6d133cdfaf1fd6cf5358813bbec7e3
george5015/procesos-agiles
/Tarea.py
460
4.15625
4
#!/usr/bin/python3 def fibonacci(limite) : numeroA, numeroB = 0,1 if (limite <= 0) : print(numeroA) elif (limite == 1) : print(numeroB) else : print(numeroA) while numeroB < limite: numeroA, numeroB = numeroB, numeroA + numeroB print(numeroA) return numeroLimite = int(input("Ingrese el numero para calcular la serie de Fibonacci :")) print ("Los numeros de fibonacci para el numero " + str(numeroLimite) + " son: ") fibonacci(numeroLimite)
false
35612faf608a4cb399dacffce24ab01767475b35
imsure/tech-interview-prep
/py/fundamentals/sorting/insertion_sort.py
775
4.15625
4
def insertion_sort(array): """ In place insertion sort. :param array: :return: """ n = len(array) for i in range(1, n): v = array[i] k = i j = i - 1 while j >= 0 and array[j] > v: array[j], array[k] = v, array[j] k = j j -= 1 def insertion_sort_2(array): """ In place insertion sort. Eliminate unnecessary variable v and k. :param array: :return: """ n = len(array) for i in range(1, n): j = i while j > 0 and array[j] < array[j-1]: array[j], array[j-1] = array[j-1], array[j] j -= 1 array = [5, 4, 3, 2, 1] insertion_sort(array) print(array) array = [5, 4, 6, 7, 1] insertion_sort(array) print(array)
false
db160f1b741178589e3b097dfdb4d46f39168350
Bngzifei/PythonNotes
/学习路线/1.python基础/day09/06-str方法.py
608
4.21875
4
"""str()就是可以自定义输出返回值,必须是str字符串""" class Dog: def __init__(self, name): self.name = name def __str__(self): # 把对象放在print()方法中输出时,就会自动调用str()方法 return '呵呵呵%s' % self.name # 只能返回字符串 # overrides method :覆盖方法 重写了 dog1 = Dog('来福') print(dog1) # 如果将str()方法注释掉,把对象放在print中输出时,默认输出的是对象的内存地址 <__main__.Dog object at 0x0000015BF223B320> # dog1.__str__() 这一步是自动调用了,自定义返回值 # ss = type(dog1) # print(ss)
false
e3d36397e4ba0307b0574963d8bfddbed8d12ef0
Bngzifei/PythonNotes
/学习路线/1.python基础/day10/09-多继承.py
1,608
4.34375
4
""" C++ 和Python 支持多继承,其他语言不支持 发现规律找规律记,记住区别.初始化只是一次.再次调用init()方法就是和普通的方法调用没区别了. 多态依赖继承. 鸭子类型不依赖继承. Python中没有重载一说,即使同名函数,方法,出现2次后,第2次的慧覆盖掉第1次的.在一个类里面只能有一个,通过修改参数来进行需要的变化. 同名属性和同名方法只会继承某个父类的一个.继承链中挨的最近的那个. """ class Dog: def eat(self): print('肉') def drink(self): print('水') class God: def fly(self): print('lll') def eat(self): print('丹') # 格式:class 类名(父类1,父类2...) 派生类:延伸的类,就是一个新的类而已 也有的叫法是 class 派生类(父类1,父类2...) class XTQ(Dog, God): # 如果想要控制,指定的就要重新写了. def eat(self): # super(Dog, self).eat() # 调的是Dog后面那个,也就是God的属性了.多继承时,看着比较混乱,所以不要这么写 God.eat(self) # 多继承时,如果调用指定父类被重写的方法,尽量直接使用指定的父类方法名去调用 xtq = XTQ() # xtq.fly() # xtq.drink() xtq.eat() # 继承链:调用第一个的,有顺序的. # print(XTQ.__mro__) # 查看指定类的继承链 (<class '__main__.XTQ'>, <class '__main__.Dog'>, <class '__main__.God'>, <class 'object'>) ,实际上注意:Dog和God是没有关系的是并列的 # print(Dog.__mro__) # (<class '__main__.Dog'>, <class 'object'>) # print(God.__mro__) # (<class '__main__.God'>, <class 'object'>)
false
d8c4501a2f890f7e63f7e08444204882e45cef5c
Bngzifei/PythonNotes
/学习路线/1.python基础/day03/01-猜拳游戏.py
970
4.1875
4
""" 石头1剪刀2布3 猜拳游戏 import random # 导入生成随机数模块 同行的注释时: #号和代码之间是2个空格,#号和注释内容之间是1个空格 这是PEP8的编码格式规范 """ import random # 导入生成随机数模块 # print(random.randint(1,3)) # 生成1,2,3其中的某一个 以后的才是左闭右开,前小后大,只能生成整数 区间: 数学意义上的()是开区间 ,[]是闭区间.取值规则是:取闭不取开.这里的random.randint(n,m)实际上是n<= 所取得值 <= m.原因是内置函数写死了. player_num = int(input('请出拳 石头(1)/剪刀(2)/布(3):')) computer_num = random.randint(1, 3) # 可以在这里直接对一个变量进行随机数值的赋值运算. if ((player_num == 1 and computer_num == 2) or (player_num == 2 and computer_num == 3) or (player_num == 3 and computer_num == 1)): print('胜利!') elif player_num == computer_num: print('平局.') else: print('输了...')
false
279e7cd4a60f94b9e7ff20e2d16660850f6a76cb
Bngzifei/PythonNotes
/学习路线/1.python基础/day06/01-参数混合使用.py
1,040
4.5
4
print('参数补充:') """ 形参:位置参数(就是def func(a,b):),默认参数(就是def func(a = 5,b = 9):),可变参数(就是def func(*args):),字典类型的可变参数(就是def func(**kwargs):) 实参:普通实参,关键字参数 形参使用顺序:位置参数 -->可变参数 -->默认参数 -->字典类型可变参数 实参使用顺序:普通实参 ---> 关键字参数 """ """位置参数和默认参数混合使用时,位置参数应该放在默认参数的前面""" """位置参数和可变参数混合使用时位置参数在可变参数的前面""" # # # def func1(a, *args): # print(a) # print(args) # # # func1(1, 2, 3, 4) """默认参数和可变参数混合使用:默认参数应该放在可变参数的后面""" # 就是来收没人要的实参,可变参数不能用关键字参数的方式指定 def func2(*args, a=10): print(a) print(args) func2(1, 2, 3) # 10 # (1, 2, 3) func2(1, 2, 3, a=20) # 20,如果需要重新给a赋值,需要重新给a赋值(调用的时候叫关键字参数) # (1, 2, 3)
false
5149018a67ac854d93a1c553f315b0b44858848a
Bngzifei/PythonNotes
/学习路线/1.python基础/day05/11-函数的参数补充.py
2,020
4.15625
4
""" 形参:有4种类型,位置参数,默认参数(缺省参数),可变参数(不定长 参数).字典类型可变参数 实参:2种类型 普通实参,关键字参数 """ """位置参数:普通参数 实参和形参位置数量必须一一对应""" # def func1(num1, num2): # print(num1) # # # func1(10, 20) """ 默认参数(缺省参数): 如果某个形参的值在多次使用时,都是传一样的值,我们可以把此参数改成默认参数 默认参数如果没有传递实参就用默认值,如果传递了实参就使用传递来的实参 默认参数必须放在非默认参数的后面.除非均是默认参数 """ # def func2(a, b=2): # print(a) # print(b) # # # func2(1) # 1,2 实参1 ,形参2(默认参数) """关键字参数(实参的时候): 关键字参数是实参 在实参赋值时候,给指定的形参设置指定的真实数据 如果函数中有多个默认参数时, 想给后面的那个参数设置实参,就必须以关键字参数方式进行指定 """ def func3(a=20, b=30): print(a) print(b) # func3(b=50) # 一定是这种格式 # b = 50就是给指定的形参b赋值50,函数调用的时候这里就不再是b = 30,直接都是b = 50 """可变参数(不定长参数):可以接收任意数量的实参,并且自动组包成元组 用的不多,这个参数类型 可变参数的本质是将传递的参数包装成了元组 *args:参数名官方指定的,减少沟通成本 args:英文参数的缩写 写一点,运行一点 函数内部使用的时候不需要加* 在形参名args前面加 * 是为了告诉python解释器此参数是一个可变参数 """ # def func4(*args,a,b,): # 这样是不对的,args会把所有的实参都接收掉,后面的a,b就不会接收到实参了 # def func4(a,b,*args): # print(args) # # # func4(1,2,3,4) # (1, 2, 3, 4) # 后天:组包,解包补充说明 # 引用的问题 # 可变类型 - 不可变类型 # 模块的使用(.py文件的使用) # 学生名片主逻辑 # # # 学生名片管理系统(150行左右)
false
b36169cf1712dca276d8bc33bca89412500342d1
Bngzifei/PythonNotes
/学习路线/1.python基础/day04/09-切片.py
834
4.1875
4
""" 切片:取出字符串的一部分字符 字符串[开始索引:结束索引:步长] 步长不写,默认为1 下一个取得索引的字符 = 当前正在取得字符索引 + 步长 其他语言叫截取 步长:1.步长的正负控制字符串截取的方向 2.截取的跨度 """ str1 = "hello python" # print(str1[0:5]) # print(str1[:5]) # 如果开始索引为0,可以省略 # str2 = str1[6:12] # str2 = str1[6:] # 如果结束索引最后,可以省略 # print(str2) # list1 = [11, 12, 14] # print(list1[-1]) # 负索引,倒着数,比较方便 # # str2 = str1[-1:] # print(str2) # str2 = str1[::-1] # 倒置,翻转 # str2 = str1[4::-1] # 步长是-1,方向:右->左,跨度1 str2 = str1[4::-2] # 步长为-2,隔一个取一个 print(str2) # 在列表,元组,字符串中都可以使用 # 可变参数.预习到这里
false
258f80cccb19730b8ad4b8f525b9fcac8ab170f2
Bngzifei/PythonNotes
/学习路线/2.python进阶/day11/02-闭包.py
1,079
4.34375
4
""" closure:闭包的意思 闭包特点: 1.>函数的嵌套定义,就是函数定义里面有另外一个函数的定义 2.>外部函数返回内部函数的引用<引用地址> 3.>内部函数可以使用外部函数提供的自由变量/环境变量 <顺序是先去找自己的位置参数,看看是否有同名,如果没有就向外扩展一层,继续这个过程.直到找到> 这就是闭包的三个特点 概念:内部函数 + 自由变量 构成的 整体 这是IBM 开发网站的一个说法 理解:内部函数 + 外部函数提供给内部函数调用的参数. """ def func(num1): # 外部函数 的变量称之为自由变量/环境变量 内部函数也可以使用 print('in func', num1) def func_in(num2): print('in func_in', (num1 + num2)) # return func_in()# 这样就会调用func_in函数了 # 返回func_in的引用地址 外部就可以进行调用func_in函数了 return func_in # 因为func_in函数并没有被调用 # func() # in func # 接收外部函数func 返回值return是 内部函数func_in的引用 f = func(99) f(100)
false
cdab2900e3495440613dfeea792f09953078fa1a
Bngzifei/PythonNotes
/学习路线/1.python基础/day03/07-定义列表.py
530
4.1875
4
""" 存储多个数据,每个数据称之为元素 格式:[元素1,元素2...] 列表中尽可能存储同类型数据,且代表的含义要一致.实际上可以存储不同类型的数据 获取元素:列表[索引] 常用的标红:整理一下好复习 增.删.改.查 """ list1 = ['11', '22', 18, 1.75, True] print(type(list1)) print(list1[4]) l1 = list() print(l1) # IndexError: list index out of range # print(list1[8]) 索引超出list范围,报错 list1[0] = '你大爷' # 修改元素的值 print(list1)
false