blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0b83e723312c427ce98ef2652f38d44296429ca1
councit/python_toy_projects
/notes/section3-notes.py
4,701
4.28125
4
# # Variables: # name = "Taylor" # age = 30 # gender = "male" # # Impliment # print(f'Hi {name}. You are {age} years old!') # # string indexing [start, stop, step] # indexText = 'Hi taylor what beer do you like?' # print(indexText[0::2]) # # Immutability # # You cannont reasign a part or index of a string once created. You can assign the whole new value as a reassignment. This is the concept of immutability. # #Build in Functions + Methods # # Length len() # lengthTest = "this is a test string" # print(len(lengthTest)) # # Exersize Type Conversion # birth_year = int(input('what year were you born?')) # age = 2020 - birth_year # print(birth_year) # print(f'Your age is {age} years old!') # # Password Checker # userName = input('Hi, please enter your user name: ') # password = input(f'Thank you {userName}, please enter a password.') # print(f'{userName} your password ***** is {len(password)} characters long.') # # Lists # cart_items = [ # 'thing 1', # 'thing 2', # 'thing 3', # ] # new_cart = cart_items[:] # copies items # print(new_cart) # Matrix arr in an arr # list_one = [1, 2, 3] # list_two = [4, 5, 6] # list_one.append(list_two[2]) # print(list_one) # Removing Items pop() you can index the pop # ecersize logical operators: # is_magician = True # is_expert = False # if is_magician and is_expert: # print("you are a master magician") # if is_magician and not is_expert: # print("at least youre getting there") # if not is_magician: # print('you need magical powers') # my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # list_sum = 0 # for i in my_list: # list_sum += i # print(list_sum) # # Find Duplicate Values # some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] # dupe_list = [] # for item in some_list: # if (some_list.count(item) > 1): # dupe_list.append(item) # print(set(dupe_list)) # # Functions # def say_hello(text): # return print(f'{text}') # say_hello('blah blah blah') # # Highest Even # def highest_even(li): # high_num = 0 # for number in li: # if (number % 2 == 0 and number > high_num): # high_num = number # return high_num # # print(highest_even([10, 2, 3, 52, 8, 11])) # x = 'hello'.replace # print(x) # # Classes # class PlayerCharacter: # def __init__(self, name, age, wepon): # self.name = name # self.age = age # self.wepon = wepon # def attack(self, attack_type): # print(attack_type) # player1 = PlayerCharacter('Taylor', 30, 'axe') # player1.attack(player1.wepon) # # Cat Excerise # class Cat: # species = 'mamal' # def __init__(self, name, age): # self.name = name # self.age = age # cat1 = Cat('fluffy', 4) # cat2 = Cat('sprinkles', 15) # cat3 = Cat('vinny', 2) # def find_old_cat(*args): # old_cat = 0 # for cat in args: # if (cat.age > old_cat): # old_cat = cat.age # return old_cat # print(f'The oldest cat is {find_old_cat(cat1, cat2, cat3)} years old!') # #Pets # class Pets(): # animals = [] # def __init__(self, animals): # self.animals = animals # def walk(self): # for animal in self.animals: # print(animal.walk()) # class Cat(): # is_lazy = True # def __init__(self, name, age): # self.name = name # self.age = age # def walk(self): # return f'{self.name} is just walking around' # class Simon(Cat): # def sing(self, sounds): # return f'{sounds}' # class Sally(Cat): # def sing(self, sounds): # return f'{sounds}' # class Vinny(Cat): # def sing(self, sounds): # return f'{sounds}' # my_cats = Simon("Simon", 20) # from functools import reduce # # 1 Capitalize all of the pet names and print the list # my_pets = ['sisi', 'bibi', 'titi', 'carla'] # def cap(item): # return item.upper() # print(list(map(cap, my_pets))) # # 2 Zip the 2 lists into a list of tuples, but sort the numbers from lowest to highest. # my_strings = ['a', 'b', 'c', 'd', 'e'] # my_numbers = [5, 4, 3, 2, 1] # new_list = list(zip(my_strings, my_numbers)) # print(new_list.sort()) # 3 Filter the scores that pass over 50% # scores=[73, 20, 65, 19, 76, 100, 88] # 4 Combine all of the numbers that are in a list on this file using reduce (my_numbers and scores). What is the total? # # Lamda test # my_list = [5, 4, 3] # print(list(map(lambda item: item**2, my_list))) # def generator_function(num): # for i in range(num): # yield i # def fib(num): # a = 0 # b = 1 # for i in range(num): # yield a # a = b # b = a + b # for i in fib(20): # print(i)
02f4ce94c002087b1695c58b0626a3440720cbe3
saierding/leetcode-and-basic-algorithm
/leetcode/二叉搜索树/Validate Binary Search Tree.py
877
3.875
4
# 98. Validate Binary Search Tree class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 中序遍历的迭代算法 def isValidBST(self, root): if not root: return True pre = None stack = [] while stack or root: if root: stack.append(root) root = root.left else: root = stack.pop() if pre and root.val <= pre.val: return False pre = root root = root.right return True node1 = TreeNode(5) node2 = TreeNode(4) node3 = TreeNode(15) node4 = TreeNode(3) node5 = TreeNode(21) node1.left = node2 node1.right = node3 node3.left = node4 node3.right = node5 s = Solution() print(s.isValidBST(node1))
1c8ed41e193f023eaf38fee38f67dedcd9b41110
Vijaya-Malini-A/guvi
/Code Kata/no_palin.py
82
3.703125
4
n = int(raw_input()) n = str(n) if n == n[::-1]: print "yes" else: print "no"
3b85489c5e60f5d991af261aa83a77f5e16451a8
subodhss23/python_small_problems
/medium_problems/box_completely_filled.py
482
3.9375
4
''' Create a function that check if the box is completely filled with the asterisk symbol * ''' def completely_filled(lst): for i in lst: if ' ' in i: return False return True print(completely_filled([ "#####", "#***#", "#***#", "#***#", "#####" ])) print(completely_filled([ "#####", "#* *#", "#***#", "#***#", "#####" ])) print(completely_filled([ "###", "#*#", "###" ])) print(completely_filled([ "##", "##" ]))
b41c8b1ab118b67ad257926743bbcfa6123e8031
Giu514/The-Python-Workbook
/Exercise/1-11.py
291
4.03125
4
#Fuel Efficiency covert from mpg to L/100 KM miles = float(input("Enter the number of miles done: ")) gallons = float(input("Enter the number of gallons consumed: ")) mpg = float(miles/gallons) can = float(235.214583 / mpg) print("{} mpg, equivalent to {:.2f} L/100km".format(mpg, can))
06ff28dcdeeca6f0eec3505513d719373c33b9ab
cloudsecuritylabs/learningpython3
/ch1/askforage2.py
377
4.09375
4
# Get the input and assign the variable in the same line age = input('How old are you?') height = input('How tall are you?') weight = input('what is your weight?') # Print using format print('You are {} years old, {} inches tall and you weight {} lbs'.format(age, height, weight)) # Print using f print(f'You are {age} years old, {height} inches tall and {weight} lbs heavy')
cba693c4fa74b5d45525791b45683fb4ace5e1f4
rmbrntt/6.00.1x
/week 3/PSet3.5_hangman.py
3,546
4.21875
4
__author__ = 'ryan@barnett.io' def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' # FILL IN YOUR CODE HERE... #correct_letters = [] guessed_word = [] for length in secretWord: guessed_word.append('_ ') for letter in lettersGuessed: if letter in secretWord: #correct_letters.append(letter) letter_occurrence = secretWord.count(letter) next_index = 0 for num_times in range(letter_occurrence): current_index = secretWord.find(letter, next_index) guessed_word[current_index] = letter next_index = current_index+1 return ''.join(guessed_word) # for c in secretWord: # print c # if c not in correct_letters: # return False # return True def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. ''' # FILL IN YOUR CODE HERE... import string alphabet = string.ascii_lowercase available_letters = [] for letter in alphabet: if letter not in lettersGuessed: available_letters.append(letter) return ''.join(available_letters) def hangman(secretWord): ''' secretWord: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secretWord contains. * Ask the user to supply one guess (i.e. letter) per round. * The user should receive feedback immediately after each guess about whether their guess appears in the computers word. * After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed. Follows the other limitations detailed in the problem write-up. ''' # FILL IN YOUR CODE HERE... print 'Welcome to the game, Hangman!' print 'I am thinking of a word that is %s letters long.' % len(secretWord) print '-------------' num_guesses = 8 lettersGuessed = [] while num_guesses > 0: print 'You have %s guesses left.' % num_guesses print 'Available letters:', getAvailableLetters(lettersGuessed) letterGuessed = raw_input('Please guess a letter: ') if letterGuessed in secretWord and letterGuessed not in lettersGuessed: lettersGuessed.append(letterGuessed.lower()) print 'Good guess:', getGuessedWord(secretWord, lettersGuessed) elif letterGuessed in lettersGuessed: print 'Oops! You\'ve already guessed that letter:', getGuessedWord(secretWord, lettersGuessed) elif letterGuessed not in secretWord and letterGuessed not in lettersGuessed: num_guesses -= 1 lettersGuessed.append(letterGuessed.lower()) print 'Oops! That letter is not in my word:', getGuessedWord(secretWord, lettersGuessed) print '-------------' if getGuessedWord(secretWord, lettersGuessed) == secretWord: return 'Congratulations, you won!' return 'Sorry, you ran out of guesses. The word was %s.' % secretWord print hangman('apple')
f16bb3f50fe9d0c01416c89acd74ec8943fbd6b6
EetheridgeIV/LeetCodePy
/9.palindromeInt/solution.py
382
3.984375
4
def isPalindrome(x: int) -> bool: strX = str(x) for i,letter in enumerate(reversed(strX)): if(letter != strX[i]): return False return True def main(): print("Testing 123") print(isPalindrome(123)) print("Testing -123") print(isPalindrome(-123)) print("Testing 123321") print(isPalindrome(123321)) main()
87ae648c40bfc46f8576c74e7a7edcb65af7648d
xoiss/python-intf
/intf/__init__.py
5,164
4.03125
4
"""``intf`` provides a simple base class for integers with specified default formatting. Define your own subclasses derived from `BaseIntF` and specify desired formatting right with the class name. Decimal, binary, octal and hexadecimal formats are supported. See `BaseIntF` for more details. Example:: from intf import BaseIntF class int_04X(BaseIntF): pass x = int_04X(123) print '{}'.format(x) # prints 0x007B class int_06o(BaseIntF): pass y = int_06o(123) print '{}'.format(y) # prints 0o000173 class int_08b(BaseIntF): pass z = int_08b(123) print '{}'.format(z) # prints 0b01111011 print '{:02x}'.format(z) # still prints 7b """ import re class _MetaIntF(type): """Metaclass for subclasses of `BaseIntF`. This metaclass creates specialized subclasses with desired integer formatting. Its main duty is to parse the class name, extract the format specification and put it into the class being created. """ def __new__(cls, name, bases, dict_): if name != _MetaIntF._base_class_name: res = _MetaIntF._class_name_template.match(name) if res is None: syntax_error = SyntaxError( "invalid name '%s' for a class derived from '%s'" % (name, _MetaIntF._base_class_name)) raise syntax_error dict_['_format_spec'] = res.group('format_spec') base_spec = res.group('pres_type').lower() dict_['_base_prefix'] = '0' + base_spec if base_spec != 'd' else '' else: dict_['_format_spec'] = '' dict_['_base_prefix'] = '' return type.__new__(cls, name, bases, dict_) _base_class_name = 'BaseIntF' _class_name_template = re.compile( r"^int_(?P<format_spec>(?:0[1-9][0-9]*)?(?P<pres_type>[dboxX]))$") class BaseIntF(int): """Base class for integers with specified default formatting. When `str.format` is called on a string with replacement field which does not define ``format_spec`` explicitly, the default formatting for `int` argument is ``"{:d}"``. This default behavior cannot be changed by ordinary means as soon as the built-in `int` class and its instances prohibit modification of their fields and methods. So, when specific formatting like ``"0x{:04X}"`` or another is desired for particular variables, it must be specified explicitly in the replacement field. However, in some cases it might be very useful to bind specific formatting to particular variable and use it implicitly everywhere when such variable is printed, logged, etc. instead of specifying the same format multiple times in distant places. At least it helps to avoid potential inconsistency between points of use and bugs in specifying formatting codes, eliminate unnecessary copy-paste and abstract the code from insignificant details. To use this feature simply define an empty subclass based on this one and name your derived class according to the following template: ``^int_(0[1-9][0-9]*)?[dboxX]$``. The second part of the class name (the one after ``'_'`` delimiter) will define the default formatting of integer values that are instances of that class: * the trailing character denotes presentation type: decimal, binary, octal, and hexadecimal using lower- or upper-case letters. For all types except decimal the output is prepended with the base prefix: ``'0b'``, ``'0o'``, ``'0x'`` * the preceding number specifies minimum field width if given. Note that base prefix such as ``'0x'`` does not consume the width * the first zero symbol instructs formatter to use zero as the fill character to pad the field to the whole width. Currently only zero is allowed, so it must be put if field width is given Example:: class int_04X(BaseIntF): pass x = int_04X(123) print '{}'.format(x) # prints 0x007B This is roughly equivalent to:: x = 123 print '0x{:04X}'.format(x) Note that different (nondefault) formatting still may be used also:: x = int_04X(123) print '{:08b}'.format(x) # prints 0b01111011 .. note:: This class should not be used directly. Derive subclasses with specific formatting as described above. .. warning:: Arithmetic operations over this class are possible as for `int` but the result will have the pure `int` type, so the formatting from the argument is not inherited by the result. """ __metaclass__ = _MetaIntF def __format__(self, format_spec): """Format this integer object. :arg str format_spec: forces the format if given, otherwise the default formatting specific to this class is used :returns: string with formatted representation of integer value """ if not format_spec: return self._base_prefix + int.__format__(self, self._format_spec) return int.__format__(self, format_spec)
92109dbb30f3430fdf8c5962eee60b5476ad763c
Lesetja2010/Python-Book
/chapter3_endof_chpt_exercises.py
4,008
4.125
4
#! /usr/bin/env python """ Counts the number of occurences of the search_string in the input_file, and prints the lines containing the search_string. command line options: -i conducts a case 'insensitive' search, ie. "text", "Text", "TEXT", etc. will all be counted -m counts multiple occurences of the search string in one line, without '-m', only one occurence per line is counted. --help prints this doc string, along with a usage message. """ import sys import getopt help_message = """ Counts the number of occurences of the search_string in the input_file, and prints the lines containing the search_string. command line options: -i conducts a case 'insensitive' search, ie. "text", "Text", "TEXT", etc. will all be counted -m counts multiple occurences of the search string in one line, without '-m', only one occurence per line is counted. --help prints this doc string, along with a usage message. """ def usage(): print >> sys.stderr, "Usage: fgrepwc [-i] [-m] search_string file_name." print >> sys.stderr, "Or try, fgrepwc --help, for more information." exit(1) def find_all(search_string, file_name, case_insensitive = False, multiple_occurences = False): try: f_handle = open(file_name, "r") except: print >> sys.stderr, ("Error openning file %s." %(file_name)) print >> sys.stderr, sys.exc_info() exit(2) count = 0 index = 0 original_line = "" lines = f_handle.readlines() f_handle.close() for line in lines: line = line.rstrip() #getting rid of the newline character at the end of the line if case_insensitive: original_line = line search_string = search_string.lower() line = line.lower() line_length = len(line) if multiple_occurences: index = 0 while line.find(search_string, index, line_length) > -1: count += 1 if index == 0: print original_line index = line.find(search_string, index, line_length) + len(search_string) else: if line.find(search_string) > -1: count += 1 print line print count #---------------------------------------------------------------------------------------------------------# def check_args(): m = False i = False argc = len(sys.argv) if argc < 2: usage() if argc == 2: if (sys.argv[1]).lower() == "--help": print >> sys.stderr, help_message usage() else: usage() options, args = getopt.getopt(sys.argv[1:], "-i-m") if options: for a, b in options: # Since options is a list of tuples (using 'multuple' assignment). b in this case will always be a null string. if a == "-i": i = True elif a == "-m": m = True else: print >> sys.stderr, ("Unrecognised command line option: "+a+".")#this part is not necessary #because getopt() throws an exception when it finds an unrecognised option find_all(args[0], args[1], i, m) if __name__ == "__main__": check_args()
75606e7e394787afb4f3fb19ebb8abf6027f15f8
fugin213/CPU_python_exercise
/Answer_exercise7.py
471
4.0625
4
while 1==1: x=input("please enter a number: ") x=int(x) tag=0 if (x==1): tag=2 for i in range(x): if (i!=0 & i!=x): if (i!=1): if x%i!=0: continue else: tag=1 if tag==0: print("This is a prime number!") elif tag==2: print("1 is not a prime number!") else: print("This is not a prime number")
d4875118a2ce89c197eed4ce7d71fc66d4dc3e2e
good5229/python-practice
/2577.py
613
3.765625
4
def count_num(num_1, num_2, num_3): if num_1 < 100 or num_2 < 100 or num_3 < 100: print("100 이하의 숫자가 입력되었습니다.") elif num_1 >= 1000 or num_2 >= 1000 or num_3 >= 1000: print("1000 이상의 숫자가 입력되었습니다.") else: result = num_1 * num_2 * num_3 count = [0 for i in range(10)] list = [] for i in str(result): digit = int(i) count[digit] += 1 for i in count: print(i) num_1 = int(input('')) num_2 = int(input('')) num_3 = int(input('')) count_num(num_1, num_2, num_3)
0fa51504eed8e748ed1efbf57d5316a5623c5dcf
MiroVatov/Python-SoftUni
/Python Basic 2020/Exam 06 - 06 high jump ver 3.py
645
3.671875
4
height_target = int(input()) letva_height = height_target - 30 jump_counter = 0 fail_counter = 0 while letva_height <= height_target: fail_counter = 0 for i in range(1, 4): jump_height = int(input()) jump_counter += 1 if jump_height > letva_height: letva_height += 5 break else: fail_counter += 1 if fail_counter == 3: print(f'Tihomir failed at {letva_height}cm after {jump_counter} jumps.') break if jump_height > height_target: print(f'Tihomir succeeded, he jumped over {height_target}cm after {jump_counter} jumps.')
a8b97ba9bb36ccdbc8ef66e725a8f3c0b2df7a57
rafaelperazzo/programacao-web
/moodledata/vpl_data/35/usersdata/101/13444/submittedfiles/dec2bin.py
187
3.828125
4
# -*- coding: utf-8 -*- from __future__ import division p = str(input('Digite um inteiro p: ')) q = str (input('Digite um inteiro q: ')) if p in q: print ('S') else: print ('N')
75bcf40a7e6632fa27b03e872b73a899c8e4164c
Lyppeh/PythonExercises
/Introductory Exercises/ex017.py
256
3.671875
4
from math import hypot cateto1 = float(input('Comprimento do cateto oposto: ')) cateto2 = float(input('Comprimento do cateto adjacente: ')) hipotenusa = hypot(cateto1 , cateto2) print('O comprimento do hipotenusa sera : {:.2f}'.format(hipotenusa))
558a6d962a78370d9750a543593e32c4b498d42e
standrewscollege2018/2020-year-11-classwork-htw0835
/hello world.py
255
3.546875
4
""" I'm so smart and have such a huge veiny brain. I made this all on my own on my very first try. I even figured out how to join strings. Put me in year 13 digi already, Phil. """ #This makes the words show up. print("Hello world!"+" I'm experimenting!")
c82bdefc311827fe5f6d6fad176925a8d6aa6cf8
Jane11111/Leetcode2021
/075_3.py
885
3.796875
4
# -*- coding: utf-8 -*- # @Time : 2021-06-04 14:55 # @Author : zxl # @FileName: 075_3.py class Solution: def sortColors(self, nums ) -> None: """ Do not return anything, modify nums in-place instead. """ arr = [0,0,0] for num in nums: arr[num] += 1 p_lst = [0,arr[0],arr[0]+arr[1]] i = 0 while i<len(nums): num = nums[i] if num>=3: i+=1 continue if p_lst[num] ==i: i+=1 p_lst[num] += 1 else: idx = p_lst[num] nums[i],nums[idx] = nums[idx],nums[i] nums[idx] +=3 p_lst[num]+=1 for i in range(len(nums)): nums[i] = nums[i]%3 obj = Solution() nums = [2,0,1] ans = obj.sortColors(nums) print(nums)
0bd3743cd02529a99339f43ce394c1d0e2039d04
Johnnyprox/APRG_projekt
/enc.py
8,218
3.5625
4
from copy import copy def number_of_matrixes(message): """This functin returns the number of matrixes""" n_o_m = len(message) // 16 + 1 return n_o_m def fill_places(message): """ This function fills all places in the matrix """ reminder = len(message) % 16 if reminder != 0: for p in range(0, 16 - reminder): message = message + " " return message def convert_m(message): """ This function converts the message to list and hex """ message = fill_places(message) message = list(message) conv_m = [] for item in message: p = hex(int(ord(item))).replace("0x", "") conv_m.append(p) return conv_m def create_matrix(message): """ This function divides the message into 16-lists """ conv_m = convert_m(message) n_o_m = number_of_matrixes(message) matrix = [] for q in range(n_o_m): p = [] for r in range(16): p.append(conv_m[0]) del conv_m[0] matrix.append(p) return matrix def edit(message): """ This function edits the matrix (replaces columns with rows) """ matrix = create_matrix(message) n_o_m = number_of_matrixes(message) n_o_m_2 = number_of_matrixes(message) new_matrix = [] index = 0 while n_o_m_2 > 0: new_matrix.append([matrix[index][0], matrix[index][4], matrix[index][8], matrix[index][12], matrix[index][1], matrix[index][5], matrix[index][9], matrix[index][13], matrix[index][2], matrix[index][6], matrix[index][10], matrix[index][14], matrix[index][3], matrix[index][7], matrix[index][11], matrix[index][15]]) n_o_m_2 -= 1 index += 1 return new_matrix, n_o_m def add_round_key(new_matrix, key): """ This function add round key """ mat = [] mat_with_key = [] for p in key: for q in p: mat.append(q) for i in range(16): mat_with_key.append("{0:02x}".format(int(bin(int(new_matrix[i], 16) ^ int(mat[i], 16)), 2)).replace("0x", "")) return mat_with_key def sub_bytes(matrix): """ This function replaces elements from matrix to element from sbox """ converted_matrix = [] s_matrix = [] for items in matrix: for item in items: if item in hex_convert: item = hex_convert[item] converted_matrix.append(item) for item in range(len(matrix)): row = int(converted_matrix[item * 2]) col = int(converted_matrix[item * 2 + 1]) s_matrix.append(sbox[row][col]) return s_matrix def shift_rows(s_matrix): """ This function shifts rows of matrix """ sh_matrix = [[s_matrix[0], s_matrix[5], s_matrix[10], s_matrix[15]], [s_matrix[4], s_matrix[9], s_matrix[14], s_matrix[3]], [s_matrix[8], s_matrix[13], s_matrix[2], s_matrix[7]], [s_matrix[12], s_matrix[1], s_matrix[6], s_matrix[11]]] return sh_matrix def galoisMult(a, b): """ This function is Galois Multiplication """ p = 0 set = 0 for i in range(8): if b & 1 == 1: p ^= a set = a & 0x80 a <<= 1 if set == 0x80: a ^= 0x1b b >>= 1 return p % 256 # mixColumn def mix_column(column) """ This function mixes columns of the matrix """ temp = copy(column) column[0] = galoisMult(temp[0], 2) ^ galoisMult(temp[3], 1) ^ \ galoisMult(temp[2], 1) ^ galoisMult(temp[1], 3) column[1] = galoisMult(temp[1], 2) ^ galoisMult(temp[0], 1) ^ \ galoisMult(temp[3], 1) ^ galoisMult(temp[2], 3) column[2] = galoisMult(temp[2], 2) ^ galoisMult(temp[1], 1) ^ \ galoisMult(temp[0], 1) ^ galoisMult(temp[3], 3) column[3] = galoisMult(temp[3], 2) ^ galoisMult(temp[2], 1) ^ \ galoisMult(temp[1], 1) ^ galoisMult(temp[0], 3) # mixColumnInv def mixColumnInv(column): """ This function mixes columns of the matrix """ temp = copy(column) column[0] = galoisMult(temp[0], 14) ^ galoisMult(temp[3], 9) ^ \ galoisMult(temp[2], 13) ^ galoisMult(temp[1], 11) column[1] = galoisMult(temp[1], 14) ^ galoisMult(temp[0], 9) ^ \ galoisMult(temp[3], 13) ^ galoisMult(temp[2], 11) column[2] = galoisMult(temp[2], 14) ^ galoisMult(temp[1], 9) ^ \ galoisMult(temp[0], 13) ^ galoisMult(temp[3], 11) column[3] = galoisMult(temp[3], 14) ^ galoisMult(temp[2], 9) ^ \ galoisMult(temp[1], 13) ^ galoisMult(temp[0], 11) def mix_columns(s_matrix): """ This function mixes columns of the matrix """ for i in range(4): column = [] for j in range(4): column.append(s_matrix[j*4+i]) mixColumn(column) # transfer the new values back into the state table for j in range(4): s_matrix[j*4+i] = column[j] def mixColumnsInv(s_matrix): """ This function mixes columns of the matrix """ for i in range(4): column = [] for j in range(4): column.append(s_matrix[j*4+i]) mixColumnInv(column) for j in range(4): s_matrix[j*4+i] = column[j] def xor_m(x, y): """ This function does XOR operation """ xor_m = [] for p in range(4): for q in range(4): xor_m.append("{0:02x}".format(int(bin(int(x[p][q], 16) ^ int(y[p][q], 16)), 2)).replace("0x", "")) return xor_m def add_next_key(mix_c, a_key): """This add round key after mix columns operation.""" add_rk = xor_m(mix_c, a_key) return add_rk def deconvert_m(m): """This transcript the message from hexadecimal""" dec_message = "" message = [m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15]] for p in message: dec_message = dec_message + (chr(int(p, 16))) return dec_message hex_convert = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15} sbox = [["63", "7c", "77", "7b", "f2", "6b", "6f", "c5", "30", "01", "67", "2b", "fe", "d7", "ab", "76"], ["ca", "82", "c9", "7d", "fa", "59", "47", "f0", "ad", "d4", "a2", "af", "9c", "a4", "72", "c0"], ["b7", "fd", "93", "26", "36", "3f", "f7", "cc", "34", "a5", "e5", "f1", "71", "d8", "31", "15"], ["04", "c7", "23", "c3", "18", "96", "05", "9a", "07", "12", "80", "e2", "eb", "27", "b2", "75"], ["09", "83", "2c", "1a", "1b", "6e", "5a", "a0", "52", "3b", "d6", "b3", "29", "e3", "2f", "84"], ["53", "d1", "00", "ed", "20", "fc", "b1", "5b", "6a", "cb", "be", "39", "4a", "4c", "58", "cf"], ["d0", "ef", "aa", "fb", "43", "4d", "33", "85", "45", "f9", "02", "7f", "50", "3c", "9f", "a8"], ["51", "a3", "40", "8f", "92", "9d", "38", "f5", "bc", "b6", "da", "21", "10", "ff", "f3", "d2"], ["cd", "0c", "13", "ec", "5f", "97", "44", "17", "c4", "a7", "7e", "3d", "64", "5d", "19", "73"], ["60", "81", "4f", "dc", "22", "2a", "90", "88", "46", "ee", "b8", "14", "de", "5e", "0b", "db"], ["e0", "32", "3a", "0a", "49", "06", "24", "5c", "c2", "d3", "ac", "62", "91", "95", "e4", "79"], ["e7", "c8", "37", "6d", "8d", "d5", "4e", "a9", "6c", "56", "f4", "ea", "65", "7a", "ae", "08"], ["ba", "78", "25", "2e", "1c", "a6", "b4", "c6", "e8", "dd", "74", "1f", "4b", "bd", "8b", "8a"], ["70", "3e", "b5", "66", "48", "03", "f6", "0e", "61", "35", "57", "b9", "86", "c1", "1d", "9e"], ["e1", "f8", "98", "11", "69", "d9", "8e", "94", "9b", "1e", "87", "e9", "ce", "55", "28", "df"], ["8c", "a1", "89", "0d", "bf", "e6", "42", "68", "41", "99", "2d", "0f", "b0", "54", "bb", "16"]] rcon = ["01", "02", "04", "08", "10", "20", "40", "80", "1b", "36"]
0a4ee4985d3d15b2b7aa081d6c150d99387fcb81
chavhanpunamchand/PythonPractice
/Strings/areaofcircle.py
342
4.5
4
''' 4. Write a Python program which accepts the radius of a circle from the user and compute the area. Go to the editor Sample Output : r = 1.1 Area = 3.8013271108436504 ''' radius=float(input("Enter the radius of circle :")) pie_value=3.141592653589793238 area_of_circle=pie_value* radius**2 print("The area of circle is :",area_of_circle)
b8a9e3ce715273f69de5e20673c0e5678b48fd23
tiagomenegaz/othello-s
/initialiseBoard.py
450
4.03125
4
## 2nd Assignment #Question 1 #def initialiseBoard(n): #initialiseBoard(n) returns the initial board for an Othello game of size n. def initialiseBoard(n): zeros = [0]*n for i in range(0,n): zeros[i]=[0]*n pos2 = int(len(zeros)/2) #Position 4 pos = int(pos2-1) #From example -> Position 3 zeros[pos][pos] = 1 zeros[pos][pos2] = -1 zeros[pos2][pos] = -1 zeros[pos2][pos2] = 1 return zeros
570d2801e21e3eb5b8875b228326fb0c3561618b
i-aditya-kaushik/geeksforgeeks_DSA
/Matrix/Codes/transpose.py
1,296
4.4375
4
""" Transpose of Matrix Write a program to find transpose of a square matrix mat[][] of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows. Input: The first line of input contains an integer T, denoting the number of testcases. Then T test cases follow. Each test case contains an integer N, denoting the size of the square matrix. Then in the next line are N*N space separated values of the matrix. Output: For each test case output will be the space separated values of the transpose of the matrix User Task: The task is to complete the function transpose() which finds the transpose of the matrix. The printing is done by the driver code. Constraints: 1 <= T <= 15 1 <= N <= 20 -103 <= mat[i][j] <= 103 Example: Input: 2 4 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 2 1 2 -9 -2 Output: 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 -9 2 -2 Explanation: Testcase 1: The matrix after rotation will be: 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4. Testcase 2: The matrix after rotation will be: 1 -9 2 -2. ** For More Input/Output Examples Use 'Expected Output' option ** """ def transpose(mat,n): for x in range(n): for y in range(n): if(y>x): break temp = mat[x][y] mat[x][y]= mat[y][x] mat[y][x]=temp
ef0232d07109e64dec7df7522cac7a761e6b3c73
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter04/0004_demonstrate_function_scope.py
587
4.09375
4
''' Program 4.3 Demonstrate Using the Same Variable Name in Calling Function and Function Definition arguments passed by the calling program and the parameters used to receive the values in the function definition may have the same variable names exist in different scopes however and thus independent ''' god_name = input("Who is the God of Seas according to Greek Mythology?") def greek_mythology(god_name): print(f"The God of seas according to Greek Mythology is {god_name}") def main(): greek_mythology(god_name) if __name__ == "__main__": main()
b5af0e48da34b1bf1f3430ac7de86994aa43a93a
RaviAnthony/Python-practice-
/dict.py
1,091
3.75
4
states = {'Telangana':'TS','Andhra':'A','Tamilnadu':'TN','Delhi':'D'} cities ={ 'hyderabad':'hyd','vijayawada':'vz', 'Madras':'M', 'Nizam':'NZ'} cities['TS'] = 'Secundrabad' cities['A'] = ' warangal' print '-' *10 print "TS State has:", cities['TS'] print " A State has :", cities['A'] print '-'*10 print " Telangana's abbrev is : ", states['Telangana'] print "Tamilnadu's abbrev is : ", states['Tamilnadu'] print '-'*10 print " Telangana's abbrev is : ", cities[states['Telangana']] print "'Andhra' abbrev is : ", cities[states['Andhra']] print '-'*10 for state, abbrev in states.items(): print"%s is abbrev %s" %(state,abbrev) print '-'*10 for cities, abbrev in cities.items(): print"%s is abbrev %s" %(cities,abbrev) print '-'*10 #for state, abbrev in states.items(): # print "%r state is abbrev %r and has city %r" % (state, abbrev, cities[abbrev]) print '-'*10 State = State.get('Telangana', None) if not State: print"sorry, no Telangana" city= cities.get('TS','Does not exit') print "The city for the state 'TS'is: %s" %city
bbe81caca211f9d5be3cf3fe9652b902888b8d73
nuljon/Python-Course-Files
/BasicCoding_Drills/statements.py
231
4.15625
4
# Define variables x = 1 # start an if statement if x == 10: print 'x = 10' # if x does not equal 10, but equals 9 elif x == 9: print 'x = 9' # if not 10 or 9 then ... else: print 'x does not equal 9 or 10'
45160f2d5b3685bc401cbd2b8171760d7de58baa
joshuazd/equations
/root.py
925
3.625
4
class Infix(object): def __init__(self, function): self.function = function def __ror__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __or__(self, other): return self.function(other) def __rlshift__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __rshift__(self, other): return self.function(other) def __call__(self, value1, value2): return self.function(value1, value2) def __pow__(self, other): return Infix(lambda x, self=self, other=other: self.function(x, other)) def __rpow__(self, other): return self.function(other) def __mul__(self, other): return self.function(other) def __rmul__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) root = Infix(lambda x,y: y**(1.0/x))
55f876d47509ac024b845c08ffa091aef743e39c
ivanpedro/pythondevelop
/cesaro/cesaro/cesaro.py
411
3.75
4
#cesaro from turtle import * from math import * from random import * import random, string def piramide (size, level): if level == 0: for i in range (3): forward(size) left (120) else: coord =[(0,0),(size/2,0),(size/4,(size/2) + sin(60))] for x,y in coord: penup() goto(x,y) pendown() piramide (size, level-1) def main (): speed(500) piramide(300,1) main ()
be5749f5d497c3f57d03ca62c4f4db88920e312b
bandeirafelipe3/Programa-oWeb2017
/Exercicio_2/lista2questao8.py
303
4
4
def quociente(x,y): return x/y def resto(x,y): return x % y def main(): n1 = float(input("Primeiro numero = ")) n2 = float(input("Segundo numero = ")) n3 = int(input("Digite um numero = ")) print("Quociente = ", quociente(n1,n2)) print("Resto = ", resto(n1,n2)) print("Numero = ", n3) main()
bfbb129a89e1e64a3d13f6b2db508eae496a9cba
marcardioid/DailyProgrammer
/solutions/234_Intermediate/solution.py
528
3.65625
4
with open("enable1.txt") as file: dictionary = set(file.read().splitlines()) def spellcheck(word): fault = None for n in range(len(word) + 1): if not any(x.startswith(word[:n]) for x in dictionary): fault = "{}<{}".format(word[:n], word[n:]) break return fault if fault else "CORRECT" if __name__ == "__main__": with open("input/input2.txt", "r") as file: words = file.read().splitlines() for word in words: print("{}\t{}".format(word, spellcheck(word)))
48f15737f477a6fc827065e871f7a7af8e950a0a
johnnymango/IS211_Assignment3
/IS211_Assignment3.py
2,965
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Imported Modules import argparse import urllib2 import csv import re # Sets up the argparse to accept the url argument when the py file is executed. parser = argparse.ArgumentParser() parser.add_argument("--url", type=str, required=True) args = parser.parse_args() url = args.url # Function downloads the data from the argparse URL argument, reads and returns the data as csv def downloadData(urlname): response = urllib2.urlopen(urlname) mywebpage = csv.reader(response) return mywebpage #Function counts total image counts, calculates their percentages and displays results. def processData(mywebpage): #Counts for the Image Hits total_image_count = 0 jpeg_count = 0 gif_count = 0 png_count = 0 #Dict to identify top browser. browsers = {'Firefox': 0, 'IE': 0, 'Safari': 0, 'Chrome': 0} #Searches the file using RE for strings instances of the image type for row in mywebpage: #print row if re.search(r'.jpg$|.gif$|.png$|.JPEG$', row[0], re.IGNORECASE): total_image_count += 1 if re.search(r'.jpg$|.JPEG$', row[0], re.IGNORECASE): jpeg_count += 1 if re.search(r'.gif$', row[0], re.IGNORECASE): gif_count += 1 if re.search(r'.png$', row[0], re.IGNORECASE): png_count += 1 #Searches for browsers in User Agent string if re.search('Firefox', row[2]): browsers['Firefox'] += 1 if re.search('MSIE', row[2]): browsers['IE'] += 1 if re.search(r'Safari/\d{0,4}.\d{0,2}$', row[2]): browsers['Safari'] += 1 if re.search(r'Chrome/\d{1,2}.\d{0,1}.\d{0,4}.\d{0,1}', row[2]): browsers['Chrome'] += 1 #Calculates percentages for each image type percentjpg = (float(jpeg_count) / float(total_image_count))*100 percentpng = (float(png_count) / float(total_image_count))*100 percentgif = (float(gif_count) / float(total_image_count))*100 #Finds the most popular browser in the browers dict popular_browser = max(browsers.iterkeys(), key=(lambda key: browsers[key])) #Prints Image Type Results print "There are a total of {} image requests found in the file.".format(total_image_count) print "GIF image requests account for {}% of all requests.".format(round(percentgif, 1)) print "JPG image requests account for {}% of all requests.".format(round(percentjpg,1)) print "PNG image requests account for {}% of all requests.".format(round(percentpng, 1)) print #Prints the most popular browser. print "The browser results are: {}".format(browsers) print print "The most popular browser is {}.".format(popular_browser) #Main function to call the other functions. def main(): mywebpage = downloadData(url) processData(mywebpage) if __name__ == "__main__": main()
c3fb87e6d81da09ef88e319b5d1f009850582bf9
VivekRajyaguru/Python-Learning
/Dictionary.py
302
3.796875
4
items = ["abc","xyz","pqri",123,456] def separateList(items): str_item = [] num_item = [] for i in items: if isinstance(i,str): str_item.append(i) elif isinstance(i,int) or isinstance(i, float): num_item.append(i) else: pass return str_item,num_item print(separateList(items))
aad9121a97178e282e9b1fefb682ba1dc3a5302b
keerthanachinna/set51
/fibonacci.py
178
4.28125
4
def fibonacci(n): if(n<=1): else: return(fibonacci(n-1)+fibonacci(n-2)) n=int(input("enter the number of terms:") print("fibonacci series:") for i in range(n) print fibonacci(i)
779524046011497965c0fe624d573eeebb493185
kimmobrunfeldt/analyze_passwords
/anapass/logger.py
762
3.515625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # """ Simple logger module. """ import time import sys __all__ = ['Logger'] class Logger(object): """Logs everything with timestamp""" def __init__(self, start_time): self.start_time = start_time def log(self, line, end_line=True): timestamp = time.strftime('[%.6f]'% (time.time() - self.start_time)) if line[-1] == '\n': # Remove '\n' line = line[-1] if end_line: print('%s %s' %(timestamp, line)) else: sys.stdout.write('%s %s'%(timestamp, line)) def stdout(self, text): """Write straight to stdout without timestamps""" sys.stdout.write(text)
db7bab9f9403c466b0dc4e1cd98e31d4b7f59d4e
N0nki/MyAlgorithms
/search.py
1,753
3.578125
4
# coding: utf-8 """ サーチアルゴリズム * リニアサーチ * バイナリサーチ """ from __future__ import division import sys def liner_search(collection, elm): """リニアサーチ""" for e in collection: if e == elm: return True return False def binary_search(collection, elm): """バイナリサーチ""" try: _abort_sorted(collection) except ValueError: sys.exit("collection must be sorted") left = 0 right = len(collection) - 1 while left <= right: mid = (left + right) // 2 if elm < collection[mid]: right = mid - 1 elif elm > collection[mid]: left = mid + 1 else: return True return False def index_liner(collection, elm): """リニアサーチで要素のインデックスを返す""" for idx,e in enumerate(collection): if e == elm: return idx raise ValueError("{} is not in collection".format(elm)) def index_binary(collection, elm): """バイナリサーチで要素のインデックスを返す""" try: _abort_sorted(collection) except ValueError: sys.exit("collection must be sorted") left = 0 right = len(collection) - 1 while left <= right: mid = (left + right) // 2 if elm < collection[mid]: right = mid - 1 elif elm > collection[mid]: left = mid + 1 else: return mid raise ValueError("{} is not in collection".format(elm)) def _abort_sorted(collection): """collectionがソート済みかチェック""" if collection != sorted(collection): raise ValueError("collection nust be sorted") return True
4f9663149cb628b6f98d1a2c5b928ba5aaecb302
jessefilho/sentimentanalysis
/ressources/scripts/trimngram.py
389
3.5625
4
#!/usr/bin/env python # This script aims at removing useless words from a sentiment classification corpus. import sys import re from nltk.util import ngrams if len(sys.argv) != 2: sys.exit() for line in sys.stdin: words = line.strip().split() tokens = [token for token in words if token != ""] output = list(ngrams(tokens, 2)) for outp in output: print outp
316277fdb2fa21a4b40568e8fd49068fd79def96
abinezer/HackerRank-Problem-Solving
/prep/TwoStrings.py
565
3.734375
4
#!/bin/python3 import math import os import random import re import sys # Complete the twoStrings function below. def twoStrings(s1, s2): s_one = {} for i in s1: s_one[i] = 1 for i in s2: if i in s_one: return 1 return 0 if __name__ == '__main__': q = int(input()) arr = [] for q_itr in range(q): s1 = input() s2 = input() result = twoStrings(s1, s2) arr.append(result) for i in arr: if i == 0: print("NO") else: print("YES")
28ca5a4b9b2a44c63e1518a4e9726b727e7d3f67
lvonbank/IT210-Python
/Ch.06/R6_1abcdefg.py
1,005
3.96875
4
# Levi VonBank # Produces a list of [1,2,3,...10] listA = [] for i in range(1,11): listA.append(i) # Produces a list of [2,4,6,...20] listB = [] for i in range(0,22,2): listB.append(i) # Produces a list of [1,4,9,...100] listC = [] for i in range(1,11): listC.append(i*i) # Produces a list of [0,...0] listD = [] for i in range(10): listD.append(0) # Produces a list of [1, 4, 9, 16, 9, 7, 4, 9, 11] listE = [] for i in range(1,5): listE.append(i*i) for i in range(9,6,-2): listE.append(i) listE.append(listE[1]) for i in range(9,12,2): listE.append(i) # Produces a list of [0,1,0,...0] listF = [] for i in range(0,11): if i % 2 == 1: listF.append(1) else: listF.append(0) # Produces a list of [0,1,2,3,4] * 2 listG = [] for i in range(0,5): listG.append(i) listG += listG # Prints all generated lists print("listA", listA) print("listB", listB) print("listC", listC) print("listD", listD) print("listE", listE) print("listF", listF) print("listG", listG)
3917c95b6f17f70e6f5e2fb068ff43fe1a815ada
fangpings/Leetcode
/202 Happy Number/untitled.py
596
3.546875
4
class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ if n == 0: return False if n == 1: return True square = 0 log = set() log.add(n) s = str(n) while square not in log: log.add(square) if square == 1: return True square = sum([int(c) ** 2 for c in s]) s = str(square) print(log) return False if __name__ == '__main__': sol = Solution() print(sol.isHappy(5))
a03120be7bb444bebb09753bb8289f05eea18ccf
ayanza/Cisco
/practica3.py
323
3.875
4
#Variables print ("VARIABLES") a = 5 print (a) print (type(a)) a = "cinco" print (a) print (type(a)) nombre = u"Ángela" #anteponiendo la u a la cadena codifica a unicode y evita los errores de tildes print (nombre) #las mayus/minus son diferentes año ="2016" print (año) #Constantes: no hay formato de definición
cbde88933f594c7040854ca18508b0faa72dcdac
YiyingW/rosalind_yw
/permutation.py
301
3.703125
4
import itertools def permutation(number): alist=[i for i in range(1, number+1)] return list(itertools.permutations(alist)) def main(): print (len(permutation(7))) for item in permutation(7): result = '' for n in item: result+=str(n)+' ' print (result) if __name__=="__main__": main()
1d21796fdfdce15e3cd74dc914c805e9eb379833
gurramdeepika/python_programming
/PycharmProjects/no1/9_Day/debugger_ex2.py
553
3.59375
4
import pdb def for_jump(count): print("entered in to the function") lis = [1,2,3,4,5,6] print("reaching to the for loop") for var in lis: print("enter in to the loop") count += 1 print(var) print(count) pdb.run("for_jump(2)") # from forloop to outside but cannot jump from outside into a loop #from outside to finally but cannot jump from finnaly to outside #l - will show the current exceuting breakpoint # !pdb.run("for_jump(9)") - can change the value while debugging but the cursor will not change
818a5ef63d0689df1c1e114b75ec3fbe317b3827
Sarthak-source/repos
/college/college.py
3,608
3.625
4
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt #Data Visualization import seaborn as sns #Python library for Vidualization # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory import os #print(os.listdir("../Mall_Customers.csv")) # Any results you write to the current directory are saved as output. #Import the dataset #Input from the user dataset = pd.read_csv(r'college.csv') Q1 = dataset.quantile(0.05) Q3 = dataset.quantile(0.75) IQR = Q3 - Q1 #Removing the Duplicates dataset.duplicated().sum() dataset.drop_duplicates(inplace=True) #Remove the NaN values from the dataset dataset.isnull().sum() dataset.dropna(how='any',inplace=True) from sklearn.preprocessing import LabelEncoder le=LabelEncoder() dataset[dataset.columns[0]]=le.fit_transform(dataset[dataset.columns[0]]) dataset.rename(columns={'Unnamed: 0':'colleges'}) index_outliers= dataset.loc[((dataset< (Q1 - 1.5 * IQR)) |(dataset > (Q3 + 1.5 * IQR))).any(axis=1)].index.tolist() #Index of the outliers outlier_values=dataset.loc[index_outliers] #List of values of outliers remove_outliers=dataset[~((dataset< (Q1 - 1.5 * IQR)) |(dataset > (Q3 + 1.5 * IQR))).any(axis=1)] # Removing outliers from dataframe and get the dataframe without outliers dataset=remove_outliers.reset_index() X1=1 X2=14 #Exploratory Data Analysis #As this is unsupervised learning so Label (Output Column) is unknown dataset.head(10) #Printing first 10 rows of the dataset dataset.shape dataset.info() dataset.describe() dataset.drop('index',axis=1) X= dataset.iloc[:, [X1,X2]].values #Building the Model #KMeans Algorithm to decide the optimum cluster number , KMeans++ using Elbow Mmethod #to figure out K for KMeans, I will use ELBOW Method on KMEANS++ Calculation from sklearn.cluster import KMeans wcss=[] #we always assume the max number of cluster would be 10 #you can judge the number of clusters by doing averaging ###Static code to get max no of clusters for i in range(1,11): kmeans = KMeans(n_clusters= i, init='k-means++', random_state=0) kmeans.fit(X) wcss.append(kmeans.inertia_) #inertia_ is the formula used to segregate the data points into clusters #Visualizing the ELBOW method to get the optimal value of K plt.plot(range(1,11), wcss) plt.title('The Elbow Method') plt.xlabel('no of clusters') plt.ylabel('wcss') plt.show() kmeansmodel = KMeans(n_clusters= 2, init='k-means++', random_state=0) y_kmeans= kmeansmodel.fit_predict(X) fig=plt.figure(figsize=(10,10),edgecolor='k') plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1],marker='*',s = 150, c = 'red', label = 'Cluster 1') plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1],marker='v',s = 150, c = 'blue', label = 'Cluster 2') plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1],marker='o', s = 150, c = 'green', label = 'Cluster 3') plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1],marker='^', s = 150, c = 'cyan', label = 'Cluster 4') plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1],marker='>', s = 150, c = 'magenta', label = 'Cluster 5') plt.scatter(kmeansmodel.cluster_centers_[:, 0], kmeansmodel.cluster_centers_[:, 1], s = 200, c = 'black', label = 'Centroids') # Set figure width to 12 and height to 9 a=list(dataset.columns) plt.xlabel(a[X1],fontsize=25) plt.ylabel(a[X2],fontsize=25)
9763163f9e92a778aaecbbe86bfa8fa771fb16a2
AmitD26/Hashing-1
/isomorphic_strings.py
488
3.734375
4
#Time complexity: O(length) #Space complexity: O(1) class Solution: def isIsomorphic(self, s: str, t: str) -> bool: h1 = {} h2 = {} for i in range(0, len(s)): if s[i] in h1 and t[i] != h1[s[i]]: return False h1[s[i]] = t[i] for i in range(0, len(t)): if t[i] in h2 and s[i] != h2[t[i]]: return False h2[t[i]] = s[i] return True
0b2f3dfcd5f187b88692f6c8c8497ddb945603c9
rppy/course
/for_list_enumerate.py
417
4.40625
4
# iterating through a list by items for item in ['apple', 'banana', 'pear']: print(item) print() # iterating through a list by index fruits = ['apple', 'banana', 'pear'] for index in range(len(fruits)): print(f'{index}. fruit is {fruits[index]}') print() # enumerate to get item and index fruits = ['apple', 'banana', 'pear'] for index, fruit in enumerate(fruits): print(f'{index}. fruit is {fruit}')
2b57e6e307b79fab811eb4a4e17fe8151fbe44c7
daks001/py102
/4/Lab4_Act1.py
1,017
3.75
4
# By submitting this assignment, all team members agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # # Names: DAKSHIKA SRIVASTAVA # MAHIRAH SAMAH # MICHAEL MARTIN # JAMES GONZALEZ # Section: 532 # Assignment: Lab4_Activity1 # Date: 17 SEPTEMBER 19 #part 1 from math import* print("This program introduces 'tolerances") TOL=1e-10 #part 2 using tolerance a=1/7 print("a is:",a) b=a*7 print("b is:",b) a=1/7 print("a is:",a) b=7*a print("b is:",b) c=2*a d=5*a e=c+d print("e is:",e) if abs(b-e)<TOL: print("b and e are equal within tolerance of", TOL) else: print("b and e are NOT equal within tolerance of", TOL) x=sqrt(1/3) print("x is:",x) y=x*x*3 print("y is:",y) z=x*3*x print("z is:",z) if abs(y-z)<TOL: print("y and z are equal within tolerance of", TOL) else: print("y and z are NOT equal within tolerance of", TOL) print("The results were surprising, YES!!!")
f392cba59873a41837e74c9f77e2e9fdf0fc5c5c
ivklisurova/SoftUni_Python_Advanced
/Comprehension/matrix_modification.py
692
3.546875
4
n = int(input()) matrix = [list(map(int, input().split(' '))) for x in range(n)] while True: args = input().split() command = args[0] if command == 'END': break row = int(args[1]) col = int(args[2]) value = int(args[3]) if command == 'Add': if 0 <= row <= len(matrix) - 1 and 0 <= col <= len(matrix[row]): matrix[row][col] += value else: print('Invalid coordinates') elif command == 'Subtract': if 0 <= row <= len(matrix) - 1 and 0 <= col <= len(matrix[row]): matrix[row][col] -= value else: print('Invalid coordinates') [print(' '.join(map(str, i))) for i in matrix]
75380903ea4ded4cd9489fe891fc772ea46d26dc
sofiathefirst/AIcode
/07python3Learn/mislice.py
507
3.515625
4
def cnt(n): while 1: yield n n+=1 c = cnt(0) ''' c[10:20] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'generator' object is not subscriptable ''' import itertools for x in itertools.islice(c,10,20): print('fisrt \n',x) for x in itertools.islice(c,10,20): print('second \n',x) #islice() 会消耗掉传入的迭代器中的数据。 必须考虑到迭代器是不可逆的 #迭代器和生成器不能使用标准的切片操作
628baf482f95ae5fead2b066eebc90c99cff7b65
kimjieun6307/itwill
/itwill/Python_1/chap05_Function/lecture/step01_func_basic.py
2,411
3.78125
4
''' 함수(Function) - 중복 코드 제거 - 재사용 가능 - 특정 기능 1개 정의 - 유형) 사용자 정의 함수, 라이브러리 함수 ''' # 1. 사용자 정의 함수 ''' 형식) def 함수명(매개변수) : 실행문1 실행문2 return 값1, 값2, ... ''' # 1) 인수가 없는 함수 def userFunc1(): print('인수가 없는 함수') print('userFunc1') userFunc1() # 인수가 없는 함수 userFunc1 # 2) 인수가 있는 함수 def userFunc2(x,y): adder = x+y print('adder =', adder) userFunc2(10,20) # adder = 30 re=userFunc2(100, 20) print(re) # None #3) 리턴 있는 함수 def userFunc3 (x,y): add = x + y sub = x - y mul = x * y div = x / y return add, sub, mul, div a, s, m, d = userFunc3(100, 20) print('add = ', a) # add = 120 print('sub = ', s) # sub = 80 print('mul = ', m) # mul = 2000 print('div = ', d) # div = 5.0 # 2. 라이브러리 함수 ''' 1) built-in : 기본함수 2) import : '모듈.함수()' 이런 형식의 함수는 모듈을 import해야 사용할 수 있다. ''' # 1) built-in : 기본함수 # - 특별한 행위 없이 바로 사용할 수 있는 함수 dataset = list(range(1,6)) print(dataset) # [1, 2, 3, 4, 5] print('sum = ', sum(dataset)) # sum = 15 print('max = ', max(dataset)) # max = 5 print('min = ', min(dataset)) # min = 1 print('len = ', len(dataset)) # len = 5 print('mean = ', mean(dataset)) # NameError: name 'mean' is not defined --- 기본 함수 아님. # 2) import : 모듈.함수() import statistics # 방법1) 통계관련 함수 제공 #@@1 ''' (1) ctrl + 클릭 : module of function source 보기 (2) print(dir(statistics)) # 해당 모듈의 정보 ['Decimal', 'Fraction', 'StatisticsError', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_coerce', '_convert', '_counts', '_exact_ratio', '_fail_neg', '_find_lteq', '_find_rteq', '_isfinite', '_ss', '_sum', 'bisect_left', 'bisect_right', 'collections', 'groupby', 'harmonic_mean', 'math', 'mean', 'median', 'median_grouped', 'median_high', 'median_low', 'mode', 'numbers', 'pstdev', 'pvariance', 'stdev', 'variance'] ''' print(dir(statistics)) from statistics import mean # 방법2) avg1 = statistics.mean(dataset) # 방법1 avg2 = mean(dataset) # 방법2 print('mean1 = ', avg1) # mean1 = 3 print('mean2 = ', avg2) # mean2 = 3
a8e46d2bad9c6fb71eea3b20d7cad4cab34d7c0d
Erick-Fernandes-dev/Python
/exercicios/importante/aula.py
961
4
4
continuar = True while continuar: op = input("DDigite o operador: ") n1 = int(input("Digite um valor: ")) n2 = int(input("Digite um outro valor: ")) if op == '+': print(n1+n2) resposta = str.upper(input("Deseja continuar, digite (s) para 'sim' e (n) para 'não': ")) if resposta != "S": continuar = False elif op == '-': print(n1-n2) resposta = str.upper(input("Deseja continuar, digite (s) para 'sim' e (n) para 'não': ")) if resposta != "S": continuar = False elif op == '*': print(n1*n2) resposta = str.upper(input("Deseja continuar, digite (s) para 'sim' e (n) para 'não': ")) if resposta != "S": continuar = False elif op == '/': print(n1/n2) resposta = str.upper(input("Deseja continuar, digite (s) para 'sim' e (n) para 'não': ")) if resposta != "S": continuar = False
fdb55709f3cdcc22ac38f5e5ec221c281b573c3f
abhishekthukaram/Flask-repo
/number-comparison,py.py
222
3.78125
4
def numbercompare(n): newlist = set(n) if len(newlist)== len(n): print "The numbers are unique" else: print "the number is repeated" numbercompare([1,2,3,4,5]) numbercompare([1,1,2,2,3,4,5])
64167acb2a8510d3d661f489d941e6b9615e6e83
dhruv395/Python_tutorial
/Networking/fileclient.py
375
3.75
4
## create a file client that will send the name of the file it want and display the contents of file. import socket #importing a socket module s=socket.socket() #create a object s.connect(('localhost',8080)) # connect to server fileName=input("enter a file name:") s.send(fileName.encode()) content=s.recv(1024) print(content.decode()) s.close()
fd8354ac13d0cf97db21e37aa3b438fbcc034900
hsaad1/Week-1---In-your-Interface
/main.py
614
3.71875
4
class Teams: def __init__(self, members): self.__myTeam = members def __len__(self): return len(self.__myTeam) # Question 1 def __contains__(self, item): return item in self.__myTeam # Question 2 def __iter__(self): yield from self.__myTeam def main(): classmates = Teams(['John', 'Steve', 'Tim']) print(len(classmates)) # Question 1 print() print('Tim' in classmates) print('Sam' in classmates) # Question 2 print() for classmate in classmates: print(classmate) main()
d1dab7b2bf0aa39872ffbaaa1deb3b2d612dec17
SANDHIYA11/myproject
/Max.py
149
4.21875
4
Lst=[] Num=int(input("Enter how many numbers:")) for i in range(Num): Number=int(input("Enter the number:")) Lst.append(Number) print(max(Lst))
1ab37fbe1a8d710bb197d0e6d93efc8a6fd6987d
Argen-Aman/chapter2task21
/task21.py
263
4.3125
4
str1 = input('Type (enter) string:\n') str1 = str1.split() start = 0 def max_word (str1): global start for i in str1: if len(i) > start: start = len(i) x = i print('The longest word is: ' + str(x)) max_word (str1)
24f61b33265ba599eec451071c0955a9d1fea527
danoliveiradev/PythonExercicios
/ex018.py
296
4.0625
4
from math import radians, sin, cos, tan angulo = float(input('Digite um ângulo em graus: ')) seno = sin(radians(angulo)) coss = cos(radians(angulo)) tang = tan(radians(angulo)) print('Para o ângulo {}º: \nseno = {:.3f} \ncosseno = {:.3f} \ntangente = {:.3f}'.format(angulo, seno, coss, tang))
5e584ef0c3da081fc39213aaa61c59ecec086059
xhlubuntu/leetcode_python
/leetcode_2.py
1,303
3.71875
4
#2 ac # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ x = (l1.val +l2.val)%10 y = (l1.val + l2.val)/10 p = l1 q = l2 l3 = ListNode(x) r = l3 while(p.next is not None and q.next is not None): p = p.next q = q.next tmp = p.val + q.val + y x = tmp%10 y = tmp/10 nNode = ListNode(x) r.next = nNode r = nNode while p.next is not None: p = p.next tmp = p.val + y x = tmp%10 y = tmp/10 nNode = ListNode(x) r.next = nNode r = nNode while q.next is not None: q = q.next tmp = q.val + y x = tmp%10 y = tmp/10 nNode = ListNode(x) r.next = nNode r = nNode if y > 0: nNode = ListNode(y) r.next = nNode r = nNode return l3
bf6295356ade384bdf53215237f7efeb3c1cbf84
rraj29/Sorting_Algorithms
/bucket_sort.py
1,896
4.03125
4
# Here, we create buckets and distribute the elements in the buckets # sort the elements within the buckets # then, simply merge the buckets # Number of buckets = round(sqrt(total no. of elements)) # Appropriate bucket for any element(value) = ceil(Value * No. of Buckets/Max Value in the array) # ceil= ceiling function, round = round off, sqrt = square root # time complexity = O(N^2) # space complexity = O(N) # Use when the numbers are uniformly distributed. e.g-( 1,2 4,5,3,9,7,8) # NOT WHEN e.g-( 1,23,400,53,9,7000,8) import random as rand # for the randomlist import math # for sqrt function # from insertion_sort import insertion_sort # importing insertion sort, so easy to sort the array directly def insertion_sort(anylist): for i in range(1,len(anylist)): key = anylist[i] j = i-1 while j>=0 and key < anylist[j]: anylist[j+1] = anylist[j] j-=1 anylist[j+1] = key return anylist def bucket_sort(anylist): number_of_buckets = round(math.sqrt(len(anylist))) maxValue = max(anylist) arr = [] for i in range(number_of_buckets): arr.append([]) # creating the required number of buckets for j in anylist: # getting the bucket number in which the element should go index_bucket = math.ceil((j * number_of_buckets) / maxValue) arr[index_bucket-1].append(j) # adding the element to the calculated bucket for i in range(number_of_buckets): arr[i] = insertion_sort(arr[i]) # sorting the elements in each bucket k = 0 for i in range(number_of_buckets): for j in range(len(arr[i])): anylist[k] = arr[i][j] k +=1 return anylist randomlist = rand.sample(range(1,1000),100) print(randomlist) print(bucket_sort(randomlist))
25fab71d1e6668a97c4ceb4ccd9cd1be45a44d48
astroidis/gml
/gisclass.py
3,489
3.515625
4
from math import radians, sin, cos, acos class _Node: def __init__(self, nodeid, latitude, longitude): self.id = nodeid self.lat = latitude self.lon = longitude def __str__(self): return f"Node {self.id} ({self.lat} {self.lon})" class _Edge: def __init__(self, source, target): self.source = source self.target = target self.distance = None def __str__(self): return f"Edge {self.source} -> {self.target}" class Graph: def __init__(self, gmlfile): self.nodes = [] self.edges = [] self.__parse_graph(gmlfile) self.__distances() def __parse_graph(self, gmlfile): with open(gmlfile, "r") as reader: line = reader.readline() while line: if "node" in line: while "]" not in line: line = reader.readline() line = line.strip() line = line.split(" ") if "id" in line: nodeid = int(line[1]) elif "Longitude" in line: longitude = float(line[1]) elif "Latitude" in line: latitude = float(line[1]) self.nodes.append(_Node(nodeid, latitude, longitude)) elif "edge" in line: while "]" not in line: line = reader.readline() line = line.strip() line = line.split(" ") if line[0] == "source": source = int(line[1]) elif line[0] == "target": target = int(line[1]) self.edges.append(_Edge(source, target)) line = reader.readline() def __distances(self): for edge in self.edges: edge.distance = \ self.get_distance(edge.source, edge.target) def get_node(self, nodeid): for node in self.nodes: if nodeid == node.id: return node @staticmethod def __great_circle_distance(node1, node2): lat1, lon1, lat2, lon2 = \ map(radians, [node1.lat, node1.lon, node2.lat, node2.lon]) delta = acos( sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(abs(lon1 - lon2)) ) return 6371 * delta def get_distance(self, nid1, nid2): node1 = self.get_node(nid1) node2 = self.get_node(nid2) return self.__great_circle_distance(node1, node2) def most_southern_node(self): return min(self.nodes, key=lambda node: node.lat) def most_northern_node(self): return max(self.nodes, key=lambda node: node.lat) def most_western_node(self): return min(self.nodes, key=lambda node: node.lon) def most_eastern_node(self): return max(self.nodes, key=lambda node: node.lon) def max_distance(self): return max(self.edges, key=lambda edge: edge.distance) if __name__ == "__main__": geo = Graph("Bbnplanet.gml") for node in geo.nodes: print(node) for edge in geo.edges: print(edge) print() print(geo.max_distance()) print(geo.most_eastern_node()) print(geo.most_northern_node()) print(geo.most_southern_node()) print(geo.most_western_node())
4c5bb0bfa4bf1272f9a4a50fc3d351e9f27fe93c
r259c280/CS101
/6.22 (LAB).py
3,172
3.96875
4
# Type all other functions here #shorten_space() function. def shorten_space(usrStr): split = usrStr.split() return ( " ".join(split) ) #replace_punctuation() function. def replace_punctuation(usrStr): return usrStr.count("!"), usrStr.count(";"), usrStr.replace("!",".").replace(";",",") #fix_capitilization() function. def fix_capitilization(usrStr): numberOfSentencesCapitalized = 0 sentences = usrStr.split('.') # looping through sentence list so we can modify the sentence in the collection for number in range(len(sentences ) ): sentence = sentences[number] # don't process the empty string if sentence ends with . if len( sentence ) > 0: # loops throug string so we can find the first non space for index in range(len(sentence) ): if not sentence[index].isspace(): # first non space character, fix or not if not sentence[index].isupper(): sentences[number] = sentence[:index] + sentence[index].upper() + sentence[index + 1:] numberOfSentencesCapitalized += 1 #break out of the range loop so we don't capitialize anything else break capitalizedString = ".".join(sentences) return numberOfSentencesCapitalized, capitalizedString def get_num_of_words(usrStr): return len( usrStr.split() ) #print_menu() to frint the menu. def print_menu(usrStr): print( 'You entered:', usrStr ) validOptions = ( 'c', 'w', 'f', 'r', 's', 'q' ) menuOp = ' ' while menuOp not in validOptions: print('MENU') print('c - Number of non-whitespace characters') print('w - Number of words') print('f - Fix capitalization') print('r - Replace punctuation') print('s - Shorten spaces') print('q - Quit') print() print('Choose an option: ') menuOp = input() if menuOp == 'c': print('Number of non-whitespace characters: %d' % get_num_of_non_WS_characters(usrStr) ) elif menuOp == 'w': print( 'Number of words: %d' % get_num_of_words(usrStr) ) elif menuOp == 'f': print( 'Number of letters capitalized: %d\nEdited text: %s' % fix_capitilization(usrStr) ) elif menuOp == 'r': print( 'Punctuation replaced\nexclamationCount: %d\nsemicolonCount: %d\nEdited text: %s' % replace_punctuation(usrStr) ) elif menuOp == 's': print( 'Edited text: %s' % shorten_space(usrStr) ) return menuOp, usrStr #get_num_of_non_WS_characters() function def get_num_of_non_WS_characters(userInput): numberOfNonWhiteSpaceCharacters = 0 for character in userInput: if not character.isspace(): numberOfNonWhiteSpaceCharacters += 1 return numberOfNonWhiteSpaceCharacters if __name__ == '__main__': # Complete main section of code menuOption = '' userInput = input('Enter a sample text: ') while ( menuOption != 'q' ): menuOption, userInput = print_menu(userInput)
1b8269debf9b69dc1618f2605520ff580fc374c8
durandal42/projects
/hearthstone/arena.py
984
3.5
4
import random import collections def new_challenger(): return (0,0) def finished(player): return player[0] >= 12 or player[1] >= 3 def play_round(pop): pop.sort() for i in range(0, len(pop), 2): pop[i], pop[i+1] = play_game(pop[i], pop[i+1]) def play_game(p1, p2): if random.choice([True, False]): return (p1[0]+1, p1[1]), (p2[0], p2[1]+1) else: return (p1[0], p1[1]+1), (p2[0]+1, p2[1]) def replace_players(pop): for i,p in enumerate(pop): if finished(p): report(p) pop[i] = new_challenger() histogram = collections.defaultdict(int) def report(player): # print 'finished:', player histogram[player] += 1 POP_SIZE = 10000 ROUNDS = 1000 population = [new_challenger() for i in range(POP_SIZE)] for i in range(ROUNDS): #print population play_round(population) replace_players(population) print '%d players completed their runs' % sum(histogram.values()) for score in sorted(histogram.keys()): print score, histogram[score]
c6ec6d4b05892d2b0a4e86a6321162c2e6fc660a
YaqoobAslam/Python3
/Chapter01/fahrenheit_to_celsius.py
201
3.953125
4
def fahrenheit_to_celsius(temp): newTemp = 5*(temp-32)/9 print("The Fahrenheit temperature",temp,"is equivalent to",newTemp,end='') print(" degrees Celsius") fahrenheit_to_celsius(50.)
47fbc8c8bc19cdec5703aba26e11e440073538fc
rproepp/spykeutils
/spykeutils/progress_indicator.py
1,633
3.59375
4
import functools class CancelException(Exception): """ This is raised when a user cancels a progress process. It is used by :class:`ProgressIndicator` and its descendants. """ pass def ignores_cancel(function): """ Decorator for functions that should ignore a raised :class:`CancelException` and just return nothing in this case """ @functools.wraps(function) def inner(*args, **kwargs): try: return function(*args, **kwargs) except CancelException: return return inner class ProgressIndicator(object): """ Base class for classes indicating progress of a long operation. This class does not implement any of the methods and can be used as a dummy if no progress indication is needed. """ def set_ticks(self, ticks): """ Set the required number of ticks before the operation is done. :param int ticks: The number of steps that the operation will take. """ pass def begin(self, title=''): """ Signal that the operation starts. :param string title: The name of the whole operation. """ pass def step(self, num_steps=1): """ Signal that one or more steps of the operation were completed. :param int num_steps: The number of steps that have been completed. """ pass def set_status(self, new_status): """ Set status description. :param string new_status: A description of the current status. """ pass def done(self): """ Signal that the operation is done. """ pass
ce80b79b3d6c15b24c5624275137c3633ce47a76
AdrianMartinezCodes/PythonScripts
/E4.py
165
3.984375
4
num = int(input("Please enter a number to divide: ")) diviser_list = [] for i in range(1,num): if num%i == 0: diviser_list.append(i) print(diviser_list)
f0b2d9453dd5669e2c619106bfddecf4139e4c57
Dorcy-ndg3/LeetCode
/Git/存在重复元素.py
394
3.5625
4
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) <= 1: return False nums.sort() for index in range(0,len(nums)-1): if nums[index] == nums[index +1]:#or nums[index] == nums[index-1]: return True return False
04386bd05e5fb66dc719cfbb0e5a3d9dac344619
FCnski/Python-Exercises
/Pssw_strenght.py
4,453
4.09375
4
import re def menu(): print("1. Verify the strenght of your password.") print("2. Exit.") while True: try: escolha = int(input("Sua opção:")) if escolha == 1: # se a escolha for == 1, ele executará a função de verificação / If you choose 1, the program will execute verifypssw() pass elif escolha == 2: #Termina programa/End program print("Untill next time!") break except ValueError or TypeError: print("Você deve escolher entre 1 e 2") pssw = 0 pontos = 0 def verifypssw(): global pssw #as variáveis precisam ser declaradas globalmente para serem utilizadas além do escopo local das funções! global pontos #the variables must be declared as global as to make them usable outside of the function local scope pssw = input("Sua senha:") pssw = str(pssw) aux = 0 pontos = 0 for i in pssw: #É necessário utilizar o if pois precisamos sequenciar todas as condições e não apenas uma, então, o elif e o else tornam-se não utlizáveis pontos += 4 #It is necessary to use only if as our condition, because we need to go through them all once, like sequential search if re.search("[A-Z]", i): #se i for igual a uma letra maiúscula, acumula 2 pontos / if i equals a uppercase key, accumulates two points pontos += 2 aux += 1 if re.search("[a-z]", i): #se i for igual a uma letra minúscula, acumula 2 pontos / If i equals a lowercase key, you get two points pontos += 2 aux += 1 if re.search("[0-9]", i): #se i for igual a um dígito, acumula 4 pontos / if i equals a digit, accumulate 4 points pontos += 4 if re.search("[!@#$%¨&*()[/?^~´`]", i): pontos += 6 aux += 1 if len(pssw) >= 8: #se tamanho for maior que 8, acumula 2 pontos / If there are more than 8 digits/characters in your pssw, you'll be awarded 2 points pontos += 2 if len(pssw)/3 >= aux: #se 3/4 forem números ou letras, acumula 2 pontos / If 3/4 of the content of your pssw are numbers or letters, you get two points pontos += 2 gradekiller() #Função para deduzir pontos da senha/ This function will deduce points awarded by your password def gradekiller(): global pontos global pssw simbolo = ["!@#$%¨&*()[]/?^~´`"] aux = [] aux2 = 0 if pssw.isdigit(): for i in range(len(pssw)): pontos -= 1 if pssw.isalpha(): for j in range(len(pssw)): pontos -= 1 for z in range(len(pssw)): if pssw[z] == pssw[z-1]: # Se o anterior for igual ao próximo, perde-se 1 ponto. pontos -= 1 if pssw[z].isupper() and pssw[z-1].isupper: # Se o anterior e o próximo forem maiúsculas, perde-se 2 pontos pontos -= 2 if pssw[z-2].isupper(): # Se 3 letras consecutivas forem maiúsculas, perde-se 3 pontos pontos -= 1 if pssw[z].islower() and pssw[z-1].islower: # Se o anterior e o próximo forem minúsculas, perde-se 2 pontos pontos -= 2 if pssw[z-2].islower(): # Se 3 letras consecutivas forem minúsculas, perde-se 3 pontos pontos -= 1 if pssw[z].isdigit() and pssw[z-1].isdigit(): # Se o anterior e o próximo forem dígitos, perde-se 2 pontos pontos -= 2 if pssw[z-2].isdigit(): # Se houver 3 dígitos consecutivos, perde-se 3 pontos pontos -= 1 if pssw[z] and pssw[z-1] in simbolo: # Se o anterior e o próximo forem simbolos, perde-se 2 pontos pontos -= 2 if pssw[z-2] in simbolo: # Se houver 3 simbolos consecutivos, perde-se 3 pontos pontos -= 1 tabela() def tabela(): global pontos if pontos < 20: print("Sua senha atingiu " + str(pontos), "points and was considered Very Weak") elif 20 <= pontos < 40: print("Sua senha atingiu " + str(pontos), "points and was considered Weak") elif 40 <= pontos < 60: print("Sua senha atingiu " + str(pontos), "points and was considered Reasonable/Medium") elif 60 <= pontos < 80: print("Sua senha atingiu " + str(pontos), "points and was considered Good") elif pontos >= 80: print("Sua senha atingiu " + str(pontos), "points and was considered Great") menu()
baeea74e07eed30466705e51a165c1850e2d83bf
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/wchgil001/question3.py
252
4.09375
4
import math i=math.sqrt(2) pi = 2 n = 0 while n != 1: n = 2/i i = math.sqrt(2+i) pi = pi * n print('Approximation of pi:',round(pi,3)) r=eval(input('Enter the radius:\n')) area=(pi*r**2) print('Area:',round(area,3))
0d7b41a253d00394163244e0a42489950767e24d
vipulchakravarthy/6023_CSPP1
/cspp1-assignments/m4/p1/vowels_counter.py
742
4.09375
4
''' #Assume s is a string of lower case characters. #Write a program that counts up the number of vowels contained in the string s. #Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', #your program should print: #Number of vowels: 5 ''' def main(): ''' #Write a program that counts up the number of vowels contained in the string s. #Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. ''' s_in = str(input()) s_input = s_in.lower() count_int = 0 for char in s_input: if char in ('a', 'e', 'i', 'o', 'u'): count_int += 1 print(count_int) # the input string is in s # remove pass and start your code here if __name__ == "__main__": main()
93c8e5ff846157cf1280465405cbc53619f7e8b2
manimaran89/python_script
/chn.py
226
3.921875
4
from copy import deepcopy a=range(6) b=deepcopy(a) b.reverse() def f1(m): for i in range(6): yield m[i] def f2(m): for i in range(6): yield m[i] f=f1(a) g=f2(b) for i in range(3): print g.next() print f.next()
bd640fb19496f0d385f1c8add3f519cd5ca0e1ee
khurath-8/SDP-python
/assignment1_simplecaculator_58_khurath.py
763
4.1875
4
a=float(input("enter a number : ")) b=float(input("enter another number :")) c=input("enter operation(add,subract,multiply,divide,reminder,exponent,floordivision):") ## ADDITION if(c=="add"): res_add=a+b print(res_add) ## SUBRACTION elif(c=="subract"): res_sub=a-b print(res_sub) ## MULTIPLICATION elif(c=="multiply"): res_mult=a*b print(res_mult) ## DIVISION elif(c=="divide"): res_div=a/b print(res_div) ## MODULUS elif(c=="reminder"): res_mod=a%b print(res_mod) ## EXPONENT elif(c=="exponent"): res_exp=a**b print(res_exp) ## FLOOR DIVISON elif(c=="floordivision"): res_divv=a//b print(res_divv) else: print("please enter valid inputs!!")
fc46ba674a97201f5857cb9b2d2767450c926593
enchainingrealm/UbcDssgBccdc-Pipeline
/util/preprocessor.py
4,088
3.75
4
import json import re def preprocess(df, organisms=False): """ Preprocesses the data in the given DataFrame. Preprocesses result_full_descriptions: - Converts all result_full_descriptions to lowercase - Removes all characters that are not letters, numbers, spaces, or pipes - Replaces all purely-numeric words with "_NUMBER_" - If organisms is True, replaces all organism names with "_ORGANISM_" Preprocesses labels: - Converts all labels in the label columns {"test_performed", "test_outcome", "level_1", "level_2"} in the given DataFrame to lowercase. Skips a label column if it does not exist in the DataFrame. :param df: the DataFrame to preprocess - required columns: {"result_full_description", "candidates" (if organisms is True)} - optional columns: {"test_performed", "test_outcome", "level_1", "level_2"} :param organisms: whether to replace organism names in the result_full_descriptions with "_ORGANISM_" :return: the preprocessed DataFrame - columns: the same as the columns of the given DataFrame """ df = df.copy() # don't mutate the original DataFrame df["result_full_description"] = df["result_full_description"].apply( lambda rfd: replace_numbers(remove_symbols(rfd.lower())) ) if organisms: def helper(row): return replace_organisms( row["result_full_description"], row["candidates"] ) df["result_full_description"] = df.apply(helper, axis=1) df = labels_to_lowercase(df) return df def remove_symbols(result_full_description): """ Removes all characters that are not letters, numbers, spaces, or pipes from the given string. :param result_full_description: the string to remove symbols from :return: the string after removing symbols """ return re.sub(r"[^a-zA-Z0-9 |]", "", result_full_description) def replace_numbers(result_full_description): """ Replaces all purely-numeric words in the given string with "_NUMBER_". :param result_full_description: the string to replace numeric words in :return: the string after replacing numeric words """ raw_tokens = result_full_description.split() tokens = [ "_NUMBER_" if all(char.isdigit() for char in token) else token for token in raw_tokens ] return " ".join(tokens) def replace_organisms(result_full_description, candidates_str): """ Replaces all organism names in the given result_full_description string with "_ORGANISM_". :param result_full_description: the string to replace organism names in :param candidates_str: a JSON string containing MetaMap candidates information :return: the result_full_description string after replacing organism names """ result = result_full_description candidates_dict = json.loads(candidates_str) matchings = [text.lower() for _, value in candidates_dict.items() for text in value["matched"]] matchings.sort(key=len, reverse=True) for text in matchings: result = result.replace(text.lower(), "_ORGANISM_") return result def labels_to_lowercase(df): """ Converts all labels in the label columns {"test_performed", "test_outcome", "level_1", "level_2"} in the given DataFrame to lowercase. Skips a label column if it does not exist in the DataFrame. :param df: the DataFrame to convert all labels to lowercase - optional columns: {"test_performed", "test_outcome", "level_1", "level_2"} :return: the DataFrame after converting all labels to lowercase - columns: the same as the columns of the given DataFrame """ df = df.copy() # don't mutate the original DataFrame outputs = ["test_performed", "test_outcome", "level_1", "level_2"] for output in outputs: if output in df.columns: df[output] = df[output].apply(str.lower) return df
5ee176d3e95f55f49a8ed6187ba5e5d8f36a1bb2
kjco/bioinformatics-algorithms
/ba4b-peptide-encoding/peptide_encoding_v2.py
3,769
4.09375
4
# Programming solution for: # Find Substrings of a Genome Encoding a Given Amino Acid String # http://rosalind.info/problems/ba4b/ # # There are three different ways to divide a DNA string into codons for # translation, one starting at each of the first three starting positions of # the string. These different ways of dividing a DNA string into codons are # called reading frames. Since DNA is double-stranded, a genome has six reading # frames (three on each strand), as shown in Figure 1. # # We say that a DNA string Pattern encodes an amino acid string Peptide if the # RNA string transcribed from either Pattern or its reverse complement Pattern # translates into Peptide. # # **Peptide Encoding Problem** # # Find substrings of a genome encoding a given amino acid sequence. # - Given: A DNA string Text and an amino acid string Peptide. # - Return: All substrings of Text encoding Peptide (if any such substrings exist). import string codon_dict = {"AAA":"K","AAC":"N","AAG":"K","AAU":"N","ACA":"T","ACC":"T","ACG":"T","ACU":"T","AGA":"R","AGC":"S","AGG":"R","AGU":"S","AUA":"I","AUC":"I","AUG":"M","AUU":"I","CAA":"Q","CAC":"H","CAG":"Q","CAU":"H","CCA":"P","CCC":"P","CCG":"P","CCU":"P","CGA":"R","CGC":"R","CGG":"R","CGU":"R","CUA":"L","CUC":"L","CUG":"L","CUU":"L","GAA":"E","GAC":"D","GAG":"E","GAU":"D","GCA":"A","GCC":"A","GCG":"A","GCU":"A","GGA":"G","GGC":"G","GGG":"G","GGU":"G","GUA":"V","GUC":"V","GUG":"V","GUU":"V","UAA":"","UAC":"Y","UAG":"","UAU":"Y","UCA":"S","UCC":"S","UCG":"S","UCU":"S","UGA":"","UGC":"C","UGG":"W","UGU":"C","UUA":"L","UUC":"F","UUG":"L","UUU":"F"} amino_acid_list = [] open_file = open('test_input.txt', 'r') dna_string = open_file.readline().rstrip('\n') open_file.close() #dna_string = "ATGGCCATGGCCCCCAGAACTGAGATCAATAGTACCCGTATTAACGGGTGA" aa_seq = "KEVFEPHYY" aa_seq_len = len(aa_seq) rna_string = dna_string.replace('T','U') rna_string_len = len(rna_string) remainder = rna_string_len%3 #print rna_string_len #print remainder output_file = [] def comp(str): intab = 'ATCG' outtab = 'TAGC' mt = string.maketrans(intab,outtab) return str.translate(mt) for i in range(3): amino_acid_list = [] for j in range((rna_string_len/3)-i): codons = rna_string[3*j+i:3*j+3+i] amino_acid = codon_dict[codons] amino_acid_list.append(amino_acid) protein_string = str(''.join(amino_acid_list)) #print protein_string for m in range(len(protein_string)-aa_seq_len): if aa_seq == protein_string[m:m+aa_seq_len]: output_file.append(dna_string[3*m+i:3*m+aa_seq_len*3+i]) #output_file.append(m) print output_file reverse_seq = dna_string[::-1] replace_seq = comp(reverse_seq) #print replace_seq rna_rev = replace_seq.replace('T','U') #print rna_rev rna_rev_len = len(rna_rev) rev_output_file = [] for i in range(3): rev_amino_acid_list = [] for j in range((rna_rev_len/3)-i): rev_codons = rna_rev[3*j+i:3*j+3+i] rev_amino_acid = codon_dict[rev_codons] rev_amino_acid_list.append(rev_amino_acid) rev_protein_string = str(''.join(rev_amino_acid_list)) #print rev_protein_string for m in range(len(rev_protein_string)-aa_seq_len+1): if aa_seq == rev_protein_string[m:m+aa_seq_len]: rev_output_file.append(replace_seq[3*m+i:3*m+aa_seq_len*3+i]) #rev_output_file.append(m) #print rev_output_file translated_output_file = [] for output_seq in rev_output_file: translated_output_file.append(comp(output_seq)[::-1]) print translated_output_file all_output = output_file + translated_output_file print all_output print '\n'.join(all_output)
415e63acc4bba306511adb334db0aa714b12b928
aston-github/CS101
/F19-Assign2-Turtles/TurtleShapes.py
1,339
3.90625
4
''' TurtleShapes.py @author: ASTON YONG ''' import turtle, BoundingBox import random def drawOneShape(turt, size): ''' Draws a square with the side length of size input ''' for i in range(4): turt.forward(size) turt.right(90) def drawOneIceCream(turt, size): ''' Draws a ice cream cone with scoop radius equal to size ''' turt.color('brown') turt.forward(size*2) turt.right(110) turt.forward(size*14/5) turt.right(140) turt.forward(size*14/5) turt.right(110) turt.up() turt.forward(size*2) turt.left(90) turt.down() turt.color('red') turt.up() turt.forward(size) turt.down() turt.circle(size) lst = ['blue', 'green'] for color in lst: turt.color(color) turt.up() turt.forward(size*2) turt.down() turt.circle(size) if __name__ == '__main__': win = turtle.Screen() BoundingBox.drawBoundingBox() ## CALL FUNCTIONS HERE t = turtle.Turtle() size = 60 t.up() t.backward(100) t.down() drawOneShape(t, size) i = turtle.Turtle() size = 40 i.up() i.forward(100) i.down() drawOneIceCream(i, size) win.exitonclick()
83f017e7653fd447a3aefce1cf1ec899f58fe41b
everbird/leetcode-py
/2015/SubstringWithConcatenationOfAllWords_v0.py
946
3.59375
4
#!/usr/bin/env python # encoding: utf-8 class Solution: # @param {string} s # @param {string[]} words # @return {integer[]} def findSubstring(self, s, words): if len(words) == 1: word = words[0] lenw = len(word) r = [] for i, c in enumerate(s[:-lenw + 1]): if word == s[i:i + lenw]: r.append(i) return r positions = self.findSubstring(s, words[:-1]) last_word = words[-1] pre_word = words[-2] lenlw = len(last_word) lenpw = len(pre_word) r = [] for i in positions: if (last_word == s[i-lenlw:i] or last_word == s[i+lenpw:i+lenpw+lenlw]): r.append(i) return r if __name__ == '__main__': a = 'barfoothefoobarman' words = ["foo", "bar"] s = Solution() r = s.findSubstring(a, words) print r
e8eaaca8886645f7ba424f70beef5eacfa627c26
sajjad065/assignment2
/Datatype/qsn22.py
475
3.78125
4
total=int(input("How many string do you want to input in list ")) lis=[] list_dub=[] count=0 for i in range(total): str1=input("Enter strings ") lis.append(str1) list_dub.append(lis[0]) for i in lis: for j in list_dub: if(i==j): count=count+1 if(count>=1): count=0 else: list_dub.append(i) print("Original List: " +str(lis)) print("List with no dublicate: " +str(list_dub))
470b761926fd82fdae8db4c160aa2f6b4105290e
gtxmobile/leetcode
/14.最长公共前缀.py
379
3.53125
4
# coding:utf-8 class Solution14(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" strs.sort() first = strs[0] last = strs[-1] i = 0 while i < len(first) and first[i] == last[i]: i += 1 return first[:i]
a30ae354b55b8c2335dca72a9d54905e626a5ad9
saddagarla/shunsvineyard
/my-python-coding-style-and-principles/my_package/my_data_structure/my_tree.py
6,128
4.15625
4
# Copyright © 2018 by Shun Huang. All rights reserved. # Licensed under MIT License. # See LICENSE in the project root for license information. """A binary tree example to demonstrate different tree traversal, including in-order, pre-order, post-order, and level-order. """ import enum # Enum to define traversal types. from typing import NoReturn # For type hints class TraversalType(enum.Enum): IN_ORDER = enum.auto() PRE_ORDER = enum.auto() POST_ORDER = enum.auto() LEVEL_ORDER = enum.auto() class _Node: """Basic data structure to build a binary tree. This is a private class should be used within this module. Attributes ---------- left: _Node or None A pointer points to the left child. If there is no child on the left, the value is `None`. right: _Node or None A pointer points to the right child. If there is no child on the right, the value is `None`. data: int Data of the node. """ def __init__(self, data: int): self.left = None self.right = None self.data = data class BinaryTree: """A binary tree with different types of tree traversal. Methods ------- insert(data: int) Inset an item into a binary tree. traverse(traversal_type: TraversalType) Traverse the tree based on different tree traversals. Examples -------- >>> from my_package.my_data_structure import my_tree >>> tree = my_tree.BinaryTree(data=30) >>> tree.insert(10) >>> tree.insert(20) >>> tree.insert(40) >>> tree.insert(50) >>> tree.traverse(traversal_type=my_tree.TraversalType.IN_ORDER) 10 20 30 40 50 >>> tree.traverse(traversal_type=my_tree.TraversalType.PRE_ORDER) 30 10 20 40 50 >>> tree.traverse(traversal_type=my_tree.TraversalType.POST_ORDER) 20 10 50 40 30 >>> tree.traverse(traversal_type=my_tree.TraversalType.LEVEL_ORDER) 30 10 40 20 50 """ def __init__(self, data: int): self._root = _Node(data=data) def _insert(self, data: int, node: _Node) -> NoReturn: """The real implementation of tree insertion. Parameters ---------- data: int The data to be inserted into the tree. node: _Node The parent node of the input data. Raises ------ ValueError If the input data has existed in the tree, `ValueError` will be thrown. """ if data == node.data: raise ValueError("Duplicate value") elif data < node.data: if node.left != None: self._insert(data=data, node=node.left) else: node.left = _Node(data=data) elif data > node.data: if node.right != None: self._insert(data=data, node=node.right) else: node.right = _Node(data=data) def _inorder_traverse(self, node: _Node): """In-order traversal. Parameters ---------- node: _Node The parent node of the inseration node. Notes ----- In-order means Left subtree, current node, right subtree (LDR) """ if node: self._inorder_traverse(node.left) print(node.data, end=" ") self._inorder_traverse(node.right) def _preorder_traverse(self, node: _Node): """Pre-order traversal. Parameters ---------- node: _Node The parent node of the inseration node. Notes ----- Pre-order means Current node, left subtree, right subtree (DLR) """ if node: print(node.data, end=" ") self._preorder_traverse(node.left) self._preorder_traverse(node.right) def _postorder_traverse(self, node: _Node): """Post-order traversal. Parameters ---------- node: _Node The parent node of the inseration node. Notes ----- Post-order means Left subtree, right subtree, current node (LRD) """ if node: self._postorder_traverse(node.left) self._postorder_traverse(node.right) print(node.data, end=" ") def _levelorder_traverse(self): """Level-order traversal. Parameters ---------- node: _Node The parent node of the inseration node. Notes ----- In-order means Level by level, from left to right, starting from the root node. """ queue = [self._root] while len(queue) > 0: temp = queue.pop(0) print(temp.data, end=" ") if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) def insert(self, data: int) -> NoReturn: """Insert an item into a binary tree. Parameters ---------- data: int The data to be inserted into the tree. Raises ------ ValueError If the input data has existed in the tree, `ValueError` will be thrown. """ self._insert(data=data, node=self._root) def traverse(self, traversal_type: TraversalType) -> NoReturn: """Traverse the tree based on traversal types. Parameters ---------- traversal_type: TraversalType The type of traversals. See Also -------- TraversalType : The definition of traversal type """ if traversal_type == TraversalType.IN_ORDER: self._inorder_traverse(self._root) elif traversal_type == TraversalType.PRE_ORDER: self._preorder_traverse(self._root) elif traversal_type == TraversalType.POST_ORDER: self._postorder_traverse(self._root) elif traversal_type == TraversalType.LEVEL_ORDER: self._levelorder_traverse() else: raise ValueError(f"{traversal_type} is invalid")
954d271d1621447ca25d38ff6be15a3b12a31763
1chaechae1/Ant-Man
/1주차/sequential_search.py
382
3.6875
4
import sys # 순차 탐색 구현 def sequential_search(n, target, array): for i in range(n): if array[i] == target: return i+1 # 인덱스가 아닌 '몇'번째 데이터인지 변환 array = [i for i in range(10, 30, 2)] n = len(array) target = 14 res = sequential_search(n, target, array) print(f"{target} 데이터는 array의 {res}번째에 존재!")
831cf73714cfc7f4edd615bc539c47f135395944
dhrubach/python-code-recipes
/simple_array/h_buy_sell_stock_twice.py
1,070
3.609375
4
########################################################################### # LeetCode Problem Number : 123 # Difficulty Level : Hard # URL : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ ########################################################################## from typing import List class BuySellStockTwice: def calculate(self, prices: List[int]) -> int: max_profit, min_price_so_far = 0, prices[0] first_buy_sell = [0] * len(prices) for i in range(1, len(prices)): max_profit_sell_today = prices[i] - min_price_so_far max_profit = max(max_profit, max_profit_sell_today) min_price_so_far = min(min_price_so_far, prices[i]) first_buy_sell[i] = max_profit max_sell_so_far = float("-inf") for i, price in reversed(list(enumerate(prices[1:], 1))): max_sell_so_far = max(max_sell_so_far, price) max_profit = max( max_profit, max_sell_so_far - price + first_buy_sell[i - 1] ) return max_profit
60da758c2a44ed111ff8833bb19e5ecfeb945c5f
limapedro2002/PEOO_Python
/Lista_06/Manuele-Myllene/Questão_03/Pessoa_3.py
1,155
3.9375
4
from Endereco import Endereco #Crie um diagrama de classes que represente uma classe Pessoa com os atributos privados identificador, #nome e CPF, e uma classe Endereço com os atributos número da casa, rua, cidade, estado e pais. Nesse caso #uma pessoa deve “agregar” um ou vários endereços. Implemente métodos para representar esse relacionamento. #Cardinalidades: #Uma Pessoa agrega um ou vários endereços (1 para muitos). #class_ indetificação # nome, cpf class Pessoa: enderecos =[] def __init__(self, nome, cpf,*ender): self.nome = nome self.cpf = cpf for endereco in ender: self.enderecos.append(endereco) def detalhar_pessoa(self): print("...............Mostrando informações da pessoa...............") print("Nome: {0}".format(self.nome)) print("Cpf: {0}".format(self.cpf)) for endereco in self.enderecos: print("=-"*30) print(f'Nº_da casa:{endereco.n_casa}') print(f'Cidade:{endereco.cidade}') print(f'Estado:{endereco.estado}')
a867ee7a0b82913ce8ef0c013cfff62402acb99a
arrancapr/Clases
/Python1ArrancaPr/Samples/firstfunction.py
469
3.640625
4
def firstFunction(throwError): if throwError: raise ValueError("showing the error functionality") else: print("function works yeah") def addHello(name): print("Welcome to the class: " + name) studentList = ["Davin", "Sarah", "Louie", "Aaron"] for var in studentList: addHello(var) def multiplyBy4(first , second): return (first + second) * 4 result = multiplyBy4(10,20) print(result) print(addHello(str(multiplyBy4(10,20))))
ed795239f4cfbe780864d1584de2dda8e3e60ffe
maha03/AnitaBorg-Python-Summer2020
/Week 7 Coding Challenges/Functions/squareroot.py
502
4.375
4
#Script: squareroot.py #Author: Mahalakshmi Subramanian #Anita Borg - Python Certification Course #DESCRIPTION: A Python program to find the square root of a number and return the integral part only '''Sample Input : 10 Sample Output : 3 ''' import math def squareroot(n): squareroot=math.sqrt(n) answer=int(squareroot) return answer user_input=input("Enter a number") try: n=int(user_input) if n<0: raise ValueError except: print("Enter a valid number") exit() print(squareroot(n))
c1ec323b5e7ecfb52fb8b57d910a1ba8b32d90cd
RodrigoVillalba/Tp-estadistica
/main.py
1,616
3.578125
4
# Tp de estadistica import random import math #1. Utilizando únicamente la función random de su lenguaje (la función que genera un número aleatorio uniforme entre 0 y 1), def calcularAleatorio(): numAleatorio = random.random() return numAleatorio #implemente una función que genere un número distribuido Bernoulli con probabilidad p. #Esto genera un experimento de bernouli con probabilidad p. def generarBernoulli(p): probabilidad_exito = p if (probabilidad_exito > calcularAleatorio()): return 1 else: return 0 #2. Utilizando la función del punto anterior, implemente otra que genere un número binomial con los parámetros n,p. ## devuelve la cantidad de exitos en n experimentos bernoulli #p -> probabilidad de exito de un experimento #n -> cantidad de experimentos def generarBinomial(n, p): j = 0 cant_exitos = 0 while j < n: if(generarBernoulli(p) == 1): cant_exitos +=1 j += 1 return cant_exitos #3. Utilizando el procedimiento descrito en el capítulo 6 del Dekking (método de la función inversa o de Monte Carlo), implementar # una función que permita generar un número aleatorio con distribución Exp(λ). #Realiza el calculo de la funcion inversa con un numero aleatorio def generarInversa(lambdaExponencial): return (-(math.log(1-calcularAleatorio())))/lambdaExponencial #4. Investigar como generar números aleatorios con distribución normal. Implementarlo. def generarNormal(media, varianza): return (1/(math.sqrt(2*math.pi*varianza)))*math.e**((-(calcularAleatorio()-media)**2)/2*varianza)
ac03cf401fa185d6e81a164a9ddc0ccbd3ae4bfb
MohamedAly8/Learning_OpenCV
/Project6.py
999
3.515625
4
import cv2 import numpy as np img = cv2.imread('chessboard.png') #Convert image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Runs Shi-Tomasi Corner Detection Algorithm args: (src image, max num of corners, quality 0 to 1, minimum euclidean distance between corners delta x^2 + delta y^2 = r^2 ) corners = cv2.goodFeaturesToTrack(gray,100,0.01,10) #Converts floats in np array to int corners = np.int0(corners) for corner in corners: #Flattens an aray, removes interior arrays [[[0],[1],[2]]]] -> [0,1,2] x, y = corner.ravel() #Draws circles at corners cv2.circle(img,(x,y),10,(0,0,255),2) for i in range(len(corners)): for j in range(i+1, len(corners)): corner1 = tuple(corners[i][0]) corner2 = tuple(corners[j][0]) # args: low , high, size color = tuple(map(lambda x: int(x), np.random.randint(0,255,size=3))) cv2.line(img,corner1,corner2, color, 1) cv2.imshow('Frame', img) cv2.waitKey(0) cv2.destroyAllWindows()
2a942cad205a3631e1b5d58b75337f666b29cd35
gitpbg/learnmatplotlib
/bar.py
378
3.640625
4
import numpy as np import matplotlib.pyplot as plt import sys #histogram and barchart x = np.arange(1, 10, 2) print(x) y = 10*np.random.rand(5) x2 = np.arange(0, 10, 2) y2 = 10*np.random.rand(5) plt.bar(x, y, label='bars1', color='blue') plt.bar(x2, y2, label='bars2', color='purple') plt.xlabel('x') plt.ylabel('y') plt.title("Interesting BarChart") plt.legend() plt.show()
9ddacb8801d5d0ee53c2b1cb21b56b9ebc5c1400
hongminpark/prgrms-algorithms
/stack_queue/lv2_프린터_queue.py
645
3.65625
4
# https://programmers.co.kr/learn/courses/30/lessons/42587 from queue import Queue def solution(priorities, location): q = Queue() count = 0 for i in range(1, len(priorities)): q.put(i) max_idx = 0 q.put(max_idx) while True: now = q.get() if q.qsize() == 0: return count + 1 elif now == max_idx: count += 1 max_idx = q.get() q.put(max_idx) if now == location: return count elif priorities[now] > priorities[max_idx]: max_idx = now q.put(now) else: q.put(now)
891f371f0fc3238669506a64f9018cd2e1ec14d4
cameronkabati/pythonexample
/python.py
189
4.25
4
#prints the output hello world print ('Hello world') #Using strings and the input function using print name =input('Please enter your name: ') print('hello', name, 'nice to meet you')
41818fafa3ba81b1c661072fc03f6b82dffa0284
sejunova/algorithm-study
/cracking_coding_interview/array_and_string/string_compression.py
678
3.609375
4
def string_compression(string): cur_char, char_count = string[0], 1 compression_list = [] for i in range(len(string)): if len(compression_list) > len(string): return string if i + 1 == len(string): compression_list.append(cur_char) compression_list.append(str(char_count)) break if cur_char == string[i + 1]: char_count += 1 else: compression_list.append(cur_char) compression_list.append(str(char_count)) cur_char = string[i + 1] char_count = 1 return ''.join(compression_list) print(string_compression('abceeddaa'))
2fc25e360354d6bd3d522b0dcd44523227f578fe
vic-ux/py_work
/parrot.py
699
4.1875
4
prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " message = "" while message != 'quit' : message = input(prompt) if message != 'quit': print(message) prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message) prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")
9fc18140e2ec19aa065d66a917216b83a9407873
kamaljahangir/adhocpywinter2018
/adhoc/input.py
209
3.9375
4
#!/usr/bin/python import time n1=raw_input("enter a number : ") # delay of 2 second time.sleep(2) n2=raw_input("enter a number : ") # typecast to int print "sum of given numbers ",int(n1)+int(n2)
5c15b534468b82cc781f80a1dfa70614f4a31755
AgastyaTeja/HackerRank
/ModifiedKaprekarNumbers.py
801
3.53125
4
#!/bin/python3 import math import os import random import re import sys # Complete the kaprekarNumbers function below. def kaprekarNumbers(p, q): output="" for i in range(p,q+1): n = i**2 temp=str(n) if len(str(n))%2==0: d=len(str(n))//2 else: d=(len(str(n))+1)//2 lp=temp[:len(temp)-d] rp=temp[len(temp)-d:len(temp)] if lp=="": lp=0 elif rp=="": rp=0 if(int(lp)+int(rp)==i): output=output+" "+str(i) if output==" ": print("INVALID RANGE") else: print(output[1:]) if __name__ == '__main__': p = int(input()) q = int(input()) kaprekarNumbers(p, q)
946fd6d911f39890360b6b8d1f64a1aa646db4b6
AthosFB/Exercicios-Python
/ExercícioDoCurso/091.py
597
3.515625
4
import random import time from operator import itemgetter jogo = {"jogador1": random.randint(1, 6), "jogador2": random.randint(1, 6), "jogador3": random.randint(1, 6), "jogador4": random.randint(1, 6)} ranking = {} print("Valore Sorteados: ") for k, n in jogo.items(): print(f"{k} recebe \033[1;32m{n}\033[m") time.sleep(1) print("-=" * 30) ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True) print(" === Ranking Dos Jogadores ===") for enu, c in enumerate(ranking): print(f" -{enu+1}º Lugar {c[0]} com \033[1;32m{c[1]}\033[m") time.sleep(1)
43ca6390c9b115ccbc3fed873bcc0215b3bad5ae
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/vrmnic005/question2.py
243
4.1875
4
def print_triangle(height): for row in range(height): print(" " * (height - row - 1) + "*" * (2*row + 1)) if __name__ == "__main__": height = int(input("Enter the height of the triangle:\n")) print_triangle(height)
ce68db4f2c2b74900948df93b42c13dbfea481c5
Kvazimado/Kvazi
/Калькулятор 2.py
223
4.0625
4
a = float (input("NUM 1 \n")) b = float (input("NUM 2 \n")) w = float (input("NUM 3 \n")) c = input("RAW \n") r = 0 if c=="+": r=a+b+w elif c=="-": r=a-b-w elif c=="*": r=a*b*w elif c=="/": r=a/b/w print (r)
b66024ce1f63908c281187cacaf37c478e2940e7
navneetspartaglobal/Data21Notes
/reptile.py
457
3.640625
4
from animal import Animal class Reptile(Animal): def __init__(self): super().__init__() self.cold_blooded = True def use_venom(self): print("if i have venom i am going to use it") def moving(self): print("moving but as a snake") def __repr__(self): return f"This is reptile" def __str__(self): return f"str version of this is reptile" bob = Reptile() #print(repr(bob)) print(bob)
c94ba5cb9058f4199101ed5205fe8bb87f0b15a1
ivanovkalin/myprojects
/softUni/tayloring_workshop.py
657
3.5
4
usd_exchange_rate = 1.85 number_of_rectangle_tables = int(input()) length_of_rectangle_tables_in_m = float(input()) width_of_rectangle_tables_in_m = float(input()) total_size_of_table_covers = number_of_rectangle_tables * (length_of_rectangle_tables_in_m + 2 * 0.30) * (width_of_rectangle_tables_in_m + 2 * 0.30) total_area_of_table_mini_cover = number_of_rectangle_tables * (length_of_rectangle_tables_in_m / 2) * (length_of_rectangle_tables_in_m / 2) price_in_usd = total_size_of_table_covers * 7 + total_area_of_table_mini_cover * 9 price_in_bgn = price_in_usd * usd_exchange_rate print(f"{price_in_usd:.2f} USD") print(f"{price_in_bgn:.2f} BGN")
100461bfaca0972089f14a34c5d800473630ac5a
TheEnzoLobo/flvs
/2-06.py
304
4.09375
4
amount = int(input("How many products you like? ")) total = float(0.00) for side in range(amount): product = str(input("Product: ")) price = float(input("Price: $")) print(product + " $" + str(price)) total = total + price print("Your total is " + " $" + str(total))
865b17bc1d2a6e8ebbdba35e7c53a2b73af6b1c3
mzakjang2/WORKSHOP2
/string/string_format.py
221
3.8125
4
age = 22 txt = "My name is BM, and I am {}" result = txt.format(age) print("result:", result) # result: My name is BB, and I am 21 # เอาage มาใส่ในtxt โดยใช้ฟังก์ชันformat
e36bb1f0024cb25690a4b4174613bd206beefba1
aaron-maritz/ctci_solutions
/chapter_1/q_5.py
1,828
4.09375
4
# Aaron Maritz # Question 1.5 # One Away -> Three types of edits that can be performed on strings # Insert char, Remove char, Replace char, Given two strings determine if they are one edit (or zero) away # example -> pale, pale -> true, ple, pale -> true, pale, bake -> false # Thoughts -> first check length, if length is >= 2 away -> false # Key is finding difference <= 1 between the two # Best run time -> O(n) where n is the length of the first string # Look at the seperate conditions def oneAway(str1, str2) : if str1 == str2 : return True # At this point we know they are not the same string # Check if count(# of inconsistenceies is > 1) # If so -> return False ptr1 = 0 ptr2 = 0 count = 0 len1 = len(str1) len2 = len(str2) if (abs(len1 - len2) >= 2) : return False # How to check if there was an inserted # Inserted check -> ptr2 -= # Remove check -> ptr1 -= # Edit check -> index stays the same while (ptr1 < len1): if ptr1 >= len2 or str1[ptr1] != str2[ptr2] : # inconsistency found count += 1 if count > 1 : return False if len1 > len2 : # checking for insert ptr2 -= 1 if len2 > len1 : # checking for remove ptr1 -= 1 ptr2 += 1 ptr1 += 1 return True if __name__ == '__main__' : print (oneAway(['p','l','e'], ['p','a','l','e'])) print (oneAway(['p','a','l','e','s'], ['p','a','l','e'])) print (oneAway(['p','a','l','e'], ['b','a','l','e'])) print (oneAway(['p','a','l','e'], ['b','a','k','e'])) print (oneAway([''], [''])) print (oneAway(['h','e'], [])) print (oneAway(['h','e'], ['h'])) print (oneAway(['h','e'], ['b'])) print (oneAway(['b'], ['h','e']))
1b40053ed8bccfa314868eed929ad575488c0eb6
Ezeaobinna/Python-Basics-Algorithms-Data-Structures-Object-Oriented-Programming-Job-Interview-Questions
/Algorithms/Sorting and Searching/sorting/bubble sort/bubble-sort-recursive.py
323
3.8125
4
alist: list = [54, 26, 93, 17, 77, 31, 44, 55, 20] def bubbleSort(alist, n: int): if n < 2: return for i in range(n): if alist[i] > alist[i + 1]: alist[i], alist[i + 1] = alist[i + 1], alist[i] bubbleSort(alist, n - 1) print(alist) bubbleSort(alist, len(alist) - 1) print(alist)
54ee32626f4f5f51bcb2e31ce9a122226f76efde
KickItAndCode/Algorithms
/DynamicProgramming/BurstBalloons.py
3,041
3.59375
4
# 312. Burst Balloons # Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent. # Find the maximum coins you can collect by bursting the balloons wisely. # Note: # You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. # 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 # Example: # Input: [3,1,5,8] # Output: 167 # Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] # coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 def maxCoins2(iNums): nums = [1] + [i for i in iNums if i > 0] + [1] n = len(nums) dp = [[0]*n for _ in range(n)] for k in range(2, n): for left in range(0, n - k): right = left + k for i in range(left + 1, right): dp[left][right] = max(dp[left][right], nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right]) return dp[0][n - 1] # Top Down ~800ms def maxCoins(nums): nums, memo = [1] + nums + [1], {} def dp(l, r): if l + 1 == r: return 0 if (l, r) not in memo: memo[(l, r)] = max(dp(l, i) + nums[l] * nums[i] * nums[r] + dp(i, r) for i in range(l + 1, r)) return memo[(l, r)] return dp(0, len(nums) - 1) # Button Up ~200ms def maxCoins(nums): nums, N = [1] + nums + [1], len(nums) + 2 dp = [[0] * N for _ in range(N)] for gap in range(2, N): for i in range(N - gap): j = i + gap dp[i][j] = max(dp[i][k] + nums[i] * nums[k] * nums[j] + dp[k][j] for k in range(i + 1, j)) return dp[0][N - 1] # PERSONAL STRUGGLE SOLUTION NO EVEN CLOSE def maxCoins(nums): nums = [1] + nums + [1] # build the complete array n = len(nums) # loop through all coins dp = [0] * len(nums) while nums: # find the max you'd get by bursting a certain balloon curr_max = float("-inf") indexToDelete = -1 for i in range(len(nums)): coins = burst(nums, i) if coins > curr_max: indexToDelete = i curr_max = coins dp[i] = coins nums = removeBalloon(nums, indexToDelete) return sum(dp) def removeBalloon(nums, i): return nums[:i] + nums[i+1:] def burst(nums, i): if i == 0 and len(nums) > 1: return nums[i] * nums[i+1] elif i == len(nums) - 1: return nums[i] * nums[i-1] else: return nums[i] * nums[i+1] * nums[i-1] print(maxCoins2([3, 1, 5, 8])) # Output: 167 # Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] # coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
54ce9a84cf1a8096251243faee80961af1ec3a3d
veyu0/Python
/les_8/les_8_task_4.py
1,397
3.890625
4
class Office_equipment: def __init__(self, name, model): self.name = name self.model = model def __str__(self): return f'Name - {self.name}, model - {self.model}' class Printer(Office_equipment): def __init__(self, name, model, amount): super().__init__(name, model) class Scanner(Office_equipment): def __init__(self, name, model, amount): super().__init__(name, model) self.amount = amount class Computer(Office_equipment): def __init__(self, name, model, amount): super().__init__(name, model) self.amount = amount p = Printer('printer', 'RX-100', 10) s = Scanner('scanner', 'Canon-SS2', 5) c = Computer('computer', 'HP-ZCE378', 20) print(f'{p},\n {s},\n {c}') while True: print('1 - for break') order = input('What equipment do you need? (p - printer, s - scanner, c - computer) ') equipment = {} if order == 'p': printer = int(input('How many? ')) equipment['printer'] = printer print(equipment) elif order == 's': scanner = int(input('How many? ')) equipment['scanner'] = scanner print(equipment) elif order == 'c': computer = int(input('How many? ')) equipment['computer'] = computer print(equipment) else: print(equipment) break