blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4a1d1439d8706fe0de36872553c1381fa06f7728
Nockternal/Burger
/intro to programming/Task 17/disappear.py
405
4.0625
4
removel_list = [] sentence = input("Please enter a centence. ") removal = input("would you like to remove a character y/n") while removal == "y": char = input("Please enter character you want to remove") removel_list.append(char) removal = input("would you like to remove a character y/n") for i in removel_list: sentence = sentence.replace(i,"") print(sentence)
111fc33b5ac687a300cf031f9a779820ee978ee2
imflash217/Project_Algorithms
/algorithms/InsertionSort.py
776
4.125
4
# Q: Given an unsorted array A[] of size N; sort the array in ascending order and return it # The below implementation takes O(n^2) running time import sys # Input Array: # input_array = [1,23,43,45,2,0,-100,-3,98,12,4,-43] # Taking the unsorted input array from user input_array = [int(x) for x in raw_input('Please enter the input array > ').split(',')] ############################################ def insertion_sort(A): n = len(A)-1 # the size of the array for j in range(1, n+1): key = A[j] i = j-1 while i >= 0 and A[i]>key: A[i+1] = A[i] i -= 1 A[i+1] = key print "Step #%d --> " % j, A print 'The sorted array is : ', A return A ############################################ insertion_sort(input_array) # insertion_sort(input_array2)
74b97e958304b6eb80637704fd53cb4c7f553ca5
Borghese-Gladiator/spam-classification
/features.py
1,884
3.546875
4
import numpy as np import nltk from utils import spam_words_list, apply_preprocess_all class FeatureExtractor(): def __init__(self, debug=True): from nltk.corpus import words nltk.download('words') self.set_words = set(words.words()) self.debug = debug def _compute_misspelled_words(self, email): """ Computes the number of misspelled words in sentence """ num_misspelled = 0 word_list = email.split() for word in word_list: if word in self.set_words: num_misspelled += 1 return num_misspelled def _compute_spam_phrases_count(self, email): """ Computes the number of known spam words in sentence """ num_spam = 0 word_list = email.split() for word in spam_words_list: if word in self.set_words: num_spam += 1 return num_spam def _compute_exclamation_point_count(self, email): """ Computes the number of exclamation points in sentence """ num_char = 0 for character in email: if character == "!": num_char += 1 return num_char def extract_features(self, email, debug=False): """ Here is where you will extract your features from the data in the given window. Make sure that x is a vector of length d matrix, where d is the number of features. """ ## PREPROCESS TEXT # email = apply_preprocess_all(email) # omit preprocessing due to how long it takes feature_vector = np.array([ self._compute_misspelled_words(email), self._compute_spam_phrases_count(email), self._compute_exclamation_point_count(email) ]) return feature_vector
65064f7fb6969b1b6df1f2dbbd0bad2e077e43d5
rvaishnavigowda/Hackerrank-SI-Basic
/compute n!.py
363
3.8125
4
''' Given a non-negative number - N. Print N! Input Format Input contains a number - N. Constraints 0 <= N <= 10 Output Format Print Factorial of N. Sample Input 0 5 Sample Output 0 120 Explanation 0 Self Explanatory ''' n=int(input()) def fact(n): if n==0 or n==1: return 1 else: m=n*fact(n-1) return m print(fact(n))
47c592baeaef95ca3e1e2406b6e6caa4399bc584
MahdiRafsan/Sorting_Algorithms_Visualizer
/sorting_algorithms/merge_sort.py
1,928
4.5
4
import time def merge_sort(data, left, right, draw, speed): """ algorithm to visualize merge sort :param data: list of integers to sort :param left: starting index of the array of integers :param right: ending index of the array of integers :param draw: funciton to draw the integers on the canvas :param speed: speed at which the algorithm is run :return: None """ if left < right: mid = (left+right) // 2 merge_sort(data, left, mid, draw, speed) merge_sort(data, mid+1, right, draw, speed) merge(data, left, mid, right) draw(data, ["Blue" if x >= left and x < mid else "Red" if x == mid else "Yellow" if x > mid and x <= right else "#a871e3" for x in range(len(data))]) time.sleep(speed) def merge(data, left, mid, right): """ function to merge the sorted arrays :param left: starting index of the list of numbers :param mid: middle index to divide the array into left and right halves :param right: last index of the list numbers :return: None """ left_half = data[left : mid + 1] right_half = data[mid + 1 : right + 1] # i → index for left_half # j → index for right_half i, j, sort_index = 0, 0, left while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: data[sort_index] = left_half[i] i += 1 else: data[sort_index] = right_half[j] j += 1 sort_index += 1 # adds remaining elements to the sorted list # when one of the left or right lists is empty while i < len(left_half): data[sort_index]= left_half[i] i += 1 sort_index += 1 while j < len(right_half): data[sort_index] = right_half[j] j += 1 sort_index += 1
ba3e72c41a6117ae4166a5444613020bb4bfc91f
OhOHOh/LeetCodePractice
/python/No27.py
1,221
3.71875
4
# -*- coding: UTF-8 -*- class Solution: def removeElement(self, nums, val): if len(nums) == 0 or nums is None: return nums left, right = 0, len(nums)-1 while left < right: while left<right and nums[right]==val: right -= 1 while left<right and nums[left]!=val: left += 1 tmp = nums[left] nums[left] = nums[right] nums[right] = tmp return nums def removeElement_1(self, nums, val): ''' 快慢指针 ''' slow, fast = 0, 0 while fast < len(nums): if nums[fast] != val: nums[slow] = nums[fast] slow += 1 fast += 1 else: fast += 1 return nums def removeElement_2(self, nums, val): slow, fast = 0, 0 while fast < len(nums): if nums[fast] == val: fast += 1 else: nums[slow] = nums[fast] slow += 1 fast += 1 return slow s = Solution() print(s.removeElement([0,1,2,2,3,0,4,2], 2)) print(s.removeElement_1([0,1,2,2,3,0,4,2], 2))
a21d5b67f1181605eb34dc9b97bb5b4182cca4ec
KoliosterNikolayIliev/Softuni_education
/Fundamentals2020/MID EXAM Preparation/Contact list Smart.py
1,083
3.65625
4
contacts = input().split(" ") while True: command = input().split(" ") cmd = command[0] if cmd == "Add": name = command[1] index = int(command[2]) if 0 <= index <= len(contacts): if name in contacts: contacts.insert(index, name) else: contacts.append(name) elif cmd == "Remove": index = int(command[1]) if 0 <= index <= len(contacts): del contacts[index] elif cmd == "Export": start = int(command[1]) stop = int(command[2]) if start + stop < len(contacts): print(f"{' '.join([contacts[x] for x in range(start, (start + stop))])}") else: print(f"{' '.join([contacts[x] for x in range(start, len(contacts))])}") elif cmd == "Print": way = command[1] if way == "Normal": print(f"Contacts: {' '.join(contacts)}") break else: reversed_c = list(reversed(contacts)) print(f"Contacts: {' '.join(reversed_c)}") break
b3fe7be9416de993645188f8c6d93d9f1b14b354
MaksimKulya/PythonCourse
/L3_task1.py
693
4.0625
4
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. print(f"Enter a1") a1 = float(input()) print(f"Enter a2") a2 = float(input()) # by try def division_try(a1, a2): try: return a1 / a2 except ZeroDivisionError: return "NaN" # by if def division_if(a1, a2): if a2 == 0: a3 = "NaN" else: a3 = a1 / a2 return a3 a3 = division_try(a1, a2) print(f"a3={a3}")
095ca91b05b1391df493e2181237a1956657c50b
daniel-reich/ubiquitous-fiesta
/fRZMqCpyxpSgmriQ6_14.py
497
3.84375
4
import string ​ def sorting(s): init = sorted(s) numbers = [] no_digit = [] ​ # store numbers for i in init: if i.isdigit(): numbers.extend(i) ​ # remove numbers from original string for i in init: if not i.isdigit(): no_digit.extend(i) ​ first_sort = sorted(no_digit, key=string.ascii_letters.index) final = sorted(first_sort, key=str.lower) ​ # makes lists to string digit = "".join(numbers) new_s = "".join(final) return new_s+digit
03d74721ed17719704f310ae60308d885701185a
gjewstic/GA-Python
/homework/hw-3_pig_game.py
2,586
4.15625
4
import random turn = 1 player_one_total = 0 player_two_total = 0 max_score = 50 selection = int(input('Who will be rolling first? Enter a 1 or 2: ')) turn = selection while True: choice = input(f'Player {turn}, do you choose to roll (r) or pass (p)? ') if choice == 'r': score = random.randint(1, 15) if score is not 1: if turn is 1: player_one_total += score print( f'Player {turn}, you scored {score}. Your current total is: {player_one_total}') else: player_two_total += score print( f'Player {turn}, you scored {score}. Your current total is: {player_two_total}') else: if turn is 1: print( f'Player {turn}, your score is {score}. You lose your turn.') player_one_total = 0 turn = 2 else: print( f'Player {turn}, your score is {score}. You lose your turn.') player_two_total = 0 turn = 1 # else: if turn == 1: turn = 2 print(f'Player {turn}, your score is {score}.') else: turn = 1 choice = input( f'Player {turn}, do you choose to roll (r) or pass (p)? ') score = random.randint(1, 15) # if score is not 1: if turn is 1: player_one_total += score print( f'Player {turn}, you scored {score}. Your current total is: {player_one_total}') else: player_two_total += score print( f'Player {turn}, you scored {score}. Your current total is: {player_two_total}') else: if turn is 1: print( f'Player {turn}, your score is {score}. You lose your turn.') player_one_total = 0 turn = 2 else: print( f'Player {turn}, your score is {score}. You lose your turn.') player_two_total = 0 turn = 1 # if player_one_total >= max_score or player_two_total >= max_score: if player_one_total > max_score: print(f'Player 1 is the winner!! Score = {player_one_total}') else: print(f'Player 2 is the winner!! Score = {player_two_total}') break
084e6ab50d1d7fccea19aa139e006242c46057cc
GrandDuelist/mRythm
/UNDER/spark-code/exploring/systems/subway/TripEntity.py
2,922
3.515625
4
class Trip(): def __init__(self,start=None,end=None,start_time=None,end_time=None,route= None): self.start = start self.end = end self.start_time = start_time self.end_time = end_time self.all_locations = None #used for intermediate points self.all_times = None #used for intermediate times self.in_vehicle_time = None self.trip_time = None self.waiting_time = None self.user_id = None self.route = route def setLocation(self,start,end): self.start = start self.end = end def setDistrictByStationName(self,subway): self.start.setDistrictByStationName(subway) self.end.setDistrictByStationName(subway) def setTime(self,start_time,end_time): self.start_time = start_time self.end_time = end_time def computeTripDistance(self): pass def computeTripTime(self): # print "start:" + str(self.start_time) + " end: " + str(self.end_time) self.trip_time = self.end_time - self.start_time def computeTripTimeToSeconds(self): return(self.trip_time.total_seconds()) def setInvehicleTime(self,in_vehicle_time): self.in_vehicle_time = in_vehicle_time def computeWaitingTime(self): self.waiting_time = self.trip_time - self.in_vehicle_time def timeToMin(self,t_hour=None,t_min=None,t_sec=None): total_min = 0 if t_hour is not None: total_min = total_min + t_hour * 60 if t_min is not None: total_min = total_min + t_min if t_sec is not None: total_min = float(total_min) + float(t_sec)/float(60) return total_min def timeSlot(self,t_hour = None, t_min=None,t_sec = None): divide_min = self.timeToMin(t_hour,t_min,t_sec) start_min = self.timeToMin(self.start_time.hour,self.start_time.minute,self.start_time.second) slot = int(start_min/divide_min) self.timeslot = slot return slot def isCircle(self): return self.start.lon == self.end.lon and self.start.lat == self.end.lat def arriveTimeSlot(self,t_hour=None,t_min=None, t_sec =None): divide_min = self.timeToMin(t_hour,t_min,t_sec) end_min = self.timeToMin(self.end_time.hour,self.end_time.minute,self.end_time.second) slot = int(end_min/divide_min) self.end_timeslot = slot return slot def waitingTime(self,in_vehicle_time): # print in_vehicle_time self.waiting_time = self.trip_time - in_vehicle_time self.waiting_time_to_min = float(self.waiting_time.total_seconds())/float(60) return self.waiting_time_to_min def originDestination(self): if self.start.station_id is None or self.end.station_id is None: return (self.start.trans_region,self.end.trans_region) return (self.start.station_id,self.end.station_id)
5d8d21a43fc0bb0cf3bffde89c7bc691a16960f6
HussainPythonista/SomeImportantProblems
/Leetcode Problems/median.py
324
3.984375
4
def median(listValue): mid=len(listValue)//2 if len(listValue)%2==1: return listValue[mid] else: left=listValue[mid-1] right=listValue[mid] return float((left+right)/2) list1=[1,2] list2=[3,4] newList=list1+list2 newList=sorted(newList) print(newList) print(median(newList))
9893633178d92374cb918432e5995f65ae03ea61
Sungchul-P/TIL
/algorithm/testdome/Python Inteview Question/3_Merge_Names.py
749
3.859375
4
# 이름이 저장된 두 리스트(Array)를 합친 결과를 리스트로 반환한다. # 중복된 이름은 제거한다. # 함수 호출 : unique_names(['Ava', 'Emma', 'Olivia'], ['Olivia', 'Sophia', 'Emma']) # 결과 : ['Ava', 'Emma', 'Olivia', 'Sophia'] # 문제 원형 # ''' def unique_names(names1, names2): return None names1 = ["Ava", "Emma", "Olivia"] names2 = ["Olivia", "Sophia", "Emma"] print(unique_names(names1, names2)) # should print Ava, Emma, Olivia, Sophia ''' # 문제 풀이 # def unique_names(names1, names2): names = set(names1 + names2) return list(names) names1 = ["Ava", "Emma", "Olivia"] names2 = ["Olivia", "Sophia", "Emma"] print(unique_names(names1, names2)) # should print Ava, Emma, Olivia, Sophia
85486b89fb548dd13e0c4f64a2df8f84fee4c8b8
ayumoesylv/draft-tic-tac-toe
/l2 class 8 project v.8.py
3,322
3.90625
4
import random def printBoard(board: list): print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print('-----------') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print('-----------') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) # lose is not necessary, create win and draw with an initial value (draw is False) def playGame(): while True: win = get_winner(user_team) lose = get_winner(opp_team) draw = tie() if (win is not True) and (lose is not True) and (draw is not True): position = int(input("Please enter a number from 1-9: ")) board[position] = user_team printBoard(board) print("===========================") opp_moves(board) elif win is True: print("You Win!") break elif lose is True: print("You Lose!") break elif draw is True: print("Draw!") break else: break def get_open_cells(board): open_cells: list = [cell for cell in range(1, 10) if board[cell] == " "] return open_cells def rows(board): row = [board[1:4], board[4:7], board[7:10], board[1:8:3], board[2:9:3], board[3:10:3], board[1:10:4], board[3:8:2]] return row def get_winner(team): v_rows = rows(board) if [team, team, team] in v_rows: return True else: return False def tie(): if get_open_cells(board) == []: return True else: return False def potential_win(board, team, testing): move = False open_pos = get_open_cells(board) for oc in open_pos: board[oc] = testing row = rows(board) for i in row: if i == [testing, testing, testing]: move = True board[oc] = team printBoard(board) break else: board[oc] = " " if move == True: break return move def placeMiddle(board): if 5 in get_open_cells(board): position = 5 board[position] = opp_team printBoard(board) return True else: return False # add a return false def placeRandom(board): while tie() == False: cell = random.choice(get_open_cells(board)) if cell in get_open_cells(board): position = cell board[position] = opp_team printBoard(board) return True else: return False def opp_moves(board): if potential_win(board, opp_team, opp_team) == True: return elif potential_win(board, opp_team, user_team) == True: return elif placeMiddle(board) == True: return elif placeRandom(board) == True: return while True: play_again = str(input("Would you like to play Tic-Tac_Toe? Type 'yes' to play again, type 'no' to quit: ")) teams = ["O", "X"] if play_again == "no": break if play_again == "yes": user_number = (int(input("Please enter 0 to choose X or 1 to choose O: "))) user_team = teams[user_number] opp_team = teams[(not user_number)] board = [' '] * 10 playGame() print("game over") # c9
a3de5fc637765d28efe7e914d6c68770ceee3039
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2019/Practicas/1er Parcial/Examen/adapter.py
888
3.765625
4
class Smartphone(object): """docstring for Smartphone""" voltaje_maximo = 5 def carga(self, enchufe): """Carga el smartphone con el voltaje de entrada proporcionado.""" self._carga(enchufe.voltaje_de_salida) @classmethod def _carga(cls, voltaje_entrante): if voltaje_entrante > cls.voltaje_maximo: print('Voltaje: {}V -- Mestoy quemando :C!!!'.format(voltaje_entrante)) else: print('Voltaje: {}V -- Cargando...'.format(voltaje_entrante)) class Enchufe(object): """docstring for Enchufe""" voltaje_de_salida = None class EnchufeEuropeo(Enchufe): """docstring for EnchufeEuropeo""" voltaje_de_salida = 220 class EnchufeAmericano(Enchufe): """docstring for EnchufeAmericano""" voltaje_de_salida = 110 smartphone = Smartphone() smartphone.carga(EnchufeEuropeo) # Mestoy quemando :C!!!
fdbf21b52d739cd368212c441c689a58c20c66a8
Aasthaengg/IBMdataset
/Python_codes/p02392/s152482423.py
159
3.640625
4
import sys nums = [ int( val ) for val in sys.stdin.readline().split( " " ) ] if nums[0] < nums[1] and nums[1] < nums[2]: print( "Yes" ) else: print( "No" )
69b9740922a731ca4ee37e97d96b4ca47235311c
kleberfsobrinho/python
/Desafio085 - Listas com Pares e Ímpares.py
280
3.609375
4
v = [[], []] valor = 0 for c in range(0, 7): valor = int(input(f'Entre com o {c+1}º valor: ')) if valor % 2 == 0: v[0].append(valor) else: v[1].append(valor) v[0].sort() v[1].sort() print(f'Os pares foram: {v[0]}') print(f'Os ímpares foram: {v[1]}')
02596a8f271ee838f8cac9311a18e4d04cb7afc8
DmytroLukianchuk/Python
/homeTaskTwoNumbers/numbers.py
3,351
3.90625
4
print("HomeWork#2: User enters number in range 20 - 99 from keyboard and get correct spelling of this number in console") dict_numbers = {"1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "ten": "ten", "twenty": "twenty", "thirty": "thirty", "forty": "forty", "fifty": "fifty", "sixty": "sixty", "seventy": "seventy", "eighty": "eighty", "ninety": "ninety"} user_input = str(input("Enter any number from 20 till 99 to know how it spells: ")) user_num_one, user_num_two = user_input while user_num_one == '0' or user_num_one == '1': user_input = str(input("First entered number was 1. Enter any number from 20 till 99 to know how it spells: ")) user_num_one, user_num_two = user_input print("first number was entered:", user_num_one) print("second number was entered:", user_num_two) if int(user_num_one) == 1 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['ten']) exit() if int(user_num_one) == 2 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['twenty']) exit() if int(user_num_one) == 3 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['thirty']) exit() if int(user_num_one) == 4 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['forty']) exit() if int(user_num_one) == 5 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['fifty']) exit() if int(user_num_one) == 6 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['sixty']) exit() if int(user_num_one) == 7 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['seventy']) exit() if int(user_num_one) == 8 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['eighty']) exit() if int(user_num_one) == 9 and int(user_num_two) == 0: print("spelling of your entered number is:", dict_numbers['ninety']) exit() if int(user_num_one) == 2: num_word_one = dict_numbers['twenty'] if int(user_num_one) == 3: num_word_one = dict_numbers['thirty'] if int(user_num_one) == 4: num_word_one = dict_numbers['forty'] if int(user_num_one) == 5: num_word_one = dict_numbers['fifty'] if int(user_num_one) == 6: num_word_one = dict_numbers['sixty'] if int(user_num_one) == 7: num_word_one = dict_numbers['seventy'] if int(user_num_one) == 8: num_word_one = dict_numbers['eighty'] if int(user_num_one) == 9: num_word_one = dict_numbers['ninety'] if int(user_num_two) == 1: num_word_two = dict_numbers['1'] if int(user_num_two) == 2: num_word_two = dict_numbers['2'] if int(user_num_two) == 3: num_word_two = dict_numbers['3'] if int(user_num_two) == 4: num_word_two = dict_numbers['4'] if int(user_num_two) == 5: num_word_two = dict_numbers['5'] if int(user_num_two) == 6: num_word_two = dict_numbers['6'] if int(user_num_two) == 7: num_word_two = dict_numbers['7'] if int(user_num_two) == 8: num_word_two = dict_numbers['8'] if int(user_num_two) == 9: num_word_two = dict_numbers['9'] print("spelling of your entered number is:", num_word_one, num_word_two)
3c6cafcaa57186f11ecd18700a15f8ee4e5945c0
isk02206/python
/informatics/previous informatics/Infomatics-1/6/REDUCTIO.py
4,374
3.78125
4
''' Created on 2015. 12. 3. @author: User ''' 5.3 Reductio ad absurdum def equivalentFraction(numerator1, denominator1, numerator2, denominator2): """ >>> equivalentFraction(19, 95, 1, 5) True >>> equivalentFraction(532, 931, 52, 91) True >>> equivalentFraction(12, 13, 2, 3) False """ # compare numerators after given both fractions a common denominator return numerator1 * denominator2 == numerator2 * denominator1 def reduction(numerator, denominator): """ >>> reduction(19, 95) (1, 5) >>> reduction(532, 931) (52, 91) >>> reduction(2349, 9396) (24, 96) >>> reduction(12, 13) (2, 3) >>> reduction(11, 10) (1, 0) >>> reduction(123, 3214) (-1, 4) """ # convert numerator and denominator into string of digits numerator, denominator = str(numerator), str(denominator) 14 # for each common digit, cancel its leftmost occurrence in both the # numerator and denominator reduced_numerator = for digit in numerator: if digit in denominator: position = denominator.index(digit) denominator = denominator[:position] + denominator[position + 1:] else: reduced_numerator += digit # convert reduced numerator and denominator into integers return ( int(reduced_numerator) if reduced_numerator else -1, int(denominator) if denominator else -1 ) def validReduction(numerator, denominator): """ >>> validReduction(19, 95) (1, 5) >>> validReduction(532, 931) (52, 91) >>> validReduction(2349, 9396) (24, 96) >>> validReduction(12, 13) (12, 13) >>> validReduction(11, 10) (11, 10) >>> validReduction(123, 3214) (123, 3214) """ # determine the reduced numerator and denominator reduced_numerator, reduced_denominator = reduction(numerator, denominator) if ( reduced_numerator >= 0 and reduced_denominator > 0 and equivalentFraction(numerator, denominator, reduced_numerator, reduced_denominator) ): # return reduced fraction if it is equivalent to the original fraction return reduced_numerator, reduced_denominator else: # otherwise return the original fraction return numerator, denominator if __name__ == __main__: import doctest doctest.testmod() 5.4 Pigpen cipher def pigpenletter(letter): """ >>> print(pigpenletter(A)) | | --+ >>> print(pigpenletter(m)) --+ .| --+ >>> print(pigpenletter(U)) | |: 15 +-- """ # optional: represent white space as three empty columns if letter.isspace(): return \n \n # if argument is no whitespace, it must be a letter assert letter.isalpha(), argument must be a letter # determine row, column and number of points in center letter = letter.upper() value = (ord(letter) - ord(A)) % 9 row = value // 3 col = value % 3 points = (ord(letter) - ord(A)) // 9 # determine whether theres a line to the left, to the right, on top and # below left = col != 0 right = col != 2 top = row != 0 bottom = row != 2 # compose letter according to pigpen cipher return {}{}{}\n{}{}{}\n{}{}{}.format( # top left + if left and top else - if top else | if left else , # top center - if top else , # top right + if right and top else - if top else | if right else , # center left | if left else , # center center (points) . if points == 1 else : if points == 2 else , # center right | if right else , # bottom left + if left and bottom else - if bottom else | if left else , # bottom center - if bottom else , # bottom right + if right and bottom else - if bottom else | if right else ) def pigpen(text): """ >>> print(pigpen(python)) --+ --+ | | +-+ +-- +-+ .| :| |:| | | |. |.| | | +-+ | | +-- +-+ >>> print(pigpen(Rosenkreutz)) +-- +-- | +-+ +-+ | | +-- +-+ | | | +-+ |. |. :| | | |.| |.| |. | | |: |:| |:| | +-- --+ +-+ +-+ +-+ | +-+ +-- +-+ | | """ # intialize three empty lines rows = [, , ] # split pigpen representation of each letter into three separate lines and # add append those with an additional space between the pigpen letters for letter in text: for index, row in enumerate(pigpenletter(letter).split(\n)): rows[index] += row + # compose rows and remove final space 16 return \n.join(row[:-1] for row in rows) if __name__ == __main__: import doctest doctest.testmod()
46900f5b8a8e12f7f5eea9ed98300e93bf6f5252
akankshaagrawal26/SeleniumBasics
/basics/scrolling.py
924
3.5
4
from selenium import webdriver import time class Scrolling: def scroll(self): base_url = "https://learn.letskodeit.com/p/practice" driver = webdriver.Firefox() driver.implicitly_wait(10) driver.maximize_window() driver.get(base_url) driver.execute_script("window.scrollBy(0,2000);") #scroll down time.sleep(3) driver.execute_script("window.scrollBy(0,-2000);") time.sleep(3) el = driver.find_element_by_id("mousehover") driver.execute_script("arguments[0].scrollIntoView(true);", el) time.sleep(3) driver.execute_script("window.scrollBy(0,-150);") driver.execute_script("window.scrollBy(0,-2000);") loc = el.location_once_scrolled_into_view time.sleep(3) driver.execute_script("window.scrollBy(0,-150);") print(driver.get_window_size()) obj = Scrolling() obj.scroll()
7a4f71c0bb76abd198a4a073326287252eea7e4c
Fabricio1984/Blue_Python_VS_CODE
/Aula06_Funcao/aula6ex003.py
527
4.125
4
# 3. Faça um programa com uma função chamada somaImposto. # A função possui dois parâmetros formais: taxaImposto, # que é a quantia de imposto sobre vendas expressa em porcentagem e custo, # que é o custo de um item antes do imposto. A função “altera” o valor de custo para incluir o imposto sobre vendas. def somaImposto(txImposto,custo): return txImposto/100*custo + custo tx = int(input('Informe a tx de imposto: ')) custo = int(input('Informe o custo do produto: ')) print(somaImposto(tx,custo))
2304f4a19b8129b244673fb73f29a10726329a8d
dominikpogodzinski/hangman_game_object
/hangman_object/hangman_text_game.py
1,287
3.78125
4
from chances_error import ChancesError from hangman import Hangman class HangmanGame: def __init__(self): self.hangman = Hangman() print(self.hangman.get_title()) def play(self): while True: print(f'You have: {self.hangman.get_chances()} chances') print(self.hangman.get_word_for_search()) letter = input('Give me some letter: ') if self.hangman.is_it_word_to_find(letter): self.win() break try: self.hangman.guess_letter(letter) except ChancesError: self.loose() break if self.hangman.are_all_letters_found(): self.win() break def loose(self): print('\nLoooser!!!!!') self.print_word_to_find() def win(self): print('\nCongratulations!!!') self.print_word_to_find() def print_word_to_find(self): print(f'Search word is: {self.hangman.get_word_to_find()}') def main(): while True: game = HangmanGame() game.play() if input('Do you play one moore time? [t/n]: ') == 'n': print('Thanks for playing') break if __name__ == '__main__': main()
f0ae9415939bbc80e9f0b41525d0962876dd7af8
npwardberkeley/Radix-Converter
/converter.py
1,767
3.59375
4
import math def bin_to_dec(binary): binary = binary[2:] result = 0 for i in range(len(binary)): result += 2 ** (len(binary) - i - 1) * int(binary[i]) return str(result) def dec_to_bin(decimal): result = "" power = int(math.log2(float(decimal))) decimal = int(decimal) while power >= 0: if 2 ** power <= decimal: decimal -= 2 ** power result += "1" else: result += "0" power -= 1 return "0b" + result hex_to_bin_map = {"0": "0000", "1": "0001", "2": "0010", "3": "0011", "4": "0100", "5": "0101", "6": "0110", "7": "0111", "8": "1000", "9": "1001", "a": "1010", "b": "1011", "c": "1100", "d": "1101", "e": "1110", "f": "1111"} bin_to_hex_map = {hex_to_bin_map[x]: x for x in hex_to_bin_map.keys()} def hex_to_bin(hexadecimal): hexadecimal = hexadecimal[2:] result = "" for digit in hexadecimal: result += hex_to_bin_map[digit] return "0b" + result def bin_to_hex(binary): binary = binary[2:] binary = "0" * (-len(binary) % 4) + binary result = "" for i in range(0, len(binary), 4): result += bin_to_hex_map[binary[i:i+4]] return "0x" + result def hex_to_dec(hexadecimal): return bin_to_dec(hex_to_bin(hexadecimal)) def dec_to_hex(decimal): return bin_to_hex(dec_to_bin(decimal)) while True: to_convert = str.lower(input("")) if len(to_convert) > 2 and to_convert[:2] == "0b": print(bin_to_hex(to_convert)) print(bin_to_dec(to_convert)) elif len(to_convert) > 2 and to_convert[:2] == "0x": print(hex_to_bin(to_convert)) print(hex_to_dec(to_convert)) else: print(dec_to_bin(to_convert)) print(dec_to_hex(to_convert)) print("")
3f33347032dc4cc3e5d9a4c1154ee9862fa201a0
Juanllamazares/informatica-uam
/CUARTO/FAA/PRACTICAS/P2/Clasificador.py
10,262
3.859375
4
# -*- coding: utf-8 -*- # Practica realizada por Tomas Higuera Viso y Alejandro Naranjo Jimenez from abc import ABCMeta,abstractmethod import numpy as np import collections import math import numpy as np from sklearn.preprocessing import normalize from scipy.spatial import distance from random import uniform class Clasificador: # Clase abstracta __metaclass__ = ABCMeta # Metodos abstractos que se implementan en casa clasificador concreto @abstractmethod # TODO: esta funcion debe ser implementada en cada clasificador concreto # datosTrain: matriz numpy con los datos de entrenamiento # atributosDiscretos: array bool con la indicatriz de los atributos nominales # diccionario: array de diccionarios de la estructura Datos utilizados para la codificacion de variables discretas def entrenamiento(self,datosTrain,atributosDiscretos,diccionario): pass @abstractmethod # TODO: esta funcion debe ser implementada en cada clasificador concreto # devuelve un numpy array con las predicciones def clasifica(self,datosTest,atributosDiscretos,diccionario): pass # Obtiene el numero de aciertos y errores para calcular la tasa de fallo # TODO: implementar def error(self,datos,pred): # Aqui se compara la prediccion (pred) con las clases reales y se calcula el error nac = len(pred) numerr = 0 #En caso de ser igual se suma uno for i in range(nac): if pred[i] != datos[i,-1]: numerr += 1 porcen = float(numerr)/float(nac) return porcen # Realiza una clasificacion utilizando una estrategia de particionado determinada # TODO: implementar esta funcion def validacion(self,particionado,dataset,clasificador,seed=None): # Creamos las particiones siguiendo la estrategia llamando a particionado.creaParticiones # - Para validacion cruzada: en el bucle hasta nv entrenamos el clasificador con la particion de train i # y obtenemos el error en la particion de test i # - Para validacion simple (hold-out): entrenamos el clasificador con la particion de train # y obtenemos el error en la particion test. Otra opción es repetir la validación simple un número especificado de veces, obteniendo en cada una un error. Finalmente se calcularía la media. errlist = [] particionado.creaParticiones(dataset, seed) for particion in particionado.particiones: train = dataset.extraeDatos(particion.indicesTrain) test = dataset.extraeDatos(particion.indicesTest) clasificador.entrenamiento(train, dataset.nominalAtributos,dataset.diccionarios) pred= clasificador.clasifica(test, dataset.nominalAtributos,dataset.diccionarios) errlist.append(clasificador.error(test,pred)) return errlist ############################################################################## class ClasificadorNaiveBayes(Clasificador): def __init__(self, doLaplace=False): self.doLaplace = doLaplace self.trainTable = [] self.prioriTable = {} def entrenamiento(self,datostrain,atributosDiscretos,diccionario): #Conseguimos los diccionorarios tam = len(diccionario) #Conseguimos el ultimo atribito que será la clase clase = len(diccionario[-1]) #Num de filas nfilas = datostrain.shape[0] #Comprobamos que el numero de filas es mayor que cero if nfilas<=0: raise ValueError('Error. El numero de filas no puede ser cero.') #Miramos todas las claves de la clase, comprobamnos el valor k-esimo de la clave y se calculan los priori(contando repeticiones y dividiendo entre las filas) for key in diccionario[-1].keys(): clave=diccionario[-1][key] self.prioriTable[key]=((datostrain[:,-1] == clave).sum())/nfilas #Miramos si es continio o nominal for i in range(tam-1): if atributosDiscretos[i]: numValAt = len(diccionario[i]) tabla = np.zeros((numValAt, clase)) #el atributo es el indice i,el valor de la clase es la columna for fila in datostrain: fil=int(fila[i]) col=int(fila[-1]) #num veces que se repite el valor del atributo con esa clase tabla[fil, col] +=1 #Si se activa el flag laplace se suma 1 a las celdas if self.doLaplace and np.any(tabla==0): tabla+=1 #Calculamos las probabilidades cont=tabla.sum(axis=0) for i in range(tabla.shape[0]): for j in range(tabla.shape[1]): tabla[i][j]/=cont[j] #Si son continuos cogemos todas las clave y hacemos la media y la desiviacion tipica else: tabla = np.zeros((2, clase)) for key in diccionario[-1].keys(): val=int(diccionario[-1][key]) #Media tabla[0, val] = np.mean(datostrain[:,i]) #Desviación típica tabla[1, val] = np.std(datostrain[:,i]) self.trainTable.append(tabla) def clasifica(self,datostest,atributosDiscretos,diccionario): listpredic = [] #Recorremos todos los datos for test in datostest: posteriori={} #Recorremos todas las clases para calcular la probabilidad MV for key in diccionario[-1].keys(): prob=1 val=diccionario[-1][key] for i in range(len(test)-1): #Conseguimos el valor del atributo y la clase y lo dividimos por el sumatorio de la columna if atributosDiscretos[i]: verosimilitud=self.trainTable[i][int(test[i]), val] evidencia=sum(self.trainTable[i][:,val]) prob*=(verosimilitud/evidencia) # en atributos continuos aplicamos la formula (1/((2*pi*desviacion)^1/2))*e{(-(valor-media)^2)/2*desviacion) else: sqrt=math.sqrt(2*math.pi*self.trainTable[i][1,val]) exp=math.exp(-(pow((test[i]-self.trainTable[i][0,val]),2))/(2*self.trainTable[i][1,val])) prob*=(exp/sqrt) #Multiplicamos por la prob a priori prob*=self.prioriTable[key] # guardamos para poder comparar con el resto posteriori[key]=prob #Guardamos el valor de la clase con mayor probabilidad mayorprob=max(posteriori, key=posteriori.get) listpredic.append(diccionario[-1][mayorprob]) return np.array(listpredic) #Funcion que normaliza los datos def normalizarDatos(clasificador,datos): # Guardamos el tamanio de nuestra matriz de datos tamanio = datos.shape[1] - 1 matriz_normalizada = datos for i in range(tamanio): # Si el atributo no es un diccionario vacio significara que estamos ante # un atributo continuo if clasificador.desvMedList[i]: # Guardamos los valores e la desviacion y la media mean = clasificador.desvMedList[i]['mean'] std = clasificador.desvMedList[i]['std'] matriz_normalizada[ : , i] = (datos[ : , i] - float(mean)) / float(std) # Si el diccionario esta vacio se tratara de un atrbuto discreto por lo que # no tiene sentido normalizar else: # Imprimimos mensaje de error print("Estas intentando normalizar con atributos discretos.") # Si es un atributo discreto matriz_normalizada[ : , i] = datos[ : , i] #Si es discreto no tiene sentido normalizar return matriz_normalizada # Esta funcion calculara las medias y desviaciones tipicas # de cada atributo continuo def calcularMediasDesv(clasificador, datostrain): # Creamos un diccionario vacio que contendra la media y la desviacion tipica media_desviacion = {} # Calculamos la media utilizando las funciones de numpy media_desviacion["mean"] = np.mean(datostrain) # Calculamos la desviacion tipica utilizando las funciones de numpy media_desviacion["std"] = np.std(datostrain) # Guardamos la desviacion tipica y la media en el clasificador clasificador.desvMedList.append(media_desviacion) # Algoritmo vecinos proximos class ClasificadorVecinosProximos(Clasificador): def __init__(self, k=2, Normal=False): self.k = k self.Normal = Normal self.trainTable = None self.desvMedList = [] def entrenamiento(self,datostrain,atributosDiscretos,diccionario): del self.desvMedList[:] del self.trainTable if self.Normal: size=len(diccionario) - 1 for i in range(size): if atributosDiscretos[i]: self.desvMedList.append({}) else: calcularMediasDesv(self,datostrain[:,i]) self.trainTable = normalizarDatos(self,datostrain) else: self.trainTable = datostrain def clasifica(self,datostest,atributosDiscretos,diccionario): if self.Normal: testList = normalizarDatos(self,datostest) else: testList = datostest clasesList = [] for fil in testList: ListDistances = [] for i in range(self.trainTable.shape[0]): ListDistances.append(distance.euclidean(self.trainTable[i,:-1], [fil[:-1]])) sortedDistancesIndex = np.argsort(ListDistances) nearClass = self.trainTable[sortedDistancesIndex[0:self.k], -1] clasesWithCount = np.bincount(nearClass.astype(int)) clasesList.append(int(clasesWithCount.argmax())) total = np.array(clasesList) return total # Algoritmo regresion logistica class ClasificadorRegresionLogistica(Clasificador): def __init__(self, Normal = False, epoch=4, num_apren = 1): self.wfin = np.array(()) self.num_apren = num_apren self.epoch = epoch self.Normal = Normal self.desvMedList = [] self.trainTable = None def reg_log(self, datos, w, i): x = np.array(()) x = np.append(x ,np.append(1, datos[i][:-1])) wx = np.dot(np.transpose(w), x) nxt = 1/(1 + np.exp(-wx)) return x,nxt def entrenamiento(self,datostrain,atributosDiscretos,diccionario): del self.desvMedList[:] del self.trainTable ejem, col = datostrain.shape w = np.array(()) if self.Normal: size=len(diccionario) - 1 for i in range(size): if atributosDiscretos[i]: self.desvMedList.append({}) else: calcularMediasDesv(self,datostrain[:,i]) self.trainTable = normalizarDatos(self,datostrain) else: self.trainTable = datostrain for i in range(col): w = np.append(w, uniform(-0.5,0.5)) for ie in range(self.epoch): for i in range(ejem): x,nxt = self.reg_log(datostrain, w, i) for d in range(col): w[d] = w[d] - self.num_apren*(nxt - datostrain[i, -1])* x[d] self.wfin = w def clasifica(self,datostest,atributosDiscretos,diccionario): ejem, col = datostest.shape predict = [] C1 = 1 C2 = 0 if self.Normal: auxtest = normalizarDatos(self,datostest) else: auxtest = datostest for i in range(ejem): x,nxt = self.reg_log(auxtest, self.wfin, i) if nxt <= 0.5: predict.append(C2) elif nxt > 0.5: predict.append(C1) return np.array(predict)
83ae22e0f17d004186ba3d0f7492c7398a34f4e6
aerosat99/JumpToPython-Ex
/연습 04-1.py
1,224
3.84375
4
# 구구단 for i in range(2,10) : # 2~9단 for j in range(1,10) : # 각 단마다 1~9까지 곱한다 print(i * j, end = ' ') # 각 단은 옆으로 보여주고 print(' ') # 단끼리는 줄 바꾼다 #4-1-1 def is_odd(a) : if a % 2 == 0 : return 'Even' else : return 'Odd' print(is_odd(7)) # 함수 안에 print 없으면 함수 사용할때 print 추가 해야 하고 #4-1-2 def avg(*args) : sum = 0 for i in args : sum += i print(sum/len(args)) avg(17,18,19,20,23) # 함수 안에 print 넣으면 함수 사용할때 print 필요 없다 #4-1-3 def mul(a) : for i in range(1,10) : print(a * i, end = ' ') a = int(input('입력 = ')) mul(a) #4-1-4 def fib(a) : if a == 0 : return 0 elif a == 1 : return 1 else : return fib(a-2) + fib(a-1) for a in range(0, 10) : print(fib(a)) #4-1-5 def myfunc(numbers): result = [] for number in numbers: if number > 5: result.append(number) return result p = myfunc([1,3,5,7,8,10]) print(p) myfunc = lambda numbers : [number for number in numbers if number > 5] p = myfunc([1,3,5,7,8,10]) print(p)
80dd6c1bb1781347e2d7a6ae8dfac06e947e182f
loc-trinh/Graphics
/Fractals/Koch.py
2,519
3.5
4
import Tkinter as tk import tkMessageBox from math import cos, sin, pi class Point(): def __init__(self, x, y): self.x = x self.y = y def __sub__(self, other): return Point(self.x-other.x, self.y-other.y) def __add__(self, other): return Point(self.x+other.x, self.y+other.y) def __rmul__(self, n): return Point(n*self.x, n*self.y) def __div__(self, n): if n == 0: raise ValueError else: return Point(self.x/n, self.y/n) def draw(start, end, iteration, n): if iteration < 1: return firstThird = start + (end-start)/3 secondThird = start + (2*(end-start))/3 angle = (cos(-pi/3), sin(-pi/3)) vector = secondThird - firstThird rotated = Point(vector.x*angle[0] - vector.y*angle[1], vector.x*angle[1]+vector.y*angle[0]) final = firstThird + rotated if n is not None: canvas.delete(n) a = canvas.create_line(firstThird.x, firstThird.y, final.x, final.y, width=2) b = canvas.create_line(final.x, final.y, secondThird.x, secondThird.y, width=2) c = canvas.create_line(start.x, start.y, firstThird.x, firstThird.y, width=2) d = canvas.create_line(secondThird.x, secondThird.y, end.x, end.y, width=2) window.update() draw(firstThird, final, iteration-1, a) draw(final, secondThird, iteration-1, b) draw(start, firstThird, iteration-1, c) draw(secondThird, end, iteration-1, d) def drawCurve(): canvas.delete("all") iteration = iterate.get() if iteration.isdigit(): curve.config(state=tk.DISABLED) snowflake.config(state=tk.DISABLED) draw(Point(0, 300), Point(700, 300), int(iteration), None) curve.config(state=tk.NORMAL) snowflake.config(state=tk.NORMAL) def drawSnowflake(): canvas.delete("all") iteration = iterate.get() if iteration.isdigit(): curve.config(state=tk.DISABLED) snowflake.config(state=tk.DISABLED) draw(Point(180, 100), Point(520, 100), int(iteration), None) draw(Point(350, 100+340*sin(pi/3)), Point(180, 100), int(iteration), None) draw(Point(520, 100), Point(350, 100+340*sin(pi/3)), int(iteration), None) curve.config(state=tk.NORMAL) snowflake.config(state=tk.NORMAL) window = tk.Tk() window.title("Koch") canvas = tk.Canvas(window, width = 700, height = 400) canvas.grid(row=1, columnspan=3) curve = tk.Button(window, text="Koch curve", command=drawCurve) curve.grid(row=0, column=0) snowflake = tk.Button(window, text="Koch snowflake", command=drawSnowflake) snowflake.grid(row=0, column=2) iterate = tk.Entry(window) iterate.insert(0, "Enter the iteration") iterate.grid(row=0, column=1) window.mainloop()
690cccf7a7c31db574551dc39f05c51bd0428bc7
CodeHemP/CAREER-TRACK-Data-Scientist-with-Python
/15_Intermediate Importing Data in Python-(part-2)/1-importing-data-from-the-internet/03_importing-non-flat-files-from-web.py
1,695
4.0625
4
''' 03 - Importing non-flat files from the web Congrats! You've just loaded a flat file from the web into a DataFrame without first saving it locally using the pandas function pd.read_csv(). This function is super cool because it has close relatives that allow you to load all types of files, not only flat ones. In this interactive exercise, you'll use pd.read_excel() to import an Excel spreadsheet. The URL of the spreadsheet is 'http://s3.amazonaws.com/assets.datacamp.com/course/importing_data_into_r/latitude.xls' Your job is to use pd.read_excel() to read in all of its sheets, print the sheet names and then print the head of the first sheet using its name, not its index. Note that the output of pd.read_excel() is a Python dictionary with sheet names as keys and corresponding DataFrames as corresponding values. Instructions: - Assign the URL of the file to the variable url. - Read the file in url into a dictionary xls using pd.read_excel() recalling that, in order to import all sheets you need to pass None to the argument sheet_name. - Print the names of the sheets in the Excel spreadsheet; these will be the keys of the dictionary xls. - Print the head of the first sheet using the sheet name, not the index of the sheet! The sheet name is '1700' ''' # Import package import pandas as pd # Assign url of file: url url = 'http://s3.amazonaws.com/assets.datacamp.com/course/importing_data_into_r/latitude.xls' # Read in all sheets of Excel file: xl df_xls = pd.read_excel(url, sheetname=None) # Print the sheetnames to the shell print(df_xls.keys()) # Print the head of the first sheet (using its name, NOT its index) print(df_xls['1700'].head())
aa90bfa4d6c026bc4d282cbb777731b7e41910e8
srivalli-project/BI_Team_Status
/Santhoshi/Python_hackerrank/find-a-string-code-11.py
862
3.671875
4
def count_substring(string, sub_string): cnt=0 ostring = list(string) osub_string=list(sub_string) string2 = [] #print(ostring,osub_string) for i in range((len(ostring)-len(osub_string))+1): j=i string2 = [] #print(j) k=0 while k < len(osub_string):#for j in range(i,len(ostring)): #j=i #print(ostring[0]) string2.append(ostring[j]) j=j+1 k=k+1 #print(string2) if string2 == osub_string: cnt = cnt+1 return cnt if __name__ == '__main__': string = raw_input().strip() sub_string = raw_input().strip() count = count_substring(string, sub_string) print count ''' #output Compiler Message Success Input (stdin) Download ABCDCDC CDC Expected Output Download 2 '''
2e9afb0bb3adcec8559e32c75180cfbd375f67ee
PacktPublishing/Modular-Programming-with-Python
/chapter-2/inventoryControl/userinterface.py
3,421
3.6875
4
# userinterface.py # # This module implements the user interface for the InventoryControl system. import datastorage ############################################################################# def prompt_for_action(): """ Prompt the user to choose an action to perform. We return one of the following action codes: "QUIT" "ADD" "REMOVE" "INVENTORY_REPORT" "REORDER_REPORT" """ while True: print() print("What would you like to do?") print() print(" A = add an item to the inventory.") print(" R = remove an item from the inventory.") print(" C = generate a report of the current inventory levels.") print(" O = generate a report of the inventory items to re-order.") print(" Q = quit.") print() action = input("> ").strip().upper() if action == "A": return "ADD" elif action == "R": return "REMOVE" elif action == "C": return "INVENTORY_REPORT" elif action == "O": return "REORDER_REPORT" elif action == "Q": return "QUIT" else: print("Unknown action!") ############################################################################# def prompt_for_product(): """ Prompt the user to select a product. We return the code for the selected product, or None if the user cancelled. """ while True: print() print("Select a product:") print() n = 1 for code,description,desired_number in datastorage.products(): print(" {}. {} - {}".format(n, code, description)) n = n + 1 s = input("> ").strip() if s == "": return None try: n = int(s) except ValueError: n = -1 if n < 1 or n > len(datastorage.products()): print("Invalid option: {}".format(s)) continue product_code = datastorage.products()[n-1][0] return product_code ############################################################################# def prompt_for_location(): """ Prompt the user to select a location. We return the code for the selected location, or None if the user cancelled. """ while True: print() print("Select a location:") print() n = 1 for code,description in datastorage.locations(): print(" {}. {} - {}".format(n, code, description)) n = n + 1 s = input("> ").strip() if s == "": return None try: n = int(s) except ValueError: n = -1 if n < 1 or n > len(datastorage.locations()): print("Invalid option: {}".format(s)) continue location_code = datastorage.locations()[n-1][0] return location_code ############################################################################# def show_error(err_msg): """ Display the given error message to the user. """ print() print(err_msg) print() ############################################################################# def show_report(report): """ Display the given report to the user. 'report' is a list of strings containing the contents of the report. """ print() for line in report: print(line) print()
d56e58c7357859197b845ef42fb53c7f6df18a77
Plain-ST/python_practice_55knock
/09.py
224
3.734375
4
""" 9. 文字列(結合) 'py'と'thon'という2つの文字列をそれぞれ変数に代入し,結合したものを出力してください. 期待する出力:python """ str1,str2='py','thon' print(str1+str2)
afb760ea31783e439c29708c09af736f4143fb0a
georgiosdoumas/BeginningPython3_2017editionApress
/chap10/page221personsDB.py
3,543
4
4
#!/usr/local/bin/python3 # page 221 My implementation of database.py with enhancements for handling some exceptions import sys, shelve, os db_store_file = '/home/yourusrename/Documents/PYTHONbooks/Beginning.Python.3rdEd.2017/ch10/persons.dat' def IDexists(pid, pdb): try: info = pdb[pid] return True except KeyError: return False def delete_person(db): pid = input('Enter unique ID number of person to remove: ') if IDexists(pid, db): del db[pid] else: print("This ID does not exist. Nothing to remove!") def store_person(db): """ Query user for data and store it in the shelf object """ pid = input('Enter unique ID number: ') if IDexists(pid, db): print("The ID you gave already exists:", pid) print(db[pid]) answer = input("Do you want to overwrite it? (N/y)") if answer.strip().lower() == 'n': print(" Not altering existing record") return # do nothing more and exit function store_person(), else for 'y' continue with next lines person = {} # initially empty dictionary, to be populated by users entered values person['name'] = input('Enter name: ') person['age'] = input('Enter age: ') person['phone'] = input('Enter phone number: ') db[pid] = person # adding this small person dictionary to the others, exisitng in database def lookup_person(db): """ Query user for ID and desired field, and fetch the corresponding data from the shelf object """ pid = input('Enter ID number: ') try: info = db[pid] field = input('What would you like to know? (name, age, phone, all) ') field = field.strip().lower() try: info = db[pid][field] print(field.capitalize() + ':', db[pid][field]) except KeyError: if field != 'all': # user typed something strange, give him a message about it, and the whole info print(field, " is not a recognized field of information. Printing all fields of ",pid, ":") print(info) # if user typed 'all', of course we again print the whole info except KeyError: print("The ID you gave ", pid, " does not exists in the database of persons!") def enter_command(): cmd = input('Enter command (? for help): ') cmd = cmd.strip().lower() return cmd def print_help(): print('The available commands are:') print('store : Stores information about a person') print('lookup : Looks up a person from ID number') print('quit : Save changes and exit') print("delete : removes a person's record") print('? : Prints this message') def main(): database = shelve.open(db_store_file) print("The database is opened, placed in RAM, and it has an object-type of :", type(database)) try: while True: cmd = enter_command() if cmd == 'store': store_person(database) elif cmd == 'lookup': lookup_person(database) elif cmd == 'delete': delete_person(database) elif cmd == '?': print_help() elif cmd == 'quit': return else: print("Not recognized input") print_help() finally: print("Even if something bad happened, do not worry! I am closing the databese now!") database.close() if __name__ == '__main__': main()
5c82c2cd878d84d8b685e60a97a8bda2534f73c6
Ator97/TkinterExamples
/seir.py
426
3.796875
4
from tkinter import * root = Tk() def leftClick(event): print("Left") def rightClick(event): print("Right") def middleClick(event): print("Middle") frame = Frame(root, width=300 ,height=400) frame.bind("<Button-1>", leftClick) #Boton izquierdo del mouse frame.bind("<Button-2>", middleClick) #Boton central del mouse frame.bind("<Button-3>", rightClick) #Boton derecho del mouse frame.pack() root.mainloop()
a69bad6b7a5c6117f5a52324bf92459c2ceea4a2
gseverina/curso-python
/Persona.py
329
3.8125
4
class Persona: def __init__(self,nombre): self.nombre = nombre def __repr__(self): return str(self.nombre) def upper_name(self): return (self.nombre).upper() if __name__ == "__main__": p = Persona("Pepo") c = Persona("Coti") print p print c p.upper_name = upper_name print p.upper_name(p) #print c.upper_name(c)
f99c497929c1d9d587ed9655161973440f6a2720
sungguenja/studying
/sort/쉘정렬.py
338
3.5625
4
def shell_sort(a): h = 4 while h >= 1: for i in range(h,len(a)): j = i while j >= h and a[j] < a[j-h]: a[j],a[j-h] = a[j-h],a[j] j -= h h //= 3 print(a) return a a = [54,88,77,26,93,17,49,10,17,77,11,31,22,44,17,20] print(a) print(shell_sort(a))
b86b4086dae4bc2d4422dc7691eb90f3e6be712c
jimmy623/LeetCode
/Solutions/ZigZag Conversion.py
873
3.53125
4
class Solution: # @return a string def convert(self, s, nRows): grid = ["" for i in range(nRows)] i = 0 zigzag = False zigStart = max(nRows-2,0) for c in s: if zigzag: grid[i]+=c i -= 1 if i <= 0: zigzag = False i = 0 else: grid[i] += c i += 1 if i == nRows: i = zigStart if i != 0: zigzag = True result = "" for r in grid: result += r return result s = Solution() #print s.convert("PAYPALISHIRING",3) #print s.convert("ABC",2) print s.convert("ABCD",2) #ZigZag Conversion #https://oj.leetcode.com/problems/zigzag-conversion/
f0825eded9c1fc91a0e6925d01fea8a81ea0ef6f
robertopc/hackerrank
/python3/introduction/print.py
196
3.6875
4
# Print Function # https://www.hackerrank.com/challenges/python-print/problem if __name__ == '__main__': n = int(input()) o = '' for i in range(n): o += str(i+1) print(o)
977bcb84162c1f0a654e57921cafafa06809022d
stefelmanns/Data_Processing
/Homework/Week_6/convertCSV2JSON.py
1,463
3.828125
4
# # convertCSV2JSON.py # # Author: L.K. Stefelmanns # Course: Data processing # Study: Minor Programming, University of Amsterdam # ''' Function that takes CSV data (saved in a txt file) and converts it into JSON data. ''' import csv import json # opens the 4 datasets used csv_input = open('C:/Users/lucst/Desktop/Minor programmeren/GitHub/Data_Processing/Homework/Datasets/GDP_growth.csv', 'r') def convert_CSV_to_JSON(csv_input): tmp_lists = [] del_list = [] JSON_list = [] for line in csv_input: tmp_lists.append(line.split(',')) for i in range(len(tmp_lists) - 1): if len(tmp_lists[i]) < 4: del_list.append(i) for i in range(len(del_list)): del tmp_lists[del_list[i] - i] for i in range(1, len(tmp_lists) - 1): for j in range(5, len(tmp_lists[i]) - 1): GDP_growth = {} GDP_growth[tmp_lists[0][0].strip('\"').strip('\n')] = tmp_lists[i][0].strip('\"').strip('\n') GDP_growth['year'] = tmp_lists[0][j].strip('\"').strip('\n') GDP_growth['GDP_growth'] = tmp_lists[i][j].strip('\"').strip('\n') JSON_list.append(GDP_growth) # dumps and loads to create JSOn file JSON_data = json.loads(json.dumps(JSON_list)) return JSON_data output_JSON = convert_CSV_to_JSON(csv_input) # source: https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file with open('C:/Users/lucst/Desktop/Minor programmeren/GitHub/Data_Processing/Homework/Week_6/GDP_growth.json', 'w') as outfile: json.dump(output_JSON, outfile)
57b366f1d8e6b333316b4b754658422cc809a385
jnxyp/ICS3U-II
/homeworks/problem_s6/q2.py
451
4.03125
4
# coding=utf-8 # Course Code: ICS3U # Author: jn_xyp # Version: 2017-11-14 # Problem Set 6 - Question 2 import random def pick(): return random.choice( ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']) + ' of ' + random.choice( ['Hearts', 'Diamonds', 'Clubs', 'Spades']) print(pick()) print(pick()) print(pick()) print(pick()) print(pick()) print(pick()) print(pick()) print(pick()) print(pick())
c839582d46243eb6776688d453e556a6e582a8cb
JLowe-N/Algorithms
/AlgoExpert/minnumofcoinsforchange.py
905
3.9375
4
# Given a target amount, n, and different denominations of coins available, # find the minimum number of coins (of types in any amount defined in denom array) # to get target amount of money # Complexity Time O(d * n) | Space O(n) # where d is # of denominations, and n is target amount def minNumberOfCoinsForChange(n, denoms): # iterate through the array of denominations, finding the minimum number of coins # for coins up to that point in the array, to make each amount between 0 and # n. Dynamically solve for minimum number of coins at each position numOfCoins = [float("inf") for amount in range(n + 1)] numOfCoins[0] = 0 for denom in denoms: for amount in range(n + 1): if denom <= amount: numOfCoins[amount] = min(numOfCoins[amount], 1 + numOfCoins[amount - denom]) return numOfCoins[-1] if numOfCoins[-1] != float("inf") else -1
c091cda930a318acdb326cf014ee2f658b68ffa6
mxmaria/coursera_python_course
/week1/Стоимость покупки.py
331
4
4
# Пирожок в столовой стоит A рублей и B копеек. # Определите, сколько рублей и копеек нужно заплатить за N пирожков. a = int(input()) b = int(input()) quant = int(input()) cost = ((a * 100 + b) * quant) print(cost // 100, cost % 100)
65f7421c01fc8447186044b7650f5792b1eff5a7
AlexxanderShnaider/AcademyPythonLabs
/5.3.nested_loops.py
240
3.671875
4
n = int(input("Введіть число: ")) if (n > 0) and (n <= 9): for i in range(1, n + 1): for j in range(1, i + 1): print(i, end='') print() else: print("Неправильне значення!")
6774a16462aeed440b97c7d785d671f1016f48ae
polusaleksandra/python-hard-way
/ex4.py
1,706
4.25
4
# Assignment the numbers of cars to a variable 'cars'. cars = 100 # Assignment the numbers of free places in car to a variable 'space_in_a_car'. space_in_a_car = 4.0 # Assignment the numbers of drivers to a variable 'drivers'. drivers = 30 # Assignment the number of passangers to a variable 'passangers'. passangers = 90 # Counting the number of cars which are not in use and assignment it # in a variable 'cars_not_driven' by substraction of number of cars and drivers. cars_not_driven = cars - drivers # Assignment the number of cars which are in use in a variable 'cars_driven' # base on the numbers of drivers. cars_driven = drivers # Counting the carpool capacity and assignment it in a variable # 'carpool_capacity' by multiplication of cars in use and free space in each car. carpool_capacity = cars_driven * space_in_a_car # Counting the avarage number of passangers in each car and assignment it in a # variable 'avarage_passangers_per_car' by division of passangers and cars in use. avarage_passangers_per_car = passangers / cars_driven # Printing the sentence with cars variable. print "There are", cars, "cars avaliable." # Printing the sentence with drivers variable. print "There are only", drivers, "drivers avaliable." # Printing the sentence with cars_not_driven variable. print "There will be", cars_not_driven, "empty cars today." # Printing the sentence with carpool_capacity variable. print "We can transport", carpool_capacity, "people today." # Printing the sentence with passangers variable. print "We have", passangers, "to carpool today." # Printing the sentence with avarage_passangers_per_car variable. print "We need to put about", avarage_passangers_per_car, "in each car."
c80b388ecf0f2d063d0eb11ae4807e0b2b4c4966
hejazizo/finTranslateBot
/translation.py
1,312
3.609375
4
#- * -coding: utf - 8 - * - import emoji from finglish import f2p ## Function to detect non english characters def isEnglish(s): try: s.encode(encoding = 'utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True ## Main translation function def translate(message): """ Function to translate finglish to persian. NOTE: #1 These messages are not processed by BOT: 1. Messages that are not english characters. 2. Messages that start with emojies. TODO: remove emojis from the beginning of a message and then process the rest of it. Args: message object Returns: translated message (str) ------------------------------ name (@username): <translated_message> ------------------------------ NOTE: - name is formatted BOLD - if user has no username, output will only include name and <translated message> """ # removing emojies msg_text = message.text raw_text = emoji.demojize(msg_text) output_message = None # 1 if isEnglish(raw_text) and not emoji.demojize(raw_text).startswith(':'): # Result # processing multiple line message translated_msg = [] splitted_msg = msg_text.split('\n') for msg in splitted_msg: translated_msg.append(f2p(msg)) output_message = '\n'.join(translated_msg) return output_message
6c022ee95a06dbdb88638430d5dcfb175613c7c3
Saranyaram4291/Python
/Activity_4.py
1,165
4.15625
4
user1=input("Enter the player 1 name ") user2=input("Enter the player 2 name ") while True: user1Option=input(user1+" Select either rock or paper or scissors ").lower() user2Option=input(user2+" Select either rock or paper or scissors ").lower() if(user1Option==user2Option): print("Its a tie") elif(user1Option=='rock'): if(user2Option=='scissors'): print(user1+" Rock wins") elif(user2Option=='paper'): print(user2+" paper wins") elif(user1Option=='scissors'): if(user2Option=='paper'): print(user2+" paper wins") elif(user2Option=='rock'): print(user1+" scissors wins") elif(user1Option=='paper'): if(user2Option=='scissors'): print(user1+" paper wins") elif(user2Option=='rock'): print(user2+" rock wins") else: print("Any one of the user entered invalid value") checkConinueOption=input("Do u want to contimue the game(yes/no) ").lower() if(checkConinueOption=='yes'): print("You will continue the game") else: raise SystemExit
a2fe091e6c95b80438f0b9e94f23091a602c9b87
inlee12/Python
/factorial.py
420
4.125
4
#edit test def factorial_for(number): result=1 for k in range(number,1,-1): result = result * k return result def factorial_recursive(number): if number < 1: return 1 else: return number * factorial_recursive(number-1) i= input("Enter number:") i= int(i) y= factorial_for(i) print("by for ",i,"! = ", y) y= factorial_recursive(i) print("by recursive ",i,"! = ", y)
3eb7615eb5068a6cfe282a087e3902a469b7c148
megthehoffman/hackbright-coding-challenges
/easier/pangram/pangram.py
922
4.34375
4
"""Given a string, return True if it is a pangram, False otherwise. For example:: >>> is_pangram("The quick brown fox jumps over the lazy dog!") True >>> is_pangram("I love cats, but not mice") False NOTES: letters can appear mroe than once, but every letter from the alphabet must be included keep a list of all letters seen, turn into set (for uniqueness), then if at the end of the string the length of the set is == 26, return True """ def is_pangram(sentence): """Given a string, return True if it is a pangram, False otherwise.""" letters_seen = set() for char in sentence.lower(): if char.isalpha(): letters_seen.add(char) if len(letters_seen) == 26: return True return False if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. YAY!\n")
ae0557f782b9cb51dc6f34a605a3f2e545ff0e37
demandingfawn/Lecture-Listener
/ll_keyword.py
20,988
3.890625
4
import operator import wikipediaapi #befoer using it, download wikipedia api using "pip install wikipedia-api" in your terminal #here is also the link to the api instruction page: "https://pypi.org/project/Wikipedia-API/" #you also need to check location and name of the transcript file before using it. (for this code, it's using "sampleText.txt") #the method of accessing the transcript might be changed when we work on the storing system in the database. #when you use this code, you only need to use "getTopKeywords()" to get a list of keywords, # and searchWiki(word) for getting a definition of a word from Wikipedia. #if you want to check if it works: # place sampleText.txt into the same folder where this code is in, # and paste the code in the multiline comment below, """ aa = keyword() aa.openTranscript("sampleText.txt") keywords = aa.getTopKeywords() print(keywords) for i in range(0, len(keywords)): print(keywords[i]) print(aa.searchWiki(keywords[i])) print("\n") """ # and try to run this module # if you want to use string input instead of reading txt file, use code below """ strInput = "" #put your string input here aa = keyword() aa.inputTrscString(strInput) keywords = aa.getTopKeywords() print(keywords) for i in range(0, len(keywords)): print(keywords[i]) print(aa.searchWiki(keywords[i])) print("\n") """ class node: #Linked List node class def __init__(self,string): self.word = string nextNode = None prevNode = None return class linkedList: #Linked List def __init__(self): self.head = None self.tail = None return def getFirst(self): return self.head def addNode(self, string): #insert node to the tail temp = node(string) temp.nextNode = None if self.head == None: self.head = temp temp.prevNode = None else: temp.prevNode = self.tail temp.prevNode.nextNode = temp self.tail = temp def deleteNode(string): return def printNode(self): #print node's string from head to tail temp = self.head while True: print(temp.word) if temp.nextNode != None: temp = temp.nextNode continue else: break return class keyword: def __init__(self): self.dict1 = {} #save all words appearing in the transcript self.dict2 = {} #save all keywords that composed of mutiple words self.dict3 = {} #save all single-word keyword self.trsc = "" #transcript string self.text = linkedList() #transcript saved in linked list format (for internal processing) def isEndingWith(self, string1, part): #check if 'string1' is ending with 'part' #it's for finding suffixes if len(string1) <= len(part): return False check = True for i in range(0, len(part)): if string1[-1-i] == part[-1-i]: continue else: check = False break return check def openTranscript(self, address): #open txt file in read mode f = open(address, 'r',encoding='utf-8') self.trsc = f.read() return def inputTrscString(self,String): #update transcript manually using string input self.trsc = String return def singleWord(self): #find all words in the transcript #store them into 'dict1' with their frequency (key = word, values = frequencies) #and create 'text' linkedList word = "" for i in range(len(self.trsc)): #for all character in the transcript if self.trsc[i] >= 'a' and self.trsc[i] <= 'z': #when the letter is lower case word += self.trsc[i] if i == (len(self.trsc)-1): #when it's the last letter in the transcript if word in self.dict1: self.dict1[word] += 1 else: self.dict1[word] = 1 continue elif self.trsc[i] >= 'A' and self.trsc[i] <= 'Z': #when it's upper case temp = self.trsc[i].lower() word += temp if i == (len(self.trsc)-1): if word in self.dict1: self.dict1[word] += 1 else: self.dict1[word] = 1 continue elif self.trsc[i] == '’': #when it has apostrophe 1 if word != "": self.text.addNode(word) if word in self.dict1: self.dict1[word] += 1 else: self.dict1[word] = 1 word = "'" elif self.trsc[i] == '\'': #when it has apostrophe 2 if word != "": self.text.addNode(word) if word in self.dict1: self.dict1[word] += 1 else: self.dict1[word] = 1 word = "'" else: #when it's non of them if word != "": self.text.addNode(word) if word in self.dict1: self.dict1[word] += 1 else: self.dict1[word] = 1 word = "" continue #list of not important words (pronouns, conjunctions, etc.) notImportant = ["'", "i", "you", "we", "he", "she", "they", "my", "your","our" , "his", "her", "their", "s", "me", "yours", "us","him", "them", "mine", "ours","hers", "myself", "himself", "herself", "ourselves", "yourself", "themselves", "a", "an", "the", "am", "is", "are", "be", "been", "being", "m", "was", "were", "what", "where", "how", "which", "whom", "who", "when", "why", "this", "that", "it","things", "thing", "its", "one", "other", "kind", "not", "some", "t", "don", "well", "'re", "'ve", "'ll", "'t", "'m", "'s", "'d", "all", "only", "have", "had", "do", "did", "here", "there", "these", "those", "can", "could", "should", "shall", "may", "might", "will", "would", "maybe", "must", "yeah", "yep", "yeap"] conjunctions = ["and", "to", "of", "as", "at", "for", "from", "both", "with", "in", "on", "about", "up", "or", "so", "if","unless", "before", "after", "by", "each", "through", "then", "now", "next", "over", "than", "too", "but", "either", "neither", "nor", "like" , "because", "since", "just", "again", "more", "very", "most", "though", "although", "despite", "even", "also", "let", "letting"] commonWords = ["new", "old", "think", "thought", "see", "saw", "show", "showed", "put", "try", "trying", "tried", "say", "saying", "said", "make", "made", "get", "got", "go", "went", "gone", "going", "do", "done", "did", "doing", "have", "had", "has", "having" "one", "two", "three", "same", "different", "remember", "way", "reason", "time"] #erase the words listed above from dictionary for i in range(len(notImportant)): if notImportant[i] in self.dict1: del self.dict1[notImportant[i]] for i in range(len(conjunctions)): if conjunctions[i] in self.dict1: del self.dict1[conjunctions[i]] for i in range(len(commonWords)): if commonWords[i] in self.dict1: del self.dict1[commonWords[i]] #erase all words that just spoken only few times time temp = [] for key in self.dict1.keys(): if self.dict1[key] <= 2: temp.append(key) for item in temp: del self.dict1[item] return def multipleWord(self): #find all keywords that is composed of more than one word #store them in 'dict2' with frequencies (key = word, values = frequencies) wordCount = 0 longWord="" temp = self.text.getFirst() while True: if temp.word in self.dict1: #when the word is in the first dictionary, #add it to longWord and increase wordCount longWord += temp.word longWord += " " wordCount += 1 elif wordCount > 1: #when the word is not in the dictionary and composed of more than 1 word, #add to dict2 and reset longWord and wordCount longWord = longWord[0:len(longWord)-1] if longWord in self.dict2: self.dict2[longWord] += 1 else: self.dict2[longWord] = 1 longWord = "" wordCount = 0 else: #when it meets non of the condition #just reset longWord and wordCount longWord = "" wordCount = 0 if temp.nextNode != None: #move to next node when it exists temp = temp.nextNode continue else: #end loop if not. break #erase multi-word keywords that appeared just once temp = [] for key in self.dict2.keys(): if self.dict2[key] == 1: temp.append(key) for item in temp: del self.dict2[item] return def singleWordFilter(self): #only noun can be a keyword #because of that, it filters verb, adverb, and adjectives #and increase count of a noun that have same radix #and modify frequencies in 'dict3' since most of frequencies in dict3 tend to be higher. advSuffixes = ["ly", "ily", "ically"] #noun -> adj adjSuffixes1 = ["al", "ial", "ary", "ful", "ic", "ical", "ish", "less", "like", "ly", "ous", "y"] #ic -> ical, #verb -> adj adjSuffixes2 = ["able", "ible", "ant", "ent", "ive", "ing", "ed", "en"] verbSuffixes = ["ate", "ates", "en", "ens", "ify", "ifies", "ise", "ises" "ize", "izes"] Prefixes = ["a", "an", "ab", "abs", "ad", "add", "ac", "acc", "af", "aff", "ag", "agg", "al", "all", "an", "ann", "ap", "app", "at", "att", "as", "ass" "ante", "anti", "ant", "be", "com", "co", "col", "con", "cor", "contra", "counter", "de", "dia", "di", "dis", "di", "en", "em", "ex", "e", "ef", "extra", "hemi", "hyper", "hypo", "in", "il", "im", "ir", "infra", "inter", "intra", "non", "ob", "oc", "of", "op", "out", "over", "peri", "post", "pre", "pro", "re", "semi", "sub", "suc", "suf", "sug", "sup", "sur", "sus", "syn", "sym", "trans", "ultra", "un", "under"] maxList = list(self.dict2.values()) sumMulti = maxList[0] + maxList[1] + maxList[2] maximum = int((sumMulti /3 ) * 2.5) #print("sum : ", sumMulti) #print("ave : ", sumMulti/3) #print("maximum frequency setting: ", maximum) for key in list(self.dict1.keys()): if self.dict1[key] > maximum or len(key) <= 1: del self.dict1[key] maxList = list(self.dict1.values()) sumSingle = maxList[0] + maxList[1] + maxList[2] divConst = round(sumSingle/sumMulti) #print("divConst: ", divConst) #remove adverb suffix #ly, y -> ily , le -> ly, ic -> ically for key in self.dict1.keys(): #print(key) tempRad = key tempSuff = "" for suff in advSuffixes: if self.isEndingWith(key, suff): if tempSuff == "": tempSuff = suff elif len(tempSuff) < len(suff): tempSuff = suff if tempSuff != "": #tempRad = key[0:(len(key)-len(tempSuff))] continue #remove adjective suffix tempSuff = "" isNoun = False for suff in adjSuffixes1: if self.isEndingWith(tempRad, suff): if tempSuff == "": tempSuff = suff elif len(tempSuff) < len(suff): tempSuff = suff if tempSuff != "": isNoun = True if tempSuff == "ical": tempRad = tempRad[0:len(tempRad) - 2] else: tempRad = tempRad[0:len(tempRad) -len(tempSuff)] #print("filtering adj suffix: ", tempSuff) #print("resulting: ", tempRad) if isNoun == False : #when it looks like verb + suffix for suff in adjSuffixes2: if self.isEndingWith(tempRad, suff): if tempSuff == "": tempSuff = suff elif len(tempSuff) < len(suff): tempSuff = suff if tempSuff != "": tempRad = tempRad[0:len(tempRad) -len(tempSuff)] #print("filtering adj suffix: ", tempSuff) #print("resulting: ", tempRad) #remove verb suffix tempSuff = "" for suff in verbSuffixes: if self.isEndingWith(tempRad, suff): if tempSuff == "": tempSuff = suff elif len(tempSuff) < len(suff): tempSuff = suff if tempSuff != "": tempRad = tempRad[0:len(tempRad) -len(tempSuff)] #print("filtering verb suffix: ", tempSuff) #print("resulting: ", tempRad) #find the word that contains radix and has shortest length wordImportant = "" for word in self.dict1.keys(): if tempRad in word: if wordImportant == "": wordImportant = word elif len(word) < len(wordImportant): wordImportant = word elif len(word) == len(wordImportant) and key == word: wordImportant = word #print("keyword found is: ", wordImportant, "\n") if wordImportant in self.dict3: self.dict3[wordImportant] += self.dict1[key] else: self.dict3[wordImportant] = self.dict1[key] for temp in list(self.dict2.keys()): if tempRad in temp: self.dict3[wordImportant] -= self.dict2[temp] #print("decrease count: ", temp, " ", self.dict2[temp]) #print("\n") #remove counts that also counted in mutil-word keywords for key in list(self.dict3.keys()): self.dict3[key] = int(self.dict3[key]/divConst) return def sortDictionary(self): #sort the dictionaries in decending order with its frequecy self.dict1 = dict( sorted(self.dict1.items(), key=operator.itemgetter(1),reverse=True)) self.dict2 = dict( sorted(self.dict2.items(), key=operator.itemgetter(1),reverse=True)) self.dict3 = dict( sorted(self.dict3.items(), key=operator.itemgetter(1),reverse=True)) return def printKeywords(self): #print the dictionaries print(self.dict1) print("\n") print(self.dict2) print("\n") print(self.dict3) print("\n") return def getTopKeywords(self): #return most frequent keywords self.singleWord() self.multipleWord() self.sortDictionary() self.singleWordFilter() self.sortDictionary() #self.printKeywords() TopList = [] count = 0 prevFreq = 0 keysSingle = list(self.dict3.keys()) keysMultiple = list(self.dict2.keys()) index1 = 0 index2 = 0 while count < 10: currentFreq = 0 a = self.dict3[keysSingle[index1]] b = self.dict2[keysMultiple[index2]] if a > b : TopList.append(keysSingle[index1]) currentFreq = a index1 += 1 elif a < b: TopList.append(keysMultiple[index2]) currentFreq = b index2 += 1 else: TopList.append(keysSingle[index1]) TopList.append(keysMultiple[index2]) currentFreq = a index1 += 1 index2 += 1 if currentFreq < prevFreq: count += 1 continue elif prevFreq == 0: count += 1 continue return TopList def searchWiki(self, word): #search word in the Wikipedia and get definition of the word if exists. #it returns empty string when: # the page not exists in the Wikipedia # or the page is a reference page that starts with "~~~ may refer to:" wiki = wikipediaapi.Wikipedia('en') if len(word) == 0: return "" tempWord = "" loopCount = 0 while loopCount < len(word): if loopCount == 0: tempWord += word[loopCount].upper() elif word[loopCount] == ' ': tempWord += ' ' tempWord += word[loopCount+1].upper() loopCount += 1 else: tempWord += word[loopCount] loopCount += 1 if tempWord != "": search = wiki.page(tempWord) if search.exists(): #when it exists #check if the page is for referencing list of page checkDef = False message = "to:" loopCount = 0 messCount = 0 while True: if messCount == len (message): checkDef = True break; if loopCount > 40: break if search.summary[loopCount] == message[messCount]: loopCount += 1 messCount += 1 else: messCount = 0 loopCount += 1 if checkDef: return "" #if the page is only about the word else: tempDef = "" loopCount = 0 while loopCount < len(search.summary): if search.summary[loopCount] == '.': tempDef += '.' break else: tempDef += search.summary[loopCount] loopCount += 1 return tempDef else: return "" return ""
497b0a2f4848431c49db7c92115da3a48ffb24fc
daniromero97/Python
/e022-StringMethods/StringMethods.py
2,250
4.40625
4
print("##################### 1 #####################") sentence = "this IS a TEST sentence." print(sentence) print(sentence.capitalize()) """ output: this IS a TEST sentence. This is a test sentence. """ print("##################### 2 #####################") print(sentence) print(sentence.upper()) """ output: this is a test sentence. THIS IS A TEST SENTENCE. """ print("##################### 3 #####################") print(sentence) print(sentence.lower()) """ output: this IS a TEST sentence. this is a test sentence. """ print("##################### 4 #####################") print(sentence) print(sentence.swapcase()) """ output: this IS a TEST sentence. THIS is A test SENTENCE. """ print("##################### 5 #####################") print(sentence) print(sentence.title()) """ output: this IS a TEST sentence. This Is A Test Sentence. """ print("##################### 6 #####################") print(sentence) print(sentence.center(40, "-")) """ output: this IS a TEST sentence. --------this IS a TEST sentence.-------- """ print("##################### 7 #####################") print(sentence) print(sentence.ljust(40, "-")) """ output: this IS a TEST sentence. this IS a TEST sentence.---------------- """ print("##################### 8 #####################") print(sentence) print(sentence.rjust(40, "-")) """ output: this IS a TEST sentence. ----------------this IS a TEST sentence. """ print("##################### 9 #####################") print(sentence) print(sentence.zfill(40)) """ output: this IS a TEST sentence. 0000000000000000this IS a TEST sentence. """ print("##################### 10 #####################") print(sentence) print(sentence.count("e")) print(sentence.count("e", 20)) print(sentence.count("e", 15, 20)) """ output: this IS a TEST sentence. 3 1 2 """ print("##################### 11 #####################") sentence *= 3 print(sentence) print(sentence.find("this")) print(sentence.find("this", 5)) print(sentence.find("this", 10)) print(sentence.find("this", 10, 20)) """ output: this IS a TEST sentence.this IS a TEST sentence.this IS a TEST sentence. 0 24 24 -1 """
abd5f5eececb87bdd17813acca7ed44134dc80e4
christy951/programming-lab
/large of 3 number.py
285
4.125
4
print("enter 3 number/n") num1=int(input("first number:")) num2=int(input("second number:")) num3=int(input("third number:")) if num1>num3 and num1>num2: print(num1,"is large") elif num2>num3: print(num2,"is large") else: print(num3,"is large")
ac713b5c794ab4203d9e00a61dcce08ad0ca6468
akb46mayu/Data-Structures-and-Algorithms
/Dynamic Programming/le64_minimum_pathsum.py
1,434
3.828125
4
""" Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. """ class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if i ==0 and j==0: continue elif i==0: grid[i][j] = grid[i][j] + grid[i][j-1] elif j==0: grid[i][j] = grid[i][j] + grid[i-1][j] else: grid[i][j] = grid[i][j] + min(grid[i-1][j], grid[i][j-1]) return grid[m-1][n-1] class Solution2(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0]) f = [[0]*n]*m for i in range(m): for j in range(n): if i ==0 and j==0: f[i][j] = grid[i][j] elif i==0: f[i][j] = grid[i][j] + f[i][j-1] elif j==0: f[i][j] = grid[i][j] + f[i-1][j] else: f[i][j] = grid[i][j] + min(f[i-1][j], f[i][j-1]) return f[m-1][n-1]
a95722323fd032517854756f8cf2965aa43ebc8a
daniel-ntr/Python
/CursoEmVideo/desafio016.py
202
3.84375
4
dias = int(input('Quantos dias o carro permaneceu alugado? ')) km = float(input('Quantos quilômetros o carro percorreu? ')) aluguel = (dias * 60) + (km * 0.15) print(f'Custo do aluguel: R${aluguel}')
b3b4889d6a315fb7bb58748b3f500965bbaeb70a
jenni22jennifer1999/jennipython
/test2.py
423
4.28125
4
#!/usr/bin/python3 name="jennifer" #initializing string func print (name) #prints the value of name print (name*3) #prints the value of name 3 times print ("My name is " + name) #prints the sentence name1="Jennifer" name2=" J" print (name1+name2) #prints Jennifer J print (name[0]) #prints J (1st position) print (name[1]) #prints print (name[3]) #prints print (name[7]) #prints print (name[8]) #prints
7b77e94595eff74e0099632223ff56e7e4a72866
EricShiqiangLiang/Udacity-CS101
/ACE Exam/Type.py
236
3.671875
4
""" Provide a definition of g such that the expression below evaluates to True: """ def g(p): if type(p) == int: return g if type(p) == str: return 1 print type(g) == type(g(1)) != type(g('alpha'))
b907b7c4544b5075ed4a0b0d09420e9e198acc02
henriquesuenaga88/adventofcode
/day2/day2.py
1,806
3.65625
4
dict = { 'U': -1 , 'D': 1 , 'L': -1 , 'R': 1 } x_position = 1; y_position = 1; def getKeypadFromPosition(x, y) : keypad = [ ['1', '2', '3'] , ['4', '5', '6'] , ['7', '8', '9'] ]; return keypad[y][x]; def isAcceptableVerticalValue(direction) : return direction in ['U','D'] and (( direction == 'U' and y_position > 0 ) or ( direction == 'D' and y_position < 2 )) def isAcceptableHorizontalValue(direction) : return direction in ['L', 'R'] and (( direction == 'L' and x_position > 0 ) or ( direction == 'R' and x_position < 2 )); def getPasswordUnitFrom(line) : global x_position, y_position; for direction in line : if isAcceptableVerticalValue(direction) : y_position += dict[direction]; elif isAcceptableHorizontalValue(direction) : x_position += dict[direction]; return getKeypadFromPosition(x_position, y_position); def getBathroomPasswordFrom(filePath) : file = open(filePath, "r").readlines() password = ""; for line in file : password += getPasswordUnitFrom(line); print "password is " + password; if __name__ == '__main__': getBathroomPasswordFrom("input.txt")
fe6338c56059d0fb363a88d0d093b6e22892112d
RussAbbott/TicTacToe
/TTT/archive/TTT - Copy/players.py
13,663
4.03125
4
from random import choice class Player: """ The board is numbered as follows. 0 1 2 3 4 5 6 7 8 """ def __init__(self, gameManager, myMark): self.emptyCell = gameManager.emptyCell self.possibleMoves = list(range(9)) # 9 possible moves self.possibleWinners = gameManager.possibleWinners self.corners = [0, 2, 6, 8] self.sides = [1, 3, 5, 7] self.myMark = myMark self.opMark = self.otherMark(myMark) # References to GameManager functions. self.formatBoard = gameManager.formatBoard # o marksAtIndices converts a list of board indices to the marks at those indices. # marksAtIndices(indices) = [board[i] for i in indices] self.marksAtIndices = gameManager.marksAtIndices # o theWinner determines if there is a winner. self.theWinner = gameManager.theWinner self.whoseTurn = gameManager.whoseTurn def finalReward(self, reward): """ This is called after the game is over to inform the player of its final reward. This function should use that information in learning. :param reward: The final reward for the game. :return: None """ pass def isAvailable(self, board, pos): return board[pos] == self.emptyCell def makeAMove(self, board, reward): """ Called by the GameManager to get this player's move. :param board: :param reward: :return: A move """ return choice(list(range(9))) @staticmethod def otherMark(mark): return {'X': 'O', 'O': 'X'}[mark] @staticmethod def oppositeCorner(pos): return {0: 8, 2: 6, 6: 2, 8: 0}[pos] def theWinner(self, board): for triple in self.possibleWinners: [a, b, c] = self.marksAtIndices(board, triple) if not self.emptyCell in [a, b, c] and a == b == c: return a return None def validMoves(self, board): valids = [i for i in range(9) if self.isAvailable(board, i)] return valids class TransformableBoard: """ This class represents boards that can be associated with equivalence classes of boards. The board is numbered as follows. 0 1 2 3 4 5 6 7 8 """ def __init__(self): """ The rotate pattern puts: the item originally in cell 6 into cell 0 the item originally in cell 3 into cell 1 the item originally in cell 0 into cell 2 etc. In other words, it rotates the board 90 degrees clockwise. The flip pattern flips the board horizontally about its center column. See transformAux() to see these patterns in action. 0 to 3 rotates and 0 or 1 flip generates all the equivalent boards. See representative() to see how all the equivalent boards are generated. """ self.rotatePattern = [6, 3, 0, 7, 4, 1, 8, 5, 2] self.flipPattern = [2, 1, 0, 5, 4, 3, 8, 7, 6] def representative(self, board): """ Generate the equivalence class of boards and select the lexicographically smallest. :param board: :return: (board, rotations, flips); rotations will be in range(4); flips will be in range(2) The rotations and flips are returned so that they can be undone later. """ sortedTransformation = sorted([(self.transform(board, r, f), r, f) for r in range(4) for f in range(2)]) return sortedTransformation[0] def restore(self, board, r, f): """ Unflip and then unrotate the board :param board: :param r: :param f: :return: """ unflipped = self.transformAux(board, self.flipPattern, f) unrotateedAndFlipped = self.transformAux(unflipped, self.rotatePattern, 4 - r) return unrotateedAndFlipped def reverseTransformMove(self, move, r, f): """ Unflip and then unrotate the move position. :param move: :param r: :param f: :return: """ board = list('_' * 9) board[move] = 'M' restoredBoard = self.restore(board, r, f) nOrig = restoredBoard.index('M') return nOrig def transform(self, board, r, f): """ Perform r rotations and then f flips on the board :param board: :param r: number of rotations :param f: number of flips :return: the rotated and flipped board """ rotated = self.transformAux(board, self.rotatePattern, r) rotatedAndFlipped = self.transformAux(rotated, self.flipPattern, f) return rotatedAndFlipped @staticmethod def transformAux(board, pattern, n): """ Rotate or flip the board (according to the pattern) n times. :param board: :param pattern: :param n: :return: the transformed board """ result = board for _ in range(n): result = [result[i] for i in pattern] return result class HumanPlayer(Player): def makeAMove(self, board, reward): print(f'\n{self.formatBoard(board)}') c = '-1' while not (c in "012345678" and (0 <= int(c) <= 8)): c = input(f'{self.myMark} to move > ') return int(c) class LearningPlayer(Player, TransformableBoard): def finalReward(self, reward): """ Update the qValues to include the game's final reward. :param reward: :return: None """ pass def makeAMove(self, board, reward): (equivBoard, r, f) = self.representative(board) """ Update qValues and select a move based on representative board from this board's equivalence class. Should not be random like the following. """ move = choice(self.validMoves(equivBoard)) return self.reverseTransformMove(move, r, f) class ValidMovePlayer(Player): def makeAMove(self, board, reward): return choice(self.validMoves(board)) class PrettyGoodPlayer(ValidMovePlayer): def makeAMove(self, board, reward): """ If this player can win, it will. If not, it blocks if the other player can win. Otherwise it makes a random valid move. :param board: :param reward: :return: selected move """ myWins = set() myBlocks = set() emptyCell = self.emptyCell for possWin in self.possibleWinners: marks = self.marksAtIndices(board, possWin) if marks.count(emptyCell) == 1: if marks.count(self.myMark) == 2: myWins.add(possWin[marks.index(emptyCell)]) if marks.count(self.opMark) == 2: myBlocks.add(possWin[marks.index(emptyCell)]) if myWins: return choice(list(myWins)) if myBlocks: return choice(list(myBlocks)) emptyCellsCount = board.count(self.emptyCell) # X's first move should be in a corner. if emptyCellsCount == 9: return choice(self.corners) # O's first move should be in the center if it's available. if emptyCellsCount == 8 and self.isAvailable(board, 4): return 4 # The following is for X's second move. It applies only if X's first move was to a corner xFirstMove = board.index(self.myMark) if emptyCellsCount == 7 and xFirstMove in self.corners: oFirstMove = board.index(self.opMark) # If O's first move is a side cell, X should take the center. # Otherwise, X should take the corner opposite its first move. if oFirstMove in self.sides: return 4 if oFirstMove == 4: oppositeCorner = self.oppositeCorner(board.index(self.myMark)) return oppositeCorner # If this is O's second move and X has diagonal corners, O should take a side move. availableCorners = [i for i in self.corners if self.isAvailable(board, i)] # If X has two adjacent corners O was forced to block (above). So, if there are 2 available corners # they are diagonal. if emptyCellsCount == 6 and len(availableCorners) == 2: return choice([pos for pos in self.sides if self.isAvailable(board, pos)]) # If none of the special cases apply, take a corner if available, otherwise the center, otherwise any valid move. move = (choice(availableCorners) if len(availableCorners) > 0 else 4 if self.isAvailable(board, 4) else super().makeAMove(board, reward) ) return move class MinimaxPlayer(PrettyGoodPlayer): def makeAMove(self, board, reward): # The first few moves are hard-wired into PrettyGoodPlayer. if board.count(self.emptyCell) >= 7: return super().makeAMove(board, reward) # Otherwise use minimax. (_, move) = self.minimax2(board) return move def makeAndEvaluateMove(self, board, move, mark): """ Make the move and evaluate the board. :param board: :param move: :param mark: :return: 'X' is maximizer; 'O' is minimizer """ boardCopy = board.copy() boardCopy[move] = mark val = self.evaluateBoard(boardCopy) return (val, move, boardCopy) def evaluateBoard(self, board): winner = self.theWinner(board) val = ( 1 if winner == 'X' else -1 if winner == 'O' else # winner == None. Is the game a tie because board is full? 0 if board.count(self.emptyCell) == 0 else # The game is not over. None ) if val is not None: print(f'\nevaluateBoard:\n{self.formatBoard(board)}\n => {val}') return val def makeMoveAndMinimax(self, board, move, mark): boardCopy = board.copy() boardCopy[move] = mark return self.minimax2(boardCopy, move) def minimax2(self, board, move=None): """ Does a minimax search. :param board: :param move: :return: best minimax value and move for current player. """ val = self.evaluateBoard(board) if val is not None: return (val, move) mark = self.whoseTurn(board)['mark'] valids = self.validMoves(board) # minimaxResults are [(val, move)] (val in [1, 0, -1]) for move in valids] minimaxResults = [self.makeMoveAndMinimax(board, move, mark) for move in valids] minOrMax = max if mark == 'X' else min (bestVal, move) = minOrMax(minimaxResults, key=lambda mmMove: mmMove[0]) print(f'\n{self.formatBoard(board)}\n{mark} => {minimaxResults} {minOrMax} {(bestVal, move)}') bestMoves = [(val, move) for (val, move) in minimaxResults if val == bestVal] return choice(bestMoves) def minimax(self, board): """ Does a minimax search. :param board: :return: (val, move) best minimax value and move for current player. """ mark = self.whoseTurn(board)['mark'] valids = self.validMoves(board) # myPossMoves are [(val, move, board)] (val in [1, 0, -1, None]) for move in valids] # The returned boards are copies of the current board. myPossMoves = [self.makeAndEvaluateMove(board, move, mark) for move in valids] # Are any of myPossMoves winners? winningVal = 1 if mark == 'X' else -1 winners = [(val, move) for (val, move, _) in myPossMoves if val == winningVal] if winners: return choice(winners) # There won't be any losers. A player can't lose on its own move. # Are there any games which are not yet decided? (val will be None.) stillOpen = [(move, board) for (val, move, board) in myPossMoves if val is None] # If stillOpen is empty, all the spaces have been taken. So game is a tie. if not stillOpen: # There is at most one tie. ties = [(val, move) for (val, move, _) in myPossMoves if val == 0] return ties[0] # Run minimax on the cases in which the game is not yet decided. Keep track of the move that got there. minimaxResults = [(self.minimax(board), move) for (move, board) in stillOpen] # val will be absolute: 1 for 'X' wins and -1 for 'O' wins. It is not relative to whoseMove. # Are we maximizing or minimizing? minOrMax = max if mark == 'X' else min # minimaxResults is a list of the form ((val, _), move). # The _ is the best move for the other side, which we don't care about. # Pick one of the moves with the best val. ((bestVal, _), _) = minOrMax(minimaxResults, key=lambda mmMove: mmMove[0][0]) bestMoves = [(val, move) for ((val, _), move) in minimaxResults if val == bestVal] return choice(bestMoves)
b10a4270c5c9170d71513b7dede490be5971deb2
ArtemiiFrolov/Courses
/Main course_Python/lesson24470_1.py
178
3.703125
4
import re pattern = r"cat" line = input() out_line = "" while line: if len(re.findall(pattern, line)) > 1: out_line += line+"\n" line = input() print(out_line)
40910079637dda9f7753b4457f67a376504c8124
AlixLieblich/CodingPracticeProblems
/Problems/high_and_low.py
2,476
4.15625
4
# In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. # Example: # high_and_low("1 2 3 4 5") # return "5 1" # high_and_low("1 2 -3 4 5") # return "5 -3" # high_and_low("1 9 3 4 -5") # return "9 -5" def high_and_low(numbers): for num in numbers: high= max(num) low=min(num) var= (high, low) return var print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")) # 1 # def high_and_low(numbers): # numbers=numbers.split() # print() # print() # print(numbers) # # for i in numbers: # # high=max(i) # # low=min(i) # print(min(numbers)) # print(max(numbers)) # # var = (f"here {high} {low}") # # return var # print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")) # 2 # def high_and_low(numbers): # numbers=numbers.split() # print() # print() # print(numbers) # for num in numbers: # num=int(num) # numbers=sorted(numbers) # print(numbers) # return (min(numbers)) # return (max(numbers)) # print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")) # 3 # def high_and_low(numbers): # print() # print() # print() # print() # numbers=numbers.split() # string_int="" # for num in numbers: # string_int+=num # num=int(num) # string_int+=" " # print(type(num)) # print("orig:") # print(string_int) # string_int=sorted(string_int) # print("sorted: ") # print(string_int) # print(high_and_low("4 5 29 54 4 0 542 1 6")) #4 (with solutions help) def high_and_low(numbers): print() print() print() print() numbers=numbers.split() i=0 highest =int(numbers[0]) lowest=int(numbers[0]) while i <len(numbers): numbers[i]=int(numbers[i]) if numbers[i] > highest: highest = numbers[i] if numbers[i] < lowest: lowest = numbers[i] i+=1 highest= str(highest) lowest=str(lowest) return highest+" "+lowest print(high_and_low("4 5 29 54 4 0 542 1 6")) def high_and_low(numbers): numlist = numbers.split(" ") i = 0 highest = int(numlist[0]) lowest = int(numlist[0]) while i < len(numlist): numlist[i] = int(numlist[i]) if numlist[i] > highest: highest = numlist[i] if numlist[i] < lowest: lowest = numlist[i] i += 1 highest = str(highest) lowest = str(lowest) return highest+" "+lowest print(high_and_low("4 5 29 54 4 0 542 1 6"))
f08e1e13a6b97028b5eb62f7d015e2b967045739
mohrtw/algorithms
/algorithms/dataStructures/stack.py
1,231
4.25
4
class Stack(object): """Represents a last-in, first-out data structure Public attributes: - items: A list of items in the stack. Functions: - push: Pushes an item to the end of the stack. - pop: Removes and returns the last item in the stack. - peek: Returns the last item in the stack. - is_empty: Returns True if the stack contains no elements. """ def __init__(self, items=[]): """Initializes a new stack object. Args: items: A list of items to initialize the stack with. Defaults to an empty list. """ self.items = items[:] def push(self, item): """Pushes an item to the end of the stack. Args: item: the item to be pushed to the stack. """ self.items.append(item) def pop(self): """Removes and returns the last item in the stack. Returns: The last item in the stack. """ return self.items.pop() def peek(self): """Returns the last item in the stack. """ return self.items[-1] def is_empty(self): """Returns True if the stack is empty. """ return not self.items
0184826ef303f513cbe9fa84841cbc397871ef21
google-code/7567-fallas1
/tp3MotorDeInferencia/python/ecuacion.py
6,293
3.640625
4
#!/usr/bin/env python #-*- coding:utf-8 -*- """ Este modulo define la clase Ecuacion, que permite interpretar una ecuacion de una cadena de caracteres y separala en sus componentes, para ser almacenados en notacion polaca inversa. """ import re class Ecuacion(object): """ Representa una ecuacion, separada por operadores. Utiliza notacion polaca inversa para almacenar los componentes de la operacion. """ def __init__(self, operadores): self._operadores = operadores self._componentes = list() self._abrir = [ '(', '[', '{' ] # Parentesis de apertura self._cerrar = [ ')', ']', '}' ] # Parentesis de cierre. # expresion regular para separar usando los operadores y los parentesis. aux = '(' aux += ')|('.join( [ re.escape(x) for x in self._abrir ] ) aux += ')|(' aux += ')|('.join( [ re.escape(x) for x in self._cerrar] ) aux += ')|(' aux += ')|('.join( [ re.escape(x) for x in self._operadores] ) aux += ')|\b' self._patron = re.compile(aux) def is_operador(self, operador): """ Permite saber si un string es uno de los operadores definidos. """ return operador in self._operadores def aridad_de(self, operador): """ Obtiene la aridad de del operador si existe. Si el operador no existe devuelve -1. """ aridad = None try: aridad = self._operadores[operador] except KeyError: aridad = -1 return aridad def __str__(self): return self.to_infija() def get_componentes(self): """ Obtiene los componentes de la ecuacion. """ return self._componentes def from_infija(self, string): """ Lee una ecuacion en notacion infija y lo convierte a notacion polaca inversa, almacenando sus componentes por separado. Ejemplo: "A+B" se transformara en ["A", "B", "+"], si se ha definido como operador a "+". """ componentes = list() # Componentes de la expresion en NPR. variables = [list()] # Pila de variables (no son operadores). operadores = list() # Pila de operadores. grado = 0 # El grado de parentesis encontrandos. aridad = None partes = [ x for x in self._patron.split(string) if x is not None ] partes = [ x.strip() for x in partes if x.strip() != '' ] for parte in partes: if self.is_operador(parte): operadores.append(parte) elif parte in self._abrir: grado += 1 while len(variables) < grado+1: variables.append(list()) else: if not parte in self._cerrar: variables[grado].append(parte) while len(operadores)>0: operador = operadores[-1] aridad = self.aridad_de(operador) if len(variables[grado]) >= aridad: operador = operadores.pop() # Elimino los elementos None de la lista. aux = variables[grado][:aridad] aux = [ x for x in aux if x is not None ] componentes.extend(aux) variables[grado] = variables[grado][aridad:] componentes.append(operador) variables[grado-1].append(None) if len(variables[grado]) == 0: grado -= 1 variables.pop() else: break # Si la ecuacion era correcta el grado debe ser cero. if None in variables[0]: variables[0].remove(None) # Todas las pilas tienen que estar vacias. cero = len(operadores) + sum( [ len(x) for x in variables ] ) + grado if cero == 0: self._componentes = componentes return (cero == 0) def to_infija(self): """ Obtiene un string representando a la ecuacion en formato infijo. Ejemplo: "A+B". """ pila = list() for parte in self.get_componentes(): if not self.is_operador(parte): # No es parentesis por construccion. pila.append(parte) else: # debo operar. operador = parte aridad = self.aridad_de(operador) if aridad <= 0: break if aridad == 1: aux = operador+'('+pila.pop()+')' pila.append(aux) elif aridad == 2: der = pila.pop() izq = pila.pop() aux = '('+ izq + operador + der +')' pila.append(aux) else: parametros = list() while len(parametros) < aridad: parametros.append(pila.pop()) aux = operador+'('+ ', '.join(parametros)+')' pila.append(aux) if len(pila) == 1: resultado = pila.pop() if resultado[0] in self._abrir and resultado[-1] in self._cerrar: resultado = resultado[1:-1] return resultado else: return None def _test(): """ Ejecuta las pruebas integradas al modulo ecuacion. """ calculadora = Ecuacion({'+':2, '-':2, '*':2, '/':2, '&':2, '|':2, 'cos':1, 'f':3 }) pruebas = [ '1+2', '(1+2)+4', '(1+2)', '(A|B)&C', 'A|[B&C]', 'cos(x)+4', 'A|B&C', '((A|B)&(B|C)&C)', '1/( 2*(3-4) )' ] for caso in pruebas: print 'Caso: "'+caso+'"' if calculadora.from_infija(caso): print ' RESULTADO: '+str(calculadora.get_componentes()) print ' str: '+str(calculadora) else: print ' ERROR' if __name__ == '__main__': _test()
b14402bd3dc6b70752338fabf66b536b0bc4b233
Lekuro/python_core
/CodeWars6/1_distance.py
254
4.03125
4
# Simple: Find The Distance Between Two Points def distance(x1, y1, x2, y2): """ function count the distance between two pont (x1, y1) and (x2, y2) """ return round(((x1 - x2)**2 + (y1 - y2)**2)**(1/2), 2) print(distance(-1, -2, 1, 2))
80dc847d3282114e5865b20c02b6c0a85796807d
jsnreddy/coding_practice
/python/find_missing_number.py
341
4.21875
4
# find the missing number from the sorted list of integers where one integer is missing between 1 to n n = 10 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10] def find_missing_number(n, numbers): sum_of_numbers = (n * (n + 1)) / 2 for num in numbers: sum_of_numbers -= num return int(sum_of_numbers) print(find_missing_number(n, numbers))
482f2a337af097b1654ed214c68d9479841d41f6
kimhjong/class2-team3
/fibonach.py
837
3.65625
4
import time #재귀함수를 통한 피보나치수열 def fibo(n): if n <= 1: return n return fibo(n - 1) + fibo(n - 2) #반복문을 통한 피보나치수열 def iterfibo(n): past = 0 current = 1 storage = 1 if (n == 0): return 0 elif (n == 1): return 1 else: for i in range(2, n+1): storage = current current = past + current past = storage return current #두개 시간비교 while True: n = int(input("Enter a number: ")) if n == -1: break ts = time.time() fibonumber = iterfibo(n) ts = time.time() - ts print("IterFibo(%d)=%d, time %.6f" % (n, fibonumber, ts)) ts = time.time() fibonumber = fibo(n) ts = time.time() - ts print("Fibo(%d)=%d, time %.6f" % (n, fibonumber, ts))
9e306bbc15b1ebe9b2a81491e7faf015e3ec1237
Will66/testsigou
/py/filetolist.py
635
3.734375
4
#!/usr/bin/env python def readFile2List(fileName, listName): listName = [] with open(fileName,"r") as f: sentences = [elem for elem in f.read().split('\n') if elem] for word in sentences: listName.append(word.split()) return listName def readFile2Dict(fileName, dictName): fileHandle = open(fileName,"r") line = fileHandle.readline().rstrip('\n') dictName = {} keycounter = 1 while line: key = str(keycounter) dictName[key] = line keycounter = keycounter + 1 line = fileHandle.readline().rstrip('\n') return dictName comm=[] comm=readFile2List("comm.txt",comm) print comm
367203ef71161797d1df204c9b4c8528769e987d
KRLoyd/holbertonschool-higher_level_programming
/original_repo/0x05-python-exceptions/2-safe_print_list_integers.py
617
4.4375
4
#!/usr/bin/python3 def safe_print_list_integers(my_list=[], x=0): """ Prints the first x elements of a list, only integers Args: my_list -- list to print x -- number of elements to print Return: number of integers printed """ # Start print counter at 0 print_count = 0 # For values up to x for i in range(0, x): # Try to print the element try: print("{:d}".format(my_list[i]), end="") print_count += 1 # Exception for non integers except (TypeError, ValueError): continue print() return print_count
9f4aad2311586efc3d0261e4596306c078722db7
amgregoi/School
/K-State/CIS505/Finished-Assingments/Ex3/Ex3-Submit/interpret.py
7,407
3.75
4
### INTERPRETER FOR OBJECT-ORIENTED LANGUAGE """The interpreter processes parse trees of this format: PTREE ::= DLIST CLIST DLIST ::= [] CLIST ::= [ CTREE* ] where CTREE* means zero or more CTREEs CTREE ::= ["=", LTREE, ETREE] | ["if", ETREE, CLIST, CLIST] | ["print", ETREE] ETREE ::= NUM | [OP, ETREE, ETREE] | ["deref", LTREE] where OP ::= "+" | "-" LTREE ::= ID NUM ::= a nonempty string of digits ID ::= a nonempty string of letters The interpreter computes the meaning of the parse tree, which is a sequence of updates to heap storage. """ from heapmodule import * # import the contents of the heapmodule.py module ### INTERPRETER FUNCTIONS, one for each class of parse tree listed above. # See the end of program for the driver function, interpretPTREE def interpretDLIST(dlist) : """pre: dlist is a list of declarations, DLIST ::= [ DTREE+ ] post: memory holds all the declarations in dlist """ for dec in dlist : interpretDTREE(dec) def interpretDTREE(d) : # covers int, proc, ob, & class declarations """pre: d is a declaration represented as a DTREE: DTREE ::= ["int", I, ETREE] post: heap is updated with d """ ### WRITE ME if d[0] == "int" : # int declaration e = interpretETREE(d[2]) if type(e) == int : declare(activeNS(), d[1], e) else : crash(e, "attempted to assign a non int val to an int") elif d[0] == "proc" : #proc allocation #if d[1] == "int": #declare(activeNS(), d[1], e) allocateClosure(activeNS(), 'proc', d[1], d[2], d[3]) elif d[0] == "ob" : # object allocation e = interpretETREE(d[2]) if type(e) != int : declare(activeNS(), d[1], e) else : crash(e, "attempted to assign int value to ob") elif d[0] == "class" : #class allocation allocateClosure(activeNS(), 'class', d[1], [], d[2]) else : crash(d[0], "not a valid delcaration!") def interpretCLIST(clist) : """pre: clist is a list of commands, CLIST ::= [ CTREE+ ] where CTREE+ means one or more CTREEs post: memory holds all the updates commanded by program p """ for command in clist : interpretCTREE(command) def interpretCTREE(c) : """pre: c is a command represented as a CTREE: CTREE ::= ["=", LTREE, ETREE] | ["if", ETREE, CLIST, CLIST2] | ["print", LTREE] post: heap holds the updates commanded by c """ # print c operator = c[0] if operator == "=" : # "=" operator handle, field = interpretLTREE(c[1]) rval = interpretETREE(c[2]) store(handle, field, rval) elif operator == "print" : # print operator print interpretETREE(c[1]) elif operator == "if" : # if operator test = interpretETREE(c[1]) if test != 0 : interpretCLIST(c[2]) else : interpretCLIST(c[3]) elif operator == "call": # call operator tempHandle, temp = interpretLTREE(c[1]) handle = lookup(tempHandle, temp) proc = lookupheap(handle) if isinstance(proc, list): p, il, cl, phandle = proc args = c[2] vals = [] for item in args : vals.append(interpretETREE(item)) newnshandle = allocateNS() namespace = lookupheap(newnshandle) namespace['parentns'] = phandle storeheap(newnshandle, namespace) for index in range(0, len(il)): declare(newnshandle, il[index], vals[index]) #interpretDLIST(il) interpretCLIST(cl) deallocateNS() else: crash(c[1], "not a procedure") else : crash(c, "invalid command") def interpretETREE(etree) : """interpretETREE computes the meaning of an expression operator tree. ETREE ::= NUM | [OP, ETREE, ETREE] | ["deref", LTREE] OP ::= "+" | "-" post: updates the heap as needed and returns the etree's value """ if isinstance(etree, str) and etree.isdigit() : #is num ans = int(etree) elif isinstance(etree, str) and etree == "nil": #is nil ans = "nil" elif etree[0] in ("+", "-") : #"+,-" operators ans1 = interpretETREE(etree[1]) ans2 = interpretETREE(etree[2]) if isinstance(ans1,int) and isinstance(ans2, int) : if etree[0] == "+" : ans = ans1 + ans2 elif etree[0] == "-" : ans = ans1 - ans2 else : crash(etree, "a value isn't an int") elif etree[0] == "deref" : # deref handle, field = interpretLTREE(etree[1]) ans = lookup(handle,field) elif etree[0] == "new": # new ans = interpretTTREE(etree[1]) else : crash(etree, "doesn't compute") return ans def interpretTTREE(ttree) : # finds meaning of ttree if isinstance(ttree, list) : # is it a list if ttree[0] == "struct" : # is it a struct phandle = activeNS() handle = allocateNS() namespace = lookupheap(handle) namespace['parentns'] = phandle storeheap(handle, namespace) interpretDLIST(ttree[1]) deallocateNS() return handle if ttree[0] == "call" : # is it a call lval = interpretLTREE(ttree[1]) handle = lookup(lval[0], lval[1]); closure = lookupheap(handle) if closure[0] == 'class' : #is it a class return interpretTTREE(closure[1]) else : crash(closure[0], "isn't a class") else: crash(ttree, "isn't a struct or class") else : crash(ttree, "isn't a ttree") def interpretLTREE(ltree) : """interpretLTREE computes the meaning of a lefthandside operator tree. LTREE ::= ID | [ "dot", LTREE, ID ] post: returns a pair, (handle,varname), the L-value of ltree """ if isinstance(ltree, str) : # ID ? ans = (activeNS(), ltree) # use the handle to the active namespace elif isinstance(ltree, list) and ltree[0] == "dot": # ["dot", LTREE, ID ]? handle, var = interpretLTREE(ltree[1]) val = lookup(handle, var) if isLValid(val, ltree[2]): ans = (val, ltree[2]) else: crash(ltree, val + " not in " + ltree[2]) else : crash(ltree, "illegal L-value") return ans def crash(tree, message) : """pre: tree is a parse tree, and message is a string post: tree and message are printed and interpreter stopped """ print "Error evaluating tree:", tree print message print "Crash!" printHeap() raise Exception # stops the interpreter ### MAIN FUNCTION def interpretPTREE(tree) : """interprets a complete program tree pre: tree is a PTREE ::= [ DLIST, CLIST ] post: heap holds all updates commanded by the tree """ initializeHeap() interpretDLIST(tree[0]) interpretCLIST(tree[1]) printHeap()
0148e757a71b95bf7bd6e5727ba9fd7f9aec0878
Krondini/CSCI-3104
/Lectures/InsertionSort.py
400
3.546875
4
import sys import csv def insertionSort(arr): key = arr[0] def main(argv): try: if(argv[1]): with open(argv[1]) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: for element in row: element = int(element) insertionSort(argv[1]) close(csv_file) except Exception as e: raise e if __name__ == '__main__': main(sys.argv)
693e1f6b51ded507f3833ed5690ec6b2993ffe71
aaveter/curs_2016_b
/3/6.py
329
3.5625
4
users = [ 'user1', 'user2', 'user3', ] users.append('user3') print( users ) users_set = set( users ) users = list( users_set ) users.sort(reverse=False) print( users ) s = {1, 2, 3} s2 = {3, 4, 5} print( s2.difference(s) ) print( s2.intersection(s) ) print( s2.issubset({3, 4, 5, 6}) ) print( s2.union(s) )
82ef6b1ef179fdc6811884f6af91b6ebfd3b9133
davidbegin/python-in-the-morning
/Fluent_Python/Day43/flag_challenge.py
584
4.0625
4
import string print("\033c") # Challenge: Make a datastructure with every two letter combination # Points for: # - Cleverness # - Shortness # - Speed # - Readability all_the_letters = string.ascii_uppercase a1 = list(all_the_letters) # create a list the length of a1, consisting only of a single character # list(len(a1), "A") def gen_letters(): letters = list(string.ascii_uppercase) for letter in letters: for letter2 in letters: yield f"{letter}{letter2}" g1 = gen_letters() next(g1) for x in g1: print(x) # breakpoint()
9dd43b6c13ce8ce62b143e6c156e192df1574436
daniel-reich/turbo-robot
/hQRuQguN4bKyM2gik_21.py
1,269
4
4
""" **Mubashir** needs your help in a simple task. Create a function which takes two positive integers `a` and `b`. These numbers are simultaneously **decreased by 1** until the **smaller one reaches 0**. During this process, the greater number can be divisible by the smaller one. Your task is to **count how many times it will happen**. ### Example 1 a = 3, b = 5 # 5 is not divisible by 3 a = 2, b = 4 # decreased by 1, 4 is divisible by 2 a = 1, b = 3 # decreased by 1, 3 is divisible by 1 a = 0, b = 2 # decreased by 1, the smaller number is 0, End The result should be 2 ### Example 2 a = 8, b = 4 # 8 is divisible by 4 a = 7, b = 3 # decreased by 1, 7 is not divisible by 3 a = 6, b = 2 # decreased by 1, 6 is divisible by 2 a = 5, b = 1 # decreased by 1, 5 is divisible by 1 a = 4, b = 0 # decreased by 1, the smaller number is 0, End The result should be 3 ### Examples simple_check(3, 5) ➞ 2 simple_check(8, 4) ➞ 3 simple_check(54, 17) ➞ 1 ### Notes N/A """ def simple_check(a, b): lo, hi = min(a,b), max(a,b) cnt = 0 for i in range(lo): if hi % lo == 0: cnt += 1 hi = hi - 1 lo = lo - 1 return cnt
ff0ae072ea009df81781fd8da0ac623ebaea66e6
cboe07/CS-Fundamentals
/Unit 4/my_hash_function.py
619
4.09375
4
def my_hash_function(value): first_letter = value[0] alphabet = "abcdefghijklmnopqrstuvwxyz" return alphabet.index(first_letter) print(my_hash_function("abe")) print (my_hash_function("carrot")) def my_hash_function(phone_number): return phone_number[0] + phone_number[1] + phone_number[2] print(my_hash_function("7708863306")) def is_palindrome(word): word_length = len(word) for i in range(word_length/2): if word[i] == word[-1-i]: return True return False print (is_palindrome('racecar')) print (is_palindrome('abcba')) print (is_palindrome('today'))
22adfa8fb297a30f531da93c074e37f57ca611a3
bmdyy/projecteuler
/027.py
682
3.578125
4
def is_prime(n): if n <= 3: return n > 1; elif n % 2 == 0 or n % 3 == 0: return False; i = 5; while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False; i = i + 6; return True; def num_con_primes(a, b): n = 0; while is_prime(n*n+a*n+b): n += 1; return n; best_coeffs = [-1001, -1001]; best_num_con_primes = 0; for a in range(-1000, 1000): # |a| < 1000 for b in range(-1000, 1001): # |b| <= 1000 curr_num_con_primes = num_con_primes(a, b); if curr_num_con_primes > best_num_con_primes: best_num_con_primes = curr_num_con_primes; best_coeffs = [a, b]; print(best_coeffs, best_coeffs[0] * best_coeffs[1]);
6c48b3fd8c73a99e2248bdf0e5d906212e92a1ae
hswang108/Algorithm_HW
/WEEK4/LeetCode/232Stacks_arraytype.py
1,252
4.25
4
class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.a = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.a.append(x) for i in range(len(self.a)-1,0,-1): self.a[i] = self.a[i-1] self.a[0] = x def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ c = self.a.pop() print(c) return c def peek(self) -> int: """ Get the front element. """ length = len(self.a)-1 return self.a[length] def empty(self) -> bool: """ Returns whether the queue is empty. """ if len(self.a) == 0: print('true') return True else: for i in range(len(self.a)): if self.a[i] != None: print('false') return False # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
5f71130945334b63455fd476a5d70d7f10901938
gurkslask/tiddur
/app/time_cmd/week.py
1,660
4.03125
4
from .scheme import Scheme class Week: """ week() week Schemes within days """ def __init__(self): self.week = {"monday": [Scheme("Work2", 10, 00, 11, 00)], "tuesday": [], "wednesday": [], "thursday": [], "friday": [], "saturday": [], "sunday": [] } def addmonday(self, s: Scheme): self.week["monday"].append(s) def addtuesday(self, s: Scheme): self.week["tuesday"].append(s) def addwednesday(self, s: Scheme): self.week["wednesday"].append(s) def addthursday(self, s: Scheme): self.week["thursday"].append(s) def addfriday(self, s: Scheme): self.week["friday"].append(s) def addsaturday(self, s: Scheme): self.week["saturday"].append(s) def addsunday(self, s: Scheme): self.week["sunday"].append(s) def popmonday(self, s: Scheme): self.week["monday"].pop(s) def poptuesday(self, s: Scheme): self.week["tuesday"].pop(s) def popwednesday(self, s: Scheme): self.week["wednesday"].pop(s) def popthursday(self, s: Scheme): self.week["thursday"].pop(s) def popfriday(self, s: Scheme): self.week["friday"].pop(s) def popsaturday(self, s: Scheme): self.week["saturday"].pop(s) def popsunday(self, s: Scheme): self.week["sunday"].pop(s) def __str__(self) -> str: return str(self.week) def __iter__(self): for day, scheme in self.week.items(): yield (day.title(), scheme)
2c57f44a10d44060954b4cee82819fa1a22e4561
icyfig/NFA_to_DFA
/nfa_to_dfa.py
9,843
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 21 17:37:07 2021 @author: icyfig """ ''' Python Program for converting an NFA to an equivalent DFA INPUT FILE FORMAT: The Input shall consist of 5 Lines. Line 1- Comma-Separated Input States Surrounded by braces Line 2- Comma-Separated Alphabets Surrounded by braces Line 3 - Transition Function in Braces, as a nested dictionary. Outer keys represent states, and inner keys represent alphabets. Inner values are lists. (See example below in 'sample run'). Line 4 - Start state (without braces) Line 5- Comma-Separated Final States Surrounded by braces NOTE: 1. The Program does not return the minimum-state DFA. To the contrary, it returns the one with the most states (2^n, where n is the number of nfa states) 2. 'epsilon' is a reserved word for the empty string ɛ 3. In the output, the name of a dfa state is in the form of a list. For eg. [1, 3] refers to a single state in the DFA (reflecting its origin from states 1 and 3 in the NFA) SAMPLE RUN The input file describes the DFA in figure 1.42 (Pg. 57, Sipser 3rd) The output file describes the equivalent NFA in figure 1.43 Input File nfa.txt - same directory as the program ------------------------------------------------------------- {1,2,3} {a,b} {1:{a:[], b: [2],epsilon:[3]}, 2:{a:[2,3], b: [3],epsilon:[]}, 3: {a:[1], b: [],epsilon:[]}} 1 {1} ------------------------------------------------------------- Output File dfa.txt - Should be created in the same directory prior to running the program ------------------------------------------------------------- States: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] Alphabets: [a, b] Transition Function: {[]: {a: [], b: []}, "[3]": {a: [1, 3], b: []}, "[2]": {a: [2, 3], b: [3]}, "[2, 3]": {a: [1, 2, 3], b: [3]}, "[1]": {a: [], b: [2]}, "[1, 3]": {a: [1, 3], b: [2]}, "[1, 2]": {a: [2, 3], b: [2, 3]}, "[1, 2, 3]": {a: [1, 2, 3], b: [2, 3]}} Start State: [1, 3] Accept States: [[1], [1, 3], [1, 2], [1, 2, 3]] ------------------------------------------------------------- ''' #Global Variables F_dfa=[] #Accepting states of the DFA d = {} #Dictionary to store DFA's transition function def delta_nfa(state, alphabet): return trans[state][alphabet] #transition function of the nfa. Returns a list def main(): #----------------------------------Input processing---------------------# f = open("nfa.txt", "r") #-----------Reading States-----------# line=f.readline() line=line.strip() length=len(line) state_comma=line[1:length-1] #Removing braces state_comma = state_comma.replace(" ", "") #Removing whitespaces global Q_nfa Q_nfa = state_comma.split(",") #Reading CSVs into a list #-----------Reading Alphabets-----------# line=f.readline() line=line.strip() length=len(line) letters_comma=line[1:length-1] letters_comma = letters_comma.replace(" ","") global sigma sigma=letters_comma.split(",") #-----------Reading Transition Function-----------# line=f.readline() line=line.strip() line=line.replace(" ", "") #Removing whitespaces qline="" oq=False #Open(Unpaired) Quote #Enclosing all states and alphabets in quotes for i in line: if(i == '{'): qline+=i continue if(i==':' or i==',' or i=='}' or i=='[' or i==']'): if(oq): qline+="'" qline+=i oq=False else: qline +=i continue if(oq==False): oq=True qline +="'" qline +=i continue if(oq==True): qline +=i global trans trans=eval(qline) #String to dictionary conversion #-----------Reading Start State-----------# line=f.readline() line=line.strip() line=line.replace(" ", "") line = str(line) global start_nfa start_nfa =line #-----------Reading Final States-----------# line=f.readline() line=line.strip() length=len(line) final_comma=line[1:length-1] final_comma = final_comma.replace(" ","") global F F = final_comma.split(",") #Getting the power set of Q_nfa, and filling #it in Q_dfa global Q_dfa Q_dfa = sub_lists(Q_nfa) construct_delta_dfa() #Calling the function to create the transition function of dfa #Start State of dfa is the e closure of the start state of nfa, #plus start state itself. start_eclose = e_closure_state(start_nfa,[]) start_eclose.append(start_nfa) start_state_dfa = find_dfa_state(start_eclose) f.close() #----------------------------------Output processing---------------------# fo = open("dfa.txt", "w") #-----------Writing States-----------# statesStr = str(Q_dfa) statesStr = statesStr.replace("'", "") #Remove quotes around states fo.write('States: '+statesStr+"\n") #-----------Writing Alphabets-----------# alphaWrite = str(sigma).replace("'","") fo.write('Alphabets: '+alphaWrite+"\n") #-----------Writing Transition Function-----------# dString = str(d).replace("'","") fo.write('Transition Function: '+dString+"\n") #-----------Writing Start State-----------# StartString = str(start_state_dfa).replace("'","") fo.write('Start State: '+StartString+"\n") #-----------Writing Accept States-----------# AcceptString = str(F_dfa).replace("'","") fo.write('Accept States: '+AcceptString) fo.close() def construct_delta_dfa():#Constructing the transition function for the DFA for i in Q_dfa: #For each state in the dfa, we figure out the transitions dict_state = {} for k in sigma:#For each alphabet to_composite = [] for j in i: #For each dfa state,corresponding to multiple nfa states, find E(q) i.e. closure to = [] tos_alpha = delta_nfa(j,k) #Add states reachable from the main state by the alphabet to.extend(tos_alpha) '''tos_epsilon = e_closure_state(j,[]) #Apparently these states are not counted in the transition, #so it is commented out. for l in tos_epsilon: #Add states reachable from the e-closure states by the alphabet tos_epsilon_alpha = delta_nfa(l,k) to.extend(x for x in tos_epsilon_alpha if x not in to)''' for l in to: #Add states e-reachable from states reachable by alphabet tos_alpha_epsilon = e_closure_state(l,[]) to= to + list(set(tos_alpha_epsilon) - set(to)) to_composite = to_composite + list(set(to) - set(to_composite)) to_composite_state = find_dfa_state(to_composite)#Sort the states in the nomenclature dict_state[k] = to_composite_state d[str(i)] = dict_state for i in Q_dfa: #Accept states of the DFA for j in i: if j in F: F_dfa.append(i) continue def delta_dfa(state, alphabet): t=tuple(state, alphabet) return d[t] def sub_lists(l): #Returns the power set of the input list def decimalToBinary(n): # converting decimal to binary b = 0 i = 1 while (n != 0): r = n % 2 b+= r * i n//= 2 i = i * 10 return b def makeList(k): # list of the binary element produced a =[] if(k == 0): a.append(0) while (k>0): a.append(k % 10) k//= 10 a.reverse() return a def checkBinary(bin, l): temp =[] for i in range(len(bin)): if(bin[i]== 1): temp.append(l[i]) return temp binlist =[] subsets =[] n = len(l) for i in range(2**n): s = decimalToBinary(i) arr = makeList(s) binlist.append(arr) for i in binlist: k = 0 while(len(i)!= n): i.insert(k, 0) # representing the binary equivalent according to len(l) k = k + 1 for i in binlist: subsets.append(checkBinary(i, l)) return subsets def e_closure_state(state,eclose): #Recursive function. Input - #a state and a list of states which are reachable from it(initially empty) primary = trans[state]['epsilon'] #A list of states one hop away primary_no_duplicates=[] [primary_no_duplicates.append(x) for x in primary if x not in primary_no_duplicates] #Remove duplicates #eclose.append(primary_no_duplicates) eclose = eclose + list(set(primary_no_duplicates) - set(eclose)) for i in primary_no_duplicates: if i not in eclose:#Base case = the state is already recorded in the e-closure eclose.append(i) secondary = e_closure_state(i,eclose.copy()) #Recursive step for j in secondary:#Sort through the e-reachable states of the secondary state if j not in eclose: #Add it to list of reachable states if it is not already added eclose.append(j) return eclose.copy() def find_dfa_state(state_list): #Given a list of nfa states in random order, find the corresponding single dfa state in correct order for i in Q_dfa: if(set(i) == set(state_list)): return i.copy() main()
ebc36c6781006bc6a5d5b19bc5f29ababf692296
katerina-g/python-fundamentals-09-2020
/Basic Syntax, Conditional Statements and Loops - Exercise/Easter Cozonacs.py
565
3.8125
4
budget = float(input()) flour_price = float(input()) eggs_price = flour_price * 0.75 milk_liter_price = flour_price * 1.25 milk_needed_price = milk_liter_price / 4 cozonac_price = eggs_price + flour_price + milk_needed_price colored_eggs = 0 count_cozonacs = 0 while budget >= cozonac_price: count_cozonacs += 1 colored_eggs += 3 if count_cozonacs % 3 == 0: colored_eggs -= count_cozonacs - 2 budget -= cozonac_price print(f"You made {count_cozonacs} cozonacs! Now you have {colored_eggs} eggs and {budget:.2f}BGN left.")
51d5d7eae6c9a2ab459aa5b28c166016697c9861
dani3390/Fondamenti-di-Programmazione
/lezione2_esercizio2.py
1,204
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 15 23:56:48 2019 @author: Danilo Testo: Scrivere una funzione che dati in ingresso il costo del biglietto per visitare un museo e il numero di studenti di una classe in gita scolastica, ritorna la spesa totale, considerando che se gli studenti sono compresi fra 10 e 30 il biglietto per studente costa il 20% in meno, se sono 31 o più il 30% in meno. """ def Sconto_Scuola_Museo(biglietto, numero): #Si può anche fare lo sconto direttamente sul totale if (numero > 0 and numero < 10): costo = biglietto * numero elif (numero >= 10 and numero <= 30): sconto = round(((biglietto * 20) / 100), 2) costo = (biglietto - sconto) * numero elif (numero >= 31): sconto = round(((biglietto * 30) / 100), 2) costo = (biglietto - sconto) * numero else: print("Hai inserito un valore negativo") #possibile errore non gestito return costo biglietto = float(input("Inserisci il costo del biglietto: ")) numero = int(input("Inserisci il numero degli studenti: ")) print(Sconto_Scuola_Museo(biglietto, numero))
d93fa2646ca684ef22c8a1b6aed235f2f0e284d7
huwenlong99/pss
/response_web_niji/the_pouden_mack/Get_search_results.py
1,392
3.625
4
# 获取搜索结果Get search results # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import time # 声明谷歌、Firefox、Safari等浏览器 browser = webdriver.Chrome() # browser= webdriver.Firefox() # browser= webdriver.Safari() # browser= webdriver.Edge() # browser= webdriver.PhantomJS() # 打开浏览器,输入白底地址,输入要搜索的值,点击搜索 try: url = "https://www.baidu.com" browser.get(url) input = browser.find_element_by_id("kw") input.send_keys("外骨骼") input.send_keys(Keys.ENTER) wait = WebDriverWait(browser, 10) wait.until(EC.presence_of_element_located((By.ID, "content_left"))) print(browser.current_url) print(browser.get_cookies()) print(browser.page_source) time.sleep(10) finally: print(url.format(1, )) browser.close() # 查找单个元素 """ from selenium.webdriver.common.by import By browser = webdriver.Chrome() browser.get("http://www.taobao.com") input_first = browser.find_element_by_id("q") input_second = browser.find_element_by_css_selector("#q") input_third = browser.find_element(By.ID, "q") print(input_first , input_second, input_first) """
9a2524ef812590e81a13ebd44d73699740c576f9
irina08/Python
/cpython.py
1,318
3.796875
4
#!/usr/local/bin/python3 # NAME: student Irina Golovko # FILE: cpython.py # DATE: 04/06/2019 # DESC: Write a universal wrapper program that expects # its command line arguments to contain the absolute path # to any program, followed by its arguments. The wrapper # should run that program and report its exit value import sys import subprocess #find command line arguments list_args = sys.argv def run(list_args): # first argument is always name of this script result = subprocess.run(list_args[1:], shell=False, stdout=subprocess.PIPE) print(result.stdout.decode()) if __name__=="__main__" : if len(list_args) == 1: print("\nPlease provide the absolute path to any program, " + "\nfollowed by its arguments or without arguments." + "\nFor example: \npython3 cpython.py /bin/ls -la " + "\npython3 cpython.py /bin/ls" + "\npython3 cpython.py /usr/local/bin/python3 filename.py" + "\n") else: print("\nThe command lines arguments:") print(*list_args, sep=" ") print("The name of this script:", list_args[0]) print("The absolute path to given program, followed " + "by its arguments:") print(*list_args[1:], sep=" ") print("\nRun it:\n") run(list_args)
08b53cc939b1a4da691b1026d4e20d1613f66aeb
rajeevj0909/FunFiles
/Circle OOP.py
485
3.984375
4
class Circle: def __init__(Circle,r): Circle.radius=r def getDiameter(Circle,r): diam=r*2 return ("Diameter: ",diam) def circum(Circle,r): circum=2*r*3.14159265359 return("Circumference: ",circum) def area (Circle,r): area=r*r*3.14159265359 return("Area: ",area) r=float(input("What's the radius?")) c = Circle(r) print(c.getDiameter(r)) print(c.circum(r)) print(c.area(r))
cf8da00e544d5b5304a87e4809b007ac7a57b2b6
pvo4/week4-tic-tac-toe
/ticTacToe.py
3,878
4.1875
4
def printBoard(board): # TO DO ################################################################# # Write code in this function that prints the game board. # # The code in this function should only print, the user should NOT # # interact with this function in any way. # # # # Hint: you can follow the same process that was done in the textbook. # ######################################################################### print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R']) print('-+-+-') print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R']) print('-+-+-') print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R']) def checkWinner(board, player): print('Checking if ' + player + ' is a winner...') # TO DO ################################################################# # Write code in this function that checks the tic-tac-toe board # # to determine if the player stored in variable 'player' currently # # has a winning position on the board. # # This function should return True if the player specified in # # variable 'player' has won. The function should return False # # if the player in the variable 'player' has not won. # ######################################################################### return ((board['top-L'] == player and board['top-M'] == player and board['top-R'] == player) or # across the top (board['mid-L'] == player and board['mid-M'] == player and board['mid-R'] == player) or # across the middle (board['low-L'] == player and board['mid-M'] == player and board['mid-R'] == player) or # across the bottom (board['top-L'] == player and board['mid-L'] == player and board['low-L'] == player) or # down the left side (board['top-M'] == player and board['mid-M'] == player and board['low-M'] == player) or # down the middle (board['top-R'] == player and board['mid-R'] == player and board['low-R'] == player) or # down the right side (board['top-L'] == player and board['mid-M'] == player and board['low-R'] == player) or # diagonal (board['top-R'] == player and board['mid-M'] == player and board['low-L'] == player)) # diagonal def startGame(startingPlayer, board): # TO DO ################################################################# # Add comments to each line in this function to describe what # # is happening. You do not need to modify any of the Python code # ######################################################################### turn = startingPlayer for i in range(9): printBoard(board) #calling on function printBoard to print the tictactoe board print('Turn for ' + turn + '. Move on which space?') #asking player X or O to pick a space move = input() #ask player to input move board[move] = turn if( checkWinner(board, 'X') ): #calls upon function checkWinner to see if player X is in winning position print('X wins!') #lets the players know that X wins and end program break elif ( checkWinner(board, 'O') ): #if X doesnt win, checks to see if O is the winner print('O wins!') #prints O is the winner and end program break if turn == 'X': #player X goes first then player O turn = 'O' else: turn = 'X' #if player O goes first then player X is second printBoard(board)
a80bb62e382c506d9651ed4e5d96b043df2f561c
mattling9/COMP1_2014
/Skeleton Program.py
10,255
3.5625
4
# Skeleton Program code for the AQA COMP1 Summer 2014 examination # this code should be used in conjunction with the Preliminary Material # written by the AQA Programmer Team # developed in the Python 3.2 programming environment # version 2 edited 06/03/2014 import random, datetime SameCardLower = True ACE_HIGH = True NO_OF_RECENT_SCORES = 3 class TCard(): def __init__(self): self.Suit = 0 self.Rank = 0 class TRecentScore(): def __init__(self): self.Name = '' self.Score = '' self.Date = '' Deck = [None] RecentScores = [None] Choice = '' def GetRank(RankNo): Rank = '' if RankNo == 1: Rank = 'Ace' elif RankNo == 2: Rank = 'Two' elif RankNo == 3: Rank = 'Three' elif RankNo == 4: Rank = 'Four' elif RankNo == 5: Rank = 'Five' elif RankNo == 6: Rank = 'Six' elif RankNo == 7: Rank = 'Seven' elif RankNo == 8: Rank = 'Eight' elif RankNo == 9: Rank = 'Nine' elif RankNo == 10: Rank = 'Ten' elif RankNo == 11: Rank = 'Jack' elif RankNo == 12: Rank = 'Queen' elif RankNo == 13: Rank = 'King' elif RankNo == 14: Rank = 'Ace' return Rank def GetSuit(SuitNo): Suit = '' if SuitNo == 1: Suit = 'Clubs' elif SuitNo == 2: Suit = 'Diamonds' elif SuitNo == 3: Suit = 'Hearts' elif SuitNo == 4: Suit = 'Spades' return Suit def DisplayMenu(): print() print('-------------------------MAIN MENU-------------------------') print() print('1. Play game (with shuffle)') print('2. Play game (without shuffle)') print('3. Display recent scores') print('4. Reset recent scores') print('5. Options') print('6. Save Recent Scores') print('7. Load Recent Scores') print() print('Select an option from the menu (or enter q to quit): ', end='') def OptionsMenu(): print("-----------------------OPTIONS MENU-------------------------") print() print('1. Ace High / Ace Low') print('2. Card of same score ends game') print() OptionsMenuChoice = input('Select an option from the menu (or enter q to quit): ') if OptionsMenuChoice == '1': ACE_HIGH_CHOICE = input("Would you like to set Ace (H)igh / Ace (L)ow? :") if ACE_HIGH_CHOICE == 'H': global ACE_HIGH ACE_HIGH = True elif OptionsMenuChoice == '2': SetSameScore() def SetSameScore(): global SameCardLower Done = False while not Done: Choice = input("Do you want the next card to have the same or lower value as the current card?: ") Choice = Choice.upper() Choice = Choice[0] if Choice == 'S': Done = True SameCardLower = False elif Choice == 'L': Done = True SameCardLower = True def GetMenuChoice(): Choice = input() Choice = Choice.capitalize() if Choice == 'Q' or Choice == 'Quit': Choice = 'q' print() return Choice def LoadDeck(Deck): CurrentFile = open('deck.txt', 'r') Count = 1 while True: LineFromFile = CurrentFile.readline() if not LineFromFile: CurrentFile.close() break Deck[Count].Suit = int(LineFromFile) LineFromFile = CurrentFile.readline() Deck[Count].Rank = int(LineFromFile) if ACE_HIGH == True and Deck[Count].Rank == 1: Deck[Count].Rank = 14 Count = Count + 1 def ShuffleDeck(Deck): SwapSpace = TCard() NoOfSwaps = 1000 for NoOfSwapsMadeSoFar in range(1, NoOfSwaps + 1): Position1 = random.randint(1, 52) Position2 = random.randint(1, 52) SwapSpace.Rank = Deck[Position1].Rank SwapSpace.Suit = Deck[Position1].Suit Deck[Position1].Rank = Deck[Position2].Rank Deck[Position1].Suit = Deck[Position2].Suit Deck[Position2].Rank = SwapSpace.Rank Deck[Position2].Suit = SwapSpace.Suit def DisplayCard(ThisCard): print() print('Card is the', GetRank(ThisCard.Rank), 'of', GetSuit(ThisCard.Suit)) print() def GetCard(ThisCard, Deck, NoOfCardsTurnedOver): ThisCard.Rank = Deck[1].Rank ThisCard.Suit = Deck[1].Suit for Count in range(1, 52 - NoOfCardsTurnedOver): Deck[Count].Rank = Deck[Count + 1].Rank Deck[Count].Suit = Deck[Count + 1].Suit Deck[52 - NoOfCardsTurnedOver].Suit = 0 Deck[52 - NoOfCardsTurnedOver].Rank = 0 def IsNextCardHigher(LastCard, NextCard): Higher = False if NextCard.Rank > LastCard.Rank: Higher = True if SameCardLower == True: if NextCard.Rank == LastCard.Rank: Higher = True return Higher def GetPlayerName(): print() ValidName = False while ValidName == False: PlayerName = input('Please enter your name: ') print() if len(PlayerName) > 0: ValidName = True return PlayerName def GetChoiceFromUser(): Choice = input('Do you think the next card will be higher than the last card (enter y or n)? ') Choice = Choice.capitalize() if Choice == 'Y' or Choice =='Yes': Choice = 'y' elif Choice == 'N' or Choice == 'No': Choice = 'n' return Choice def DisplayEndOfGameMessage(Score): print() print('GAME OVER!') print('Your score was', Score) if Score == 51: print('WOW! You completed a perfect game.') print() def DisplayCorrectGuessMessage(Score): print() print('Well done! You guessed correctly.') print('Your score is now ', Score, '.', sep='') print() def ResetRecentScores(RecentScores): for Count in range(1, NO_OF_RECENT_SCORES + 1): RecentScores[Count].Name = '' RecentScores[Count].Score = 0 RecentScores[Count].Date = '' def DisplayRecentScores(RecentScores): ##BubbleSortScores(RecentScores) print() print('Recent Scores: ') print() print("{0:<10}{1:<10}{2:<10}".format("Name","Score","Date")) for Count in range(1, NO_OF_RECENT_SCORES + 1): print("{0:<10}{1:<10}{2:<10}".format(RecentScores[Count].Name, RecentScores[Count].Score, RecentScores[Count].Date)) print() print('Press the Enter key to return to the main menu') input() print() def UpdateRecentScores(RecentScores, Score): Date = datetime.datetime.now() PlayerName = GetPlayerName() FoundSpace = False Count = 1 while (not FoundSpace) and (Count <= NO_OF_RECENT_SCORES): if RecentScores[Count].Name == '': FoundSpace = True else: Count = Count + 1 if not FoundSpace: for Count in range(1, NO_OF_RECENT_SCORES): RecentScores[Count].Name = RecentScores[Count +1].Name RecentScores[Count].Score = RecentScores[Count +1].Score RecentScores[Count].Date = RecentScores[Count +1].Date Count = NO_OF_RECENT_SCORES RecentScores[Count].Name = PlayerName RecentScores[Count].Score = Score RecentScores[Count].Date = Date.strftime("%d/%m/%Y") def SaveScores(RecentScores): with open('save_scores.txt', mode = 'w', encoding= 'UTF-8')as my_file: for Count in range(1, NO_OF_RECENT_SCORES +1): my_file.write(str(RecentScores[Count].Score)+ "\n") my_file.write(str(RecentScores[Count].Name)+ "\n") my_file.write(str(RecentScores[Count].Date)+ "\n") def LoadScores(): try: with open("save_scores.txt",mode="r")as my_file: counter =1 count =1 done = False for line in my_file: if (count -1) != NO_OF_RECENT_SCORES: if counter == 1: RecentScores[count].Name = line.rstrip("\n") elif counter == 2: RecentScores[count].Score= line.rstrip("\n") elif counter == 3: RecentScores[count].Date = line.rstrip("\n") count+=1 counter=0 counter+=1 except IOError: print() print("Sorry No File Was Found") print() def BubbleSortScores(RecentScores): Swapped = True while Swapped: Swapped = False for Count in range(1, NO_OF_RECENT_SCORES): if RecentScores[Count + 1].Score > RecentScores[Count].Score: temp = RecentScores[Count + 1] RecentScores[Count +1] = RecentScores[Count] RecentScores[Count] = temp Swapped = True def PlayGame(Deck, RecentScores): RecentScoreCounter = 0 LastCard = TCard() NextCard = TCard() GameOver = False GetCard(LastCard, Deck, 0) DisplayCard(LastCard) NoOfCardsTurnedOver = 1 while (NoOfCardsTurnedOver < 52) and (not GameOver): GetCard(NextCard, Deck, NoOfCardsTurnedOver) Choice = '' while (Choice != 'y') and (Choice != 'n'): Choice = GetChoiceFromUser() DisplayCard(NextCard) NoOfCardsTurnedOver = NoOfCardsTurnedOver + 1 Higher = IsNextCardHigher(LastCard, NextCard) if (Higher and Choice == 'y') or (not Higher and Choice == 'n'): DisplayCorrectGuessMessage(NoOfCardsTurnedOver - 1) LastCard.Rank = NextCard.Rank LastCard.Suit = NextCard.Suit else: GameOver = True if GameOver: DisplayEndOfGameMessage(NoOfCardsTurnedOver - 2) HighScoreChoice = input("Do you want to Add your score to the High Score Table? (y/n): ") HighScoreChoice = HighScoreChoice.upper() if HighScoreChoice == 'Y': UpdateRecentScores(RecentScores, NoOfCardsTurnedOver - 2) else: DisplayEndOfGameMessage(51) HighScoreChoice = input("Do you want to Add your score to the High Score Table? (y/n): ") HighScoreChoice = HighScoreChoice.upper() if HighScoreChoice == 'Y': UpdateRecentScores(RecentScores, 51) if __name__ == '__main__': for Count in range(1, 53): Deck.append(TCard()) for Count in range(1, NO_OF_RECENT_SCORES + 1): RecentScores.append(TRecentScore()) Choice = '' while Choice != 'q': DisplayMenu() Choice = GetMenuChoice() if Choice == '1': LoadDeck(Deck) ShuffleDeck(Deck) PlayGame(Deck, RecentScores) elif Choice == '2': LoadDeck(Deck) PlayGame(Deck, RecentScores) elif Choice == '3': DisplayRecentScores(RecentScores) elif Choice == '4': ResetRecentScores(RecentScores) elif Choice == '5': OptionsMenu() elif Choice == '6': SaveScores(RecentScores) elif Choice == '7': LoadScores()
a6484398bdaf6778d5b056fc56bdba670221ddae
IAmAbszol/DailyProgrammingChallenges
/Problem_29/solution.py
895
3.75
4
import unittest def solve(case): ''' AABBCCD A, 1 A = iter.next() A, 2 A != iter.next() Result append (2A) B, 1 .... ''' if case is None or not case or not all([c.isalpha() for c in case]): return None iterator = iter(list(case)) character, count = 0, 0 resultant = "" while True: try: tmp = next(iterator) if character == 0: character, count = tmp, 1 continue if tmp == character: count += 1 else: resultant += "{}{}".format(count, character) character, count = tmp, 1 except: resultant += "{}{}".format(count, character) break return resultant class Test(unittest.TestCase): data = [("AAAABBBCCDAA", "4A3B2C1D2A"), ("AABBCCYY", "2A2B2C2Y"), ("", None)] def test(self): for case, expected in self.data: actual = solve(case) self.assertEquals(actual, expected) if __name__ == '__main__': unittest.main()
ad34945e094673f7e4aba6f0df80aaffc650f34f
Puzyrinwrk/Stepik
/Поколение Python/Только_плюс.py
1,172
4.53125
5
""" Напишите программу, которая считывает три числа и подсчитывает сумму только положительных чисел. Формат входных данных На вход программе подаются три целых числа. Формат выходных данных Программа должна вывести одно число – сумму положительных чисел. Примечание. Если положительных чисел нет, то следует вывести 00. Sample Input 1: 4 -22 1 Sample Output 1: 5 Sample Input 2: 33 55 63 Sample Output 2: 151 Sample Input 3: -1 37 62 Sample Output 3: 99 """ a = int(input()) b = int(input()) c = int(input()) if a > 0 and b > 0 and c > 0: print(abs(a + b + c)) elif a > 0 and b > 0 and c < 0: print(abs(a + b)) elif a > 0 and b < 0 and c > 0: print(abs(a + c)) elif a < 0 and b > 0 and c > 0: print(abs(b + c)) elif a < 0 and b < 0 and c > 0: print(abs(c)) elif a > 0 and b < 0 and c < 0: print(abs(a)) elif a < 0 and b > 0 and c < 0: print(abs(b)) else: print(0)
8eb00c4e0f3132690a0c692e6d75260bc3d86cd3
hetvi14/ICT-Project
/mail.py
1,709
3.578125
4
import smtplib #simple mail transfer protocol used for email server i.e to create client session obj from io import StringIO from io import BytesIO from email.mime.base import MIMEBase #This is the base class for all the MIME-specific subclasses of Message from email.mime.text import MIMEText #The MIMEText class is used to create MIME objects of major type text from email import encoders from email.mime.multipart import MIMEMultipart #This is an intermediate base class for MIME messages that are multipart print('Sending email...') sender_id = '' #email of sender email_password = '' receiver_id = '' #email of receiver subject = 'ICT' message = MIMEMultipart() message['From'] = sender_id #USING MULTIPART() WE CAN DIVIDE MESSAGE INTO DIFFERENT PARTS message['To'] = receiver_id message['Subject'] = subject message_body = 'DEMO MAIL FROM PYTHON PROGRAM' message.attach(MIMEText(message_body,'plain')) #USING ATTACH WE CAN ATTACH MAIL MULTIPARTS AS ONE SINGLE MESSAGE file_name='C:\\Users\\Hetvi\\Desktop\\ICT.txt' attachment=open(file_name,'rb') part = MIMEBase('application','octet-stream') #TO POST DATA part.set_payload((attachment).read()) encoders.encode_base64(part) #Encodes the payload into base64(TO ENCODE DATA) part.add_header('Content-Disposition',"attachment; filename= "+file_name) message.attach(part) text = message.as_string() #CONVERTS MESSAGE INTO STRING TYPE server = smtplib.SMTP('smtp.gmail.com',587) #PORT NUMBER FOR GMAIL server.starttls() #STARTS THE EMAIL SERVER server.login(sender_id,email_password) server.sendmail(sender_id,receiver_id,text) server.quit() #QUIT CONNECTION TO THE EMAIL SERVER print('\nEmail sent...')
d862d9dbc133adacab4ad2878df37a1bfcf95cf5
paddyjclancy/eng_57_class_notes
/Python/exercises/107_fizz_buzz.py
970
4.1875
4
# Write a fizz-buzz game ##project # as a user I should be able prompted for a number, the program will print all the numbers up to and including said number while following the constraints / specs. (fizz and buzz for multiples or 3 and 5) # As a user I should be able to keep giving the program different numbers and it will calculate appropriately until you use the key word: 'penpinapplespen' # write a program that take a number # prints back each individual number, but # if it is a multiple of 3 it returns fizz # if a multiple of 5 it return buzz pen_pineapple_pen = 6 while True: choice = int(input("Choose a number! ")) for i in range(1, choice + 1): if choice == pen_pineapple_pen: print("You beat the game!") break elif i % 15 == 0: print("FUZZBUZZ") elif i % 5 == 0: print("BUZZ") elif i % 3 == 0: print("FIZZ") else: print(i)
8e28360d226b62d01152ba495482c289c8297388
khalil-hassayoun/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
288
3.75
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): a = [0, 0] b = [0, 0] for i in range(min(len(tuple_a), 2)): a[i] += tuple_a[i] for i in range(min(len(tuple_b), 2)): b[i] += tuple_b[i] new_tup = (a[0] + b[0], a[1] + b[1]) return (new_tup)
f65a642d95a1a1a9d0f2483d850801bb11fdd1b9
Natsu1270/Codes
/Hackerrank/LinkedList/GetNodeFromEnd.py
453
3.65625
4
from LinkedList import * def getNode(head,pos): index, run ,res = 0, head, head while run.next: run = run.next index +=1 if index > pos: res = res.next return res.data def getNode2(head,pos): run,res = head,head while pos>0: run = run.next while run.next: run = run.next res = res.next return res.data llist = input_linkedlist() print(getNode2(llist.head,0))
80eb6b187720ca594bade970e9d6669c375acff5
GruberQZ/AoC-2017
/Day19/day19.py
1,748
3.546875
4
import os import os.path def go(): # Build grid grid = [] input = open(os.path.join(os.getcwd(), 'Day19', 'input.txt')) for line in input: grid.append(list(line.replace('\n', ''))) grid.append([' '] * len(grid[0])) letters = set(list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')) path = [] # Find the starting position in the first row pos = [0, grid[0].index('|')] direction = [1, 0] count = 0 while True: count += 1 # Check the character at the current position char = grid[pos[0]][pos[1]] # Track order of letters seen if char in letters: path.append(char) # Figure out the next position nextPos = [pos[0] + direction[0], pos[1] + direction[1]] # Can we keep going in the same direction? if grid[nextPos[0]][nextPos[1]] != ' ': pos = nextPos continue # Have to switch directions # Must go 90 degrees from current direction if direction[1] != 0: # Figure out of if we should go left or right if grid[pos[0] + 1][pos[1]] != ' ': direction = [1, 0] elif grid[pos[0] - 1][pos[1]] != ' ': direction = [-1, 0] else: return path, count else: # Figure out of if we should go up or down if grid[pos[0]][pos[1] + 1] != ' ': direction = [0, 1] elif grid[pos[0]][pos[1] - 1] != ' ': direction = [0, -1] else: return path, count # Compute next position pos = [pos[0] + direction[0], pos[1] + direction[1]] path, steps = go() print(''.join(path)) print(str(steps))
f309bc43579b79a27986def0681e785071bbf37c
smanisha92/HackRank
/hackerrankpracticeprojects/miniongame.py
840
3.765625
4
"""Kevin and Stuart want to play the 'The Minion Game'. Game Rules Both players are given the same string, S. Both players have to make substrings using the letters of the string S. Stuart has to make words starting with consonants. Kevin has to make words starting with vowels. The game ends when both players have made all possible substrings. Scoring A player gets +1 point for each occurrence of the substring in the string S""" def minion_game(string): k = 0 s = 0 vowels = "AaEeIiOoUu" for i in range(len(string)): if string[i] in vowels: k = k + len(string) - i else: s = s + len(string) - i if k > s: print("Kevin", k) elif k == s: print("Draw") else: print("Stuart", s) if __name__ == '__main__': s = input() minion_game(s)
2a41a811f7c4ec5d223de6ae52ea5395611e294a
yanzixiong/Python-
/10day/03-new.py
260
3.859375
4
class Person(object): def __new__(cls,name,age): print('__new__') instance = object.__new__(cls) return instance def __init__(self,name,age): print('__init__') self.name = name self.age = age p = Person('laowang',33) print(p.name) print(p.age)
19c7cef0a17b3d8a4922d14b355c51ee832a9844
jordanwu97/FooBar
/Level_1_2/bunny_prisoner_locating.py
264
3.515625
4
def answers(x,y): m = 1 for j in range(1, y): m = m + j print m num = y - 1 n = 0 for i in range(y+1,y+x): n = n + i print n + m # for i in range(1,x+1): # n = n + i # print n # answers(input(),input())
8c6e99402c5fc18608b4276e686f2c61c48f2df9
asgarzee/interview-preparation
/bfs_and_dfs.py
831
3.84375
4
from collections import deque from collections import OrderedDict def bfs(graph, start_node): queue = deque([start_node]) visited = OrderedDict({start_node: True}) while queue: v = queue.popleft() for i in graph[v]: if i not in visited: queue.append(i) visited[i] = True return list(visited.keys()) def dfs(graph, start_node, visited=[]): if start_node not in visited: visited.append(start_node) for i in graph[start_node]: dfs(graph, i, visited) return visited if __name__ == '__main__': graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'D'], 'D': ['B', 'C', 'E'], 'E': ['B', 'D'] } print(bfs(graph, 'A')) print(dfs(graph, 'A')) # A,B,D,C, E
ef4ffe9497cc469170fbeacaf6cba50550f57b95
leoashcraft/Python-OOP-Blackjack
/blackjack.py
3,838
3.65625
4
import random class BlackJack: def __init__(self): self.cards = [] self.clubs = [] self.diamonds = [] self.hearts = [] self.spades = [] self.suits = (self.clubs, self.diamonds, self.hearts, self.spades) self.suitNames = ("clubs", "diamonds", "hearts", "spades") self.cardsDictionary = {} # 1 : '1 clubs' self.totalDealerCards = 0 self.totalPlayerCards = 0 print("Computer is the dealer while you are the player") # join all suits together count = -1 for suit in self.suits: count = count + 1 for num in range(1, 14): cardName = str(num) + " " + self.suitNames[count] suit.append(cardName) self.cardsDictionary[cardName] = num self.cards = self.cards + suit print("There are",len(self.cards), "cards") print(self.cardsDictionary) # generate random cards def randomCards(self): return random.sample(self.cards, 1) # calculate sum of dealer's and player's cards def cardTotal(self): self.totalDealerCards = 0 for singleDealerCard in self.dealerCards: self.totalDealerCards = self.totalDealerCards + self.cardsDictionary[singleDealerCard] self.totalPlayerCards = 0 for singlePlayerCard in self.playerCards: self.totalPlayerCards = self.totalPlayerCards + self.cardsDictionary[singlePlayerCard] # check who wins def checkWinner(self, s = None): # if player enters 's' if s == "s": print("Dealer cards are", self.dealerCards, " = ", self.totalDealerCards) print("Your cards are", self.playerCards, " = ", self.totalPlayerCards) if self.totalDealerCards > self.totalPlayerCards: print("Game over!\nDealer wins") return "Dealer wins" elif self.totalPlayerCards > self.totalDealerCards: print("Game over!\nYou win") return "You win" # is sum of dealer's or player's cards equal to 21, if so return winner self.cardTotal() if self.totalPlayerCards == 21: print("Blackjack!", "You win") return "You win" return "No winner" # start game def start(self): print("Game has started") self.dealerCards = [] self.playerCards = [] # generate 2 random cards each for the dealer and the player for cardLoop in [self.dealerCards, self.playerCards]: for _ in range(2): cardLoop.append(self.randomCards()[0]) print("Cards have been dealed for you and the dealer") self.cardTotal() print("Dealer's cards are", [self.dealerCards[0], "hidden"]) print("Your cards are", self.playerCards, " = ", self.totalPlayerCards) # check if dealer's or player's cards are up to 21 and anounce winner winner = self.checkWinner() while winner == "No winner": playerInput = input("Enter h to hit, Enter s to stand:\n") if playerInput == "h": print("New card has been dealed for you") self.playerCards.append(self.randomCards()[0]) self.cardTotal() print("Your cards are", self.playerCards, " = ", self.totalPlayerCards) elif playerInput == "s": self.checkWinner("s") break self.cardTotal() if (self.totalDealerCards < 21) or (self.totalDealerCards >= 21): self.dealerCards.append(self.randomCards()[0]) self.cardTotal() print("Dealer just dealed a new card for itself") b = BlackJack() b.start()
e5dd52e81123daf39c092740db3d5fad08e51bfa
jaijaish98/ProblemSolving
/invert_binary_tree.py
1,147
4.125
4
""" Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 4 / \ 7 2 / \ / \ 9 6 3 1 """ #Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def invert_binary_tree(self, root): if root==None: return root.left, root.right = self.invert_binary_tree(root.right), self.invert_binary_tree(root.left) return root def inorder_traversal(self, root): if root==None: return self.inorder_traversal(root.left) print(root.val) self.inorder_traversal(root.right) if __name__ == "__main__": tree = TreeNode(4,None,None) tree.right = TreeNode(7,None,None) tree.left = TreeNode(2,None,None) tree.right.right = TreeNode(9, None, None) tree.right.left = TreeNode(6, None, None) tree.left.right = TreeNode(3, None, None) tree.left.left = TreeNode(1, None, None) invert = Solution() invert.invert_binary_tree(tree) invert.inorder_traversal(tree)
661faef519cd939da80e73c4472b67a11074fc75
bunnydev26/learn_py_asyncio
/tutorial_edge/future_example.py
699
3.640625
4
import asyncio # Define a coroutine that takes async def myCoroutine(future): # simulate some 'work' await asyncio.sleep(1) # set the result of our future project future.set_result("My Coroutine-turned-future has completed") async def main(): # define a future object future = asyncio.Future() # wait for the completion of our coroutine that we've # turned into a future object using the ensure_future() function await asyncio.ensure_future(myCoroutine(future)) print(future.result()) # Spin up a quick and simple event loop # and run until completed loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.close()
e96ee3612a15cea97c7afe71b7c3f74a13761bcf
samarthupadhyaya/python-programming
/rock_paper_scissor.py
182
3.578125
4
a=input() b=input() x=input() y=input() if((len(x)==4 and len(y)==7) or (len(x)==7 and len(y)==5) or(len(x)==5 and len(y)==4)): print(f"{a} Win") else: print(f"{b} Win")
fa4833023f64ec475be441b23d5b2e1ffcd49294
ksaubhri12/ds_algo
/interviews/dsa/gameskraft/print_valid_ip.py
2,119
3.53125
4
def print_valid_ip(string_value: str): result_arr = [] def print_util_min(string_value: str): return '.'.join(i for i in string_value) def print_ip(string_value: str, len_needed, output_string: str): if len_needed <= 0: return output_string if len_needed == 1: return string_value if len_needed > len(string_value): return output_string if len_needed == len(string_value): return print_util_min(string_value) res = print_ip(string_value[1:], len_needed - 1, string_value[1:] + output_string) if res is not None: one_string = string_value[0] + "." + res print(one_string) res = print_ip(string_value[2:], len_needed - 2) if res is not None: two_string = string_value[0] + string_value[1] + "." + res print(two_string) res = print_ip(string_value[3:], len_needed - 3) if res is not None: three_string = string_value[0] + string_value[1] + string_value[2] + "." + res print(three_string) def print_valid_ip_util(string_value: str): if len(string_value) < 4: return if len(string_value) == 4: print(print_util_min(string_value)) return def print_ip_v2(string_value, len_needed, output_string: str): if len_needed < 0: return if len_needed == 1: print(output_string + string_value) return if len_needed > len(string_value): # print(output_string + "." + string_value) return if len_needed == len(string_value): print(output_string + print_util_min(string_value)) return print_ip_v2(string_value[1:], len_needed - 1, output_string + string_value[0] + ".") if len(string_value) > 2: print_ip_v2(string_value[2:], len_needed - 1, output_string + string_value[0] + string_value[1] + ".") if len(string_value) > 3: print_ip_v2(string_value[3:], len_needed - 1, output_string + string_value[0] + string_value[1] + string_value[2] + ".") if __name__ == '__main__': print(print_util_min('123')) print_ip_v2('12345', 4, '')
b5e5368076b16def0635cfce2c673d80101760be
ivan-verges/BreastCancerClassifier
/script.py
1,202
3.609375
4
import codecademylib3_seaborn from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt #Load Breast Cancer data from imported dataset breast_cancer_data = load_breast_cancer() #Split data into Training Data, Validation Data, Training Labels and Validation Labels, 80% of all data to Traing and 20% to Validate (Test) training_data, validation_data, training_labels, validation_labels = train_test_split(breast_cancer_data.data, breast_cancer_data.target, test_size = 0.2, random_state = 100) #Finds the best K parameter and store it's value and it's scores best_k = 0 best_score = 0 k_list = range(1, 100) accuracies = [] for i in k_list: classifier = KNeighborsClassifier(n_neighbors = i) classifier.fit(training_data, training_labels) tmp = classifier.score(validation_data, validation_labels) accuracies.append(tmp) if(tmp > best_score): best_score = tmp best_k = i #Set plotter to show our model results as K parameter changes plt.title("Breast Cancer Classifier") plt.xlabel("K-Value") plt.ylabel("Accuracy") plt.plot(k_list, accuracies) plt.show()
9d40c94848ef76665c653b670715f0e08fff2248
90sidort/exercises_Python
/directions_Reduction.py
536
3.5625
4
# Description: https://www.codewars.com/kata/550f22f4d758534c1100025a # My solution: def dirReduc(arr): while True: if arr == []: return [] for x in range(0, len(arr)): if x + 1 == len(arr): return arr elif (arr[x] == 'NORTH' and arr[x+1] == 'SOUTH') or (arr[x] == 'SOUTH' and arr[x+1] == 'NORTH') or (arr[x] == 'WEST' and arr[x+1] == 'EAST') or (arr[x] == 'EAST' and arr[x+1] == 'WEST'): del arr[x] del arr[x] break
d074207560ea3b30430489e57386bee321b3a743
hasibzunair/randomfun
/algo/greedy.py
1,245
3.9375
4
''' Given a set of intervals L, find the min set of points so that each inteval is covered at least once by a given point. eg input: (1, 3), (2, 5), (3, 6) output: 3 Algo: - sort intervals in increasing order - for interval in interval-set add interval endpoint to set of points ''' def min_points(intervals): sorted_intvl = sorted(intervals, key=lambda x: x[1]) points = [sorted_intvl[0][-1]] for interv in sorted_intvl: if not(points[-1] >= interv[0] and points[-1] <= interv[-1]): points.append(interv[-1]) return points pts = [[2, 5], [1, 3], [3, 6]] #print(min_points(pts)) pts = [[4, 7], [1, 3], [2, 5], [5, 6]] #print(min_points(pts)) ''' Given an integer n, find maximum number of unique summands. e.g: input:n=8 output: [1 + 2 + 5] = 3 ''' def max_summands(n): summands = [] sum_summands = 0 next_int = 1 while sum_summands + next_int <= n: sum_summands += next_int summands.append(next_int) next_int += 1 # show values print(n, summands) # calc number of summands in the list #summands[-1] += n - summands num_of_summands = len(summands) return num_of_summands print(max_summands(8))