blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
5ee94aae7eee89f853af061525ce1c76a0022a67
jblaze2908/hacktoberfest2020
/Basic Programs/Sum of Digits in A Number/SolutionBy_AmeyaChawla27.py
125
3.875
4
n=int(input("Enter the NUmber")) sum=0 b=n while n>0: sum=sum+n%10 n=n/10 print("Sum of digits "+" of "+b+" is "+sum)
b3d65225de9b62b3297eed7977fae68ff935f5ed
nortonhelton1/classcode
/hello-python (2)/hello-python/calculator.py
446
4.125
4
first_number = int(input("Enter the first number: ")) operand = input("Enter the mathmatecial operation: ") second_number = int(input("Enter the second number: ")) def calculator(x, operation, y): if operation == "+" : return x + y elif operation == "-" : return x - y elif operation == "*" : return x * y else: return x/y answer = calculator(first_number, operand, second_number) print(answer)
d23208c27cc368d719d37fc203f4eb8cde0f9c07
CateGitau/Python_programming
/ace_python_interview/lists/challenge_8.py
929
4.21875
4
# Right rotate List ''' Implement a function which will rotate the given list by K. This means that the right most elements will appear at the left-most positions in the list and so on, You only have to rotate the list by one element at a time ''' lst = [10,20,30,40,50] n = 3 #Manual Rotation #O(n) def right_rotate(lst, k): if len(lst) == 0: k = 0 else: k = k % len(lst) rotatedList = [] # get the elements from the end for item in range(len(lst) - k, len(lst)): rotatedList.append(lst[item]) # get the remaining elements for item in range(0, len(lst) - k): rotatedList.append(lst[item]) return rotatedList print(right_rotate(lst, n)) # Pythonic rotation def right_rotate(lst, k): # get rotation index if len(lst) == 0: k = 0 else: k = k % len(lst) return lst[-k:] + lst[:-k] print(right_rotate([10, 20, 30, 40, 50], abs(3)))
7ff2f01a7212c3f047adfaf77e91f0478e0d0bf7
ivanmopa/sumalista
/básicos/basico3.py
245
3.921875
4
#!/usr/bin/env python #-*- coding: utf-8 -*- li = [int(raw_input('Introduce un valor: ')), int(raw_input('Introduce otro: ')), int(raw_input('Introduce uno más: '))] suma = 0 for elemento in li: suma = suma + elemento print 'la suma es', suma
3ff82b6eabaf98aa3b6f888c97491935100d5f25
wargreimon501/CYPRafaelSA
/libro/problemas_resueltos/capitulo3/ej3_1.py
123
3.75
4
NOMINA=0 i=1 for i in range (11): SUE=int(input("dame tu sueldo :")) NOMINA=NOMINA+SUE i=i+1 print(NOMINA)
2499ed5f92b11014ea4f37f4059ff4e3f87a0ec6
gabriellaec/desoft-analise-exercicios
/backup/user_103/ch131_2020_04_01_17_16_54_473387.py
1,121
3.796875
4
import random dado1=random.randint(1,10) dado2=random.randint(1,10) soma=dado1+dado2 dinheiro=10 while dinheiro>0: num1=int(input('digite um numero:')) num2=int(input('digite um numero maior que o anterior')) somaaposta=num1+num2 if somaaposta!=soma: if soma< num1: print('Soma menor') if soma> num2: print('Soma maior') else: print('Soma no meio') print('Você tem {0}'.format(dinheiro)) chutes=int(input('você quer comprar quantos chutes?')) dinheiro-=chutes while chutes>0: num1=int(input('digite um numero:')) num2=int(input('digite um numero maior que o anterior')) novasoma=num1+num2 if novasoma!=soma: chutes-=1 else: ganha=dinheiro+5*dinheiro print('Você ganhou {0}'.format(ganha))
0ad637830f6c8250686db8cdcbf7dc38d1db0d2c
Krodrig25/Module1_challenge
/module1_challenge.py
2,386
3.734375
4
import csv from pathlib import Path loan_costs = [500, 600, 200, 1000, 450] #Total number of loans. len(loan_costs) print(f"The total number of loans is: {len(loan_costs)}") # sum of all loans. sum_result=sum(loan_costs) print(f"The total of all loans is: {sum_result}") # average price of loans total_loan_costs= 2750 total_number_of_loans= 5 average_price = total_loan_costs / total_number_of_loans print(f"The average loan price is:${average_price}") loan = { "loan_price": 500, "remaining_months": 9, "repayment_interval": "bullet", "future_value": 1000, } #Calculation to determine present value of loan future_value= 1000 discount_rate= .20 remaining_months= 9 present_value = future_value / (1 + discount_rate/12) ** remaining_months print(f"The present value of the loan is: {present_value}") # conditional statement to determine if the loan is a fair value. average_loan_price=550 present_value= 862 future_value=1000 if present_value - future_value: print("This a fair deal!") else: print("This is not a fair deal") new_loan = { "loan_price": 800, "remaining_months": 12, "repayment_interval": "bullet", "future_value": 1000, } present_value = new_loan["loan_price"] -0.20 print(f"The present value of the loan is:${present_value}") loans = [ { "loan_price": 700, "remaining_months": 9, "future_value": 1000, }, { "loan_price": 500, "remaining_months": 13, "repayment_interval": "bullet", "future_value": 1000, }, { "loan_price": 200, "remaining_months": 16, "repayment_interval": "bullet", "future_value": 1000, }, { "loan_price": 900, "remaining_months": 16, "repayment_interval": "bullet", "future_value": 1000, }, ] # list of loans $500 or less inexpensive_loans=[] for loan in loans: if loan["loan_price"] <= 500: inexpensive_loans.append(loan) print(f"Loans $500 or less: {inexpensive_loans}") import csv header = ["loan_price", "remaining_months", "repayment_interval", "future_value"] output_path = Path("inexpensive_loans.csv") with open(output_path, "w") as f: csvwriter = csv.writer(f) csvwriter.writerow(header) for loan in inexpensive_loans: csvwriter.writerow(loan.values()) print(loan.values())
e8609d9a700d578a8799bd8ccaca173903b81f13
ShubhangiKukreti/Data-Structures-Algorithms
/Stacks/StacksUsingLinkedList.py
1,362
4.25
4
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.top = None self.bottom = None self.length = 0 def pop(self): if self.length == 0: print("stack is empty!") elif self.top == self.bottom: self.bottom = None self.length -= 1 else: current = self.top.next self.top = current self.length -= 1 def push(self, new_value): new_node = Node(new_value) if self.top is None: self.top = new_node self.bottom = new_node else: temp = self.top self.top = new_node self.top.next = temp self.length += 1 def peek(self): if self.length == 0: print("The stack is empty!") else: print(self.top.value) def traverse(self): if self.top is None: print("stack is empty") else: current = self.top while current: print(current.value) current = current.next stack = Stack() stack.push(8) stack.push(4) stack.push(9) stack.push(7) print(stack.peek()) print("the full stack") stack.traverse() stack.pop() print("the full stack") stack.traverse()
d239ac9ad0729554d89a04049c419455a6bf2524
ConniePingJiang/Python
/Learning Python/test26.py
611
4.46875
4
''' 11. Define a function generate_n_chars() that takes an integer n and a character c and returns a string, n characters long, consisting only of c:s. For example, generate_n_chars(5,"x") should return the string "xxxxx". (Python is unusual in that you can actually write an expression 5 * "x" that will evaluate to "xxxxx". For the sake of the exercise you should ignore that the problem can be solved in this manner.) Created on Aug 12, 2015 @author: conniejiang ''' def generate_n_chars(y, x): z = '' for i in range(0, y): z = z + x return(z) m = generate_n_chars(5, "*") print(m)
d57cb07ed57a82b555564b74948badf8c7d3afbb
pranjay01/leetcode_python
/JumpGameII.py
547
3.5
4
nums=[1,2,1,1,1] def findindexOfMax(nums,cur,maxD,l): #l=len(nums)-1 limit=cur+maxD-1 if limit==(l): return (l) elif limit>(l): limit=l maxv=nums[cur] index=cur for i in range(cur,limit): if maxv<nums[i]: maxv=nums[i] index=i return index l=len(nums) if l==1: print (0) maxD=nums[0] count=0 cur=0 while l-cur>maxD and cur<l-1: count+=1 cur=findindexOfMax(nums,cur+1,maxD,l-1) maxD=nums[cur] if l-cur<=maxD and cur<l-1: count+=1 print (count)
e2825e00c97d56a3d3f368480288cd626c1c0c24
XingxinHE/PythonCrashCourse_PracticeFile
/Chapter 5 If Statement/if practice pro.py
1,145
4.375
4
account_list = ['Eric','Morris','Steven','admin','Oscar'] for account in account_list: if account == 'admin': print('Hello '+account+', would you like to see a status report?') else: print('Hello '+account+',thank you for logging in again.') if account_list: for account in account_list: print(account) else: print('We need to find some users!') current_users = ['Eric','Morris','steven','admin','Oscar'] new_users = ['Yolanda','Eva','Mandy','Oscar','Steven'] #lower() is for string, but how can I convert a list to lower case. #the answer is you have to create a brand new lower list current_users_lower = [] for user in current_users: current_users_lower.append(user.lower()) #Meanwhile, you can use list comprehension: #current_users_lower = [user.lower() for user in current_users] for account in new_users: if account.lower() in current_users_lower: print('Sorry, '+account+' has been registered.') else: print(account+' is a valid account name!') #lower() is for string, but how can I convert a list to lower case.
55cbd33c566c072acf25c90ef0795b1214c3041d
KhauTu/Python3-Hardway
/ex15.py
378
3.9375
4
from sys import argv script, filename = argv # assign filename to argv[1] txt = open(filename) # open file with filename print(f"Here's your file {filename}:") print(txt.read()) # print file content print("Type the filename again:") file_again = input("> ") # input filename again txt_again = open(file_again) # open file again print(txt_again.read()) # print file content
587fde4ee945706b5c455880354bb1e9644a526d
mohsenabedelaal/holbertonschool-machine_learning
/supervised_learning/0x01-classification/16-deep_neural_network.py
1,161
3.75
4
#!/usr/bin/env python3 """ Creates a deep neural network. """ import numpy as np class DeepNeuralNetwork: """ Deep neural network class. """ def __init__(self, nx, layers): """ Initializer for the deep neural network. """ if type(nx) != int: raise TypeError('nx must be an integer') if nx < 1: raise ValueError('nx must be a positive integer') if type(layers) != list or not layers: raise TypeError('layers must be a list of positive integers') self.L = 0 self.cache = {} self.weights = {} rand = np.random.randn for idx, neurons in enumerate(layers): if type(neurons) != int or neurons <= 0: raise TypeError('layers must be a list of positive integers') if idx == 0: self.weights['W1'] = rand(neurons, nx) * np.sqrt(2 / nx) else: p = layers[idx - 1] r = rand(neurons, p) self.weights["W{}".format(idx + 1)] = r * np.sqrt(2 / p) self.L += 1 self.weights["b{}".format(idx + 1)] = np.zeros((neurons, 1))
17feb8e9a091840658a624eaa19611f8cb125e9e
gbrosman27/price_comparison
/main.py
1,689
4.03125
4
import tkinter as tk class Item: def __init__(self, name, price, servings): self.name = name self.price = price self.servings = servings def item_count(): items_list = [] items = None while True: answer = input("Would you like to add an item (yes or no)? ").lower() if answer == "yes" or answer == "y": items = add_item_to_list(items_list) elif answer == "no" or answer == "n": print("ok") break else: print("I didn't recognize that.") cost_per_unit(items) def add_item_to_list(items_list): try: name_of_item = input("What is the name of the item? ") price_of_item = float(input("What is the price of the item? (x.xx) ")) servings_of_item = int(input("How many servings are in the item? (x) ")) new_item = Item(name_of_item, price_of_item, servings_of_item) items_list.append(new_item) return items_list except ValueError: print("Enter valid input") def cost_per_unit(item): cost_list = [] for x in item: total = format(x.price / x.servings, ".2f") result = f"The {x.name} cost per serving is: ${total}" cost_list.append(result) gui_kinter(cost_list) def gui_kinter(display_string_list): root = tk.Tk() # loop over the list and convert to string format with new line. convert_list = '\n\n'.join(map(str, display_string_list)) label = tk.Label(root, text=convert_list, fg="blue", font="Arial 16 bold") label.pack(fill=tk.X, padx=10, pady=10) root.mainloop() if __name__ == "__main__": item_count()
542621ac8ccd116be478c05508c1f49749641d0e
AryaAbhishek/Leetcode
/342-PowerOf4.py
607
3.890625
4
class Solution: def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if num & num-1 == 0: # right shift the given value while num>0: if num == 1: return True num >>= 2 # or left shift 1 util equal to given value # temp = 1 # while temp<=num: # if temp == num: # return True # temp <<= 2 return False if __name__ == "__main__": s = Solution() print(s.isPowerOfFour(4))
6a96f50759041c6869698a05409daee254d451ca
endiliey/pysql
/Python/mitx_600/01_basics/pset1/problem3.py
975
4.28125
4
# -*- coding: utf-8 -*- """ Snippets for Problem 3 @author : Endilie Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh n the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print Longest substring in alphabetical order is: abc """ s = 'azcbobobegghakl' temp = s[0] # first letter as first temporary longest = s[0] for i in range(1, len(s)): # if subsequent next letter is inorder, concat it if s[i] >= s[i - 1]: temp = temp + s[i] # if not, restart building with new letter else: temp = s[i] # if temp string is longer than longest, change it if len(temp) > len(longest): longest = temp print("Longest substring in alphabetical order is: " + longest)
d87df89b056028c3db1f7d62789550d4f3612374
ShawnM76/Sprint-Challenge--Data-Structures-Python
/ring_buffer/ring_buffer.py
1,119
3.5625
4
from doubly_linked_list import DoublyLinkedList # Plan # The capacity and storage have to be the same length # whenever the capcity and storage are the same length # replace the new input with the oldest input # this could go like first in first out like a que class RingBuffer: def __init__(self, capacity): self.capacity = capacity self.current = None self.storage = DoublyLinkedList() def append(self, item): if self.capacity == len(self.storage): head = self.storage.head while(self.current is not None): else: self.storage.add_to_head(item) def get(self): # Note: This is the only [] allowed list_buffer_contents = [] current_node = self.storage.head for node in range(self.storage.length): list_buffer_contents.append(current_node.value) return list_buffer_contents # ----------------Stretch Goal------------------- class ArrayRingBuffer: def __init__(self, capacity): pass def append(self, item): pass def get(self): pass
be6879d9edf5259b5da5806fbebba4f41923c36d
RishabhK88/PythonPrograms
/3. ControlFlow/breakS.py
723
4.21875
4
successful = True for number in range(3): print("Attempt") if successful: print("Successfull") break # basically break statement is used to break out of a loop. so is the interpreter # reaches the break statement before loop ends, it will not execute loop any further # instead execute next line of code after loop ends successful = False for number in range(3): print("Attempt") if successful: print("Successfull") break else: print("Attempted 3 times and failed") # the above is a for-else loop. the else statement will be executed only if the loop # is fully executed. if the loop breaks before full execution, else statement is not # executed
65b61271b5058e03768a7c4e912384ce0f66a0a8
hat/leetcode
/april2020_challenge/performStringShifts.py
1,775
4
4
# You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]: # direction can be 0 (for left shift) or 1 (for right shift). # amount is the amount by which string s is to be shifted. # A left shift by 1 means remove the first character of s and append it to the end. # Similarly, a right shift by 1 means remove the last character of s and add it to the beginning. # Return the final string after all operations. # Example 1: # Input: s = "abc", shift = [[0,1],[1,2]] # Output: "cab" # Explanation: # [0,1] means shift to left by 1. "abc" -> "bca" # [1,2] means shift to right by 2. "bca" -> "cab" # Example 2: # Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]] # Output: "efgabcd" # Explanation: # [1,1] means shift to right by 1. "abcdefg" -> "gabcdef" # [1,1] means shift to right by 1. "gabcdef" -> "fgabcde" # [0,2] means shift to left by 2. "fgabcde" -> "abcdefg" # [1,3] means shift to right by 3. "abcdefg" -> "efgabcd" from collections import deque class Solution: def stringShift(self, s: str, shift: [[int]]) -> str: total_left = 0 total_right = 0 shift_right = False for num in shift: if num[0] == 0: total_left += num[1] elif num[0] == 1: total_right += num[1] if total_right > total_left: shift_right = True total_shift = abs(total_left - total_right) d = deque(s) while total_shift > 0: if shift_right: d.rotate(1) else: d.rotate(-1) total_shift -= 1 return ''.join(d) answer = Solution() answer.stringShift("abcdefg", [[1,1],[1,1],[0,2],[1,3]])
eb08f4a3e56585bce0a1029ebdb3da56744a6e26
gabriellaec/desoft-analise-exercicios
/backup/user_026/ch26_2020_04_08_15_07_28_321913.py
341
3.859375
4
valor= int(input("qual o valor da casa a se comprar? ")) salario= int(input("qual o seu salário? ")) quant_meses= int(input("em quantos meses deseja pagar? ")) prest_mensal = valor/quant_meses if prest_mensal<(salario/100)*30: print('Empréstimo aprovado') if prest_mensal>(salario/100)*30: print('Empréstimo não aprovado')
07f32c2e9db5a939cc5f504461d429c0ea3061cb
sunnyyeti/Leetcode-solutions
/974_Subarray_Sums_Divisible_by_K.py
875
3.546875
4
# Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K. # Example 1: # Input: A = [4,5,0,-2,-3,1], K = 5 # Output: 7 # Explanation: There are 7 subarrays with a sum divisible by K = 5: # [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] # Note: # 1 <= A.length <= 30000 # -10000 <= A[i] <= 10000 # 2 <= K <= 10000 class Solution: def subarraysDivByK(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ cnt = {A[0]%K:1} for i in range(1,len(A)): A[i]+=A[i-1] cnt[A[i]%K] = cnt.setdefault(A[i]%K,0)+1 cnt[0] = cnt.setdefault(0,0)+1 res = 0 for key,val in cnt.items(): if val>=2: res+=(val*(val-1))//2 return res
3f31ab4f84c6680f6b6e9ec1d1720552cb135e03
nsreeen/fcc-algorithms-python
/roman.py
1,616
4.09375
4
"""Convert the given number into a roman numeral. All roman numerals answers should be provided in upper-case. Link to Free Code Camp challenge: https://www.freecodecamp.com/challenges/roman-numeral-converter""" #Roman numeral symbols and the amounts they symbolize: symbols = ['M', 'D', 'C', 'L', 'X', 'V', 'I'] amounts = [1000, 500, 100, 50, 10, 5, 1] #Lists for the cases when a smaller number symbol preceeds a larger symbol: to_replace = ['VIIII', 'IIII', 'LXXXX', 'XXXX', 'DCCCC', 'CCCCC'] replace_with = ['IX', 'IV', 'XC', 'XL', 'CM', 'CD'] def convert_to_roman_numeral(num): roman_num = '' """Iterate through the symbols in the list of symbols. If the number to convert is longer than the amount the symbol represents, add the symbol to the roman numeral, and remove the amount it represents from the number.""" for i in range(len(symbols)): while num >= amounts[i]: num = num - amounts[i] roman_num = roman_num + symbols[i] """Iterate through the to_replace list, if an item from the list is present in the roman numeral, replace it with it's equivalent in replace_with.""" for i in range(len(to_replace)): start = roman_num.find(to_replace[i]) if start != -1: end = start + len(to_replace[i]) roman_num = roman_num[:start] + replace_with[i] + roman_num[end:] return roman_num tests = [2, 3, 4, 5, 9, 12, 16, 29, 44, 45, 68, 83, 97, 99, 500, 501, 649, 798, \ 891, 1000, 1004, 1006, 1023, 2014, 3999] for number in tests: print number, convert_to_roman_numeral(number)
3ae37ff5a0ca74679b00af9bdc87845d71a84f85
shreyapattewar1999/Tic-Tac-Toe
/Tic Tac Toe.py
1,838
3.921875
4
board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"] def display_board(board): print() for i in range(0,9,3): print(board[i] + " | " + board[i+1]+ " | " + board[i+2]) print() def check_win(board, char): for i in range(0, 9, 3): if board[i]==char and board[i+1]==char and board[i+2]==char: return True j = 0 while j<3: if board[j]==char and board[j+3]==char and board[j+6]==char: return True j+=1 if board[0] == char and board[4] == char and board[8] == char: return True if board[2] == char and board[4] == char and board[6] == char: return True return False def check_game_over(board): for i in range(len(board)): if board[i] == "-": return False print() print("GRID IS FULL") return True game_over = False turn = "X" while not game_over: display_board(board) if turn == "X": print("Turn - X") else: print("Turn - O") position, char = input("Enter a position and character(X or O) : ").split(" ") position = int(position) position -= 1 if char != turn: print("Its not your turn") continue if position < 0 or position > 8: print("You have entered wrong position number") continue if board[position] != "-": print(f"{position+1} is already filled") print("Please enter right position") continue board[position] = char win = check_win(board, char) if win: game_over = True print("*******************************************************") print(char+" wins") if not game_over: game_over = check_game_over(board) if game_over: print("*********** Game Over *****************") turn = "O" if turn=="X" else "X"
e9f7cd9486d647c51fbf1b7be6c30a62e5025b04
natkam/adventofcode
/2017/aoc_04_passphrase1.py
1,199
3.734375
4
''' --- Day 4: High-Entropy Passphrases --- A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces. To ensure security, a valid passphrase must contain no duplicate words. For example: aa bb cc dd ee is valid. aa bb cc dd aa is not valid - the word aa appears more than once. aa bb cc dd aaa is valid - aa and aaa count as different words. The system's full passphrase list is available as your puzzle input. How many passphrases are valid? [puzzle input: in a separate file, 04_imput.txt ] ''' from collections import Counter f = open('04_input.txt', 'r') def check_validity(passphrase): pass_list = passphrase.split() pass_set = set(pass_list) return len(pass_set) == len(pass_list) def check_validity_file(f): results = [check_validity(line) for line in f] return results def count_valid_phrases(validated_list): c = Counter(validated_list) return c[True] validated_list = check_validity_file(f) truths = count_valid_phrases(validated_list) print('The number of valid passphrases is %s.' % truths)
7d5d945dc46a6d58ae112386ad9e21a43017189d
gwccu/day2-nladino215
/day3problem.py
490
4.1875
4
number=input("input an integer") oddnum=int(0) if(int(number) % 2 == 0): print("even") elif not(int(number) % 2 == 0): print("odd") oddnum += 1 number=input("input an integer") if(int(number) % 2 == 0): print("even") elif not(int(number) % 2 == 0): print("odd") oddnum += 1 number=input("input an integer") if(int(number) % 2 == 0): print("even") elif not(int(number) % 2 == 0): print("odd") oddnum += 1 print(oddnum) print("find out your weirdness") q1
bedcdd0933d56c1af17f851e2c29c7e412118856
tomiriszhashibekova/Web-Dev
/week8/informatics/2959.py
74
3.859375
4
a = int(input()) if a>0:print('1') elif a==0:print ('0') else: print('-1')
4cead64a776f0c55b95106bf605fc88fc2f2287b
versachin/chapter-4
/alannaturtle1011.py
230
3.78125
4
import turtle wn= turtle.Screen() wn.bgcolor("hotpink") alanna=turtle.Turtle() alanna.pensize(3) def draw_poly(turt,num,size): for i in range(num): turt.forward(size) turt.left(360/num) draw_poly(alanna,8,50)
dffee0fcf80a8f8aa5f2e161a8a071479b4b99ac
NataliiaBidak/py-training-hw
/Homework4/dict_task7.py
228
4.03125
4
""" Write a Python program to find all the values in a list are greater than a specified number """ def greater_than(lst:list, number:int): return [x for x in lst if x > number] print(greater_than([34,56,23,1,45,2,3,87],25))
377298f7ec144d74595eb17fff457ebe4e939df1
brian-gpu/assignments
/week1/assignment9/9-exercises.py
1,236
3.734375
4
def format_orders1(orders): order_numbers = list(map(lambda x: x[0], orders)) totals = list(map(lambda x: x[2] * x[3] + ((int(x[2] * x[3]) < 100) * 10), orders)) results = list(map(lambda x, y: (x, round(y,2)), order_numbers, totals)) return results # Assumption: cost update of +10 when under 100, is not requested def format_orders2(orders): order_numbers = list(map(lambda x: x[0], orders)) totals = list(map(lambda x: x[1][1] * x[1][2], orders)) results = list(map(lambda x, y: (x, round(y,2)), order_numbers, totals)) return results orders1 = [ ['Order Number', 'Book Title and Author', 'Quantity', 'Price per Item'], [34587,'Learning Python, Mark Lutz',4,40.95], [98762,'Programming Python, Mark Lutz',5,56.80], [77226,'Head First Python, Paul Barry',3,32.95], [88112,'Einführung in Python3, Bernd Klein',3,24.99]] orders2 = [ ['Order Number', ('Book Title and Author', 'Quantity', 'Price per Item')], [34587,('Learning Python, Mark Lutz',4,40.95)], [98762,('Programming Python, Mark Lutz',5,56.80)], [77226,('Head First Python, Paul Barry',3,32.95)], [88112,('Einführung in Python3, Bernd Klein',3,24.99)]] print("Exercise 1:") print(format_orders1(orders1[1:])) print("Exercise 2:") print(format_orders2(orders2[1:]))
a9abd049379c814c890e5ee622a989673e305b83
ellipsis-tech/Coders-Assembly-Materials
/8A_List_Tuple/Resource/Resource/q4.py
1,090
3.78125
4
def get_cheapest_product(product_list): pass if __name__ == "__main__": print('Test 1') str_list = [('apple', 70), ('orange', 80), ('pear', 60), ('durian', 1000)] result = get_cheapest_product(str_list) print("Expected:pear") print('Actual :' + str(result)) print() print('Test 2: Check data type') str_list = [('apple', 70), ('orange', 80), ('pear', 60), ('durian', 1000)] result = get_cheapest_product(str_list) print("Expected:<class 'str'>") print('Actual :' + str(type(result))) print() print('Test 3') str_list = [('apple', 70), ('orange', 80), ('pear', 60), ('banana', 60)] result = get_cheapest_product(str_list) print("Expected:banana") print('Actual :' + str(result)) print() print('Test 3') str_list = [('apple', 70)] result = get_cheapest_product(str_list) print("Expected:apple") print('Actual :' + str(result)) print() print('Test 4') str_list = [] result = get_cheapest_product(str_list) print("Expected:None") print('Actual :None') print()
6b768ce8ff2c65149ce085cbcaabcaa9d3ee7f74
Valinor13/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
260
3.546875
4
#!/usr/bin/python3 """A module containing a class called MyList""" class MyList(list): """A class that inherits list objects and attributes""" def print_sorted(self): """A function that prints the sorted list""" print(sorted(self))
0374211aa65bf867ae286e02fa60416e3767237d
ekougs/crack-code-interview-python
/ch2/linked_list_duplicates_remover.py
1,314
4.03125
4
""" Implementations relative to ex 2.1 about removal in a linked list """ def remove_duplicates(linked_list): """ Removes duplicates in a linked list :param linked_list: a linked list :return: linked list with unique elements """ unique_elements = [] previous_node = None for current_node in linked_list: if previous_node is not None and current_node.value not in unique_elements: previous_node.next_node = current_node.next_node else: unique_elements.append(current_node.next_node) previous_node = current_node return linked_list def remove_duplicates_no_buff(linked_list): """ Removes duplicates in a linked list with no additional buffer :param linked_list: a linked list :return: linked list with unique elements """ def not_in_list(node): cur_node = linked_list.root while cur_node != node: if cur_node.value == node.value: return True cur_node = cur_node.next_node return False previous_node = None for current_node in linked_list: if previous_node is not None and not_in_list(current_node): previous_node.next_node = current_node.next_node previous_node = current_node return linked_list
2ed7f0cc374f93352b518624847088904a319e60
NoahBarrett98/Learning-on-PatternNet
/models/VAE-PatternNet.py
7,834
3.828125
4
import functools from modules.Loader import * """ Idea use debiased network to learn latent features of the dataset Furthermore maybe we can the same approach used in this lab: Positive and Negative data Use a combination of all other classes as negative dataset Is it feasible to use this debiased system within each sub class? In doing so we will account for biased instances of a given label """ ### Define the CNN model ### n_filters = 12 # base number of convolutional filters '''Function to define a standard CNN model''' def make_standard_classifier(n_outputs=1): Conv2D = functools.partial(tf.keras.layers.Conv2D, padding='same', activation='relu') BatchNormalization = tf.keras.layers.BatchNormalization Flatten = tf.keras.layers.Flatten Dense = functools.partial(tf.keras.layers.Dense, activation='relu') model = tf.keras.Sequential([ Conv2D(filters=1 * n_filters, kernel_size=5, strides=2), BatchNormalization(), Conv2D(filters=2 * n_filters, kernel_size=5, strides=2), BatchNormalization(), Conv2D(filters=4 * n_filters, kernel_size=3, strides=2), BatchNormalization(), Conv2D(filters=6 * n_filters, kernel_size=3, strides=2), BatchNormalization(), Flatten(), Dense(512), Dense(n_outputs, activation=None), ]) return model # Training hyperparameters batch_size = 32 num_epochs = 2 # keep small to run faster learning_rate = 5e-4 optimizer = tf.keras.optimizers.Adam(learning_rate) # define our optimizer @tf.function def standard_train_step(x, y): with tf.GradientTape() as tape: # feed the images into the model logits = standard_classifier(x) # Compute the loss loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits) # Backpropagation grads = tape.gradient(loss, standard_classifier.trainable_variables) optimizer.apply_gradients(zip(grads, standard_classifier.trainable_variables)) return loss # The training loop! #loader must be implemented for epoch in range(num_epochs): for idx in tqdm(range(loader.get_train_size()//batch_size)): # Grab a batch of training data and propagate through the network x, y = loader.get_batch(batch_size) loss = standard_train_step(x, y) # TODO: add tf lost history and plotter standard_classifier = make_standard_classifier() def vae_loss_function(x, x_recon, mu, logsigma, kl_weight=0.0005): # TODO: Define the latent loss. Note this is given in the equation for L_{KL} # in the text block directly above latent_loss = 0.5 * tf.reduce_sum(np.exponent(logsigma) + mu**2 -1 -logsigma) # TODO: Define the reconstruction loss as the mean absolute pixel-wise # difference between the input and reconstruction. Hint: you'll need to # use tf.reduce_mean, and supply an axis argument which specifies which # dimensions to reduce over. For example, reconstruction loss needs to average # over the height, width, and channel image dimensions. # https://www.tensorflow.org/api_docs/python/tf/math/reduce_mean reconstruction_loss = tf.reduce_mean(tf.abs(x - x_recon), axis=(1,2,3)) # TODO: Define the VAE loss. Note this is given in the equation for L_{VAE} # in the text block directly above vae_loss = (kl_weight * latent_loss) + reconstruction_loss return vae_loss def sampling(z_mean, z_logsigma): # By default, random.normal is "standard" (ie. mean=0 and std=1.0) batch, latent_dim = z_mean.shape epsilon = tf.random.normal(shape=(batch, latent_dim)) # TODO: Define the reparameterization computation! # Note the equation is given in the text block immediately above. z = z_mean + tf.math.exp(0.5 * z_logsigma) * epsilon # z = # TODO return z def debiasing_loss_function(x, x_pred, y, y_logit, mu, logsigma): # TODO: call the relevant function to obtain VAE loss vae_loss = vae_loss_function(x, x_pred, mu, logsigma) # vae_loss = vae_loss_function('''TODO''') # TODO # TODO: define the classification loss using sigmoid_cross_entropy # https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits classification_loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=y_logit) # classification_loss = # TODO # Use the training data labels to create variable face_indicator: # indicator that reflects which training data are images of faces face_indicator = tf.cast(tf.equal(y, 1), tf.float32) # TODO: define the DB-VAE total loss! Use tf.reduce_mean to average over all # samples total_loss = tf.reduce_mean( classification_loss + face_indicator * vae_loss ) # total_loss = # TODO return total_loss, classification_loss n_filters = 12 # base number of convolutional filters, same as standard CNN latent_dim = 100 # number of latent variables def decoder_network(): # Functionally define the different layer types we will use Conv2DTranspose = functools.partial(tf.keras.layers.Conv2DTranspose, padding='same', activation='relu') BatchNormalization = tf.keras.layers.BatchNormalization Flatten = tf.keras.layers.Flatten Dense = functools.partial(tf.keras.layers.Dense, activation='relu') Reshape = tf.keras.layers.Reshape # Build the decoder network using the Sequential API decoder = tf.keras.Sequential([ # Transform to pre-convolutional generation Dense(units=4*4*6*n_filters), # 4x4 feature maps (with 6N occurances) Reshape(target_shape=(4, 4, 6*n_filters)), # Upscaling convolutions (inverse of encoder) Conv2DTranspose(filters=4*n_filters, kernel_size=3, strides=2), Conv2DTranspose(filters=2*n_filters, kernel_size=3, strides=2), Conv2DTranspose(filters=1*n_filters, kernel_size=5, strides=2), Conv2DTranspose(filters=3, kernel_size=5, strides=2), ]) return decoder class DB_VAE(tf.keras.Model): def __init__(self, latent_dim): super(DB_VAE, self).__init__() self.latent_dim = latent_dim # Define the number of outputs for the encoder. Recall that we have # `latent_dim` latent variables, as well as a supervised output for the # classification. num_encoder_dims = 2*self.latent_dim + 1 self.encoder = make_standard_classifier(num_encoder_dims) self.decoder = make_face_decoder_network() # function to feed images into encoder, encode the latent space, and output # classification probability def encode(self, x): # encoder output encoder_output = self.encoder(x) # classification prediction y_logit = tf.expand_dims(encoder_output[:, 0], -1) # latent variable distribution parameters z_mean = encoder_output[:, 1:self.latent_dim+1] z_logsigma = encoder_output[:, self.latent_dim+1:] return y_logit, z_mean, z_logsigma # VAE reparameterization: given a mean and logsigma, sample latent variables def reparameterize(self, z_mean, z_logsigma): # TODO: call the sampling function defined above z = sampling(z_mean, z_logsigma) # z = # TODO return z # Decode the latent space and output reconstruction def decode(self, z): # TODO: use the decoder to output the reconstruction reconstruction = self.decoder(z) # reconstruction = # TODO return reconstruction # The call function will be used to pass inputs x through the core VAE def call(self, x): # Encode input to a prediction and latent space y_logit, z_mean, z_logsigma = self.encode(x) # TODO: reparameterization z = self.reparameterize(z_mean, z_logsigma) # z = # TODO # TODO: reconstruction recon = self.decode(z) # recon = # TODO return y_logit, z_mean, z_logsigma, recon # Predict face or not face logit for given input x def predict(self, x): y_logit, z_mean, z_logsigma = self.encode(x) return y_logit dbvae = DB_VAE(latent_dim)
6f9be2c95af1434b5b32960c945d06899851a203
chetanpawar06/python-simple-programs
/assi_Q5_time.py
405
4
4
#Greet the user good morning, good evening, good afternoon depending on the time of the day inside variable hrs input from the user in 24hrs format. time=float(input("Enter Time:--")) if(time<12): print("Good Morning.......!") elif(time<17): print("Good Afternoon.......!!") elif(time<21): print("Good Evening......!!!") else: print("Good Night......!!!!!")
a161928648a8f306193a92f8276332915ca7e4a8
letthink/Machine_learning
/day1.py
4,017
3.734375
4
# coding=utf-8 # Author: Lishiyao # CreatTime: 2021/2/26 20 55 # FileName: day1 # Description: Simple introduction of the code from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer import jieba def datasets_demo(): """ sklearn数据集使用 """ iris = load_iris() print("鸢尾花数据集\n", iris) print("DESCR\n", iris.DESCR) print("name\n", iris["feature_names"]) print("data\n", iris.data) print("shape\n", iris.data.shape) # 数据的划分 x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=22) print("x_train训练集的特征值:\n", x_train) print("x_test:测试集的特征值\n", x_test) print("y_train训练集的目标值\n", y_train) print("y_train测试集的目标值\n", y_test) def dict_demo(): # 字典特征抽取 data = [{'city': '北京', 'temperature': 100}, {'city': '上海', 'temperature': 60}, {'city': '深圳', 'temperature': 30}] # 1.实例化一个转换器类 transfer = DictVectorizer(sparse=False) # 2.调用fit_transform data = transfer.fit_transform(data) print("返回的结果:\n",data) #打印特征名字 print("特征名字:\n",transfer.get_feature_names()) return None def text_count_demo(): #对文本进行特征抽取,countvetorizer data = ["life is short,i like python and like C too", "life is too long,i dislike python"] #1.实例化一个转换器类 transfer = CountVectorizer() #2.调用fit_transform data = transfer.fit_transform(data) print("文本特征抽取结果\n",data.toarray()) #实例的一种格式转换 toarray() print("返回特征名字\n",transfer.get_feature_names()) def cut_word(text): return " ".join(jieba.lcut(text)) # return " ".join(list(jieba.cut(text))) def text_chinese_count_demo(): data = ["一种还是一种今天很残酷,明天更残酷,后天很美好,但绝对大部分是死在明天晚上,所以每个人不要放弃今天。", "我们看到的从很远星系来的光是在几百万年之前发出的,这样当我们看到宇宙时,我们是在看它的过去。", "如果只用一种方式了解某样事物,你就不会真正了解它。了解事物真正含义的秘密取决于如何将其与我们所了解的事物相联系。"] text_list = [] for i in data: text_list.append(cut_word(i)) #1.实例化转化器类 transfer = CountVectorizer() # print(text_list,"text.list测试") #2.调用fit_transform data = transfer.fit_transform(text_list) #注意变量的选择 data是还未处理过的数据 print("特征值:\n",data.toarray()) print("名称:\n",transfer.get_feature_names()) if __name__ == '__main__': print("测试开始") #第一部分:sklearn数据集的使用 # datasets_demo() #第二部分:字典的特征抽取 # dict_demo() #第三部分:文本的特征抽取 # text_count_demo() #第四五六部分,中文文本特征抽取(自动分词) # print(cut_word("人生苦短,我学python")) text_chinese_count_demo() #jieba断词测试 # data = ["一种还是一种今天很残酷,明天更残酷,后天很美好,但绝对大部分是死在明天晚上,所以每个人不要放弃今天。", # "我们看到的从很远星系来的光是在几百万年之前发出的,这样当我们看到宇宙时,我们是在看它的过去。", # "如果只用一种方式了解某样事物,你就不会真正了解它。了解事物真正含义的秘密取决于如何将其与我们所了解的事物相联系。"] # tmp_list = [] # for i in data: # print(cut_word(i)) # tmp_list.append(cut_word(i)) # print(tmp_list)
7cf7672458d54993a4e5a0ed7b53f6a66af80712
abobeng/Chapter-2
/ques11.py
133
3.78125
4
for i in range(1): print ('*' *10) for i in range(2): print ('*', ' '*6, '*') for i in range(1): print('*' * 10)
f076462db30c2fcb14096b9ed1d46979d8852da7
usedvscode0/01_W3Cschool_python
/scr/py18_Exception00.py
9,165
4.21875
4
# coding=utf-8 ''' Python3 错误和异常 Python 错误和异常 作为Python初学者,在刚学习Python编程时,经常会看到一些报错信息,在前面我们没有提及,这章节我们会专门介绍。 Python有两种错误很容易辨认:语法错误和异常。 语法错误 Python 的语法错误或者称之为解析错,是初学者经常碰到的,如下实例 >>> while True print('Hello world') File "<stdin>", line 1, in ? while True print('Hello world') ^ SyntaxError: invalid syntax 这个例子中,函数 print() 被检查到有错误,是它前面缺少了一个冒号(:)。 语法分析器指出了出错的一行,并且在最先找到的错误的位置标记了一个小小的箭头。 异常 即便Python程序的语法是正确的,在运行它的时候,也有可能发生错误。运行期检测到的错误被称为异常。 大多数的异常都不会被程序处理,都以错误信息的形式展现在这里: >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: Can't convert 'int' object to str implicitly 异常以不同的类型出现,这些类型都作为信息的一部分打印出来: 例子中的类型有 ZeroDivisionError,NameError 和 TypeError。 错误信息的前面部分显示了异常发生的上下文,并以调用栈的形式显示具体信息。 异常处理 以下例子中,让用户输入一个合法的整数,但是允许用户中断这个程序(使用 Control-C 或者操作系统提供的方法)。用户中断的信息会引发一个 KeyboardInterrupt 异常。 >>> while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again ") try语句按照如下方式工作; 首先,执行try子句(在关键字try和关键字except之间的语句) 如果没有异常发生,忽略except子句,try子句执行后结束。 如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。 如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。 一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。 处理程序将只针对对应的try子句中的异常进行处理,而不是其他的 try 的处理程序中的异常。 一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组,例如: except (RuntimeError, TypeError, NameError): pass 最后一个except子句可以忽略异常的名称,它将被当作通配符使用。你可以使用这种方法打印一个错误信息,然后再次把异常抛出。 import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error: {0}".format(err)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise try except 语句还有一个可选的else子句,如果使用这个子句,那么必须放在所有的except子句之后。这个子句将在try子句没有发生任何异常的时候执行。例如: for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') f.close() 使用 else 子句比把所有的语句都放在 try 子句里面要好,这样可以避免一些意想不到的、而except又没有捕获的异常。 异常处理并不仅仅处理那些直接发生在try子句中的异常,而且还能处理子句中调用的函数(甚至间接调用的函数)里抛出的异常。例如: >>> def this_fails(): x = 1/0 >>> try: this_fails() except ZeroDivisionError as err: print('Handling run-time error:', err) Handling run-time error: int division or modulo by zero 抛出异常 Python 使用 raise 语句抛出一个指定的异常。例如: >>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)。 如果你只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出。 >>> try: raise NameError('HiThere') except NameError: print('An exception flew by!') raise An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in ? NameError: HiThere 用户自定义异常 你可以通过创建一个新的exception类来拥有自己的异常。异常应该继承自 Exception 类,或者直接继承,或者间接继承,例如: >>> class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) >>> try: raise MyError(2*2) except MyError as e: print('My exception occurred, value:', e.value) My exception occurred, value: 4 >>> raise MyError('oops!') Traceback (most recent call last): File "<stdin>", line 1, in ? __main__.MyError: 'oops!' 在这个例子中,类 Exception 默认的 __init__() 被覆盖。 异常的类可以像其他的类一样做任何事情,但是通常都会比较简单,只提供一些错误相关的属性,并且允许处理异常的代码方便的获取这些信息。 当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类: class Error(Exception): """Base class for exceptions in this module.""" pass class InputError(Error): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """ def __init__(self, expression, message): self.expression = expression self.message = message class TransitionError(Error): """Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """ def __init__(self, previous, next, message): self.previous = previous self.next = next self.message = message 大多数的异常的名字都以"Error"结尾,就跟标准的异常命名一样。 定义清理行为 try 语句还有另外一个可选的子句,它定义了无论在任何情况下都会执行的清理行为。 例如: >>> try: raise KeyboardInterrupt finally: print('Goodbye, world!') Goodbye, world! KeyboardInterrupt 以上例子不管try子句里面有没有发生异常,finally子句都会执行。 如果一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后再次被抛出。 下面是一个更加复杂的例子(在同一个 try 语句里包含 except 和 finally 子句): >>> def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is", result) finally: print("executing finally clause") >>> divide(2, 1) result is 2.0 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >>> divide("2", "1") executing finally clause Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str' 预定义的清理行为 一些对象定义了标准的清理行为,无论系统是否成功的使用了它,一旦不需要它了,那么这个标准的清理行为就会执行。 这面这个例子展示了尝试打开一个文件,然后把内容打印到屏幕上: for line in open("myfile.txt"): print(line, end="") 以上这段代码的问题是,当执行完毕后,文件会保持打开状态,并没有被关闭。 关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法: with open("myfile.txt") as f: for line in f: print(line, end="") 以上这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭。 '''
3da8fe99f158a473c65fcc587466b281da170f87
vmchenni/PythonTest
/Module -2 Case Study-1 Assignment 14.py
517
3.8125
4
# 14.Write a program to compute 1/2+2/3+3/4+...+n/n+1 # with a given n input by console (n>0). # Example:If the following n is given as input to the program:5 # Then, the output of the program should be:3.55 print("Enter a number :-") iNumber=5 iSum = 0.00 iIndex=1 iFirstNumber=1 iSecondNumber=2 while iIndex <= iNumber: iValue = iFirstNumber / iSecondNumber iSum=iValue+iSum iFirstNumber=iSecondNumber iSecondNumber=iSecondNumber+1 iIndex=iIndex+1 print("Value of sum is :-", iSum)
114c83117319140af60ee6b10d7e4aff00ce11cc
studybar-ykx/python
/实验一.py
1,919
3.890625
4
import time import numpy def insertion_sort(arr): #插入排序 # 第一层for表示循环插入的遍数 for i in range(1, len(arr)): # 设置当前需要插入的元素 current = arr[i] # 与当前元素比较的比较元素 pre_index = i - 1 while pre_index >= 0 and arr[pre_index] > current: # 当比较元素大于当前元素则把比较元素后移 temp=arr[pre_index] arr[pre_index + 1] = temp # 往前选择下一个比较元素 pre_index -= 1 # 当比较元素小于当前元素,则将当前元素插入在 其后面 arr[pre_index + 1] = current return arr def quicksort(arr): if len(arr) < 2: # 基线条件:为空或只包含一个元素的数组是“有序”的 return arr else: # 递归条件 pivot = arr[0] # 由所有小于基准值的元素组成的子数组 less = [i for i in arr[1:] if i <= pivot] # 由所有大于基准值的元素组成的子数组 greater = [i for i in arr[1:] if i > pivot] return quicksort(less) + [pivot] + quicksort(greater) def bubble_sort(arr): #冒泡排序 # 第一层for表示循环的遍数 for i in range(len(arr) - 1): # 第二层for表示具体比较哪两个元素 for j in range(len(arr) - 1 - i): if arr[j] > arr[j + 1]: # 如果前面的大于后面的,则交换这两个元素的位置 arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr arr1=input('请输入:') arr1 = [int(c) for c in arr1] start = time.clock() print(insertion_sort(arr1)) end1 = time.clock() print('插入排序时间为%s毫秒'%(end1-start)) print(quicksort(arr1)) end2 = time.clock() print('快速排序时间为%s毫秒'%(end2-end1)) print(bubble_sort(arr1)) end3 = time.clock() print('冒泡排序时间为%s毫秒'%(end3-end2))
af808437742d411432faaa1792ac286bb4c700c2
Rudresh-sisode/Python_machin_with_pandas
/FirstAt.py
262
3.8125
4
#What are the top 10 zipcode for 911, are zipcodes 19446 and 19090 present? import pandas as pd df=pd.read_csv('911.csv') p=df['zip'].value_counts().head(10); print(p) if all((any(df['zip']==19446),any(df['zip']==19090))): print('yes') else: print('no')
824efd56ca8b845d72cd42014073307ec9bd822d
Saacman/image_processing
/pyramids.py
386
3.671875
4
import cv2 as cv import numpy as np image = cv.imread("images/input.png") smaller = cv.pyrDown(image) larger = cv.pyrUp(image) # Retorna una imagen del size original, pero tiene perdida de calidad cv.imshow("Original", image) cv.imshow("Smaller", smaller) cv.imshow("Larger", larger) cv.waitKey() cv.destroyAllWindows() # Se puede usar en un loop para obtener imagenes mas reducidas.
0d00bac7f0ac1b2d188209044295891f1451c117
SeanMcP/rimoria
/utils/print.py
3,448
3.84375
4
def new_line(string): print(f''' {string}''') def new_line_input(string): return str(input(f''' {string} >> ''')) def print_logo(): print(''' ***** *** ****** * ** * * ** * * ** *** *** * * * ** * * * * * **** *** **** ** ** * *** *** **** **** * *** * **** **** * *** **** ** ** * *** *** **** *** * * **** ** **** *** * *** * ** **** ** ** **** **** ** ** ** ** * **** ** ** *** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * ** ** ** ** ** ** ** ** ** ** ** ** * ** ** ** ** ** ** ** ** ** ** ** **** *** ** ** ** ** ****** *** ** ** ** * **** ** *** * *** *** *** **** *** *** * ***** ** * ** * *** *** *** *** *** *** ** * ** A text-based adventure game in Python ''') def print_map(current_location, world_map, animals): # Must be odd map_width, map_height = 9, 7 row = build_map_divider(map_width) output = '\n' output += row location = current_location.split(',') x, y = int(location[0]), int(location[1]) map_x = x - (map_width // 2) map_y = y + (map_height // 2) for ly in range(map_height): for lx in range(map_width): coordinates = f'{map_x + lx},{map_y - ly}' output += '┆ ' if coordinates in world_map: if coordinates == current_location: # X marks the spot output += '★' else: # Returns first letter of terrain type output += world_map[coordinates].type[0].upper() else: # Blank if undiscovered output += ' ' if coordinates == '0,0': # Trailing asterisk if origin output += '°' elif coordinates in animals and animals[coordinates]: # Trailing dagger if animal output += '‡' else: # Trailing blank for spacing output += ' ' output += f'┆\n{row}' output += ''' ↑ N Key: ★ - Current location A - Terrain type - Undiscovered terrain ° - Origin (0,0) ‡ - Location with animal''' return print(output) def build_map_divider(width): output = ' ' for _ in range(width): output += '--- ' if _ == width - 1: output += '\n' return output def gameover_results(player, map): score = player.level * 1000 + len(map) * 100 print(f''' GAME OVER Explorer name: {player.name} Final level: {player.level} Terrains explored: {len(map)} FINAL SCORE: {score} ''')
9c7ef85640a4722242bfeb68dc6852705e4317ba
javpelle/ComputerGeometry
/scprits .py/k-NN.py
6,378
3.609375
4
import numpy as np import matplotlib.pyplot as plt from scipy.stats import mode from sklearn.model_selection import train_test_split class kNN: ''' k-nearest neighbors classification algorithm class. ---------- Attributes ---------- - k: number of nearest neighbors to be considered. Default value is 1. - norm: Function. Vector Space Norm. Default value is euclidean norm (numpy.linalg.norm). - data_X: Data Matrix training set. - data_y: Vector of classes. data_X[i,:] class is data_y[i]. ''' def __init__(self, k = 1, norm = np.linalg.norm): self.k = k self.norm = norm def fit(self, data_X, data_y): ''' Fit function, just save training set. ---------- Paramaters ---------- - data_X: Data Matrix training set. - data_y: Vector of classes. data_X[i,:] class is data_y[i]. ''' self.data_X = data_X self.data_y = data_y def predict(self, test_X): ''' Predict function, executes kNN algorithm. ---------- Paramaters ---------- - test_X: Data Matrix. Function will predict the class for each data test_X[i,:]. ------ Return ------ - test_y: Vector of classes. test_X[i,:] class is test_y[i]. ''' len_test_X = test_X.shape[0] distances = [] test_y = [] for x in self.data_X: ''' For each data in training set, it calculates the distance between its and each test data. ''' distances.append(self.norm(test_X - x, axis = 1)) distances = np.array(distances) for i in range (0, len_test_X): ''' For each test data, it calculates k nearest neighbors index, and assings most frequently class. ''' idx = np.argsort(distances[:,i]) ''' Reorder tags according to the previous order of distances to train_X''' closestTags = np.array(self.data_y)[idx] closestTags = closestTags[:self.k] test_y_mode, _ = mode(closestTags) test_y.append(test_y_mode[0]) return np.array(test_y) def predict_proba(self, test_X): ''' Predict_proba function, execute kNN algorithm. ---------- Paramaters ---------- - test_X: Data Matrix. Function will predict the class for each data test_X[i,:]. ------ Return ------ - test_y: list of lists of pairs (probabilty, class) ''' len_test_X = test_X.shape[0] distances = [] test_y = [] for x in self.data_X: ''' For each data in training set, it calculates the distance between its and each test data. ''' distances.append(self.norm(test_X - x, axis = 1)) distances = np.array(distances) for i in range (0, len_test_X): ''' For each test data, it calculates k nearest neighbors index, and assings probabilties based on frequency of each class. ''' idx = np.argsort(distances[:,i]) closestTags = np.array(self.data_y)[idx] closestTags = closestTags[0:self.k] test_y_mode = [(closestTags.tolist().count(j) / self.k, j) for j in set(closestTags)] test_y.append(test_y_mode) return test_y def clusterPlot(clusters, x, y): ''' Draw all members of a cluster list and centroids ---------- Paramaters ---------- - clusters: Clusters list and each cluster is a data Matrix of points - x: coordinate x in graphic. - y: coordinate y in graphic. ''' for cluster in clusters: plt.plot(cluster[:,x], cluster[:,y], 'o') plt.show() def create_2d_data(K, sigma_class=10, sigma=0.5, min_num=10, max_num=20): '''Creates some random 2D data for testing. Return points X belonging to K classes given by tags. Args: K: number of classes sigma_class: measures how sparse are the classes sigma: measures how clustered around its mean are the points of each class min_num, max_num: minimum and maximum number of points of each class Returns: X: (N, 2) array of points tags: list of tags [k0, k1, ..., kN] ''' tags = [] N_class_list = [] mu_list = [] mu_list = [np.random.randn(2)*sigma_class] for k in range(1, K): try_mu = np.random.randn(2)*sigma_class while min([np.linalg.norm(mu - try_mu) for mu in mu_list]) < 2*sigma_class: try_mu = np.random.randn(2)*sigma_class mu_list.append(try_mu) for k in range(K): N_class = np.random.randint(min_num, max_num) tags += [k] * N_class N_class_list += [N_class] N = sum(N_class_list) X = np.zeros((2, N)) count = 0 for k in range(K): X[:, count:count + N_class_list[k]] = \ mu_list[k][:, np.newaxis] + np.random.randn(2, N_class_list[k])*sigma count += N_class_list[k] return X.T, tags if __name__ == '__main__': K = 5 X, y = create_2d_data(K, sigma = 5) train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.5) model = kNN(3) model.fit(train_X, train_y) pred_y = model.predict(test_X) classes_set = list(set(pred_y)) clusters = [[] for i in classes_set] # If i-data has class j, introduces it in cluster j for i in range(0, len(pred_y)): clusters[classes_set.index(pred_y[i])].append(test_X[i]) clusters = [np.array(c) for c in clusters] clusterPlot(clusters,0,1) classes_set = list(set(test_y)) clusters = [[] for i in classes_set] # If i-data has class j, introduces it in cluster j for i in range(0, len(test_y)): clusters[classes_set.index(test_y[i])].append(test_X[i]) clusters = [np.array(c) for c in clusters] clusterPlot(clusters,0,1) print('Accuracy: ', np.round(np.mean(pred_y == test_y)*100, 2),'%')
bec7494df37f5f79019c3a8963d47b1da2f051b6
seabravitor/Phyton_100_Exercises
/Exercicios/ex 57.py
213
4.03125
4
sexo = str(input('Escolha um sexo [M/F]: ')).strip().upper()[0] while sexo not in 'MF': sexo = str(input('Sexo Inválido. Por favor, escolha um sexo [M/F]:')).strip().upper()[0] print('Cadastrado com Sucesso')
03e1d6d47f021a7ac6673f0dd0ef0d9588a6f0f7
huojinhui/PycharmProjects
/初级python/8.16作业回顾/if语句.py
3,641
3.890625
4
# 0. # 实现简易计算器功能, 如图 # a = int(input("请输入第一个数:")) # b = int(input("请输入第二个数:")) # c = input("请输入需要做的运算符(+ - * /):") # if c == '+' or c == '': # print('结果为:', end='') # print(a + b) # if c == '-': # print('结果为:', end='') # print(a - b) # if c == '*': # print('结果为:', end='') # print(a * b) # if c == '/': # print('结果为:', end='') # print(a / b) # 1. # 让用户输入两个任意的整数, 比较两个数的大小, 输出最大的数 # a, b = int(input('请输入第一个数:')), int(input('请输入第二个数:')) # if a > b: # print('较大的数为:', end='') # print(a) # else: # print('较大的数为:', end='') # print(b) # 2. # 用户输入一个数, 打印出奇数还是偶数 # while True: # a = input("请输入一个数:") # if a == 'q': # print('退出') # break # if int(a) % 2 == 0: # print('此数为偶数.') # if int(a) % 2 != 0: # print('此数为奇数.') # 3. # 用户输入帐号密码, 帐号为admin, 密码为8888显示登录成功, 其余的显示登录失败 # while True: # account_number = input('请输入账号:') # pass_word = input('请输入密码:') # if account_number == 'admin' and pass_word == '8888': # print('登陆成功') # break # else: # print('登陆失败') # 4. # 用户输入一个数, 输出结果是否为水仙花数(水仙花数: 水仙花数是指一个 # 位数,它的每个位上的数字的 # 3 # 次幂之和等于它本身(例如:1 ^ 3 + 5 ^ 3 + 3 ^ 3 = 153)。) # number = input('请输入一个数:') # sum = 0 # for i in range(len(number)): # sum += int(number[i]) ** 3 # if number == sum: # print('是水仙花数') # else: # print('不是水仙花数') # 5. # 用户输入年份, 输出结果是闰年还是平年(闰年: 1. # 能整除4且不能整除100 # 2. # 能整除400) # year = int(input('输入年份:')) # if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: # print('闰年') # else: # print('平年') # 6. # 输入公交卡当前的余额, 空座位数,只要超过2元,就可以上公交车; # 没钱, 撵走;如果空座位的数量大于0,就可以坐下; # 7. # 成绩等级: # 90 # 分以上: 等级为A # # 80 - 90: 等级为B # # 60 - 80: 等级C # # 0 - 60: 等级为D # # 8. # 场景应用: 上火车(用户输入表示是否有票, 是否有刀具) # 是否有票, 有票打印可以进站; # 进站查看是否带有刀具, 有刀具, 没收上车, 没有刀具, 直接上车 # 没票打印不可以进站 # # 9. # 女友的节日: # 定义holiday_name字符串变量记录节日名称 # 如果是 # 情人节 # 应该 # 买玫瑰/看电影 # 如果是 # 平安夜 # 应该 # 买苹果/吃大餐 # 如果是 # 生日 # 应该 # 买蛋糕 # 其他的时候, 每天都是节日 # 10. # 英雄联盟(LOL) # 李青技能: # q, Q: 天音波 # w, W: 金钟罩 / 铁布衫 # e, E: 天雷破 / 摧筋断骨 # r, R: 猛龙摆尾 # # 11. # 用户决定是否发工资, 工资数是多少, 信用卡欠款; # 有剩余的时候, 显示剩余金额(图1) # # 12. # 让用户输入三个任意的整数, 比较三个数的大小, 输出最大的数 # a, b, c = int(input('请输入第一个数:')), int(input('请输入第二个数:')), int(input('请输入第三个数:')) # if a > b > c or a > c > b: # print('最大值为%s' %(a)) # if b > c > a or b > a > c: # print('最大值为%s' %(b)) # if c > a > b or c > b > a: # print('最大值为%s' %(c))
35df659196c329959d5b5e3b9748389cec1edb27
AngheloAlf/Programacion-CIAC-2019
/intensivos S2/Fase 1/11/Code/funciones_auxiliares.py
3,103
3.578125
4
# Recibe una tupla de 3 enteros (ANNO, MES, DIA) # Retorna un string con formato de fecha "ANNO-MES-DIA" def tupla_a_fecha(tupla): lista = map(str, tupla) return "-".join(lista) # Recibe un string con formato de fecha "ANNO-MES-DIA" # Retorna una tupla de 3 enteros (ANNO, MES, DIA) def fecha_a_tupla(fecha): fecha = fecha.split("-") return (int(fecha[0]), int(fecha[1]), int(fecha[2])) # Recibe arch usuarios y nombre de un usuario. # Si el usuario existe, retorna el id asociado como string. # Si no existe, retorna None. def obtener_id_usuario(archUsers, username): ide = None primera = True arch = open(archUsers) for linea in arch: if primera: primera = False else: user_id, nombre, _, _, _ = linea.strip().split(",") if nombre == username: ide = user_id arch.close() return ide # Recibe el nombre de un archivo csv. # Retorna el id mas grande que contiene el archivo. def obtener_ultimo_id(archivo): ultimo = 0 primera = True arch = open(archivo) for linea in arch: if primera: primera = False else: datos = linea.strip().split(",") # El id siempre es el primer elemento de cada fila. ide = int(datos[0]) if ide > ultimo: ultimo = ide arch.close() return ultimo # Recibe el nombre de un csv y un id. # Retorna una lista de strings, la cual corresponde al id entregado. # Si no se encuentra el id en el archivo, retorna None. def obtener_datos_por_id(archivo, ide): datos_buscados = None primera = True arch = open(archivo) for linea in arch: if primera: primera = False else: datos = linea.strip().split(",") if datos[0] == ide: datos_buscados = datos arch.close() return datos_buscados # Recibe el archivo de posts y el id de un usuario. # Retorna una lista que contiene los posts realizados por dicho usuario. # Cada uno de los posts son listas de strings. def obtener_posts_de_usuario(archPosts, user_id): lista = list() primera = True arch = open(archPosts) for linea in arch: if primera: primera = False else: datos = linea.strip().split(",") if user_id == datos[3]: lista.append(datos) arch.close() return lista # Recibe el archivo de comentarios y el id de un usuario. # Retorna una lista que contiene los comentarios realizados por dicho usuario. # Cada uno de los comentarios son listas de strings. def obtener_comentarios_de_usuario(archComs, user_id): lista = list() primera = True arch = open(archComs) for linea in arch: if primera: primera = False else: datos = linea.strip().split(",") if user_id == datos[2]: lista.append(datos) arch.close() return lista
b273d3ccb1ed6b17d88a759f73f5f6313910c42d
DanCordova/Mision-04
/Triangulo.py
1,086
4.28125
4
#Autor Daniel Cordova Bermudez #Grupo 02 #Descripcion: El programa determina el tipo de triangulo con los datos de los lados. #Funacion tipoTriangulo compara la información de los lados para ver si es correcta, en ese caso ve que tipo de triangulo es según los ángulos- def tipoTriangulo(a, b, c): if (a > 0) and (b > 0) and (c > 0): if a == b == c: return "Los lados corresponden a un triángulo equilatero" if c != a != b != c: return "Los lados corresponden a un triángulo rectangúlo" if a == b != c or a != b == c or b != c == a: return "Los lados corresponden a un triángulo isósceles" else: return "Estos lados no corresponden a un triángulo" #Función principal que pide los datos e los lados e imprime el resultado del tipo de triangulo. def main(): lado1 = int(input("Primer lado del triangulo: ")) lado2 = int(input("Segundo lado del triangulo: ")) lado3 = int(input("Tercer lado del triangulo: ")) resultado = tipoTriangulo(lado1,lado2,lado3) print(resultado) main()
004dc77972dcd05d645ea90472b982e82835f133
shashank1094/pythonTutorials
/tutorials/iteratorTut.py
743
3.8125
4
class zrange: def __init__(self, n): self.n = n def __iter__(self): return zrange_iter(self.n) class zrange_iter: def __init__(self, n): self.i = 0 self.n = n def __iter__(self): # Iterators are iterables too. # Adding this functions to make them so. # Removing this function makes the class just an iterator and not iterable. return self def __next__(self): if self.i < self.n: i = self.i self.i += 1 return i else: raise StopIteration() z = zrange(5) print(z) print(list(z)) print(list(z)) z = zrange_iter(5) print(z) print(list(z)) print(list(z))
0b45fefcbd606b653a2752d99478cf241bbe59f9
RafaelLua13/Grafico-sem-Imports
/Gráfico Oficial.py
3,753
4.0625
4
# Nome do projeto: Gráfico de Barras sem imports # Linguagem: Python # Utilizações: Variáveis, Repetições, Listas e Funções # Autor: Rafael Lua de Sousa e Silva - rafaellua13 print('\033c') # Comando para limpar terminal nam = [] # Lista Nomes tam = [] # Lista Tamanhos lista = [] # Armazenar valores da coluna finalAlfabeto = [] # Lista final de alfabetos numeros = ['1','2','3','4','5','6','7','8','9','0'] alfabeto = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] def nomes_tamanhos(quantidade): for aaa in range(1,quantidade + 1): print() test = False nome = input('Nome da coluna {}: '.format(aaa)) nam.append(nome) while True: tamanho = input('Tamanho da coluna {}: '.format(aaa)) for kar in range(len(tamanho)): if tamanho[kar] in numeros: tamanho = int(tamanho) tam.append(tamanho) test = True break else: print('Formato Invalido, digite um numero inteiro') if test == True: break print('\n\n\n') return tam def numeros_eixoY(tam,quantidade): # Numeros eixo y vazio = ' ' maior = max(tam) vetor = [vazio] * len(tam) * maior * 2 linha = (quantidade * 2) # Tamanho da linha voz = 0 care = 0 for b in range(maior): if maior - voz < 10: # vetor[care] = ' ' + str(maior - voz) vetor[care] = maior - voz else: vetor[care] = maior - voz # Somar +1 no care para mudar a coluna voz += 1 care += linha return vetor def adicionando_grafico(tam,vetor,quantidade): # Preenchendo o grafico lista = [] care = 0 nan = 1 maior = max(tam) marca = '■' linha = (quantidade * 2) # Tamanho da linha # ■ - quadrado -> Alt + 254 for i in range(len(tam)): for k in range(tam[i]): lista.append(tam[i]) # print(lista) # lista auxiliar com os valores da coluna care = 0 for b in range(maior): if vetor[care] <= lista[0]: vetor[care + nan] = marca if care + linha < len(vetor): care += linha # Mudar de linha elif vetor[care] > lista[0]: if care + linha < len(vetor): care += linha # Mudar de linha # print(vetor) nan += 2 # Mudar de coluna lista = [] return vetor def arrumando(tam,vetor,quantidade): # Arrumando a formatação do grafico nos numeros menores que 10 # Numeros eixo y em str voz = 0 care = 0 maior = max(tam) linha = (quantidade * 2) # Tamanho da linha for b in range(maior): if maior - voz < 10: vetor[care] = ' ' + str(maior - voz) # Em string para arrumar a formatação do grafico else: vetor[care] = maior - voz # Somar +1 no care para mudar a coluna voz += 1 care += linha return vetor def esqueleto(vetor,quantidade): # Esqueleto Gráfico linha = (quantidade * 2) # Tamanho da linha cont = 0 for x in range(len(vetor)): print(vetor[x], end = ' ') cont += 1 if cont == linha: print() cont = 0 def nomes_eixoX(nam): # Nomes A B C for z in range(len(nam)): if z == 0: print(' ',end = '') print(alfabeto[z], end = ' ') finalAlfabeto.append(alfabeto[z]) print('\n\n\n') for w in range(len(nam)): print(finalAlfabeto[w],'=',nam[w]) print('\n') def grafCalc(quantidade): tam = nomes_tamanhos(quantidade) vetor = numeros_eixoY(tam,quantidade) adicionando_grafico(tam,vetor,quantidade) vetor = arrumando(tam,vetor,quantidade) esqueleto(vetor,quantidade) nomes_eixoX(nam) def main(): # Inicio do programa quantidade = int(input('Quantidade de Colunas: ')) grafCalc(quantidade) ######################## main()
db49014754853f641242055f53d106359bce161a
dmosyan/CodeSignal_tasks_C-sharp
/Python/Slithering_in_Strings/New_Style_Formatting/New_Stle_Formatting.py
287
3.59375
4
def newStyleFormatting(s): #The re.sub() function in the re module can be used to replace substrings. #The syntax for re.sub() is re.sub(pattern,repl,string). s = re.sub("%%", "{%}", s) s = re.sub("%[sfFeEGgnNxXoOdDcCbB]", "{}", s) return re.sub("{%}", "%", s)
34e7983b5ca95bc9ef3fe8655f19c26fd595d903
aprilxyc/coding-interview-practice
/leetcode-problems/108-sorted-array-to-bst.py
752
3.859375
4
""" Given an array where elements are sorted in ascending order, convert it to a height balanced BST. """ # go over this and study it # there is also a slicing method that takes up a lot more memory class Solution: def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ return self.helper(nums, 0, len(nums) - 1) def helper(self, nums, low, high): if low > high: return None mid = (low + high) // 2 # this should be left + (right - left) / 2 to account for very large numbers root = TreeNode(nums[mid]) root.left = self.helper(nums, low, mid - 1) root.right = self.helper(nums, mid + 1, high) return root
1463f38f1901d1cd6b00eb2e7839e8067864c141
bocato/ori_lista_1-27-03-2018
/ex1.py
1,348
4.1875
4
# Questão 1: Faça um programa em Python que leia uma string e conte: # • o número de caracteres alfabéticos; # • o número de caracteres numéricos; # • o número de caracteres não alfabéticos; # • o número de palavras (assuma que entra cada par de palavras existe ao menos um caracter de espaço, tabulação ou "/n"); # • o número de consoantes. # Functions def countLettersFrom(string): letters = 0 for letter in string: letters += letter.isalpha() return letters def countNumbersFrom(string): numbers = 0 for letter in string: numbers += letter.isdigit() return numbers def countNonAlphasFrom(string): alphas = 0 for letter in string: alphas += not(letter.isalpha()) return alphas def countWordsFrom(string): return len(string.split()) def countConsonantsFrom(string): consonants = 0 for character in string: consonants += not(character in ('a', 'e', 'i', 'o', 'u')) return consonants # Input stringInput = input("Give me the input:\n") print("Letters = %s" %(countLettersFrom(stringInput))) print("Numbers = %s" %(countNumbersFrom(stringInput))) print("NonAlphas = %s" %(countNonAlphasFrom(stringInput))) print("Words = %s" %(countWordsFrom(stringInput))) print("Consonants = %s" %(countConsonantsFrom(stringInput)))
e159fc27457340ab6e95e715282624e958066faf
EdwinTinoco/Python-Course
/Numbers/pemdas.py
267
3.515625
4
""" # P parans() # E exponents ** # M multiplication * # D division / # A addition + # S sustraction - 8 + 2 * 5 - (9 + 2) ** 2 8 + 2 * 5 - (11) ** 2 8 + 2 * 5 - 121 8 + 10 - 121 18-121 -103 """ calculation = 8 + 2 * 5 - (9 + 2) ** 2 print(calculation)
60b84474b4de681e99e5718d268ae6c663328286
saqibns/CodeVita
/codesprint/bigger_is_greater.py
944
3.53125
4
def main(tests): for dummy in range(tests): s = input() if invariant(s): print('no answer') else: work_horse(s) def work_horse(string): chars = list(string) # print(chars) idx = len(chars) - 2 last = ord(chars[-1]) flag = False while idx >= 0: if ord(chars[idx]) < last: #flag = True break idx -= 1 #if flag: temp = chars[-1] chars[-1] = chars[idx] chars[idx] = temp new_list = chars[idx + 1:] s = sorted(new_list) start = 0 while start <= idx: print(chars[start], end = '') start += 1 for char in s: print(char, end = '') ## else: ## print('no answer', end = '') print() def invariant(x): i = 0 while i < len(x) - 1: if x[i] < x[i + 1]: return False i += 1 return True tsts = int(input()) main(tsts)
cdc0ecbef646f9c1f899cce7f9af673396997dbd
scMarth/Learning
/Leetcode/3_longest_substring_without_repeating_chars.py
1,101
3.5
4
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ print("input: " + s) longest_substring = "" start = 0 while start <= len(s) - 1: curr_char = s[start] char_hash = {} char_hash[curr_char] = True end = start + 1 while end <= len(s) - 1: if s[end] in char_hash: break else: char_hash[s[end]] = True end += 1 print(s[start:end]) print("\tstart: " + str(start)) print("\tend: " + str(end)) if s[end - 1] == s[end]: start = end - 1 else: start = end sol = Solution() print(sol.lengthOfLongestSubstring("abcabcbb")) print("") print(sol.lengthOfLongestSubstring("bbbbb")) print("") print(sol.lengthOfLongestSubstring("pwwkew")) print("") print(sol.lengthOfLongestSubstring("auuwx")) print("") print(sol.lengthOfLongestSubstring("dvdf"))
ca30243187cd23e0ee773971f9c5f740f0202a2d
xuejiangao1/git-test
/test4.py
1,124
4.03125
4
class Employee: '所有员工的基类' empCount = 0 def __init__(self, name, salary,age): self.name = name self.salary = salary self.age = age Employee.empCount += 1 def displayCount(self): print ("Total Employee %d" % Employee.empCount) def displayEmployee(self): print( "Name : ", self.name, ", Salary: ", self.salary,"age:",self.age) "创建 Employee 类的第一个对象" emp1 = Employee("Zara", 2000,7) "创建 Employee 类的第二个对象" emp2 = Employee("Manni", 5000,8) """ getattr(obj, name[, default]) : 访问对象的属性。 hasattr(obj,name) : 检查是否存在一个属性。 setattr(obj,name,value) : 设置一个属性。如果属性不存在,会创建一个新属性。 delattr(obj, name) : 删除属性。 """ hasattr(emp1, 'age') # 如果存在 'age' 属性返回 True。 getattr(emp1, 'age') # 返回 'age' 属性的值 setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8 delattr(emp1, 'age') # 删除属性 'age' emp1.displayEmployee() emp2.displayEmployee() print ("Total Employee %d" % Employee.empCount)
6ba8085639fcdcf898782a0035c400e926f9b784
quintuspai/data_structures
/Searching/Jump_Search.py
748
3.796875
4
#JumpSeacth def jump_Search(n : int, arr, item : int) -> str(): import math step = int(math.floor((math.sqrt(n)))) arr = sorted(arr) pos = -1 low = 0 high = n-1 i = 0 while i < step: if item < arr[step]: high = step - 1 else: low = step + 1 i = i + 1 for i in range(low,high+1): if arr[i] == item: pos = i break if pos == -1: return "Element {} not found".format(item) else: return "Element found at {}".format(pos) if __name__ == "__main__": *arr_list, item = input().split() arr_list = list(map(int, arr_list)) print(jump_Search(len(arr_list), arr_list, int(item)))
7a916aae8c8728fe52565a0013012313ca2dc6fd
thisis-vishal/snake-game
/scoreboard.py
1,136
3.765625
4
from turtle import Turtle, write class Scoreboard(Turtle): def __init__(self): super().__init__() self.score=0 with open("highscore.txt") as file: score=int(file.read()) self.highscore=score self.penup() self.color("white") self.hideturtle() self.goto(0,270) self.write(f"score:{self.score} High score: {self.highscore}",move=False,align="center",font=("Arial",24,"normal")) def incscore(self): self.score+=1 self.updatescoreboard() def updatescoreboard(self): self.clear() self.write(f"score:{self.score} High score: {self.highscore}",move=False,align="center",font=("Arial",24,"normal")) def reset(self): if self.score>self.highscore: with open("highscore.txt",mode="w") as file: file.write(f"{self.score}") self.highscore=self.score self.score=0 self.updatescoreboard() # def gameover(self): # self.goto(0,0) # self.write(f"GAME OVER.",align="center",font=("Arial",24,"normal"))
861177d16bf0d6d2e3cfc8b518d5f7a5fb94c3d1
AlanFermat/leetcode
/array + Design/menuCombo.py
465
3.703125
4
def solve(candidates, target): res = [] candidates = sorted(candidates) def comboHelper(temp, arr, target): summ = sum(temp) if summ == target: res.append(temp) elif summ > target: return else: for i, num in enumerate(arr): if summ + num > target: return else: comboHelper(temp + [num], arr[i:], target) comboHelper([], candidates, target) return res target = 7 candidates = [2,3,6,7] print (solve(candidates, target))
232ce2bb00c93fc11f1efc747af21453279a83a9
tiaotiao/leetcode
/357-count-numbers-with-unique-digits.py
534
3.765625
4
class Solution: def countNumbersWithUniqueDigits(self, n): """ :type n: int :rtype: int """ if n == 0: return 1 if n < 0 or n > 10: return 0 total = 9 for i in range(9, 9-n+1, -1): total = total * i # print(n, total) total += self.countNumbersWithUniqueDigits(n-1) return total def main(): s = Solution() print(s.countNumbersWithUniqueDigits(3)) if __name__ == '__main__': main()
ce08abc73e8a247242de59e5a6b33163afadc9f0
chrissmart/python_tutorial_basic_part
/football_data_access.py
2,364
4.0625
4
""" This py file is used to demonstrate the data structure in python lanauge via the world cup dataset. . Dataframe . Array . List . Tuple . Dictionary . Set """ """ Dataframe """ import pandas as pd # create: import data df_player = pd.read_csv(r".\dataset\WorldCupPlayers.csv") # read: inspect data structure df_player.info() # show overall information df_player.head() # show the first five rows df_player.index # show the total number of rows df_player.columns # show all columns # read: find data df_player.loc[0:2, ['Coach Name']] df_player.iloc[0:2, 3] df_player['Coach Name'][0:2] # update: edit data df_player.iloc[-1, 3] = 'Chris Chien (Earth)' # change the value of the last row df_player = df_player.append({'Player Name': 'Ian Chen (Universe)'}, ignore_index=True) # add a new row # delete df_player = df_player.iloc[:-1, :] # remove the last row """ Array """ import numpy as np # create: import data array_player = df_player.values # read: inspect data structure array_player.shape # show the number of rows and columns in an array # read: find data array_player[0] # show the first row array_player[0][0] # show the first element in the first row # update: array_player[-1][0] = 201 array_player = np.append(array_player, [[201, 1096.0, 'Universe', 'Christopher Chris (Universe)', 'S', 0.0, 'Faster Chien', 'GK', None]], axis=0) # delete: array_player = np.delete(array_player, -1, axis = 0) """ List """ # create: import data list_player = df_player.values.tolist() # read: inspect data structure len(list_player) # show the total number of rows in a list max(list_player) min(list_player) # read: find data list_player[0] # show the first row list_player[0][0] # show the first element in the first row # update: edit data list_player[0][3] = 'UNI' # change the value of the list list_player[0].append('Hi I\'m here') # add a new element # delete: del list_player[0][-1] # delete the value in a list """ Dictionary """ # create dict_player = {'messi':['argentina', 30, 'striker'], 'dembele':['france', '25', 'striker']} # read dict_player['messi'] # update dict_player['messi'][1] = 31 # delete del dict_player['dembele'] """ Tuple: cannot be changed """ # create tup = ("ronaldo", "xavi", "iniesta") # read tup[0] tup[1] # update: tuple cannot be modified tup[0] = 'messi' tup*4 # delete del tup[0] # not allowed del tup # feasible
ca005a605097c7829f992d04343cbf25b68de214
kaka0525/Leet-code-practice
/lastElement.py
713
4.09375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None def find_length(self, head): """ A helper function for the last_element to determine the length of the linked list """ length = 0 current = head while current is not None: length += 1 current = current.next return length def last_element(self, head, k): """ You have a linked list and want to find the kth to last node. """ length = self.find_length(head) step_to_element = length - k current = head for element in xrange(step_to_element): current = current.next return current
a10ea33c3abdbea4514c4b73d749e40a60c0db59
Aasthaengg/IBMdataset
/Python_codes/p02391/s221067919.py
167
3.921875
4
input_line = input().split() a = int(input_line[0]) b = int(input_line[1]) if a > b: symbol = ">" elif a < b: symbol = "<" else: symbol = "==" print("a",symbol,"b")
3c3297d2c73bdb1a9a8c8cd4725622ebecdc822f
kapilthakkar72/minorProject
/SIL802 Work/assignment_2/Graphs and Charts/what_to_grow_next_bar.py
515
3.734375
4
import numpy as np import matplotlib.pyplot as plt #Graph 1 y = [10,1,1] N = len(y) x = range(N) #width = 1/1.5 width = 0.35 # the width of the bars: can also be len(x) sequence plt.bar(x, y, width, color="blue") plt.xlabel('Method') plt.ylabel('Number of Farmers') plt.title('How do you decide what to grow next?') plt.ylim([0,11]) ind = np.arange(N) # the x locations for the groups plt.xticks(ind+width/2., ('ancestral crop','Depending on price','Crop rotation (good for land)' ) ) plt.show()
7505b04e1221533600511825b580209030d0573d
Ribiro/InvoiceApp
/test.py
438
3.625
4
""" customers - clients : orders pseudo column orders - invoices : customer_id, product_id products - products : customer pseudo column # """ from datetime import datetime d = datetime.now() month = d.month months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', ' October', 'November', 'December'] month = months[month-1] year = d.year month = month + ' ' + str(year) print(month)
31a95ba52a3d10ac486fd2ecb8ced942de910262
nishantchauhan00/GeeksForGeeks
/Companies Question/156 The Celebrity Problem.py
2,249
3.75
4
# brute force approach def getId1(m,n): for i in range(n): # find row with all elements zeroes, i.e, a celebrity who doesn't know # anyone if not(1 in m[i]): # make the i'th element of that row '1' for easy search m[i][i] = 1 # now we confirm that everyone knows him for j in range(n): # if there is someone who doesn't know him, then return -1, # because there is no possibility of other answer because # the current celetity knows noone if m[j][i] == 0: return -1 return i return -1 ''' using stack https://youtu.be/LtGnA5L6LIk ''' ''' The following observations can be made in this problem: > If A knows B, then A can’t be celebrity. Discard A and B may be celebrity. > If A doesn’t know B, then B can’t be celebrity. Discard B, and A may be celebrity. we will do it using O(1) space ''' def getId(arr,n): candidate = 0 for i in range(1, n): # if candidate knows 'i', then candidate can't be celebrity, but its # possible that 'i' is celebrity if arr[candidate][i] == 1: candidate = i # Now, we check if candidate is really a celbrity or not for i in range(n): if (i != candidate) and (arr[candidate][i] == 1 or arr[i][candidate] == 0): return -1 return candidate # ################################ # ################################ # Driver Code Starts # ################################ #Initial Template for Python 3 import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) if __name__ == '__main__': test_cases = int(input()) for cases in range(test_cases) : n = int(input()) a = list(map(int,input().strip().split())) k = 0 m = [] for i in range(n): row = [] for j in range(n): row.append(a[k]) k+=1 m.append(row) print(getId(m,n))
152bc7c1ce6847dfd2caa0dfa0e418c91a406f7c
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/sublist/f9fb50d8d4c84717b81a4ed3561d8c2f.py
552
3.96875
4
SUBLIST='sublist' SUPERLIST='superlist' EQUAL='equal' UNEQUAL='unequal' def check_lists(first, second): first.sort() second.sort() if len(first) == len(second): if first == second: return 'equal' return 'unequal' if len(first)>len(second): return checker(second, first, True) return checker(first, second) def checker(one, two, swap=False): one_hist = {x:one.count(x) for x in one} for item in one_hist: if item not in two or one_hist[item]>two.count(item): return 'unequal' if swap: return 'superlist' return 'sublist'
5ace06040ded9832855e21305cb549fa897945bc
KULDEEPMALIKM41/Practices
/Python/Python Basics/79.list.py
7,325
4.1875
4
# python sequence -> # sequence are collection capable to store bulk amount of data # simultaneously.in python collection have capability to store # heterogeneous reference simultaneously. # # NOTE:- as per storage type the collection may vary. # 1.list sequence 2.tuple sequence 3.dictionary sequence # # # 1. list sequence -> # list is an collection capable to store multiple heterogeneous reference # simultaneously each reference in a list will be given by an integer number. # # syntax:- # list_name=[ele1,ele2,ele3....] # # ele1,ele2,ele3... -> these are heterogeneous elements. # l=[10,20,30,40,50] print('list : ',l) print('list type : ',type(l),'\n') l=[10010001,'amit',3000.11,True] print('list : ',l) print('list type : ',type(l),'\n') l=[10,20,30,40,50] print('list : ',l) print('list menual access') print('l[1] : ',l[1],'\n') l=[10,20,30,40,50] print('list : ',l) print('list loop access by index') for i in range(0,len(l)): print(l[i],end=' ') print('\n') l=[10,20,30,40,50] print('list : ',l) print('list loop access by element') for element in l: print(element,end=' ') print('\n') # a) operator of list -> #concatenation operator l1=[10,20,30] l2=[40,50,60] l=l1+l2 print('new list is',l,'\n') #multiplier operator l1=[10,20,30] l2=3 l=l1*l2 print('new list is',l,'\n') #membership operator l1=[10,20,30] l2=20 l=l2 in l1 print('found',l,'\n') l1=[10,20,30,[40]] l2=40 l=l2 in l1 print('found',l,'\n') l1=[10,20,30,[40]] l2=[40] l=l2 in l1 print('found',l,'\n') #range &slice operator l1=[10,20,30,40,50,60,70,80,90] print('list: ',l1) print('l1[2]=',l1[2]) print('l1[-2]=',l1[-2]) print('l1[1:9]=',l1[1:9]) print('l1[:7]=',l1[:7]) print('l1[3:]=',l1[3:]) print('l1[:]=',l1[:]) print('l1[-1:-10:-1]=',l1[-1:-10:-1]) print('l1[::-1]=',l1[::-1]) print('l1[::1]=',l1[::1]) print('l1[::]=',l1[::]) print('l1[-1:4:-1]=',l1[-1:4:-1]) print('l1[7:0:-2]=',l1[7:0:-2]) print('l1[1:7:2]=',l1[1:7:2],'\n') # b)mutable and immutable -> # list is mutable. # l=[10,20,30,40,50] print(' before list: ',l) l[1]=100 del l[4] print(' after list: ',l,'\n') # c)function in list -> #max and min function l=[10,20,30,40,50] print('list is : ',l) print('maximum element is: ',max(l)) print('manimum element is: ',min(l),'\n') l=[10010001,'amit',3000.11,True] #string,int or float and boolean type data is not compare. print('list is : ',l,'\n') #print('maximum element is: ',max(l)) #print('manimum element is: ',min(l),'\n') l=[10,20,30,[40]] #error - list and integer not compare. print('list is : ',l,'\n') #print('maximum element is: ',max(l)) #print('manimum element is: ',min(l),'\n') l=[10,20,33.12,20.01,33.13] print('list is : ',l) print('maximum element is: ',max(l)) print('manimum element is: ',min(l),'\n') #len function l=[10010001,'amit',3000.11,True] print('length of l = ',len(l),'\n') #list and type function s='universal' print('s= ',s) print('type of s: ',type(s)) l=list(s) print('l= ',l) print('type of l: ',type(l),'\n') #id function l1=[10010001,'amit',3000.11,True] l2=[10,20,33.12,20.01,33.13] l3=[10,20,30,[40]] l4=[10010001,'amit',3000.11,True] l5=[10,20,33.12,20.01,33.13] l6=[10,20,30,[40]] print('id of l1',id(l1)) print('id of l2',id(l2)) #Note:- same sequence data different different reference. print('id of l3',id(l3)) print('id of l4',id(l4)) print('id of l5',id(l5)) print('id of l16',id(l6),'\n') # d)method in list -> import sys l1=[10010001,'amit',3000.11,True] l2=[10,20,33.12,20.01,33.13] l3=[10,20,30,[40]] l4=[] print('size of l1 : ',sys.getsizeof(l1)) #list class+value size print('size of l2 : ',sys.getsizeof(l2)) #list class+value size print('size of l3 : ',sys.getsizeof(l3)) #list class+value size print('size of l4 : ',sys.getsizeof(l4),'\n') #list class size #Note:- 1) ubuntu # type total size class size data size # # list 72 byte 64 byte 8 byte/element # # 2) windows # list 40 byte 36 byte 4 byte/element #copy method l=[10010001,'amit',3000.11,True] print(l) print('id of t',id(l)) t=l #in this type copy data store in same reference id. print(t) print('id of t',id(t)) t=l.copy() #in this type copy data store in deferent reference id. print(t) print('id of t',id(t),'\n') #reverse method l=[10,20,30,40,50] print('before revers : ',l) l.reverse() print('after revers : ',l,'\n') #sort method l=[20,10,30,50,40] print('before sort(ascending) : ',l) l.sort() #ascending order(by default). print('after sort(ascending) : ',l,'\n') #reverse&sort method l=[20,10,30,50,40] print('before sort(descending) : ',l) l.sort() l.reverse() # for descending order. print('after sort(descending) : ',l,'\n') #insert method l=[20,10,30,50,40] print('list is : ',l) l.insert(2,100) #write index no. then write value. print('after insertion : ',l,'\n') #remove method l=[20,10,30,50,40] print('list is : ',l) l.remove(50) #remove number bye his value. print('after remove : ',l,'\n') #POP method l=[20,10,30,50,40] print('list is : ',l) l.pop(1) #removes and returns element having given index otherwise print('after pop : ',l) # by default last value is remove. r=l.pop(1) #removes and returns element having given index otherwise print('after pop : ',r) # by default last value is remove. print('after pop : ',l,'\n') #del keyword not a method l=[20,10,30,50,40] print('list is : ',l) del l[3] #delete any index value. print('after delete : ',l,'\n') #del keyword not a method l=[20,10,30,50,40] print('list is : ',l) del l #list l is deleted and not existence in code. #print('after delete : ',l,'\n') #append method l=[20,10,30,50,40] print('list is : ',l) l.append(60) l.append(70) l.append(80) #add value in last of list. print('after 3 time append : ',l,'\n') #index method l=[20,10,30,50,40,10,20,50] n=l.index(10) print('found index: ',n) n=l.index(40) #return first element index number. print('found index: ',n) #n=l.index(70) #if element is not found it will give error. #print('found index: ',n) n=l.index(30,2) #search after index number 1. print('found index: ',n,'\n') n=l.index(50,1,4) #search between 1to 4index number. print('found index: ',n) #count method l=[20,10,30,50,40,10,20,50] print('list is : ',l) n=l.count(10) #total number of 10 in list. print('total number: ',n,'\n') #clear method l=[20,10,30,50,40,10,20,50] print('list is : ',l) l.clear() print('list is : ',l) #encoding and decoding not support for list. '''l=[20,10,30,50,40,10,20,50] print('actual list: ',l) l=l.encode('utf-8') #encoding print('encoded list: ',l) l=l.decode('utf-8') #decoding print('decoded list: ',l)''' #rindex method --> this method is not work on list. '''l=[20,10,30,50,40,10,20,50] n=l.rindex(10) print('found index: ',n) n=l.rindex(40) #return first element index number. print('found index: ',n) #n=l.rindex(70) #if element is not found it will give error. #print('found index: ',n) n=l.rindex(30,2) #search after index number 1. print('found index: ',n,'\n') n=l.rindex(50,1,4) #search between 1to 4index number. print('found index: ',n)''' # find method --> this method is not work on list. # rfind method --> this method is not work on list.
e921d7de1b954e6a78e0ccaa501197e895dc7dc2
Star2227/study_python
/013.py
439
3.9375
4
#简单的类 class Dog(): """ 一次模拟小狗的尝试 """ def __init__(self, name, age): self.name = name self.age = age def sit(self): print(self.name.title()+"现在坐下了") def roll_over(self): print(self.name.title() + "打滚") my_dog = Dog("wangcai", 6) print("我的狗叫" + my_dog.name) print('我的狗' + str(my_dog.age) + '岁') my_dog.sit() my_dog.roll_over()
c60ee3fa01e7654eb136316dc5a023bff46d896e
jrballot/PythonFundamentals
/aula_02/exercicio01.py
925
3.640625
4
# Missão 1: # Criar uma função 'cadastrar_usuario' # que retorne um dicionário de usuário. # O dicionário deve conter a propriedades: # - nome # - email # - idade # e os valores devem ser digitados # pelo usuário do através do terminal (input) import datetime import os import time usuarios = [] def cadastrar_usuarios(): usuario = { 'nome': input('Entre com nome do usuario: '), 'idade': input('Entre com idade do usuario: '), 'email': input('Entre com email do usuario: '), 'data_cadastro': datetime.datetime.now() } usuarios.append(usuario) return usuarios start_time = time.process_time() os.system('clear') usuario = cadastrar_usuarios() print(usuario) d = usuario[0]['data_cadastro'] print(d.strftime('%B %d, %Y %c')) end_time = time.process_time() print("Operacao iniciada em {} e finalizada em {}\ \nTotal de {} decoridos".format(start_time,end_time,end_time-start_time))
6b39b7ebde06a67bb4b1b473e0b4f238284b7e5c
ziejaCode/Exercises
/BegginerPractice/4.py
253
3.984375
4
''' Created on 31 May 2020 @author: czarn ''' word = input() revword = "" for w in range(len(word)- 1, -1, -1): revword += word[w] if word == revword: print(word + " is Palindrome ") else: print(revword + " is Palindrome ")
dee7ef2559c8dec6e9f62074fe8c8ffdd16b356f
bokveizen/leetcode
/105_Construct Binary Tree from Preorder and Inorder Traversal.py
2,311
3.8125
4
# https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # recursion class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def buildT(pre_order_list, in_order_list): if not pre_order_list: return None if len(pre_order_list) == 1: # pre_order_list and in_order_list are the same, containing only one node return TreeNode(pre_order_list[0]) root = TreeNode(pre_order_list[0]) root_in_order_index = in_order_list.index(pre_order_list[0]) left_child_pre_order_list = pre_order_list[1:root_in_order_index + 1] left_child_in_order_list = in_order_list[:root_in_order_index] right_child_pre_order_list = pre_order_list[root_in_order_index + 1:] right_child_in_order_list = in_order_list[root_in_order_index + 1:] root.left = buildT(left_child_pre_order_list, left_child_in_order_list) root.right = buildT(right_child_pre_order_list, right_child_in_order_list) return root return buildT(preorder, inorder) # stack class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if not preorder: return None if len(preorder) == 1: return TreeNode(preorder[0]) T = TreeNode(preorder[0]) stack = [T] cur = T index_i = 0 for index_p in range(1, len(preorder)): val_p = preorder[index_p] cur = stack[-1] if stack[-1].val == inorder[index_i]: # stack top has no left child, preorder[index_p] is the right child of some ancestor node of stack top while stack and stack[-1].val == inorder[index_i]: cur = stack.pop() index_i += 1 cur.right = TreeNode(val_p) stack.append(cur.right) else: # preorder[index_p] is the left child of stack top cur.left = TreeNode(val_p) stack.append(cur.left) return T
200ce693031b0a776c1621cc50141fb9fe6a21a5
betulbeyazoglu/Python-Assignments
/if_assgnment1.py
187
4.25
4
name=input("Please enter your name: ") my_name="Betul" if name==my_name: print("Hello, Betul! The password is: willpower ") else: print("Hello, {}! See you later.".format(name))
e2f1efd853999b21067146ffb63f9e182746da6c
suqcnn/research-project
/src/Communication.py
2,564
3.578125
4
import socket import threading from abc import ABC, abstractmethod EXIT = 'exit' ENCODING = 'utf-8' BUFFER_SIZE = 16 class Communicator(threading.Thread, ABC): """ Abstract class for bidirectional traffic handling """ def __init__(self, name, host, port, other_host, other_port): """ Initializes a communicator :param name: Name for the communicator :param host: Own host name :param port: Own port :param other_host: Other host name :param other_port: Other port """ threading.Thread.__init__(self, name=name) self.name = name self.host = host self.port = port self.other_host = other_host self.other_port = other_port def send(self, data: str): """ Sends a string of data :param data: String of data """ print('%-10s OUT: %s' % (self.name, data)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((self.other_host, self.other_port)) s.sendall(data.encode(ENCODING)) s.shutdown(2) s.close() def send_exit(self): self.send(EXIT) def run(self): """ Starts listening for requests """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((self.host, self.port)) sock.listen(10) try: while self.handle_client(sock.accept()): pass finally: print('Shutting down %s' % self.name) sock.shutdown(socket.SHUT_RDWR) sock.close() def handle_client(self, accept): """ Handles a connection with a client :param self: :param accept: :return: """ connection, client_address = accept cont = True try: data = "" while True: rcv = connection.recv(BUFFER_SIZE) data += rcv.decode(ENCODING).strip() if not rcv: if data == EXIT: cont = False else: cont = self.handle_request(data) break except AssertionError as error: print('EXCEPTION:', str(error)) # self.send(EXIT) cont = False finally: connection.shutdown(2) connection.close() return cont @abstractmethod def handle_request(self, data: str) -> bool: raise NotImplementedError
3be90d6e41dffd4bd0086b2d96a0bbf0547619e3
mhzangooei/GenomicCoverageCalculation
/test_binary_search.py
954
3.609375
4
import unittest from sortedcontainers import SortedDict from binary_search import * class TestCase_read_CSV_file(unittest.TestCase): def test_binary_search(self): #for example suppose Data {Start (Or key):Length (Or value)} => {3:7, 3:9, 3:8, 2:9, 2:9, 1:9} then we construct a nested sorted dictionary treeMap = SortedDict() treeMap.update({3:SortedDict({7:1, 9:1, 8:1}),2:SortedDict({9:2}),1:SortedDict({9:1})}) # it sorts: {1:{9:1}, 2{9:2, 3{7:1, 8:1, 9:1}}} last_index_search_for_key = binary_search.binary_search_key(2, treeMap) #for 2, last index of keys is 1 first_index_search_for_value = binary_search.binary_search_value(5,treeMap[treeMap.keys()[2]]) # for value 8 of 3, first index is 0 => binary_search_value(8-3,{7:1,8:1, 9:1}) self.assertEqual(last_index_search_for_key, 1) self.assertEqual(first_index_search_for_value, 0) if __name__ == '__main__': unittest.main()
5e0efdc540ba6c504217c854ac363c532b6ad090
sjha3/WebAcessUsingPython
/find_sum.py
445
3.703125
4
#Find sum of all numbers in a file import re sum = 0 with open('text.txt') as fp: for line in fp: ll = re.findall('\d+', line) #Finds list of numbers in this line (\d+ => 1 or more continous digits sum_list = 0 if len(ll) > 0: print(ll) for i in ll: sum_list = sum_list + int(i) print ("sum_list : ", sum_list) sum = sum + sum_list print ("sum : ", sum)
1b5895712d364b834f3a8c0faf2600c6d6efa285
sfalkoff/skills01
/skills01.py
3,103
4.0625
4
# Things you should be able to do. number_list = [3, 2, 77, 2] word_list = [ "What", "about", "the", "Spam", "sausage", "spam", "spam", "bacon", "spam", "tomato", "and", "spam"] # Write a function that takes a list of numbers and returns a new list with only the odd numbers. def all_odd(number_list): odds = [number for number in number_list if number % 2 != 0] return odds print all_odd(number_list) # Write a function that takes a list of numbers and returns a new list with only the even numbers. def all_even(number_list): even = [number for number in number_list if number % 2 == 0] return even print all_even(number_list) # Write a function that takes a list of strings and return a new list with all strings of length 4 or greater. def long_words(word_list): list_of_long_words = [lw for lw in word_list if len(lw) >= 4] return list_of_long_words print long_words(word_list) # Write a function that finds the smallest element in a list of integers and returns it. def smallest(number_list): smallest_so_far = number_list[0] for number in number_list: if number < smallest_so_far: smallest_so_far = number return smallest_so_far print smallest(number_list) # Write a function that finds the largest element in a list of integers and returns it. def largest(number_list): greatest_so_far = number_list[0] for number in range(1, len(number_list)): if number_list[number] > greatest_so_far: greatest_so_far = number_list[number] return greatest_so_far print largest(number_list) # Write a function that takes a list of numbers and returns a new list of all those numbers divided by two. def halvesies(number_list): halved = [(num/2.0) for num in number_list] return halved print halvesies(number_list) # Write a function that takes a list of words and returns a list of all the lengths of those words. def word_lengths(word_list): wl = [len(word) for word in word_list] return wl print word_lengths(word_list) # Write a function (using iteration) that sums all the numbers in a list. def sum_numbers(number_list): sum_num = 0 for i in range(len(number_list)): sum_num = sum_num + number_list[i] return sum_num print sum_numbers(number_list) # Write a function that multiplies all the numbers in a list together. def mult_numbers(number_list): product = 1 for i in range(len(number_list)): product *= number_list[i] return product print mult_numbers(number_list) # Write a function that joins all the strings in a list together (without using the join method) and returns a single string. def join_strings(word_list): final_string = "" for word in word_list: final_string += " " + word return final_string print join_strings(word_list) # Write a function that takes a list of integers and returns the average (without using the avg method) def average(number_list): sum_nums = sum_numbers(number_list) count_nums = len(number_list) return sum_nums/(count_nums*1.0) print average(number_list)
da3ccb5c66d34a7833f9662deaeaa48fb8ffbdaa
nickcharlton/termisoc-python-tutorial
/hello_name.py
194
3.65625
4
# note: we use raw_input here, as a normal input will try to evalute what you give it as normal python, causing all manner of problems name = raw_input('Enter your name: ') print 'Hello,', name
e5baa558c2670cd7b2ab58c7c402d7116c667fa4
sidinorris/Seguranca
/DH/DH.py
240
3.6875
4
base = 3 mod = 68 PKey = int(input("Informe a chave privada: ")) print((base ** PKey) % mod) IKey = int(input("Informe a chave intermediaria: ")) print("Chave compartilhada:", (IKey ** PKey) % mod) input("Tecle enter para continuar.")
c6215a5af6817f1d888266e6a5f425848d5cb91c
dxmahata/codinginterviews
/leetcode/closest_bst_value.py
1,416
4.15625
4
""" Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Note: Given target value is a floating point. You are guaranteed to have only one unique value in the BST that is closest to the target. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def closestValue(self, root, target): """ :type root: TreeNode :type target: float :rtype: int """ min_dif = float("inf") closestVal = None if root == None: return None else: while root: root_val = root.val val_dif = abs(root_val - target) if val_dif < min_dif: min_dif = val_dif closestVal = root_val if target < root_val: if root.left != None: root = root.left else: root = None else: if root.right != None: root = root.right else: root = None return closestVal
c34d2f762028428b353f6476ede7d2a28d378167
rajlath/rkl_codes
/CodeForces/CFBR_69_2_A.py
201
3.59375
4
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] curr, nexts = [int(x) for x in input().split()] if primes[primes.index(curr) + 1] == nexts: print("YES") else: print("NO")
bb185ca8c9ee2a5f1fbacf1b18db1287a8f79701
sachinssagar/cal
/app.py
1,409
4.15625
4
from src import calculator choice = True while choice: print("\n-------------------------") print("------ CALCULATOR -------") print("-------------------------") num1 = int(input("\nEnter first number: ")) num2 = int(input("\nEnter second number: ")) print("\nSelect an option") print("1.Addition") print("2.Subtraction") print("3.Multiplication") print("4.Division") choose = input("Enter Your option:") if choose in ("1", "2", "3", "4"): if choose == "1": result = calculator.add(num1, num2) print(num1, "+", num2, "=", result) elif choose == "2": result = calculator.sub(num1, num2) print(num1, "-", num2, "=", result) elif choose == "3": result = calculator.multi(num1, num2) print(num1, "*", num2, "=", result) elif choose == "4": result = calculator.div(num1, num2) print(num1, "/", num2, "=", result) else: print("-----------------") print("--Invalid Input--") print("-----------------") break new = input("\nWould you want to contine? Enter 'y' or 'n': ") if new[0].lower() == "y": choice = True else: choice = False print("\n---------------------------") print(" Thank You. See You Later ") print("---------------------------")
6d347063b15f74332d13edbd8225aa43adab3127
elenaborisova/Python-Fundamentals
/09. Lists Advanced - Lab/04_even_numbers.py
146
3.65625
4
nums = list(map(int, input().split(", "))) even_nums_indices = [index for index, num in enumerate(nums) if num % 2 == 0] print(even_nums_indices)
10ff986c5fb367437d12d1910ea8ac562025bfcc
LobbyBoy-Dray/PyShare
/Archived/Lecture1/L1_Solution/2_7.py
297
3.78125
4
# ========== 2.7 计算年数和天数========== import math totalminutes = eval(input("Enter the number of minutes: ")) totalDays = math.ceil(totalminutes // (24*60)) years = totalDays // 365 days = totalDays % 365 print(totalminutes, "minutes is approximately", years, "years and", days, "days")
84ed64a3096080ffb41bc0e82deef0d29a803145
DucAnh2111/VuDucAnh-C4T8
/session6/input_number.py
115
3.984375
4
txt = input("Enter a number?") print (txt) if txt.isdigit(): print("A number") else: print("Not a number")
b329e3b7aa19b489665f586dd6eb4a9cce5cb184
agibsonccc/storedserver
/storedserver/basestorage.py
1,076
3.953125
4
""" BaseStorage is an abstraction for a dictionary meant to store values depending if the user wants to append values to a list or replace the values """ class BaseStorage(object): def __init__(self,replace=True): self.dict = {} self.replace = replace def add(self,k,v): if k not in self.dict: self.dict[k] = v print 'keys ' + ''.join(self.dict.keys()) elif( self.replace ): self.dict[k] = v elif k in self.dict: v_original = self.dict[k] if( isinstance(v,list) ): for item in v: v_original.append(item) else: newlist = [] newlist.append(v_original) newlist.append(v) self.dict[k]=newlist def delete(self,k): self.dict[k] = None def get(self,k): if k in self.dict : return self.dict[k] return None def keys(self): return self.dict.keys() def entries(self): return self.dict.items()
c47eded2c1904296e97a16e54639c8239eccb28c
jawad1505/SoftwareEngineering
/BigO/constant.py
137
3.734375
4
def sum2(n): """ Take an input of n and return the sum of the numbers from 0 to n """ return (n*(n+1))/2 print(sum2(10))
c3a4eece89098bd54c9f58176638e1e4438af349
SteveJSmith1/leetcode-solutions
/Solutions/349_Intersection_of_Two_Arrays.py
1,177
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 17 12:36:11 2017 @author: SteveJSmith1 Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. Note: Each element in the result must be unique. The result can be in any order. """ class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ set_a = set(nums1) set_b = set(nums2) return list(set(set_a & set_b)) from nose.tools import assert_equal class TestIntersection(object): def test_intersection(self): solution = Solution() assert_equal(solution.intersection([],[]), []) assert_equal(solution.intersection([1, 2, 2, 1],[2, 2]), [2]) assert_equal(solution.intersection([1, 2, 3, 4, 3, 2, 1], [2, 2, 3, 3, 1]), [1,2,3]) print('Success: test_intersection') def main(): test = TestIntersection() test.test_intersection() if __name__ == '__main__': main()
b05e5577ec61e8ecc45843e41a09eb467367e9f9
alirezahi/AI-LocalSearchAlgorithms
/SimulatedAnnealing.py
969
3.6875
4
import random from math import exp class SimulatedAnnealing(): def __init__(self, problem, *args, **kwargs): self.problem = problem def solve(self): current_state = self.problem.initial_state() count = 0 local_try = 1000 temperature = 10000 sch = 0.99 t_min = 1 while temperature > t_min: print(current_state) random_neighbour = random.choice(self.problem.neighbours(current_state)) efficiency = self.problem.heuristic(random_neighbour) - self.problem.heuristic(current_state) #Replace new state if it is better than older one if efficiency < 0: current_state = random_neighbour #Replace new state if the probability is good elif exp((-(efficiency))/temperature) > random.random(): current_state = random_neighbour temperature *= sch print(current_state)
c089ea9c8b6ea09f68fd565ea29da5851abfbc2d
xuhyang/algo-practice
/bfs/topologic_sort.py
6,629
3.796875
4
class topological_sort: """ @param: graph: A list of Directed graph node @return: Any topological order for the given graph. """ def topSort(self, g): indgr, rslt = {}, [] for n in g: #graph to indegree for nxt in n.neighbors: indgr[nxt] = indgr.get(nxt, 0) + 1 #start bfs with node have no indegree q = collections.deque([n for n in g if n not in indgr]) while q: n = q.popleft() rslt.append(n) for nxt in n.neighbors: indgr[nxt] -= 1 if indgr[nxt] == 0: q.append(nxt) return rslt """ 605. Sequence Reconstruction https://www.lintcode.com/problem/sequence-reconstruction/description Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 10^4. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence. Input:org = [1,2,3], seqs = [[1,2],[1,3]] Output: false Explanation: [1,2,3] is not the only one sequence that can be reconstructed, because [1,3,2] is also a valid sequence that can be reconstructed. Input: org = [1,2,3], seqs = [[1,2]] Output: false Explanation: The reconstructed sequence can only be [1,2]. Input: org = [1,2,3], seqs = [[1,2],[1,3],[2,3]] Output: true Explanation: The sequences [1,2], [1,3], and [2,3] can uniquely reconstruct the original sequence [1,2,3]. Input:org = [4,1,5,2,6,3], seqs = [[5,2,6,3],[4,1,5,2]] Output:true """ def sequenceReconstruction(self, org, seqs): d, g = {}, {} for s in seqs: for i in range(len(s)): g[s[i]], d[s[i]] = g.get(s[i], []), d.get(s[i], 0) if i > 0: g[s[i - 1]].append(s[i]) d[s[i]] += 1 q, rslt = collections.deque([k for k, v in d.items() if v == 0]), [] while q: if len(q) > 1: # 出现了两条 top sort return False rslt.append(q[0]) for n in g[q.popleft()]: d[n] -= 1 if d[n] == 0: q.append(n) return rslt == org """ 615. Course Schedule https://www.lintcode.com/problem/course-schedule/descr’iption There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? Input: n = 2, prerequisites = [[1,0]] Output: true Input: n = 2, prerequisites = [[1,0],[0,1]] Output: false """ def canFinish(self, n, p): ind, g, cnt = {i : 0 for i in range(n)}, collections.defaultdict(list), 0 for u, v in p: ind[u], g[v] = ind[u] + 1, g[v] + [u] q = collections.deque([i for i in range(n) if ind[i] == 0]) while q: cnt += 1 for u in g[q.popleft()]: ind[u] -= 1 if ind[u] == 0: q.append(u) return cnt == n """ 616. Course Schedule II https://www.lintcode.com/problem/course-schedule-ii/description There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. Input: n = 2, prerequisites = [[1,0]] Output: [0,1] Input: n = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,1,2,3] or [0,2,1,3] """ def findOrder(self, n, p): ind, g, ans = {i: 0 for i in range(n)}, collections.defaultdict(list), [] for u, v in p: ind[u], g[v] = ind[u] + 1, g[v] + [u] q = collections.deque([i for i in range(n) if ind[i] == 0]) while q: ans.append(q.popleft()) for u in g[ans[-1]]: ind[u] -= 1 if ind[u] == 0: q.append(u) return ans if len(ans) == n else [] """ 892. Alien Dictionary https://www.lintcode.com/problem/alien-dictionary/description There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language. Input:["wrt","wrf","er","ett","rftt"] Output:"wertf" Explanation: from "wrt"and"wrf" ,we can get 't'<'f' from "wrt"and"er" ,we can get 'w'<'e' from "er"and"ett" ,we can get 'r'<'t' from "ett"and"rftt" ,we can get 'e'<'r' So return "wertf" Input:["z","x"] Output:"zx" Explanation: from "z" and "x",we can get 'z' < 'x' So return "zx" Notice You may assume all letters are in lowercase. The dictionary is invalid, if a is prefix of b and b is appear before a. If the order is invalid, return an empty string. There may be multiple valid order of letters, return the smallest in normal lexicographical order """ def alienOrder(self, words): # Construct Graph in_degree = {ch: 0 for word in words for ch in word} neighbors = {ch: [] for word in words for ch in word} for pos in range(len(words) - 1): for i in range(min(len(words[pos]), len(words[pos+1]))): pre, next = words[pos][i], words[pos+1][i] if pre != next: in_degree[next] += 1 neighbors[pre].append(next) break # Topological Sort heap = [ch for ch in in_degree if in_degree[ch] == 0] heapify(heap) order = [] while heap: ch = heappop(heap) order.append(ch) for child in neighbors[ch]: in_degree[child] -= 1 if in_degree[child] == 0: heappush(heap, child) # order is invalid if len(order) != len(in_degree): return "" return ''.join(order)
ca2ef55210858b60e7ab4a2bcf93c9b976f31d52
SidneyKim/python-learning-examples-2018
/day 1 기초/data type 5.py
197
3.71875
4
a = {'a':100, 'b':'x', "c": "100"} print (a) print(type(a)) print(type(a.keys())) a['a'] = 'abc' print(a) a['x'] = 'xxx' print(a) print(a.values()) print(a.items()) a.pop('a') print(a)
94a7dcf22d42f2b0eb20fd83ffd0e8505871abaf
benkeanna/pyladies
/08/ukol0-6.py
1,698
3.609375
4
domaci_zvirata = ['pes', 'kočka', 'králík', 'had'] print('Ukol0: ', domaci_zvirata) def jmena_kratsi_5(domaci_zvirata): # ukol1 ukol1 = [] for zvire in domaci_zvirata: if len(zvire) < 5: ukol1.append(zvire) return ukol1 print('Ukol1: ',jmena_kratsi_5(domaci_zvirata)) def jmena_k(domaci_zvirata): # ukol2 ukol2 = [] for zvire in domaci_zvirata: if zvire[0] == 'k': ukol2.append(zvire) return ukol2 print('Ukol2: ',jmena_k(domaci_zvirata)) #ukol3 = input('Zadej slovo, podívám se, jestli se v seznamu zvířat. ') def je_v_seznamu(ukol3): if ukol3 in domaci_zvirata: return True return False print('Ukol3 - pes:',je_v_seznamu('pes')) print('Ukol3 - holub:',je_v_seznamu('holub')) ukol4 = ['klokan','pes','had','tygr',] def porovnani_ukol4(ukol4, domaci_zvirata): oba_seznamy = [] prvni_seznam = [] druhy_seznam = [] for zvire2 in ukol4: for zvire in domaci_zvirata: if zvire == zvire2: oba_seznamy.append(zvire) elif zvire not in ukol4: if zvire not in druhy_seznam: # zajisti, aby se zvirata do seznamu nezapsala pri kazdem pruchodu polem druhy_seznam.append(zvire) elif zvire2 not in domaci_zvirata: if zvire2 not in prvni_seznam: # zajisti, aby se zvirata do seznamu nezapsala pri kazdem pruchodu polem prvni_seznam.append(zvire2) return oba_seznamy, prvni_seznam, druhy_seznam print('Ukol4: ',porovnani_ukol4(ukol4, domaci_zvirata)) def serad(domaci_zvirata): ukol5 = sorted(domaci_zvirata) return ukol5 print('Ukol5: ',serad(domaci_zvirata))
b185d88e88b286539bd4accf188f85cdd806da5d
LordVader197/python_prerelease_task1
/task1.py
771
3.5625
4
total = raw_input("eeror") careers = 2 meal = 0 theatre = 0 price = 0 coach = 0 ppc = 0 if total >= 36 : print "error more than 36 cannot go" if total > 24: careers = careers + 1 if total >= 12 and total <= 16: meal = 14 theatre = 21 coach = 150 price = meal * theatre + coach ppc = price / total print "your total cost per person is " ppc if total >= 17 and total <= 26: meal = 13.50 theatre = 20 coach = 190 price = meal * theatre + coach ppc = price/total if total >= 27 and total <= 36: meal = 13 theatre = 19.0 coach = 225 ppc = price/ total
b65ac45d7df3fdc5ced231941ed45e9ce8f4fe61
flavius87/aprendiendo-python
/02-variables-y-tipos/tipos.py
676
3.640625
4
nada = None cadena = "Hola, soy Flavio Scheck" entero = 99 flotante = 4.2 booleano = True lista = [10, 20, 30, 40, 50] tuplaNoCambia = ("master", "en", "python") diccionario = { "nombre": "Flavio", "apellido": "Scheck"} # imprimir variable print(nada) print(entero) print(flotante) print(booleano) print(lista) print(tuplaNoCambia) print(diccionario) # mostrar tipo de dato print(type(nada)) print(type(cadena)) print(type(entero)) print(type(flotante)) print(type(booleano)) print(type(lista)) print(type(tuplaNoCambia)) print(type(diccionario)) # convertir datos texto = "hola soy un texto" numerito = str(776) print(texto + " " + numerito) numerito = int(776) print(numerito)
eb4eb4223b75b57d2b26c20b9912503d5fbcaaf3
jfuini/Data-Structures
/Queue.py
911
3.9375
4
# -*- coding: utf-8 -*- """ Created on Sun May 08 14:08:26 2016 @author: John Fuini """ class Queue: def __init__(self): self.items = [] def is_empty(self): if len(self.items) == 0: return True else: return False def enqueue(self, item): self.items.append(item) return self def dequeue(self): item = self.items[0] self.items = self.items[1:] return item def print_que_items(self): for i in range(len(self.items)): print(self.items[i]) def size(self): return len(self.items) que1 = Queue() print(que1.is_empty()) que1.enqueue('a') que1.enqueue('b') que1.enqueue('c') que1.enqueue('d') que1.print_que_items() removed_item = que1.dequeue() print("removed item %s" % removed_item) que1.print_que_items() print(que1.size())
9a0a81ca5901b5f6e20fab0eb2615e27489ea228
Afahakani/Python-Tasks
/calculator.py
92
4.0625
4
import math radius = int(input("Enter a number: ")) area = math.pi * radius**2 print(area)
52b4962d31d19137b1978e1801a596690ab1326f
Debjit337/School_management
/extra.py
4,095
4.1875
4
import os def choices(): message=''' ----------------------------------- welcome Admin ----------------------------------- 1.Create New School 2.Choose Existing School 3.Exit ----------------------------------- Only enter number: ''' try: option=int(input(message)) except ValueError: print('\nYou have entered wrong input in the place of number.Please do it again with the right input.') except NameError: print('You have entered alphabet which is wrong input.Please do it again with the right input.') except: print('There is a problem in the input.Please do it again with the right input.') else: if option==1: print('\nCreate New School') elif option==2: print('\nChoose Existing School') elif option==3: print('\nYou have successfully Exited.') else: print('You have entered wrong ipuut.Please do it again with the right input.') #Function for class choice def class_choice(school_name): message=''' ----------------------------------- School {0} ----------------------------------- 1.Create New Class 2.Choose Existing Class 3.Exit ----------------------------------- Only enter number: ''' .format(school_name) try: option=int(input(message)) except ValueError: print('\nYou have entered wrong input in the place of number.Please do it again with the right input.') except NameError: print('You have entered alphabet which is wrong input.Please do it again with the right input.') except: print('There is a problem in the input.Please do it again with the right input.') else: if option==1: print('\nCreate New Class') elif option==2: print('\nChoose Existing Class') elif option==3: print('\nYou have successfully Exited.') else: print('You have entered wrong ipuut.Please do it again with the right input.') # Create new school function:yaha par ek school ke name se folder create hoga and school ka name ek school_list.txt # me addon hoga. def create_new_school(): #print('\nCreate New School') #get school name school_name = input('Enter new school name: ') add_school_name = open('school_list','a') add_school_name.write('\n'+school_name) add_school_name.close() #school name se folder create karna hai os.mkdir('C:/python/School_management/Schools/'+school_name) print('\nCongratulations,new school'+ school_name +'has been created.') #new school create hone ke baad me class ke option ke function ko call karna hai. class_choice(school_name) # Choose school function :yaha se existing school folder ke andar enter honge. def choose_school(): print('\nChoose Existing School') message=''' ----------------------------------- welcome Admin ----------------------------------- 1.Create New School 2.Choose Existing School 3.Exit ----------------------------------- Only enter number: ''' try: option=int(input(message)) except ValueError: print('\nYou have entered wrong input in the place of number.Please do it again with the right input.') except NameError: print('You have entered alphabet which is wrong input.Please do it again with the right input.') except: print('There is a problem in the input.Please do it again with the right input.') else: if option==1: #print('\nCreate New School') create_new_school() elif option==2: #print('\nChoose Existing School') choose_school() elif option==3: print('\nYou have successfully Exited.') else: print('You have entered wrong ipuut.Please do it again with the right input.')
4872efc517dc76252673d05df4f830ce36ec5f68
GrishaAdamyan/All_Exercises
/Medium.py
150
3.515625
4
count = 0 a = 0 x = float(input()) while x > -300: count += 1 a += x x = float(input()) print(a/count) #22.3 #24.1 #24.0 #24.4 #-301 23.7
cc245806fff8817ca2695ccb360cb46ae5a93212
gitby15/cs231n
/first-assignment/classifiers/K_Nearest_Neighbor.py
1,092
3.59375
4
# -*-coding:utf8-*- import numpy as np class KNearestNeighbor(object): """ K Nearest Neighbor Classifier 输入一个K值 计算每个分类的distances,选出最小的k个分类 让这k个分类分别对测试数据进行投票,票数最高的分类获胜 """ def __init__(self): self.data_train = [] self.label_train = [] def train(self, X, y): """ :param X: 训练集数据 :param y: 训练集标签 """ self.data_train = X self.label_train = y pass def predict(self, X): """ :param X: 测试集数据 :return: 测试集标签 """ length = X.shape[0] label_test = np.zeros(length, dtype=self.label_train.dtype) for i in xrange(length): print 'predict: %s'%i distances = np.sum(np.abs(self.data_train - X[i, :]), axis=1) min_index = np.argmin(distances) label_test[i] = self.label_train[min_index] print 'label:%s'%label_test[i] return label_test
616cbfc8b527115ca92f85f474a69e1cc9940d60
chrylzzz/first_py
/day10/1.学院管理.py
2,542
3.859375
4
""" """ # 添加 #pass为还没有写的时候,避免出错 def add_info(): """添加""" # pass new_id = input('输入学号:') new_name = input('输入姓名:') new_tel = input("输入手机号:") global info # 遍历 info for i in info: # 用户名存在 if new_name == i['name']: print('用户已存在') return # 用户名不存在,添加 info_dict = {} info_dict['id'] = new_id info_dict['name'] = new_name info_dict['tel'] = new_tel info.append(info_dict) print(info) # 删除 def del_info(): # 显示所有 show_infos() this_id = str(input('请输入要删除的学生id:')) """删除""" global info for i in info: if this_id == i['id']: info.remove(i) break show_infos() # 修改 def update_info(): """修改""" show_infos() this_id = str(input('请输入要删除的学生id:')) global info for i in info: if this_id == i['id']: print(f'编号:{i["id"]},姓名:{i["name"]},电话:{i["tel"]}') this_name = input("请重新输入名字: ") this_tel = input("请重新输入手机号: ") i['name'] = this_name i['tel'] = this_tel break show_infos() # 查询 def find_info(): this_name = input('请输入名字:') for i in info: if this_name in i['name']: print(f'编号:{i["id"]},姓名:{i["name"]},电话:{i["tel"]}') break print('您查询的名字不存在') # 显示所有 def show_infos(): """显示所有""" for i in info: print(f'编号:{i["id"]},姓名:{i["name"]},电话:{i["tel"]}') def info_print(): print('请选择功能:------------') print('1.添加') print('2.删除') print('3.修改') print('4.查询') print('5.显示所有') print('6.退出') print('-' * 20) info = [] while True: # 显示功能 info_print() # 输入 use_num = int(input('输入功能: ')) if use_num == 1: # 添加 add_info() elif use_num == 2: # 删除 del_info() elif use_num == 3: # 修改 update_info() elif use_num == 4: # 查询名字 find_info() elif use_num == 5: # 查所有 show_infos() elif use_num == 6: flag = input('确定要退出吗? yes or no') if flag == 'yes': break else: print('输入有误..')