blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
1d8a72ca967b535316af5da98e010f349846da8c
tammytdo/Self_Paced-Online
/students/mkdir01/lesson03/list_lab.py
3,513
4.15625
4
#!/usr/bin/env python3 #SERIES 1 # Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”. fruits = ["Apples", "Pears", "Oranges", "Peaches"] # Display the list (plain old print() is fine…). print(fruits) # Ask the user for another fruit and add it to the end of the list. response_fruits = input("Type another fruit: ") fruits.append(response_fruits) # Display the list. print(fruits) # Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). Remember that Python uses zero-based indexing, so you will need to correct. response_num = input("Type a number: ") print(response_num) print(fruits[int(response_num) - 1]) # Add another fruit to the beginning of the list using “+” and display the list. fruits = ["Berries"] + fruits[:] print(fruits) # Add another fruit to the beginning of the list using insert() and display the list. fruits.insert(0, "Plums") print(fruits) # Display all the fruits that begin with “P”, using a for loop. for i in range(len(fruits)): if "P" in fruits[i]: print(fruits[i]) # SERIES 2 # Display the list. print(fruits) # Remove the last fruit from the list. fruits.pop() # Display the list. print(fruits) # Ask the user for a fruit to delete, find it and delete it. response_del = input("Type a fruit to delete: ") fruits.remove(response_del) # (Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences.) fruits = fruits[:] * 2 while True: # we'll break out of loop once we've found a match and deleted the fruits match = 0 response_new_fruit = input("Type a new fruit to delete: ") for n in range(len(fruits)): if response_new_fruit == fruits[n]: match += 1 # counting number of matches makes this extensible to a list with any # of repetitions if not match: print("Fruit not found in list.") match -= 1 # sets match to -1 to avoid the break statement while match > 0: fruits.remove(response_new_fruit) match -= 1 if not match: break # breaks the top loop if match == 0, i.e. if all found fruits were removed # SERIES 3 # Ask the user for input displaying a line like “Do you like apples?” for each fruit in the list (making the fruit all lowercase). tracker = [] #this will track which fruits to remove() for fruit in fruits: response_r = input("Do you like {}? ".format(fruit.lower())) # For any answer that is not “yes” or “no”, prompt the user to answer with one of those two values (a while loop is good here) while (response_r.lower() != "yes"): # i.e., Yes, YES, yes, etc. if response_r.lower() == "no": tracker.append(fruit) # if we remove() now, we will be off by one in our list break else: print("Answer with \"yes\" or \"no\" only.") response_r = input("Do you like {}? ".format(fruit.lower())) # For each “no”, delete that fruit from the list. for fruit in tracker: fruits.remove(fruit) # Display the list. print(fruits) #SERIES 4 #Make a copy of the list and reverse the letters in each fruit in the copy. fruits_copy = [] for i in range(len(fruits)): fruits_copy.append(fruits[i][::-1]) # append(fruits_list[a_particular_fruit[read backwards]]) #Delete the last item of the original list. Display the original list and the copy. fruits.pop() print(fruits) print(fruits_copy)
16f91cade4d7a6e4c5a362c23438e72bf84390a7
jerzycup/fractions
/fraction.py
2,303
4.1875
4
""" This file contains definition of a fraction class. You should put complete class here. It must be named `Fragion` and must have the following properties: - four basic mathematical operators defined; - elegant conversion to string in the form '3/2'; - simplification and clean-up on construction: both attribute divided by the greatest common divisor sign in the nominator, denominator not zero (ValueError should be raised in such case), both attributes must be integers (ValueError if not), - method `value` returning float value of the fraction. """ from math import gcd class Fraction(object): """ Fraction class. """ def __init__(self, nom, denom): if denom == 0: raise ValueError('denominator cannot be 0.') self._nom = int(nom) self._denom = int(denom) self.simplify() def __str__(self): return ('{0.nom}/{0.denom}'.format(self)) def __mul__(self, other): return Fraction(self.nom * other.nom, self.denom * other.denom) def __truediv__(self, other): return Fraction(self.nom * other.denom, self.denom * other.nom) def __add__(self, other): return Fraction(self.nom*other.denom + other.nom*self.denom, self.denom *other.denom) def __sub__(self, other): return Fraction(self.nom * other.denom - other.nom * self.denom, self.denom * other.denom) def __pow__(self, power, modulo=None): return Fraction(self.nom**power, self.denom**power) def __repr__(self): return f"Fraction({self.nom}, {self.denom})" def __eq__(self, other): return self.nom == other.nom and self.denom == other.denom def value(self): return self.nom/self.denom def simplify(self): nom = self._nom denom = self._denom self._denom = int(denom / gcd(nom, denom)) self._nom = int(nom/gcd(nom, denom)) @property def denom(self): return self._denom @denom.setter def denom(self, value): if value == 0: raise ValueError('denominator cannot be 0.') self._denom = int(value) self.simplify() @property def nom(self): return self._nom @nom.setter def nom(self, value): self._nom = int(value) self.simplify()
0e720665d741634b9a82958c626996afdc1d14f1
nonyeezekwo/cs-module-project-algorithms
/moving_zeroes/moving_zeroes.py
766
4.21875
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): # Your code here # check to see if you are not a zero cur_index = 0 zero_count = 0 while cur_index < len(arr): if arr[cur_index] != 0: # count how many zeros you have passed swap_index = cur_index - zero_count # swap between that zero and where you are not a zero arr[swap_index], arr[cur_index] = arr[cur_index], arr[swap_index] else: zero_count += 1 cur_index += 1 return arr if __name__ == '__main__': # Use the main function here to test out your implementation arr = [0, 3, 1, 0, -2] print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
80abe80821720f8aa95efbf8376c1be140d08b9d
erinmsong/Hangman
/HangmanGame.py
1,990
3.84375
4
""" Erin Song 7.12.21 Hangman Game (fruits) """ import random MAX_STRIKES = 5 def get_random_word(): words = ['apple', 'banana', 'coconut', 'dill', 'eggplant', 'fruit', 'grape', 'mango', 'pear', 'strawberry'] ind = random.randint(0, len(words)-1) return words[ind].upper() def update_blanks(gues, targ, t_print): index = 0 for i in targ: if(i == gues): t_print[index] = i.upper() index = index + 1 return t_print def update_num_strikes(gues, targ, n_strikes): if gues in targ: n_strikes else: n_strikes = n_strikes + 1 return n_strikes def print_word(t_print): for i in range(len(t_print)): print(t_print[i] , end = ' ') def print_strikes(n_strikes): print("\nStrikes: ", end = ' ') for i in range(n_strikes): print("X" , end = ' ') def make_array(targ): arr = [] for i in targ: arr.append("_") return arr def get_input(): g = str(input("\nGuess a letter from A-Z: ")).upper() while(g.isalpha() == False): g = str(input("\nPlease try again with a letter: ")).upper() return g def get_keep_going(t_print, n_strikes): if("_" not in t_print): return False elif(n_strikes < MAX_STRIKES): return True elif(n_strikes > MAX_STRIKES): return False def main(): target = get_random_word() to_print = make_array(target) num_strikes = 0 print_word(to_print) while(get_keep_going(to_print, num_strikes)): print_strikes(num_strikes) guess = get_input() num_strikes = update_num_strikes(guess, target, num_strikes) print_word(update_blanks(guess, target, to_print)) if("_" not in to_print): print("\nYou won :)") elif("_" in to_print): print("\nStrikes:", end = ' ') for i in range(MAX_STRIKES): print("X", end = ' ') print("\nYou lost :(") print("The word was '" + target + "'") main()
7774128d24471a95359e15439f34b30457e3c7ef
lisha1992/LeetCode
/leetcode-4.py
1,985
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 23 14:20:00 2016 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 """ ## Idea(binary search, recursive): # 求A,B的中位数即求两个list排序后第(m+n)/2 小的数,于是将问题转化为求第k小的数问题,k=(m+n)/2 # assume that A=[A1,A2,A3,A4,....Am], B[B1,B2,B3,B4,...Bn] # compare A[k/2-1] and B[k/2-1]: # if A[k/2-1]<B[k/2-1]: # 第k小的数不可能出现在A[0:k/2-1],可以将A[0:k/2-1]的数ignore, # 求A[k/2:m]与B[0,k/2-1]的第(k-k/2+1)小的数 class Solution: def get_k_small(self, A, B, k): A_len=len(A) B_len=len(B) if A_len > B_len: return self.get_k_small(B, A, k) if A_len==0: return B[k-1] if k==1: return min(A[0],B[0]) A_pt=min(k/2, A_len) B_pt=k-A_pt if A[A_pt-1]<=B[B_pt-1]: return self.get_k_small(A[A_pt:], B, B_pt) else: return self.get_k_small(A, B[B_pt:], A_pt) def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ len1=len(nums1) len2=len(nums2) k=(len1+len2)/2 if (len1+len2)%2==1: return self.get_k_small(nums1,nums2,k+1) else: return 0.5*( self.get_k_small(nums1,nums2, k) + self.get_k_small(nums1,nums2, k+1 )) def __init__(self,nums1,nums2): self.nums1=nums1 self.nums2=nums2 self.ans=self.findMedianSortedArrays(nums1, nums2) def test(self): print self.ans sol = Solution([2,3,4],[1]) sol.test()
361c2a5a213c47df9777107daebbc19ab18e7e31
NobuhiroHoshino/stock_and_python_book
/chapter2/csv_to_db.py
1,346
3.765625
4
# -*- coding: utf-8 -*- import csv import glob import datetime import os import sqlite3 def generate_price_from_csv_file(csv_file_name, code): with open(csv_file_name, encoding="shift_jis") as f: reader = csv.reader(f) next(reader) # 先頭行を飛ばす for row in reader: d = datetime.datetime.strptime(row[0], '%Y/%m/%d').date() #日付 o = float(row[1]) # 初値 h = float(row[2]) # 高値 l = float(row[3]) # 安値 c = float(row[4]) # 終値 v = int(row[5]) # 出来高 yield code, d, o, h, l, c, v def generate_from_csv_dir(csv_dir, generate_func): for path in glob.glob(os.path.join(csv_dir, "*.T.csv")): file_name = os.path.basename(path) code = file_name.split('.')[0] for d in generate_func(path, code): yield d def all_csv_file_to_db(db_file_name, csv_file_dir): price_generator = generate_from_csv_dir(csv_file_dir, generate_price_from_csv_file) conn = sqlite3.connect(db_file_name) with conn: sql = """ INSERT INTO raw_prices(code,date,open,high,low,close,volume) VALUES(?,?,?,?,?,?,?) """ conn.executemany(sql, price_generator)
41f78e09b087ffea0bc830eab6503acc8b00eb57
Telcoltar/AdventOfCodeDay16
/Field.py
1,070
3.515625
4
class Field: def __init__(self, identifier: str, first_range: str, second_range: str): self.identifier = identifier first_range_first_number: str first_range_second_number: str second_range_first_number: str second_range_second_number: str first_range_first_number, first_range_second_number = first_range.split("-") second_range_first_number, second_range_second_number = second_range.split("-") self.first_range = (int(first_range_first_number.strip()), int(first_range_second_number.strip())) self.second_range = (int(second_range_first_number.strip()), int(second_range_second_number.strip())) def is_number_valid(self, number: int): return ((self.first_range[0] <= number <= self.first_range[1]) or (self.second_range[0] <= number <= self.second_range[1])) def __str__(self): return f"{self.identifier}, {self.first_range}, {self.second_range}" def __repr__(self): return f"{self.identifier}, {self.first_range}, {self.second_range}"
9d32a76a46de5c7b974f70e9bce07c58f1135efe
VasilenkoStep/DangerTerritory
/home_work_5/Zadacha_2.py
389
3.609375
4
import random print("Введите число, которое создаст МОЩНЕЙШИЙ СПИСОК ") n = [random.randint(0,10) for _ in range(15)] print ("Получившийся список:" + " "+ str(n)) while 0 in n: n.remove(0) print(print ("Получившийся список без нулей:" + " "+ str(n))) print ("Задание 2 выполнено :D")
7ca752b80e8c430cf614c7d05e4acc221ee38f02
willbryk720/cracking-the-coding-interview-python
/chap_01_arrays_and_strings/is_unique.py
1,089
4.28125
4
''' Implement an algorithm to determine of a string has all unique characters. A: Create hashtable of possible ascii characters. Run through characters and check if character has already been hashed. ''' def is_unique(s): chars = [False] * 256 for c in s: ascii_value = ord(c) if chars[ascii_value]: return False else: chars[ascii_value] = True return True ''' Followup: What if you cannot use additional data structures? A: We can sort the string and check for the same character next to each other. Note this assumes sort does not use Other data structures ''' def is_unique2(s): list(s).sort() for i in range(len(s) - 1): if s[i] == s[i + 1]: return False return True solutions = [["", True],["h", True], ["hh", False], ["hellothere", False], ["hellllothere", False], ["ethr", True]] for solution in solutions: print solution, is_unique(solution[0]), is_unique2(solution[0]) assert is_unique(solution[0]) == solution[1] assert is_unique2(solution[0]) == solution[1]
d0efdd00184e2592b1c6802f24a2f69e8f63e77b
PedroHTeixeira/Nautilus_Cap
/Python OO/brasileirao.py
1,451
4.03125
4
# PYTHON OO 17/11/2020 17:00 Part-1 HW class Team(): def __init__(self,name,punctuation,matches,victories,draws,defeats): self.name = name self.punctuation = punctuation self.matches=matches self.victories=victories self.draws=draws self.defeats=defeats def __repr__(self): r = "The team {} has {} points. It has played {} matches and there were {} wins, {} draws and {} losses".format(self.name,self.punctuation,self.matches,self.victories,self.draws,self.defeats) return r def __add__(self,other): s=self.punctuation+other.punctuation return s def __gt__(self,other): gt = self.punctuation>other.punctuation return gt def __lt__(self,other): lt = self.punctuation<other.punctuation return lt def __sub__(self, other): s=self.punctuation-other.punctuation return s team1=Team("Vasco",22,"19","6","4","9") team2=Team("Flamengo",36,"21","10","6","5") team3=Team("Fluminense",32,"21","9","5","7") team4=Team("Botafogo",20,"20","3","11","6") team5=Team("Goias",12,"19","2","6","11") team6=Team("Atlético-Mg",38,"20","12","2","6") team7=Team("Sport-Recife",25,"21","7","4","10") teams=[team1,team2,team3,team4,team5,team6,team7] teams.sort() print(teams) s= team2+team1 d= team2-team1 print("The sum of Vasco and Flamengo is :",s) print("The subtraction between Vasco and Flamengo is :",d)
ab6116d3c73a45d72edf5808adc0372e736687a0
glissader/Python
/ДЗ Урок 6/main3.py
1,769
3.96875
4
# Реализовать базовый класс Worker (работник). # - определить атрибуты: name, surname, position (должность), income (доход); # - последний атрибут должен быть защищённым и ссылаться на словарь, содержащий # элементы: оклад и премия, например, {"wage": wage, "bonus": bonus}; # - создать класс Position (должность) на базе класса Worker; # - в классе Position реализовать методы получения полного имени сотрудника # (get_full_name) и дохода с учётом премии (get_total_income); # - проверить работу примера на реальных данных: создать экземпляры класса Position, # передать данные, проверить значения атрибутов, вызвать методы экземпляров. class Worker: def __init__(self, name: str, surname: str, position: str, income: dict): self.name = name self.surname = surname self.position = position self._income = income class Position(Worker): def __init__(self, name: str, surname: str, position: str, income: dict): super().__init__(name, surname, position, income) def get_full_name(self): return f'{self.name} {self.surname}' def get_total_income(self): return self._income.get('wage') + self._income.get('bonus') p = Position(name='Vasiliy', surname='Pupkin', position='manager', income={'wage': 120000, 'bonus': 1000}) print(f'{p.get_full_name()}, {p.position}, total income = {p.get_total_income()}')
011469992c360c67b091e9de8573b96f71c7649f
abrosua/ml-with-numpy
/benchmarks/pca_bench.py
1,333
3.578125
4
import numpy as np from sklearn.decomposition import PCA as PCA_sk from models.pca import PCA as PCA_np if __name__ == "__main__": num_components = 2 A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype="float") print(A) # create the PCA instance print("\n\nPCA with sklearn..............") pca_sk = PCA_sk(n_components=num_components) pca_sk.fit(A) # access values and vectors print("Components:") print(pca_sk.components_) print("Explained variance:") print(pca_sk.explained_variance_) # transform data A_sk = pca_sk.transform(A) print("PCA results with sklearn:") print(A_sk) # PCA with numpy print("\n\nPCA with NumPy..............") pca_np = PCA_np(n_components=num_components) pca_np.fit(A) # access values and vectors print("Components:") print(pca_np.components_) print("Explained variance:") print(pca_np.explained_variance_) # transform data A_np = pca_np.transform(A) print("PCA results with sklearn:") print(A_np) # Difference diff = (np.abs(A_np) - np.abs(A_sk)) print(f"\n\nResult difference:") print(diff) # asserting the components assert np.allclose(abs((pca_sk.components_ * pca_np.components_).sum(1)), 1)
2338bacf5ea87613cd951cf37475c98efbeb833a
rocketpy/tricks
/API_example.py
785
3.640625
4
import json import requests url = "https://api.github.com" response = requests.get(url) print("Status code is : ", response.status_code) response_json = response.json() print(response_json) # working with JSON # save data to JSON def storeJSON(fileName, data = {}): with open(fileName, 'w') as fd: json.dump(data, fd, indent = 4, separators = (',', ': ')) # load data from a JSON file def loadJSON(fileName): with open(fileName) as fd: data = json.load(fd) print(data) return data if __name__ == '__main__': data = loadJSON('file_name.json') print(data['menu']['value']) data['menu']['value'] = 'movie' storeJSON('file_name.json', data) print() loadJSON('file_name.json') print(data['menu']['value'])
235f34a09178932a48e5f0000b42f203dee00bf8
RAVURISREESAIHARIKRISHNA/Python-2.7.12-3.5.2-
/Resizing_Labels.py
537
3.875
4
from Tkinter import* obj=Tk() Label1 = Label(obj,text="LABEL 1",bg="black",fg="white") Label2 = Label(obj,text="LABEL 2",bg="yellow",fg="blue") Label3 = Label(obj,text="LABEL 3",bg="green",fg="red") Label4 = Label(obj,text="LABEL 4",bg="red",fg="black") BottomFrame = Frame(obj) BottomFrame.pack(side=BOTTOM) Button1 = Button(BottomFrame,text="IT IS A BUTTON !!!",bg="white",fg="red") Button1.pack() Label1.pack() Label2.pack(fill=X) Label3.pack(side=LEFT,fill=Y) Label4.pack(side=RIGHT,fill=Y) obj.mainloop()
357b8fcfdde35741a07b7a0d193ce8e4e0b9e4e4
hafeez1988/msc-ai-assignment-2
/AIAssignment2/AlgoExperiment.py
9,344
3.953125
4
#!/usr/bin/python ### Data Structures # # Sample current states for testing is shown below. # Add following lines one by one into state.txt for testing: # # 8 1 7 2 4 6 3 0 5 # 1 0 7 8 2 6 3 4 5 # 8 1 7 0 2 6 3 4 5 # 8 1 7 3 2 6 4 0 5 # 8 1 7 0 2 6 3 4 5 # 8 1 7 0 2 6 3 4 5 # 8 1 7 2 6 0 3 4 5 # 8 0 7 2 1 6 3 4 5 # 8 1 7 2 4 6 3 0 5 # # The 0 denotes the empty space. goal_state = [1, 2, 7, 8, 4, 6, 3, 0, 5] import time import tracemalloc from pythonds.basic.stack import Stack def move_up(state): """Moves the blank tile up on the board. Returns a new state as a list.""" # Perform an object copy new_state = state[:] index = new_state.index(0) # Sanity check if index not in [0, 3, 6]: # Swap the values. temp = new_state[index - 1] new_state[index - 1] = new_state[index] new_state[index] = temp return new_state else: # Can't move, return None (Pythons NULL) return None def move_down(state): """Moves the blank tile down on the board. Returns a new state as a list.""" # Perform object copy new_state = state[:] index = new_state.index(0) # Sanity check if index not in [2, 5, 8]: # Swap the values. temp = new_state[index + 1] new_state[index + 1] = new_state[index] new_state[index] = temp return new_state else: # Can't move, return None. return None def move_left(state): """Moves the blank tile left on the board. Returns a new state as a list.""" new_state = state[:] index = new_state.index(0) # Sanity check if index not in [0, 1, 2]: # Swap the values. temp = new_state[index - 3] new_state[index - 3] = new_state[index] new_state[index] = temp return new_state else: # Can't move it, return None return None def move_right(state): """Moves the blank tile right on the board. Returns a new state as a list.""" # Performs an object copy. Python passes by reference. new_state = state[:] index = new_state.index(0) # Sanity check if index not in [6, 7, 8]: # Swap the values. temp = new_state[index + 3] new_state[index + 3] = new_state[index] new_state[index] = temp return new_state else: # Can't move, return None return None def create_node(state, parent, operator, depth, cost): return Node(state, parent, operator, depth, cost) def expand_node(node): """Returns a list of expanded nodes""" expanded_nodes = [] expanded_nodes.append(create_node(move_up(node.state), node, "u", node.depth + 1, 0)) expanded_nodes.append(create_node(move_down(node.state), node, "d", node.depth + 1, 0)) expanded_nodes.append(create_node(move_left(node.state), node, "l", node.depth + 1, 0)) expanded_nodes.append(create_node(move_right(node.state), node, "r", node.depth + 1, 0)) # Filter the list and remove the nodes that are impossible (move function returned None) expanded_nodes = [node for node in expanded_nodes if node.state != None] # list comprehension! return expanded_nodes def bfs(start, goal): """Performs a breadth first search from the start state to the goal""" # A list (can act as a queue) for the nodes. goal = goal start_node = create_node(start, None, None, 0, 0) fringe = [] fringe.append(start_node) current = fringe.pop(0) path = [] while (current.state != goal): fringe.extend(expand_node(current)) current = fringe.pop(0) while (current.parent != None): path.insert(0, current.operator) current = current.parent return path pass def dfs(start, goal, depth=10): start_node = create_node(start, None, None, 0, 0) fringe_stack = Stack() fringe_stack.push(start_node) current = fringe_stack.pop() path = [] while (current.state != goal): temp = expand_node(current) for item in temp: fringe_stack.push(item) current = fringe_stack.pop() if (current.depth > 10): return None while (current.parent != None): path.insert(0, current.operator) current = current.parent return path def greedy(start, goal): start_node = create_node(start, None, None, 0, 0) fringe = [] path = [] fringe.append(start_node) current = fringe.pop(0) while (current.state != goal): fringe.extend(expand_node(current)) for item in fringe: h(item, goal) fringe.sort(key=lambda x: x.heuristic) current = fringe.pop(0) while (current.parent != None): path.insert(0, current.operator) current = current.parent return path def a_star(start, goal): start_node = create_node(start, None, None, 0, 0) fringe = [] path = [] fringe.append(start_node) current = fringe.pop(0) while (current.state != goal): fringe.extend(expand_node(current)) for item in fringe: h(item, goal) item.heuristic += item.depth fringe.sort(key=lambda x: x.heuristic) current = fringe.pop(0) while (current.parent != None): path.insert(0, current.operator) current = current.parent return path def h(state, goal): dmatch = 0 for i in range(0, 9): if state.state[i] != goal[i]: dmatch += 1 state.heuristic = dmatch # Node data structure class Node: def __init__(self, state, parent, operator, depth, cost): # Contains the state of the node self.state = state # Contains the node that generated this node self.parent = parent # Contains the operation that generated this node from the parent self.operator = operator # Contains the depth of this node (parent.depth +1) self.depth = depth # Contains the path cost of this node from depth 0. Not used for depth/breadth first. self.cost = cost self.heuristic = None def readfile(filename): f = open(filename) data = f.read() # Get rid of the newlines data = data.strip("\n") # Break the string into a list using a space as a seperator. data = data.split(" ") state = [] for element in data: state.append(int(element)) print('state: ', state) print('goal: ', goal_state) return state def validate_response(result): if result == None: print("No solution found") elif result == [None]: print("Start node was the goal!") else: print(len(result), " moves") def bfs_matrics_collector(starting_state): print("") print("************ RUNNING BFS ALGORITHM ************") start_time = time.perf_counter_ns() tracemalloc.start() result = bfs(starting_state, goal_state) validate_response(result) current, peak = tracemalloc.get_traced_memory() print(f"Current memory: {current / 10 ** 6}MB | Peak memory: {peak / 10 ** 6}MB") tracemalloc.stop() elapsed = (time.perf_counter_ns() - start_time) print("Time elapsed(nanoseconds): ", elapsed) print("***********************************************") print("") def dfs_matrics_collector(starting_state): print("") print("************ RUNNING DFS ALGORITHM ************") start_time = time.perf_counter_ns() tracemalloc.start() result = dfs(starting_state, goal_state) validate_response(result) current, peak = tracemalloc.get_traced_memory() print(f"Current memory: {current / 10 ** 6}MB | Peak memory: {peak / 10 ** 6}MB") tracemalloc.stop() elapsed = (time.perf_counter_ns() - start_time) print("Time elapsed(nanoseconds): ", elapsed) print("***********************************************") print("") def greedy_matrics_collector(starting_state): print("") print("************ RUNNING GREEDY ALGORITHM *********") start_time = time.perf_counter_ns() tracemalloc.start() result = greedy(starting_state, goal_state) validate_response(result) current, peak = tracemalloc.get_traced_memory() print(f"Current memory: {current / 10 ** 6}MB | Peak memory: {peak / 10 ** 6}MB") tracemalloc.stop() elapsed = (time.perf_counter_ns() - start_time) print("Time elapsed(nanoseconds): ", elapsed) print("***********************************************") print("") def a_star_matrics_collector(starting_state): print("") print("************ RUNNING A* ALGORITHM *************") start_time = time.perf_counter_ns() tracemalloc.start() result = a_star(starting_state, goal_state) validate_response(result) current, peak = tracemalloc.get_traced_memory() print(f"Current memory: {current / 10 ** 6}MB | Peak memory: {peak / 10 ** 6}MB") tracemalloc.stop() elapsed = (time.perf_counter_ns() - start_time) print("Time elapsed(nanoseconds): ", elapsed) print("***********************************************") print("") def main(): starting_state = readfile(r"state.txt") bfs_matrics_collector(starting_state) dfs_matrics_collector(starting_state) greedy_matrics_collector(starting_state) a_star_matrics_collector(starting_state) if __name__ == "__main__": main()
f40ff81d77a8c4029f77cc6422fc16afb46bae8b
enrico-spada/py4e
/access_data_web/xml_parse_2.py
600
3.625
4
import xml.etree.ElementTree as ET input = ''' <stuff> <users> <user x="2"> <id>001</id> <name>Chuck</name> </user> <user x="7"> <id>009</id> <name>Brent</name> </user> </users> </stuff>''' stuff = ET.fromstring(input) #let's search for all the user tags below users user_list = stuff.findall("users/user") #note that it returns a list of tags! not a list of strings print("User count:", len(user_list)) for item in user_list: print("Name: ", item.find("name").text) print("Id: ", item.find("id").text) print("Attribute: ", item.get("x"))
d09a10a4770405d70d4fd4dc5657297a45ccd6f8
joshnroy/computationalLinguisticsIndependentStudy
/pythonSecondAttempt/unigramGenerator.py
702
3.71875
4
# Declare input text file textfile = "furniture.txt" # Create a dictionary to store unigrams Unigrams = {} # Open and read file for line in open(textfile): line = line.rstrip() # tokenize the text tokens = line.split() #loop over the unigrams for word in tokens: # Check to see if the unigram already exists in the dict. If it does, increase its count, else add it if word in Unigrams: Unigrams[word] += 1 else: Unigrams[word] = 1 # Write Unigrams to output file output_file = open('unigrams.txt', 'w') for unigram in Unigrams: count = Unigrams[unigram] output_file.write(str(count)+'\t'+unigram+'\n') output_file.close()
e02f13a263881ff8441f1940203eada223f3ac7d
lambainsaan/Drone-CSV-and-KML-Generator
/code/srt.py
1,681
3.515625
4
""" This module contains functions to read and parse the srt file for cordinates. """ def path_from_srt_file(srt_file): """Reads all the srt files in the path and returns the latitude and longitude of the path of the drone as a list Arguments: srt_file_path {string} -- The path to be scanned for the srt files Returns: list -- The path of the drone in all different srt files stiched together """ import pysrt import logging import helper path = [] # for every srt file open it and # for every subtitle in subtitles # append the cordinate to the path try: for subt in pysrt.open(srt_file): try: lon_lat = get_lat_longitude(subt.text) except ValueError: logging.info(srt_file + " file contains subtitle in incorrect form.") continue if not helper.is_lon_lat(lon_lat[0], lon_lat[1]): logging.info( srt_file + " file contains lon lat out of bounds.") continue path.append(lon_lat) except FileNotFoundError: logging.error(srt_file + " does not exist.") return path def get_lat_longitude(text): """Gets the latitude and longitude from a line's text representation Arguments: text {string} -- The text in the format "lat, long" Returns: Tuple - Containing the float based latitude and longitude, throws ValueError if text does not contain number """ arr = text.split(',') return (float(arr[0]), float(arr[1]))
f3a7116f908005874f8115b7476d32d1c295adfa
aswinichejarla/pythonprogramm
/pl55.py
116
3.703125
4
s1,s2=map(str,raw_input().split()) s11=s1.lower() s12=s2.lower() if(s11==s12): print "yes" else: print "no"
e7eff18c2c7aff6377beddd975c803c498790a54
vishalkumar95/ECE-4802-Cryptography-and-Communication-Security
/Vigenere_Cipher.py
1,998
3.875
4
# This function is an implementation of the Vigenere cipher algorithm. def decryptVigenere(ciphertext, key): ciphertextbreak = [] ciphertextbreakextra = [] finalplaintext = ' ' Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' smallLetters = 'abcdefghijklmnopqrstuvwxyz' keylength = len(key) ciphertextlength = len(ciphertext) modval = ciphertextlength % keylength if (modval == 0): for i in range(0, ciphertextlength, keylength): ciphertextbreak.append(ciphertext[i : i + keylength]) for i in range(0, len(ciphertextbreak)): for j in range(0, keylength): indkey = smallLetters.index(key[j]) indcipher = Letters.index(ciphertextbreak[i][j]) newindcipher = indcipher - indkey modindcipher = newindcipher % 26 finalplaintext = finalplaintext + Letters[modindcipher] elif (modval != 0): for i in range(0, ciphertextlength - modval, keylength): ciphertextbreak.append(ciphertext[i : i + keylength]) for i in range(0, len(ciphertextbreak)): for j in range(0, keylength): indkey = smallLetters.index(key[j]) indcipher = Letters.index(ciphertextbreak[i][j]) newindcipher = indcipher - indkey modindcipher = newindcipher % 26 finalplaintext = finalplaintext + Letters[modindcipher] ciphertextbreakextra.append(ciphertext[-modval:]) for i in range(0, len(ciphertextbreakextra)): for j in range(0, modval): indkey = smallLetters.index(key[j]) indcipher = Letters.index(ciphertextbreakextra[i][j]) newindcipher = indcipher - indkey modindcipher = newindcipher % 26 finalplaintext = finalplaintext + Letters[modindcipher] print (finalplaintext)
37ce54c9e12405b79927a59738cd656acbda663f
mcmoralesr/Learning.Python
/Code.Forces/P0287A_IQ_Test.py
564
3.5
4
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def can_paint(wall: list) -> bool: for i in range(3): for j in range(3): temp = wall[i][j] + wall[i + 1][j] + wall[i][j + 1] + wall[i + 1][j + 1] if temp.count('.') != temp.count('#'): return True return False def main() -> int: wall = [input(), input(), input(), input()] print('YES' if can_paint(wall) else 'NO') return 0 if __name__ == '__main__': exit(main())
178a0896c850acb06ec008709dc06e4fbe1907fc
angusmit/Hackerrank
/String Formatting.py
636
4.125
4
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/python-string-formatting/problem # Difficulty: Easy # Max Score: 10 # Language: Python # ======================== # Solution # ======================== def print_formatted(number): # your code goes here width=len(bin(number)[2:]) for i in range(1,number+1): print(str(i).rjust(width),oct(i).replace("0o", "").rjust(width),hex(i).replace("0x", "").upper().rjust(width),bin(i).replace("0b", "").rjust(width)) if __name__ == '__main__': n = int(input()) print_formatted(n)
3c8575707937d05c78722ce4f2cd1017f86524d2
jmarcelonunes/PseudoSO
/modules/file_system.py
3,984
3.53125
4
# -*- coding: utf-8 -*- ''' Módulo do Sistema de Arquivos ''' ''' Classe FileSystem ''' from modules import process class FileSystem(): def __init__(self, filename): self.disk = [] self.ftable = {} with open(filename, 'r') as f: # Leitura de parâmetros do sistema de arquivos disk_size = int(f.readline()) self.disk = disk_size * [None] # Criação dos arquivos iniciais quant_files = int(f.readline()) for _ in range(quant_files): # Obtém informações de cada arquivo new_file_info = f.readline().split(',') map(str.strip, new_file_info) new_file = File( new_file_info[0], # Nome do arquivo int(new_file_info[2]), # Tamanho do arquivo start = int(new_file_info[1]) # Primeiro bloco ) # Adiciona no sistema self.__add_file(new_file) # Cria a estrutura de arquivo e adiciona no sistema def create_file(self, instruction, process): name = instruction.filename size = instruction.filesize if(name in self.ftable): raise Exception("Arquivo com nome inválido") else: if not self.__add_file(File(name, size, process)): raise Exception("O processo %d não pode criar o arquivo %c por falta de espaço" %(process.pid, name)) file = self.ftable[name] return file # Deleta um arquivo do sistema pelo nome # Além de verificar as permissões de acesso def delete_file(self, instruction, process): name = instruction.filename if(name not in self.ftable): raise Exception("Arquivo não encontrado") file = self.ftable[name] if( process.priority != 0 and file.process != process): raise Exception("Processo %d não possui permissão de acesso para o arquivo %c" %(process.pid, name)) if not self.__remove_file(file): raise Exception("Erro ao remover arquivo %d", name) # Adiciona um arquivo no sistema def __add_file(self, file): if(file.start is None): idx = self.__find_space(file.size) if idx is not None: file.set_start(idx) else: return False self.disk[file.start : file.end] = file.size * file.name self.ftable[file.name] = file return True # Remove um arquivo do sistema def __remove_file(self, file): if(file.name not in self.ftable): return False self.disk[file.start : file.end] = file.size * [None] del self.ftable[file.name] return True # Obtém posição inicial de bloco refêrente a um # espaço no disco de determinado tamanho def __find_space(self, size): space_count = 0 for idx, f in enumerate(self.disk): if f is None: space_count += 1 if space_count == size: return idx - (size - 1) else: space_count = 0 return None def __str__(self): string = 'Mapa de ocupação do disco\n' string += '\n0\t|' for idx, block in enumerate(self.disk): if idx % 10 == 0 and idx != 0: string += f'\n{idx}\t|' if block is None: string += ' |' else: string += block + '|' string += '\n' return string class File(): def __init__(self, name, size, process = None, start = None): self.name = name self.start = start self.size = size self.process = process if start is None: self.end = None else: self.end = start + size def set_start(self, idx): self.start = idx self.end = self.start + self.size
51314de1a5a1c59e87bc70e823d07dedf0dbafbd
Diakakodo/classrooms
/api/BST.py
3,242
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ November 2018 BST: S2#-API """ from algopy import bintree # BST -> list def __bst2list(B, L): if B != None: __bst2list(B.left, L) L.append(B.key) __bst2list(B.right, L) def bst2list(B): L = [] __bst2list(B, L) return L # list -> BST: warning, works only with strictly increasing lists! # warning: we work on [left, right[ here! def __list2bst(L, left, right): if left == right: return None else: mid = left + (right - left) // 2 B = bintree.BinTree(L[mid], None, None) B.left = __list2bst(L, left, mid) B.right = __list2bst(L, mid+1, right) return B #or def __list2bst(L, left, right): if left == right: return None else: mid = left + (right - left) // 2 return bintree.BinTree(L[mid], __list2bst(L, left, mid), __list2bst(L, mid+1, right)) def list2bst(L): return __list2bst(L, 0, len(L)) # bonus: try to avoid the problem with not strictly increasing lists # first version: with an "ugly" loop... (a nicer version?) def __list2bst2(L, left, right): if left == right: return None else: mid = left + (right - left) // 2 while mid < right - 1 and L[mid] == L[mid + 1]: mid += 1 return bintree.BinTree(L[mid], __list2bst2(L, left, mid), __list2bst2(L, mid+1, right)) def list2bst2(L): return __list2bst2(L, 0, len(L)) # test def __testbst(B, inf, sup): if B == None: return True else: if B.key > inf and B.key <= sup: return __testbst(B.left, inf, B.key) \ and __testbst(B.right, B.key, sup) else: return False def testbst(B): return __testbst(B, -float('inf'), float('inf')) # Researches def minBST(B): """ B != None """ if B.left == None: return B.key else: return minBST(B.left) def maxBST(B): """ B != None """ while B.right != None: B = B.right return B.key def searchBST(B, x): if B == None or B.key == x: return B else: if x < B.key: return searchBST(B.left, x) else: return searchBST(B.right, x) def searchBST_iter(B, x): while B != None and B.key != x: if x < B.key: B = B.left else: B = B.right return B # insertions def leaf_insert(B, x): if B == None: return bintree.BinTree(x, None, None) else: if x <= B.key: B.left = leaf_insert(B.left, x) else: B.right = leaf_insert(B.right, x) return B def leaf_insert_iter(B, x): new = bintree.BinTree(x, None, None) P = None T = B while T != None: P = T if x <= T.key: T = T.left else: T = T.right if P == None: return new else: if x <= P.key: P.left = new else: P.right = new return B
1a9d8b14c31d86db3cc0a1d7e5255d8d33a782df
kamit17/Python
/Think_Python/Chp4/Examples/distance_between_points.py
340
4.25
4
def distance(x1,y1,x2,y2): """ Program to find distance between 2 points given by the coordinates using Pythagorean theorem sqrt((x2-x1)**2 + (y2-y1)**2). """ dx = x2-x1 dy = y2 - y1 dsquared = dx + dx + dy + dy result = dsquared**0.5 return result # returns a float value print(distance(1,2,4,6))
33b8797da617ea26336ca43317ace8149e550132
ArtemYurlov/ucl_MachineVision
/01_FittingProbDistribs_Python_mysol/log_normal.py
575
3.578125
4
import numpy as np from normal import normal def log_normal(X, mu, sigma): """Return log-likelihood of data given parameters" Computes the log-likelihood that the data X have been generated from the given parameters (mu, sigma) of the one-dimensional normal distribution. Args: X: vector of point samples mu: mean sigma: standard deviation Returns: a scalar log-likelihood """ N = len(X) loglik = -(N/2)*np.log(2*np.pi) - (N/2)*np.log(sigma**2) - (1/(2*sigma**2))*(np.sum((X-mu)**2)) return loglik
2736f12ae3af8b2bff5fc0aa90dcc8ee89c34399
twinkle2002/Python
/operator_dunder.py
911
4.125
4
class Employee: no_of_leaves = 8 def __init__(self, name, salary, role): #Dunder method self.name = name self.salary = salary self.role = role def printdetails(self): return f"name is {self.name}. salary is {self.salary}. and role is {self.role}" @classmethod def change_leaves(cls, newleaves): cls.no_of_leaves = newleaves def __add__(self, other): #used for operator overloading return self.salary + other.salary def __truediv__(self, other): return self.salary / other.salary def __repr__(self): return f"Employee ({self.name}, {self.salary}, {self.role})" def __str__(self): return f"name is {self.name}. salary is {self.salary}. and role is {self.role}" emp1 = Employee("Murat", 956, "student") # emp2 = Employee("Doruk", 756, "Programmer") print(emp1) # mapping operator google
ff1dbfde3303a6b7cefad18677224e8f4a3ade27
andresparrab/Python_Learning
/A_Numpys/about_nummpy.py
680
4.0625
4
import numpy as np #creates a array of type numpy with lists a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) #creates a np array from 0-99 b= np.arange(0,100) #creates a np list with zeros. with dimention 3 rows and 5 columms c= np.zeros((3,5)) #printing the ndimentionals arrays print(a) print(b) print(c) #Creates a np array with 8 zeroes in one line x=np.zeros(8) print(x) #reshapes the x array in 2x2 shapes array3d= x.reshape((2,2,2)) print(array3d) #ravels flattas the reshaped array arrayflatten = array3d.ravel() print(arrayflatten) #creates a np array from 2-19 d=np.arange(2,20) #from this array select the element in index 6 element = d[6] print(d) print(element)
f7e0c1a6996617d9e22e5feaacae0b30967ad060
Rabbi50/PythonPracticeFromBook
/primeNumber4.py
525
4.0625
4
import math def is_prime(n): if n<2: return False if n==2: return True if n%2==0: return False m=math.sqrt(n) m=int(m)+1 for y in range(3,n,2): if n%y==0: return False return True number1=input('Plese enter first number: ') number2=input('Plese enter second number: ') number1=int(number1) number2=int(number2) if number1>number2: temp=number1 number1=number2 number2=temp count=0 for x in range(number1,number2): if is_prime(x) is True: print(x) count+=1 print("Total prime number: ",count)
ab9281a2657ffc891c35261a37f0c02c9b897337
supriyamarturi/pyphonprograming
/42.py
103
3.515625
4
a1,a2=map(str,raw_input().split()) if a1==a2: print a1 elif a1>a2: print a1 else: print a2
0c90e81a1d6fb51c30bf8fe09e8f388235192d76
GeoVa19/ai-examples
/minimax and alpha-beta/minimax.py
676
3.828125
4
from tree import tree def minimax(node, maxPlayer): # base case of recursion: returns when node is of int type if isinstance(node, int): return node if maxPlayer: # MAX player value = -999 # an arbitrary low value for child in node: v = minimax(child, False) value = max(value, v) print("MAX best value:", value) return value else: # MIN player value = 999 # an arbitrary high value for child in node: v = minimax(child, True) value = min(value, v) print("MIN best value:", value) return value print("Final value:", minimax(tree, True))
fea1ea6ae619706ec888ab632eba4f4b7ab0c31d
RexAevum/Python_Learning
/input.py
964
4.375
4
# Getting user input in python and string formatting # To get user input command name = input("Enter your name: ") print(name) # All inputs will be of type str, so if you will have to cast it to another type # To cast x = input("Enter number: ") temp1 = int(x) temp2 = float(x) # Need to be carfull, since if user inputs a float and you try to cast it as int -> will give you an error #------------------------------------------------------------------------------------------------------------ # To format the user input userIn = input("Enter info: ") # To print text with variable in python userIn = int(2) formatMessage = "You entered %s" % userIn # or formatMessage2 = "You entered {}".format(userIn) # New method since python 3.6 formatMessage36 = f"You entered {userIn}" print(formatMessage) # For multiple variables x = 20 y = 100 text = "First is %s and then comes %s" % (x, y) print(text) text36 = f"First is {x} and then comes {y}" print(text36)
b0b0b2b53de925a0c2b10ebc0759a5e21eb3f02d
karlweir/python-exercises
/python3/collatzFunction.py
363
4.1875
4
def collatz(number): if (number % 2) == 0: # checks if the parameter passed to the collatz function is an even number number = number // 2 print(number) return number else number = 3 * number + 1 print(number) return number print('Enter number:') try: i = int(input()) except: print('Must enter an integer.') while i != 1: i = (collatz(i))
183ffb6a3cea3b6538fbc512d42c8b9cc7b7edd4
11031/project-canteen
/canteen database.py
2,054
3.859375
4
import sqlite3 con=sqlite3.connect('canteen124543.db') cursor=con.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS Cold_Dish(Id integer primary key,name text, price real, quantity real)') cursor.execute('CREATE TABLE IF NOT EXISTS Hot_Dish(Id integer primary key, name text, price real,quantity real)') cursor.execute('CREATE TABLE IF NOT EXISTS Sweets(Id integer primary key, name text, price real)') cursor.execute('CREATE TABLE IF NOT EXISTS Drinks(Id integer primary key, name text, price real)') cursor.execute('CREATE TABLE IF NOT EXISTS Quantity(Name_Food text primary key,ingredients text)') con.commit() con.close() def join_Cold(): con=sqlite3.connect('canteen124.db') cursor=con.cursor() cursor.execute('''SELECT quantity FROM Cold_Dish INNER JOIN Quantity ON Cold_Dish.quantity=Quantity.ingredients ''') con.commit() con.close() def join_hot(): con=sqlite3.connect('canteen124.db') cursor=con.cursor() cursor.execute('''SELECT quantity FROM Hot_Dish INNER JOIN Quantity ON Hot_Dish.quantity=Quantity.ingredients ''') con.commit() con.close() def Add_Cold(): con=sqlite3.connect('canteen124.db') cursor=con.cursor() da="INSERT INTO Cold_Dish(Id,name,price,quantity) VALUES(?,?,?,?)" cursor.execute() con.commit() con.close() def Add_Hot(): con=sqlite3.connect('canteen124.db') cursor=con.cursor() da="INSERT INTO Hot_Dish(Id,name,price,quantity) VALUES(?,?,?,?)" cursor.execute() con.commit() con.close() def Add_sweets(): con=sqlite3.connect('canteen124.db') cursor=con.cursor() da="INSERT INTO Sweets(Id,name,price) VALUES(?,?,?)" cursor.execute() con.commit() con.close() def Add_drinks(): con=sqlite3.connect('canteen124.db') cursor=con.cursor() da="INSERT INTO Drinks(Id,name,price) VALUES(?,?,?)" cursor.execute() con.commit() con.close()
5c9522289c23988f6bf489e5b9ab7ebc3cc698b2
Sergii-Kravets/Learn-Python
/02_Functions/Done-task/01_hw.py
3,626
3.8125
4
''' Некоторые встроенные функции в Python имеют нестандартное поведение, когда дело касается аргументов и их значений по умолчанию. Например, range, принимает от 1 до 3 аргументов, которые обычно называются start, stop и step и при использовании всех трех, должны указываться именно в таком порядке. При этом только у аргументов start и step есть значения по умолчанию (ноль и единица), а у stop его нет, но ведь аргументы без значения по умолчанию, то есть позиционные аргументы, должны указываться до именнованных, а stop указывается после start. Более того, при передаче функции только одного аргумента он интерпретируется как stop, а не start. Подумайте, каким образом, можно было бы добиться такого же поведения для какой-нибудь нашей пользовательской функции. Напишите функцию letters_range, которая ведет себя похожим на range образом, однако в качестве start и stop принимает не числа, а буквы латинского алфавита (в качестве step принимает целое число) и возвращает не перечисление чисел, а список букв, начиная с указанной в качестве start (либо начиная с 'a', если start не указан), до указанной в качестве stop с шагом step (по умолчанию равным 1). Добавить возможность принимать словарь с заменами букв для подобия траслитерации. Т.е. замена символов из оригинального алфавита другими, возможно несколькими символами. Пример: >>>letters_range('b', 'w', 2) ['b', 'd', 'f', 'h', 'j', 'l', 'n', 'p', 'r', 't', 'v'] >>>letters_range('g') ['a', 'b', 'c', 'd', 'e', 'f'] >>>letters_range('g', 'p') ['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'] >>>letters_range('g', 'p', **{'l': 7, 'o': 0}) ['g', 'h', 'i', 'j', 'k', '7', 'm', 'n', '0'] >>>letters_range('p', 'g', -2) ['p', 'n', 'l', 'j', 'h'] >>>letters_range('a') [] ''' def letters_range(*arguments, **kwargs): if len(arguments) == 3: start = arguments[0] stop = arguments[1] step = arguments[2] elif len(arguments) == 2: start = arguments[0] stop = arguments[1] step = 1 elif len(arguments) == 1: start = 'a' stop = arguments[0] step = 1 letters = [] for number_of_letter in range(ord(start), ord(stop), step): letter = chr(number_of_letter) for key in kwargs: if letter == key: letter = kwargs[key] letters.append(letter) return letters print(letters_range('b', 'w', 2)) print(letters_range('g')) print(letters_range('g', 'p')) print(letters_range('g', 'p', **{'l': 7, 'o': 0})) print(letters_range('p', 'g', -2)) print(letters_range('a'))
2d22fe129aa49061607345493392c28865f7f348
RobertCurry0216/AoC
/2018/day8.py
1,087
3.578125
4
## part 1 ##with open('day8.txt') as f: ## data = f.read() ## ##def next_int(data): ## while len(data) > 1: ## n, data = data.split(maxsplit=1) ## yield int(n) ## yield int(data) ## ##def branch(d): ## ## child = next(d) ## meta = next(d) ## total = 0 ## for __ in range(child): ## total += branch(d) ## ## for __ in range(meta): ## total += next(d) ## ## return total ## ## main ##d = next_int(data) ##print(branch(d)) ## part 2 with open('day8.txt') as f: data = f.read() def next_int(data): while len(data) > 1: n, data = data.split(maxsplit=1) yield int(n) yield int(data) def branch(d): child = next(d) meta = next(d) total = 0 if child: child_values = [branch(d) for __ in range(child)] for __ in range(meta): i = next(d) try: total += child_values[i-1] except: pass else: for __ in range(meta): total += next(d) return total # main print(branch(next_int(data)))
db84dc2a7512f4c3e03b19dd75aa5ef191c078c9
detroyejr/2018-advent-of-code
/src/02.py
1,158
3.84375
4
""" Day 2 """ # Part 1 def read_input(x): x = open(x).readlines() x = [x.replace("\n", "") for x in x] x = [x.replace("+", "") for x in x] return x def appears_twice(x): counter = 0 for v in x: for i in set(v): n = v.count(i) if n == 2: counter += 1 break return counter def appears_three(x): counter = 0 for v in x: for i in set(v): n = v.count(i) if n == 3: counter += 1 break return counter def get_answer(x): twice = appears_twice(x) three = appears_three(x) res = twice * three return res x = read_input("data/2-1.txt") "The answer is: {}".format(get_answer(x)) # Part 2 def match(x): n = len(x[0]) r = list(range(0, n)) for i in r: res = [] for v in x: v = list(v) v.pop(i) v = "".join(v for v in v) res += [v] for r in res: f = res.count(r) if f == 2: return r x = read_input("data/2-1.txt") "The answer is: {}".format(match(x))
35ece92f1ff62d868f3e7dd1001155e3b1fe86ca
gabriellaec/desoft-analise-exercicios
/backup/user_082/ch15_2020_03_04_20_43_39_298970.py
152
3.828125
4
qual_o_nome= input('Qual o seu nome? ') if qual_o_nome == Chris print ("Todo mundo odeia o Chris") else: print ("Olá, {0}".format(qual_o_nome))
c8d6f0ff57d95d6b892de1aa880ac4a8ab9b1c41
jkfer/LeetCode
/Reversed_Lined_List.py
910
4.0625
4
""" 206. Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ class ListNode: def __init__(self, val): self.val = val self.next = None # defining a node root = ListNode(1) root.next = ListNode(2) root.next.next = ListNode(3) def Lprint(node): if not node: print('No input given') while node: print(node.val, end=" ") node = node.next print('\n') class Solution: def reverseList(self, head): # defining three variables prev = None curr = head while curr: next = curr.next curr.next = prev prev = curr curr = next return prev S = Solution() Lprint(root) H = S.reverseList(root) Lprint(H)
27a4afe060a50407f989288c0c8e6aacb93a278f
staug/OrangeLord
/Utilities.py
1,623
3.71875
4
#Utilities.py module # CONSTANT and UTILITIES FILES import pygame # set up the window SPRITEWIDTH = 24 # Ref for the default sprite size SPRITEHEIGHT = 32 # Ref for the default sprite size SPRITEDELAY = 0.1 # Ref for the default sprite delay NBTILEX = 30 # Define the world game max size (unit: a sprite width) NBTILEY = 20 # Define the world game max size (unit: a sprite height) NBSPRITX_DISP = 30 # Define how many sprites should be displayed on screen (unit: sprite) NBSPRITY_DISP = 20 # Define how many sprites should be displayed on screen (unit: sprite) # Utilities def convertTilePosToScreenPos(tilex, tiley): """ this function converts a tile index couple (x,y) to a screen index. The screen index returned in the top left corner position """ return (tilex * SPRITEWIDTH, tiley * SPRITEHEIGHT) def convertScreenPosToTilePos(posx, posy): """ returns the x,y coordinates of the tile[x][y] to which the screen point belongs returns -1,-1 if the pos is out of the screen coordinate """ if posx > SPRITEWIDTH * NBTILEX or posy > SPRITEHEIGHT * NBTILEY: print("convertScreenPosToTilePos error: posx or posy out of bound") return (-1,-1) return (int(posx/SPRITEWIDTH), int(posy/SPRITEHEIGHT)) def getTileRect(tilex, tiley): """ create a PyGame.Rect struct associated to the tile """ return pygame.Rect(tilex * SPRITEWIDTH, tiley * SPRITEHEIGHT, SPRITEWIDTH, SPRITEHEIGHT) def getTileCenter(tilex, tiley): """ Return the centerx, centery of the tile """ tileRec = getTileRect(tilex,tiley) return (tileRec.centerx, tileRec.centery)
11fa3cc6434bc2f62afe85baf567628d07661271
jwkimani/Project-Euler
/id3_largest_prime_factor.py
516
3.796875
4
__author__ = 'James W. Kimani' ''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' def largestprimeFactor(number): primes = [] for num in range(2,number): if number%num == 0: if isPrime(num) == 'true': primes.append(num) print(num) def isPrime(n): prime = 'true' for a in range(2,n): if n%a == 0: prime = 'false' return prime largestprimeFactor(600851475143)
29b7a5cf13bf5dca7103e885dac669144968ad36
priyank-py/GettingStarted
/PythonBatch-(M-P-N-K-A-R)/retext1.py
301
3.546875
4
import re target_text= ''' 12 jan 2019 12/06/1998 22-10-2013 5 July, 2018 ''' #pattern = re.compile("\d\d[-]\w\w[-]\d\d\d\d") pattern = re.compile("\d\d?( |/|-)(\d\d)|(\w+)[ |/|,] ?\d\d\d\d") matches = pattern.finditer(target_text) for match in matches: print(match)
7f31573b7e43ed8bfefd2ff5e39ba5ee008facb5
ampinzonv/covid19-CO
/funciones.py
1,727
3.84375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ === PLOTME ==== Funcion para plotear #x: eje X. y: Array con los datos del eje Y labels = titulos de cada una de los datos en Y tile: Título de la gráfica #Lista de markers y demas formatting: #https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html #Color picking: #https://learnui.design/tools/data-color-picker.html """ #Llamando matplotlib desde acá fue la única manera de evitar que Python # no viera a "plt". import matplotlib.pyplot as plt def plotme(x,y,label,title): #Acá se asume que "Y" tanto como "label" tienen la misma longitud for i in range(0,len(y)): plt.plot(x,y[i],label = label[i], marker ='.',linewidth='1.5') plt.grid() plt.legend() #caracteristicas de los ticks: #https://matplotlib.org/3.1.1/tutorials/text/text_intro.html plt.tick_params(axis='x', rotation=70) plt.suptitle(title) #https://matplotlib.org/2.0.2/examples/pylab_examples/annotation_demo.html plt.annotate('Tapabocas obligatorio', xy=(26, 70), xycoords='data', xytext=(-50, 50), textcoords='offset points', arrowprops=dict(facecolor='#58508d', shrink=0.05), horizontalalignment='right', verticalalignment='bottom') plt.show() #plt.savefig('/Users/andresmpinzonv/Desktop/plot.png', dpi=200) #Este comando abre la ventana para mostrar la grafica. Es probable #que en spyder no sea necesario, pero e IpYthon solo debería necesitarse. """ Funcion para calcular porcentajes simples Retorna un entero de 64 """ def percentage(part, whole): return 100 * float(part)/float(whole)
48888e69eb9bcf067a152949e51686c104832be1
Akshay-agarwal/DataStructures
/General/FibCalls.py
438
3.796875
4
class Counter(object): def __init__(self): self.counter = 0 def increment(self): self.counter += 1 def __str__(self): return str(self.counter) def fib(n,counter): counter.increment() if n<3: return 1 else: return fib(n-1,counter)+fib(n-2,counter) c= Counter() problemSize = 2 for i in range(5): fib(problemSize,c) print(problemSize,c) problemSize *= 2
01908f074f5c89c82f2e3e3417d79a600beb78e2
apiotrowski255/cs1531-lab03
/numberGuesser.py
2,630
4.0625
4
''' Number Guessing Game. Guesses are made until all numbers are guessed. The game reveals whether the closest unguessed number is higher or lower than each guess. Numbers are distinct. Typing 'q' quits the game. ''' import random MIN = 0 MAX = 10 NUM_VALUES = 3 def handle_guess(guess, values): # This function should return a duplicate list of values # with the guessed value removed if it was present. # copy = list(values) if guess in values: index = values.index(guess) del values[index] else: find_closest(guess, values) return values ''' try : index = values.index(guess) del values[index] return values #return copy except: find_closest(guess, values) return values ''' # critics from myself, my function does not return a duplicate list # because it would be much faster to edit the values in place # rather than creating a new list and then reassigning it to values def find_closest(guess, values): # This function should return the closest value # to the guessed value. copy = list(values) copy.append(guess) copy= sorted(copy) index = copy.index(guess) if index == 0 or index == len(copy) - 1: if index == 0: print('higher') return copy[1] else: print('lower') return copy[-2] else: lower = copy[index - 1] higher = copy[index + 1] if higher - guess <= guess - lower: print('higher') return higher else: print('lower') return lower def run_game(values): # While there are values to be guessed and the user hasn't # quit (with 'q'), the game should wait for the user to input # their guess and then reveal whether the closest number is # lower or higher. print(f'Numbers are between {MIN} and {MAX} inclusive. There are {len(values)} values left.') guess = input('There are {} values left. Guess: '.format(len(values))) # Your code goes here. while True: if guess == 'q' or values == []: break guess = int(guess) print(guess) values = handle_guess(guess, values) #print(values) if values == []: print("Congratulations! You won!") break guess = input('There are {} values left. Guess: '.format(len(values))) print('Thanks for playing! See you soon.') if __name__ == '__main__': values = sorted(random.sample(range(MIN, MAX+1), NUM_VALUES)) #print(values) run_game(values)
293a6ff33d74f680e11a6fb86ea650a51365dd1f
gapav/face_recognition
/blur_implementations/blur_image.py
648
3.71875
4
from blur_implementations.blur_2 import Blur_2 import cv2 import numpy as np def blur_image(input_filename, output_filename = None): """ Args: input_filename(string) : filename of original image output_filename = None(string)(optional) : filename of output image Return: Integer 3D array of a blurred image of input filename. """ if output_filename is None: new_image_to_blur = Blur_2(input_filename) return new_image_to_blur.get_3D_array_blurred() else: new_image_to_blur = Blur_2(input_filename, output_filename) return new_image_to_blur.get_3D_array_blurred()
2331ead212581b5551962c9c72eea19b045ee524
max180643/PSIT-IT
/Week-10/MissingCard I 3.0.py
306
3.734375
4
""" MissingCard I Author : Chanwit Settavongsin """ def main(key, card): """ Find missing card """ _ = [card.append(rank + suit) for rank in key for suit in "SHDC"] _ = [card.remove(input()) for i in range(51)] print(card[0]) main(["A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"], [])
b1ed798590bbccd3e0be77338bf23e703ad4117c
sirius206/LeetcodePython
/0204-Count_Primes.py
411
3.671875
4
class Solution: def countPrimes(self, n: int) -> int: if n <= 2: return 0 isPrime =[True] * n isPrime[0], isPrime[1] = False, False for i in range(2, int((n - 1)**0.5) + 1): if isPrime[i]: for j in range(i * i, n, i): isPrime[j] = False return len([x for x in range(2, n) if isPrime[x]])
46f1902c945c6c1fd1d0f90e7fce2d2b1ed52fd1
Kiseloff/algorithms
/move_zeroes.py
278
3.609375
4
nums = [0, 1, 3, 0, 12] # new_arr = [num for num in arr if num != 0] # new_arr.extend([0 for i in range(arr.count(0))]) # # print(new_arr) j = 0 for num in nums: if num != 0: nums[j] = num j += 1 for i in range(j, len(nums)): nums[i] = 0 print(nums)
60ff379e0336b0a90d895b0bda1051fb8c1055f1
atvinodhkumar/Images_OpenCV
/draw_rectangle_put_text_on_image.py
1,534
3.96875
4
""" This script draws a rectangle and puts text anywhere on the image using OpenCV. The edited image can be viewed during the run-time and saved in the desired location. Syntax to draw a rectangle on an image: cv2.rectangle(image, starting_point_coordinates, ending_point_coordinates, color, thickness) cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 0, 0), 5) Reference: https://docs.opencv.org/master/d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9 Syntax to put a text on an image: cv2.putText(image, 'text', coordinates, font, fontScale, color, thickness, lineType) cv2.putText(image, 'text', (xmin, ymin), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), 2, cv2.LINE_AA) Reference: https://docs.opencv.org/master/d6/d6e/group__imgproc__draw.html#ga5126f47f883d730f633d74f07456c576 Dimension of the image used here is 1024 * 500 """ import os import cv2 def main(): path = "C:/Users/Desktop/" BGR_image = cv2.imread(path + r"python_logo.png") RGB_image = cv2.cvtColor(BGR_image, cv2.COLOR_RGB2BGR) RGB_image = cv2.rectangle(RGB_image, (594, 400), (984,460), (255,0,0), 3) RGB_image = cv2.putText(RGB_image, 'Enter Text', (604, 450), cv2.FONT_HERSHEY_TRIPLEX, 2, (255,0,0), 2, cv2.LINE_AA) cv2.imwrite(os.path.join(path, 'python_logo_text.png'), cv2.cvtColor(RGB_image, cv2.COLOR_RGB2BGR)) cv2.imshow('Image', cv2.cvtColor(RGB_image, cv2.COLOR_RGB2BGR)) # cv2.waitKey(0) if __name__ == '__main__': main()
1a5d4e2732d0237947b0541da82fcd0d2abd65e3
songlin1994/myedu-1904
/day02/list_type.py
2,549
4.09375
4
# 这就是一个列表的数据类型,英文 是 list, 也叫 数组 alist = ['是打发',2,'你好',6,7,1,3] # 访问list def list_sel(): # 通过索引访问 顺序取值: 从0开始数 print(alist[0]) # 访问倒数第三位 ,# 倒序取值: 从 -1 开始数 print(alist[-3]) # 通过切片访问, 语法: 前索引值 : 后索引值 取的时候取到后索引值的前一位 print(alist[2:3]) # 访问 从第五个开始到后面的所有 print(alist[4:]) # 不填值的话 从第一个开始取值 print(alist[:4]) # 删除list中的元素 def list_del(): # 调用删除方法 不填参数 默认删除最后一位 alist.pop() print(alist) # 调用删除方法, 填写参数: 索引值 就可以删除指定元素; 并把删除的元素返回回来,赋值给a a=alist.pop(3) print(alist) print(a) # 增加list中的元素 def list_add(): blist = [1,2,3,'4'] # 增加元素 ,增加在末尾 blist.append('5') print(blist) clist = [4,5,6] # 合并两个list 中的元素 blist.extend(clist) print(blist) def list_update(): qlist = [1,2,6,4,5] # 更新列表中的元素 , 根据索引进行更新,值写在= 后面 就可以了 qlist[0] = 100 print(qlist) # 更新第三位 ,改为200 qlist[2] = 200 print(qlist) def list_order_by(): qlist = [1, 2, 6, 4, 5] # 从小到大排序 qlist.sort() print(qlist) # 从大到小排序 # 指定参数入参: reverse=True qlist.sort(reverse=True) print(qlist) def list_distinct(): vlist = [1,2,2,6,6,4,5] # set(vlist) : 使用set 方法对 list进行去重,去重后不是list类型,用list() 方法 将这个数据转换成list类型 print(type(set(vlist))) vlist = list(set(vlist)) print(vlist) # len(): 获取列表的长度,有几个元素 就 返回几 print(len(vlist)) # 题: 新建一个list变量,里面有五个元素,访问索引2,切片访问索引1到4,删除索引3,添加两个元素,第0位元素改成字符5,获取索引长度 def home_work(): alist = [1,2,3,4,5] print(alist[2]) print(alist[1:4]) alist.pop(3) alist.append(6) alist.append(7) # blist = [6,7] # alist.extend(blist) alist[0]='5' print(len(alist)) print(alist) if __name__ == '__main__': # list_del() # list_add() # list_update() # list_order_by() list_distinct() # home_work() # qlist = [1, # 2, 6, 4, 5] # qlist.reverse() # print(qlist)
a823faab998a3b1d892dbaba46496853f80a6b9e
manjusha18119/manju18119python
/python/stslup.py
1,155
4.40625
4
string="hello python" print(string) print(string[0:3].upper()+string[3:7]+string[7:9].upper()+string[9:10]+string[10:11].upper()+string[11:12]) print(len(string)) #Retruns length of the given string. print(string.upper()) #Converts string to uppercase. print(string.lower()) print(string.startswith('he')) #Returns True if string starts with given substring. print(string.startswith('on')) print(string.endswith('he')) #Returns True if string endswith given substring. print(string.endswith('on')) result=string.count('o') #Returns the count of given substring. print(result) print(string.capitalize()) #Capitalize the first letter of the string. print(string.title()) #Capitalizefirst letter of each word in the given string. print(string.strip('h')) #Removes any character from both ends of the string. print(string.strip('n')) print(string.lstrip('h')) #Removes any character from the left end of the string. print(string.rstrip('n')) #Removes any character from the right end of the string. print(string.split('o')) #To split the string print(string.replace('h','e')) #To replace a string with given substring. print(string) # print(del string[0])
825e24e62cdbba41d67a6dba0ae91c0409a70460
johnehunt/PythonCleanCode
/08-functions/Product.py
1,291
4.125
4
from typing import List credit = 10 class Product: def __init__(self, name, price): self.name = name self.price = price Cart = List[Product] def calculate_price(products: Cart) -> float: """Returns the final price of all selected products""" price = 0 for product in products: price += product.price print('Final price is:', price) if price > credit: raise ValueError("Don't have money to pay") return price def calculate_price2(products: Cart) -> float: """Returns the final price of all selected products""" price = 0 for product in products: price += product.price return price def check_credit(amount): return credit > amount cart = [Product("bread", 1.55), Product("jam", 1.33)] cost = calculate_price2(cart) print('Cost of cart is:', cost) print('Can pay for cart:', check_credit(cost)) def check_can_pay(cart): cost = calculate_price2(cart) return check_credit(cost) print('Check can pay:', check_can_pay(cart)) def compose(func1, func2): def composed_function(args): result = func1(args) return func2(result) return composed_function check_price_and_credit = \ compose(calculate_price, check_credit) print(check_price_and_credit(cart))
e60b51bd9201b17f4487d67099afb31da410f5e6
zixuedanxin/100
/12素数.py
344
3.65625
4
#素数(101,200) import math print(int(12.90877)) a=0 loop = 1 for i in range(101,201): k=int(math.sqrt(i)) for j in range(2,k+1): #这里要注意+1 , int是取整 if i%j==0: loop = 0 break if loop == 1: print(i) a+=1 loop = 1 print('%d个' %a) print(int(math.sqrt(121)))
a0079163eab467a228cc904133dda4b3904ce862
hqqiao/pythonlearn
/8-Advanced features1-slice.py
4,479
3.65625
4
# -*- coding: utf-8 -*- #1-构造一个1, 3, 5, 7, ..., 99的列表,可以通过循环实现: L =[] n =1 while n<=99: L.append(n) n+=2 print(L) #2-取一个list或tuple的部分元素 #取前N个元素,也就是索引为0-(N-1)的元素,可以用循环 ''' python range()函数可创建一个整数列表,一般用在for循环中。 函数语法 range(start, stop[, step]) 参数说明: start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5); stop:计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5 step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1) ''' #方法一:循环取值 r = [] n = 3 L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] for i in range(n): r.append(L[i]) print(r) #方法二:切片[起始:终止前:间隔几个] #L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。 #即索引0,1,2,正好是3个元素。 #如果第一个索引是0,还可以省略,L[:3] r=L[0:] #从索引0开始直到最后 ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] print(r) r=L[0:4] #从索引0开始,0,1,2,3共4个 ['Michael', 'Sarah', 'Tracy', 'Bob'] print(r) #同样支持倒数切片 从右边开始为-1 r=L[-4:-1] #从-4开始,到-1为止但不包括索引-1,['Sarah', 'Tracy', 'Bob'] print(r) r=L[-5:] #从-5即最开始的Michael开始,直到所有,即后五个数 print(r) ''' 切片操作总结: [start:stop:step] a = [0,1,2,3,4,5,6,7,8,9] b = a[i:j] 表示复制a[i]到a[j-1],以生成新的list对象 b = a[1:3] 那么,b的内容是 [1,2] 当i缺省时,默认为0,即 a[:3]相当于 a[0:3] 当j缺省时,默认为len(alist), 即a[1:]相当于a[1:10] 当i,j都缺省时,a[:]就相当于完整复制一份a了 b = a[i:j:s],s表示步进,缺省为1. a[i:j:1]相当于a[i:j] 当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1 所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍,即全部倒序复制 上述例子为 a[-1:-11:-1] ''' a = [0,1,2,3,4,5,6,7,8,9] print('a[-1:-11:-1]',a[-1:-11:-1]) # a[-1:-11:-1] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] #切片应用举例[start:end:interval] list/tuple/string ''' 在很多编程语言中,针对字符串提供了很多各种截取函数(例如,substring) 其实目的就是对字符串切片。 Python没有针对字符串的截取函数,只需要切片一个操作就可以完成,非常简单 本例总结代码经验: 出现'list' object is not callable错误的原因 通常都是因为在之前定义了与函数名称相同的变量,导致在调用函数时报错。 但重复定义的不一定是list,有可能是其他函数名 在命名变量时要注意,应避免和python的函数名、关键字冲突。 ''' s = list(range(100)) print(s) print(s[:10]) #前十个数 print(s[-10:]) #倒数十个数 print(s[10:20:2]) #前11-20个数,每两个取一个: print(s[::5]) #所有数,每五个取一个 print(s[:]) #直接全部复制一个list ''' tuple也是一种list,唯一区别是tuple不可变。 因此,tuple也可以用切片操作,只是操作的结果仍是tuple: >>> (0, 1, 2, 3, 4, 5)[:3] (0, 1, 2) 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。 因此,字符串也可以用切片操作,只是操作结果仍是字符串: >>> 'ABCDEFG'[:3] 'ABC' >>> 'ABCDEFG'[::2] 'ACEG' ''' a = (0,1,2,3,4,5) b = a[:3][:1] print(b) #(0,) 可以连续两次切片,从而得到只含一个元素的元组。 c = 'ABCDEFG' d = c[::2] print(d) ''' 练习:利用切片操作,实现一个trim()函数,去除字符串首尾的空格 注意不要调用str的strip()方法: ''' # -*- coding: utf-8 -*- def trim(s): while s[0:1]==" ": #首部有空格,每次检查一个字符,依次向后 s=s[1:] while s[-1:]==" ": #尾部有空格,每次检查一个字符,依次向前 s=s[0:-1] return s # 测试: if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!')
0dec9069bae1139d85c726a0f21aa795acb5e955
josejpalacios/codecademy-python3
/Lesson 05: Loops/Lesson 02: Code Challenge: Loops/Exercise 03: Greetings.py
713
4.46875
4
# Create a function named add_greetings() which takes a list of strings named names as a parameter. # In the function, create an empty list that will contain each greeting. # Add the string "Hello, " in front of each name in names and append the greeting to the list. # Return the new list containing the greetings. #Write your function here def add_greetings(names): # Create empty_list greetings = [] # Iterate through names for name in names: # Add Hello greeting = "Hello, " + name # Append greeting to greetings greetings.append(greeting) # Return greetings return greetings #Uncomment the line below when your function is done print(add_greetings(["Owen", "Max", "Sophie"]))
2f13e842d6ce1d32ff34a0026228bf2041c14bcd
msayin/python-challenge
/pyPoll.py
1,686
3.59375
4
# coding: utf-8 # In[71]: # Dependencies import csv # Files to load and output (Remember to change these) file_to_load = "Downloads/election_data.csv" file_to_output = "Downloads/pythonchallenge2.txt" total_votes = 0 number_candidates = 0 candidate_list = [] candidate_votes = {} maxvotes = -1 # Read the csv and convert it into a list of dictionaries with open(file_to_load) as poll_data: reader = csv.DictReader(poll_data) for row in reader: current_candidate = row['Candidate'] if current_candidate not in candidate_list : number_candidates = number_candidates + 1 candidate_list.append(current_candidate) candidate_votes[current_candidate] = 0 candidate_votes[current_candidate]=candidate_votes[current_candidate]+1 total_votes = total_votes + 1 if candidate_votes[current_candidate] > maxvotes : maxvotes = candidate_votes[current_candidate] maxcandidate = current_candidate # In[72]: line1 = ' Election Results' line2 = ' -------------------------' line3 = (' Total Votes: %d' %(total_votes)) line4 = ' -------------------------' output = line1 + '\n' + line2 + '\n' + line3 + '\n' + line4 for name in candidate_list : linex = (' %s: %.3f%% (%d)' %(name, 100*candidate_votes[name]/(0.0+total_votes), candidate_votes[name])) output = output + '\n' + linex output = output + '\n' + ' -------------------------' output = output + '\n' + (' Winner: %s' %maxcandidate) output = output + '\n' + ' -------------------------' print(output) with open(file_to_output,'w') as outputfile: outputfile.write(output)
cfe3464f7b141b0f837fc36692f1aee2ca2203ec
evelinRodriguez/tareaProgramacion
/operadores logicos.py
522
4.125
4
#operadores logicos print("conjuncion (and)") num1=int(input("escriba un numero mayor que 2 y menor a 5")) if num1 > 2 and num1 < 5 : print("el numero " , num1 , " cumploe condicion ") else: print("no se cumple") print("disyuncion (or)") palabra= input("para cumplir escriba si o yes") if palabra == "si" or palabra== "yes": print("cumple") else: print("no cumple") print("negacion (not)") num2= int(input(" introduce numero = a 5")) if not num2==5: print("cumple") else: print("no cumple")
ccc535645885edeab24d8fe5f4b9961f8dc4eff1
marinka01126/hw_Marina
/Lesson_2/_4_practice.py
779
4.375
4
""" Пользователь вводит что-нибудь с клавиатуры. Если какие-нибудь данные были введены, то на экране должно выводиться сообщение "Данные записаны." Если данные не были получены, а пользователь просто нажал Enter, то программа выводит сообщение "Данных не обнаружено." """ data = input("Введие данные") print(repr(data), type(data)) if data == "": print("Данных не обнаружено") else: print("Данніе записаны") if data: print("Записано") else: print("не обнаружено")
451ef42260f6c17ba9b9f1f7ded071247be19809
Nelinger91/Projects
/intro2cs/ex11/node.py
506
3.546875
4
class Node(object): def __init__(self, task, next = None): self.task = task self.next = next self.task.priority = self.task.get_priority() def get_priority(self): return self def set_priority(self, new_priority): self.priority = new_priority return self.task.priority def get_task(self): return self.task def get_next(self): return self.get_next def set_next(self, next_node): self.next = next_node return self.next def has_next(self): return (if self.next != None)
532bceb4f8026cab4fe002b8be8431d045b298fa
ArunShishodia/Smaller-Programs
/Advanced_Python_Class/Exercisesheet 1/Exercise 3.5.py
387
4.375
4
# Exercise 3.5 """Here python copies each list by reference""" a_list = [5] * 4 a_list[2] = 1 print(a_list) """This means that now when you change the elements of one sublist, then python uses the elements of the inner list and applies the same reference to the outer lists as well""" a_list = [[5]] * 4 a_list[2][0] = 1 print(a_list) a_list = [[5]] * 4 a_list[2] = 1 print(a_list)
6b17c9494319faef8c955445f8d74ab331c9a53f
Kyohei-1/first
/knock22.py
2,175
3.5625
4
# coding: utf-8 import sys import re path = sys.argv[1] # ファイルのパス def isCategory(splitedWord): # # カテゴリー行を正規表現で判定 a = '' pattern = ( r'\[\[Category:(.+)\]\]' # \[\[Category: # []はエスケープが必要だった気がするので\を付けて # [[Category から始まって ]] で終わる 3 桁以上の文字列なので、.+ ) a = re.match(pattern, splitedWord) return a def pickInnerWord(text): # print(text) text = text.split('|')[0] # re.subで置換して生き残る'|'までを0番目、 # 以降を1番目と判断するので、'|'までを取ってくる # str.find()、str.partitionでも同様に動いた。 # print(text) # text = re.sub(r"\W", "", text) # \Wで英数字以外を置換 text = text.replace('Category', '') # text = text.replace('', '') # text = text.split('|')[0] # print(text) # 邪魔なので置換 return text with open('./KF22.txt', 'w') as wFile: with open(path, 'r') as File1: ReadFile = File1.readlines() # print(ReadFile) for word in ReadFile: splitedWord = word.split('\n') # 改行を消す splitedWord = ''.join(splitedWord) # print(splitedWord) # print(a) a = isCategory(splitedWord) if a is not None: # Noneのもの(カテゴリーじゃないもの)は要らないので、ここで判定 for w in a.groups(): # groups()で値を取ってこれるみたい。 # groupsがないとre.Match objectとやらが返ってきた # print(w) w = pickInnerWord(w) wFile.write(w+'\n') # 実行結果 # イギリス # イギリス連邦加盟国 # 英連邦王国 # G8加盟国 # 欧州連合加盟国 # 海洋国家 # 現存する君主国 # 島国 # 1801年に成立した国家・領域 # python knock22.py ./knock20_result.txt
fb8ffa22b3cf24f0631e605b38d2a7ea6383308a
MyVeli/ohjelmistotekniikka-harjoitustyo
/src/logic/investment_revenue.py
497
3.625
4
class YearlyRevenue: """Class for holding revenue items for one year. Is used by InvestmentPlan class. """ def __init__(self, rev): self.year = rev[2] self.revenue = list() self.rev_sum = 0 self.add_revenue(rev) def add_revenue(self, rev): self.revenue.append((rev[0], rev[1], rev[2])) self.rev_sum += float(rev[1]) def get_revenue(self): return self.revenue def get_revenue_sum(self): return self.rev_sum
aba7b468da1a76fcb924949d6fe36da4043af6cd
gronkyzog/Puzzles
/problems/Euler180.py
547
3.515625
4
from fractions import Fraction import itertools def f(n,x,y,z): # due to Fermat's last theorem only n in (-2,-1,1,2) will yield zero for x,y,z <> 0 return (x+y+z)*(x**n + y**n - z**n) A = set([Fraction(a,b) for b in range(1,36) for a in range(1,b)]) counter = 0 solution = set() for n in range(-2,3): AN = {a**n:a for a in A} for x,y in itertools.combinations_with_replacement(A,2): zn = x**n + y**n if zn in AN: z = AN[zn] solution.add(x+y+z) print len(solution) total = sum(solution) print total.numerator+total.denominator
044bfca8747eeede6eb7a56c5740f7658a2b06e9
rojiani/algorithms-in-python
/divide-and-conquer/mergesort.py
985
3.890625
4
# assume length(A) > 0 def mergesort(A): n = len(A) if n == 1: return A else: mid = int(n/2) left = mergesort(A[0:mid]) right = mergesort(A[mid:n]) return merge(left, right) def merge(left, right): n_left = len(left) n_right = len(right) aux = [None] * (n_left + n_right) idx_l = idx_r = idx_aux = 0 # In case of tie, merge must select element from the left, or mergesort # isn't stable. while idx_l < n_left and idx_r < n_right: if left[idx_l] <= right[idx_r]: aux[idx_aux] = left[idx_l] idx_l += 1 idx_aux += 1 else: aux[idx_aux] = right[idx_r] idx_r += 1 idx_aux += 1 while idx_r < n_right: aux[idx_aux] = right[idx_r] idx_r += 1 idx_aux += 1 while idx_l < n_left: aux[idx_aux] = left[idx_l] idx_l += 1 idx_aux += 1 return aux
80842ef082a3ebfd5a79cc82651b4bcd0f9eeec6
jamwine/Data-Structures-and-Algorithm
/DataStructures/DoubleLinkedList.py
4,804
4.1875
4
class DoublyLinkedListNode: def __init__(self,value): self.info=value self.prev=None self.next=None class DoubleLinkedList: def __init__(self): self.start=None def display_list(self): if self.start is None: print("List is empty.") return else: print("List is:") p=self.start while p is not None: print(p.info," ",end="") p=p.next print() def count_nodes(self): p=self.start n=0 while p is not None: n+=1 p=p.next print("Number of nodes in the list:",n) return n def search(self,x): position=1 p=self.start while p is not None: if p.info==x: print(x,"is at position:",position) return True position+=1 p=p.next else: print(x,"not found in the list.") return False def insert_in_beginning(self,data): temp=DoublyLinkedListNode(data) temp.next=self.start self.start.prev=temp self.start=temp def insert_in_empty_list(self,data): temp=DoublyLinkedListNode(data) self.start=temp def insert_at_end(self,data): temp=DoublyLinkedListNode(data) p=self.start while p.next is not None: p=p.next p.next=temp temp.prev=p def create_list(self): n=int(input("Enter the number of nodes:")) if n==0: return data=int(input("Enter the first element to be inserted:")) self.insert_in_empty_list(data) for i in range(n-1): data=int(input("Enter the next element to be inserted:")) self.insert_at_end(data) def insert_after(self,data,x): temp=DoublyLinkedListNode(data) p=self.start while p is not None: if p.info==x: break p=p.next if p is None: print(x," not present in the list") else: temp.prev=p temp.next=p.next if p.next is not None: p.next.prev=temp p.next=temp def insert_before(self,data,x): if self.start is None: print("List is empty") return if x==self.start.info: temp=DoublyLinkedListNode(data) temp.next=self.start self.start.prev=temp self.start=temp return p=self.start while p is not None: if p.info==x: break p=p.next if p is None: print(x,"is not present in the list") else: temp=DoublyLinkedListNode(data) temp.prev=p.prev temp.next=p p.prev.next=temp p.prev=temp def delete_node(self,x): if self.start is None: print("List is empty") if self.start.next is None: if self.start.info==x: self.start=None else: print(x,'not found') return if self.start.info==x: self.start=self.start.next self.start.prev=None return p=self.start.next while p.next is not None: if p.info==x: break p=p.next if p.next is not None: p.prev.next=p.next p.next.prev=p.prev else: if p.info==x: p.prev.next=None else: print("Element",x,"is not in the list") def delete_first_node(self): if self.start is None: return if self.start.next is None: self.start=None return self.start=self.start.next self.start.prev=None def delete_last_node(self): if self.start is None: return if self.start.next is None: self.start=None return p=self.start while p.next is not None: p=p.next p.prev.next=None def reverse_list(self): if self.start is None: return p1=self.start p2=p1.next p1.next=None p1.prev=p2 while p2 is not None: p2.prev=p2.next p2.next=p1 p1=p2 p2=p2.prev self.start=p1 print("List is reversed")
30d46281f7df3e5ddf1565751aff5c5c5b236854
xieh1987/MyLeetCodePy
/Reorder List.py
936
3.78125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return nothing def reorderList(self, head): if not head or not head.next: return front, rear = head, head while True: if front.next: front = front.next else: break if front.next: front, rear = front.next, rear.next else: break dummy = ListNode(0) dummy.next, curr = rear.next, rear.next while curr.next: tmp = curr.next curr.next = tmp.next tmp.next = dummy.next dummy.next = tmp curr1, curr2, rear.next = head, dummy.next, None while curr2: tmp, curr2 = curr2, curr2.next tmp.next, curr1.next = curr1.next, tmp curr1 = curr1.next.next
5421a1cbbcd6499cb7833a8f9c761e2670155f73
anilized/Coding-Interview-Python
/Tests/test3.py
565
3.90625
4
def binToDec(bin_value): bin_value = int(bin_value) # converting binary to decimal decimal_value = 0 count = 0 while(bin_value != 0): digit = bin_value % 10 decimal_value = decimal_value + digit * pow(2, count) bin_value = bin_value//10 count += 1 # returning the result return decimal_value print(binToDec("000111010101000101001100100101000101001011010101010101100100100100100101001001001")) print(int("000111010101000101001100100101000101001011010101010101100100100100100101001001001",2))
375f15eaaab4750ee669f26089896fb653324e01
borislavstoychev/Soft_Uni
/soft_uni_basic/Nested Loops/lab/05. Travelling.py
274
3.984375
4
while True: destination = input() if destination == 'End': break budget = float(input()) curent_money = 0 while curent_money < budget: money = float(input()) curent_money += money print(f'Going to {destination}!')
64229d94c5a92310d71502856a5671bebd9e2514
jih3508/study_ml
/Numpy/2D_arry.py
208
3.546875
4
#2D Array with Numpy import numpy as np t = np.array([[1., 2., 3.], [4. , 5., 6.], [7., 8., 9.], [10., 11., 12.]]) print(t) print('Rank of t: ', t.ndim) # print('shape of t: ', t.shape) #
4f85222ca09d09136e093166b121f47b173018e1
wayde-P/python_study
/day2_161016/list.py
323
3.71875
4
names = ["tom", "jerry", "shuke", "beita", ""] names.insert(2, "bbb") # 插入到index的前面 # 删除 names.remove("bbb") del names[3] names.pop() # 删除并返回删除的值 # 改 names[1] = '汤姆' # 查 names[1] names[-3:] # 获取最后3个元素 names.index() # 取下标 names.extend() # 合并字符串
a2b25c4d698bb543ae5b97e59df137cf5bb6b7ca
kailunfan/lcode
/242.有效的字母异位词.py
1,221
3.734375
4
# # @lc app=leetcode.cn id=242 lang=python # # [242] 有效的字母异位词 # # https://leetcode-cn.com/problems/valid-anagram/description/ # # algorithms # Easy (59.44%) # Likes: 206 # Dislikes: 0 # Total Accepted: 109.9K # Total Submissions: 182.3K # Testcase Example: '"anagram"\n"nagaram"' # # 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。 # # 示例 1: # # 输入: s = "anagram", t = "nagaram" # 输出: true # # # 示例 2: # # 输入: s = "rat", t = "car" # 输出: false # # 说明: # 你可以假设字符串只包含小写字母。 # # 进阶: # 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况? # # # @lc code=start from collections import defaultdict class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) != len(t): return False dic = defaultdict(int) for i in range(len(s)): dic[s[i]] += 1 dic[t[i]] -= 1 for v in dic.values(): if v != 0: return False return True # @lc code=end
5e33a9f8aecfc470f683ced39fae30f29879737f
jaeho310/algorithm
/algorithm50.py
334
3.640625
4
def solution(numbers): answer = '' cache = [] for i in numbers: temp = list(map(str,str(i))) cache.append(temp) sortedNum = sorted(cache,key=lambda x: x*3,reverse=True) for i in sortedNum: for j in i: answer += str(j) return str(int(answer)) print(solution([6,10,2]))
24f9e282a9374a9a66746502afbc9c431c5943e8
isimic95/leetcoding
/concatenation_sum.py
148
3.65625
4
def concatenationsSum(a): result = 0 for x in a: for y in a: result += int("".join([str(x), str(y)])) return result
15fa9048c99c7f6f17c74fb16463d84e85ca5397
ynikitenko/lena
/lena/structures/hist_functions.py
21,710
3.65625
4
"""Functions for histograms. These functions are used for low-level work with histograms and their contents. They are not needed for normal usage. """ import collections import copy import itertools import operator import re import sys if sys.version_info.major == 3: from functools import reduce as _reduce else: _reduce = reduce import lena.core from .graph import graph as _graph class HistCell(collections.namedtuple("HistCell", ("edges, bin, index"))): """A namedtuple with fields *edges, bin, index*.""" # from Aaron Hall's answer https://stackoverflow.com/a/28568351/952234 __slots__ = () def cell_to_string( cell_edges, var_context=None, coord_names=None, coord_fmt="{}_lte_{}_lt_{}", coord_join="_", reverse=False): """Transform cell edges into a string. *cell_edges* is a tuple of pairs *(lower bound, upper bound)* for each coordinate. *coord_names* is a list of coordinates names. *coord_fmt* is a string, which defines how to format individual coordinates. *coord_join* is a string, which joins coordinate pairs. If *reverse* is True, coordinates are joined in reverse order. """ # todo: do we really need var_context? # todo: even if so, why isn't that a {}? Is that dangerous? if coord_names is None: if var_context is None: coord_names = [ "coord{}".format(ind) for ind in range(len(cell_edges)) ] else: if "combine" in var_context: coord_names = [var["name"] for var in var_context["combine"]] else: coord_names = [var_context["name"]] if len(cell_edges) != len(coord_names): raise lena.core.LenaValueError( "coord_names must have same length as cell_edges, " "{} and {} given".format(coord_names, cell_edges) ) coord_strings = [coord_fmt.format(edge[0], coord_names[ind], edge[1]) for (ind, edge) in enumerate(cell_edges)] if reverse: coord_strings = reversed(coord_strings) coord_str = coord_join.join(coord_strings) return coord_str def _check_edges_increasing_1d(arr): if len(arr) <= 1: raise lena.core.LenaValueError("size of edges should be more than one," " {} provided".format(arr)) increasing = (tup[0] < tup[1] for tup in zip(arr, arr[1:])) if not all(increasing): raise lena.core.LenaValueError( "expected strictly increasing values, " "{} provided".format(arr) ) def check_edges_increasing(edges): """Assure that multidimensional *edges* are increasing. If length of *edges* or its subarray is less than 2 or if some subarray of *edges* contains not strictly increasing values, :exc:`.LenaValueError` is raised. """ if not len(edges): raise lena.core.LenaValueError("edges must be non-empty") elif not hasattr(edges[0], '__iter__'): _check_edges_increasing_1d(edges) return for arr in edges: if len(arr) <= 1: raise lena.core.LenaValueError( "size of edges should be more than one. " "{} provided".format(arr) ) _check_edges_increasing_1d(arr) def get_bin_edges(index, edges): """Return edges of the bin for the given *edges* of a histogram. In one-dimensional case *index* must be an integer and a tuple of *(x_low_edge, x_high_edge)* for that bin is returned. In a multidimensional case *index* is a container of numeric indices in each dimension. A list of bin edges in each dimension is returned.""" # todo: maybe give up this 1- and multidimensional unification # and write separate functions for each case. if not hasattr(edges[0], '__iter__'): # 1-dimensional edges if hasattr(index, '__iter__'): index = index[0] return (edges[index], edges[index+1]) # multidimensional edges return [(edges[coord][i], edges[coord][i+1]) for coord, i in enumerate(index)] def get_bin_on_index(index, bins): """Return bin corresponding to multidimensional *index*. *index* can be a number or a list/tuple. If *index* length is less than dimension of *bins*, a subarray of *bins* is returned. In case of an index error, :exc:`.LenaIndexError` is raised. Example: >>> from lena.structures import histogram, get_bin_on_index >>> hist = histogram([0, 1], [0]) >>> get_bin_on_index(0, hist.bins) 0 >>> get_bin_on_index((0, 1), [[0, 1], [0, 0]]) 1 >>> get_bin_on_index(0, [[0, 1], [0, 0]]) [0, 1] """ if not isinstance(index, (list, tuple)): index = [index] subarr = bins for ind in index: try: subarr = subarr[ind] except IndexError: raise lena.core.LenaIndexError( "bad index: {}, bins = {}".format(index, bins) ) return subarr def get_bin_on_value_1d(val, arr): """Return index for value in one-dimensional array. *arr* must contain strictly increasing values (not necessarily equidistant), it is not checked. "Linear binary search" is used, that is our array search by default assumes the array to be split on equidistant steps. Example: >>> from lena.structures import get_bin_on_value_1d >>> arr = [0, 1, 4, 5, 7, 10] >>> get_bin_on_value_1d(0, arr) 0 >>> get_bin_on_value_1d(4.5, arr) 2 >>> # upper range is excluded >>> get_bin_on_value_1d(10, arr) 5 >>> # underflow >>> get_bin_on_value_1d(-10, arr) -1 """ # may also use numpy.searchsorted # https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.searchsorted.html ind_min = 0 ind_max = len(arr) - 1 while True: if ind_max - ind_min <= 1: # lower bound is close if val < arr[ind_min]: return ind_min - 1 # upper bound is open elif val >= arr[ind_max]: return ind_max else: return ind_min if val == arr[ind_min]: return ind_min if val < arr[ind_min]: return ind_min - 1 elif val >= arr[ind_max]: return ind_max else: shift = int( (ind_max - ind_min) * ( float(val - arr[ind_min]) / (arr[ind_max] - arr[ind_min]) )) ind_guess = ind_min + shift if ind_min == ind_guess: ind_min += 1 continue # ind_max is always more that ind_guess, # because val < arr[ind_max] (see the formula for shift). # This branch is not needed and can't be tested. # But for the sake of numerical inaccuracies, let us keep this # so that we never get into an infinite loop. elif ind_max == ind_guess: ind_max -= 1 continue if val < arr[ind_guess]: ind_max = ind_guess else: ind_min = ind_guess def get_bin_on_value(arg, edges): """Get the bin index for *arg* in a multidimensional array *edges*. *arg* is a 1-dimensional array of numbers (or a number for 1-dimensional *edges*), and corresponds to a point in N-dimensional space. *edges* is an array of N-1 dimensional arrays (lists or tuples) of numbers. Each 1-dimensional subarray consists of increasing numbers. *arg* and *edges* must have the same length (otherwise :exc:`.LenaValueError` is raised). *arg* and *edges* must be iterable and support *len()*. Return list of indices in *edges* corresponding to *arg*. If any coordinate is out of its corresponding edge range, its index will be ``-1`` for underflow or ``len(edge)-1`` for overflow. Examples: >>> from lena.structures import get_bin_on_value >>> edges = [[1, 2, 3], [1, 3.5]] >>> get_bin_on_value((1.5, 2), edges) [0, 0] >>> get_bin_on_value((1.5, 0), edges) [0, -1] >>> # the upper edge is excluded >>> get_bin_on_value((3, 2), edges) [2, 0] >>> # one-dimensional edges >>> edges = [1, 2, 3] >>> get_bin_on_value(2, edges) [1] """ # arg is a one-dimensional index if not isinstance(arg, (tuple, list)): return [get_bin_on_value_1d(arg, edges)] # arg is a multidimensional index if len(arg) != len(edges): raise lena.core.LenaValueError( "argument should have same dimension as edges. " "arg = {}, edges = {}".format(arg, edges) ) indices = [] for ind, array in enumerate(edges): cur_bin = get_bin_on_value_1d(arg[ind], array) indices.append(cur_bin) return indices def get_example_bin(struct): """Return bin with zero index on each axis of the histogram bins. For example, if the histogram is two-dimensional, return hist[0][0]. *struct* can be a :class:`.histogram` or an array of bins. """ if isinstance(struct, lena.structures.histogram): return lena.structures.get_bin_on_index([0] * struct.dim, struct.bins) else: bins = struct while isinstance(bins, list): bins = bins[0] return bins def hist_to_graph(hist, make_value=None, get_coordinate="left", field_names=("x", "y"), scale=None): """Convert a :class:`.histogram` to a :class:`.graph`. *make_value* is a function to set the value of a graph's point. By default it is bin content. *make_value* accepts a single value (bin content) without context. This option could be used to create graph's error bars. For example, to create a graph with errors from a histogram where bins contain a named tuple with fields *mean*, *mean_error* and a context one could use >>> make_value = lambda bin_: (bin_.mean, bin_.mean_error) *get_coordinate* defines what the coordinate of a graph point created from a histogram bin will be. It can be "left" (default), "right" and "middle". *field_names* set field names of the graph. Their number must be the same as the dimension of the result. For a *make_value* above they would be *("x", "y_mean", "y_mean_error")*. *scale* becomes the graph's scale (unknown by default). If it is ``True``, it uses the histogram scale. *hist* must contain only numeric bins (without context) or *make_value* must remove context when creating a numeric graph. Return the resulting graph. """ ## Could have allowed get_coordinate to be callable # (for generality), but 1) first find a use case, # 2) histogram bins could be adjusted in the first place. # -- don't understand 2. if get_coordinate == "left": get_coord = lambda edges: tuple(coord[0] for coord in edges) elif get_coordinate == "right": get_coord = lambda edges: tuple(coord[1] for coord in edges) # *middle* between the two edges, not the *center* of the bin # as a whole (because the graph corresponds to a point) elif get_coordinate == "middle": get_coord = lambda edges: tuple(0.5*(coord[0] + coord[1]) for coord in edges) else: raise lena.core.LenaValueError( 'get_coordinate must be one of "left", "right" or "middle"; ' '"{}" provided'.format(get_coordinate) ) # todo: make_value may be bad design. # Maybe allow to change the graph in the sequence. # However, make_value allows not to recreate a graph # or its coordinates (if that is not needed). if isinstance(field_names, str): # copied from graph.__init__ field_names = tuple(re.findall(r'[^,\s]+', field_names)) elif not isinstance(field_names, tuple): raise lena.core.LenaTypeError( "field_names must be a string or a tuple" ) coords = [[] for _ in field_names] chain = itertools.chain if scale is True: scale = hist.scale() for value, edges in iter_bins_with_edges(hist.bins, hist.edges): coord = get_coord(edges) # Since we never use contexts here, it will be optimal # to ignore them completely (remove them elsewhere). # bin_value = lena.flow.get_data(value) bin_value = value if make_value is None: graph_value = bin_value else: graph_value = make_value(bin_value) # for iteration below if not hasattr(graph_value, "__iter__"): graph_value = (graph_value,) # add each coordinate to respective array for arr, coord_ in zip(coords, chain(coord, graph_value)): arr.append(coord_) return _graph(coords, field_names=field_names, scale=scale) def init_bins(edges, value=0, deepcopy=False): """Initialize cells of the form *edges* with the given *value*. Return bins filled with copies of *value*. *Value* must be copyable, usual numbers will suit. If the value is mutable, use *deepcopy =* ``True`` (or the content of cells will be identical). Examples: >>> edges = [[0, 1], [0, 1]] >>> # one cell >>> init_bins(edges) [[0]] >>> # no need to use floats, >>> # because integers will automatically be cast to floats >>> # when used together >>> init_bins(edges, 0.0) [[0.0]] >>> init_bins([[0, 1, 2], [0, 1, 2]]) [[0, 0], [0, 0]] >>> init_bins([0, 1, 2]) [0, 0] """ nbins = len(edges) - 1 if not isinstance(edges[0], (list, tuple)): # edges is one-dimensional if deepcopy: return [copy.deepcopy(value) for _ in range(nbins)] else: return [value] * nbins for ind, arr in enumerate(edges): if ind == nbins: if deepcopy: return [copy.deepcopy(value) for _ in range(len(arr)-1)] else: return list([value] * (len(arr)-1)) bins = [] for _ in range(len(arr)-1): bins.append(init_bins(edges[ind+1:], value, deepcopy)) return bins def integral(bins, edges): """Compute integral (scale for a histogram). *bins* contain values, and *edges* form the mesh for the integration. Their format is defined in :class:`.histogram` description. """ total = 0 for ind, bin_content in iter_bins(bins): bin_lengths = [ edges[coord][i+1] - edges[coord][i] for coord, i in enumerate(ind) ] # product vol = _reduce(operator.mul, bin_lengths, 1) cell_integral = vol * bin_content total += cell_integral return total def iter_bins(bins): """Iterate on *bins*. Yield *(index, bin content)*. Edges with higher index are iterated first (that is z, then y, then x for a 3-dimensional histogram). """ # if not isinstance(bins, (list, tuple)): if not hasattr(bins, '__iter__'): # cell yield ((), bins) else: for ind, _ in enumerate(bins): for sub_ind, val in iter_bins(bins[ind]): yield (((ind,) + sub_ind), val) def iter_bins_with_edges(bins, edges): """Generate *(bin content, bin edges)* pairs. Bin edges is a tuple, such that its item at index i is *(lower bound, upper bound)* of the bin at i-th coordinate. Examples: >>> from lena.math import mesh >>> list(iter_bins_with_edges([0, 1, 2], edges=mesh((0, 3), 3))) [(0, ((0, 1.0),)), (1, ((1.0, 2.0),)), (2, ((2.0, 3),))] >>> >>> # 2-dimensional histogram >>> list(iter_bins_with_edges( ... bins=[[2]], edges=mesh(((0, 1), (0, 1)), (1, 1)) ... )) [(2, ((0, 1), (0, 1)))] .. versionadded:: 0.5 made public. """ # todo: only a list or also a tuple, an array? if not isinstance(edges[0], list): edges = [edges] bins_sizes = [len(edge)-1 for edge in edges] indices = [list(range(nbins)) for nbins in bins_sizes] for index in itertools.product(*indices): bin_ = lena.structures.get_bin_on_index(index, bins) edges_low = [] edges_high = [] for var, var_ind in enumerate(index): edges_low.append(edges[var][var_ind]) edges_high.append(edges[var][var_ind+1]) yield (bin_, tuple(zip(edges_low, edges_high))) def iter_cells(hist, ranges=None, coord_ranges=None): """Iterate cells of a histogram *hist*, possibly in a subrange. For each bin, yield a :class:`HistCell` containing *bin edges, bin content* and *bin index*. The order of iteration is the same as for :func:`iter_bins`. *ranges* are the ranges of bin indices to be used for each coordinate (the lower value is included, the upper value is excluded). *coord_ranges* set real coordinate ranges based on histogram edges. Obviously, they can be not exactly bin edges. If one of the ranges for the given coordinate is outside the histogram edges, then only existing histogram edges within the range are selected. If the coordinate range is completely outside histogram edges, nothing is yielded. If a lower or upper *coord_range* falls within a bin, this bin is yielded. Note that if a coordinate range falls on a bin edge, the number of generated bins can be unstable because of limited float precision. *ranges* and *coord_ranges* are tuples of tuples of limits in corresponding dimensions. For one-dimensional histogram it must be a tuple containing a tuple, for example *((None, None),)*. ``None`` as an upper or lower *range* means no limit (*((None, None),)* is equivalent to *((0, len(bins)),)* for a 1-dimensional histogram). If a *range* index is lower than 0 or higher than possible index, :exc:`.LenaValueError` is raised. If both *coord_ranges* and *ranges* are provided, :exc:`.LenaTypeError` is raised. """ # for bin_ind, bin_ in iter_bins(hist.bins): # yield HistCell(get_bin_edges(bin_ind, hist.edges), bin_, bin_ind) # if bins and edges are calculated each time, save the result now bins, edges = hist.bins, hist.edges # todo: hist.edges must be same # for 1- and multidimensional histograms. if hist.dim == 1: edges = (edges,) if coord_ranges is not None: if ranges is not None: raise lena.core.LenaTypeError( "only ranges or coord_ranges can be provided, not both" ) ranges = [] if not isinstance(coord_ranges[0], (tuple, list)): coord_ranges = (coord_ranges, ) for coord, coord_range in enumerate(coord_ranges): # todo: (dis?)allow None as an infinite range. # todo: raise or transpose unordered coordinates? # todo: change the order of function arguments. lower_bin_ind = get_bin_on_value_1d(coord_range[0], edges[coord]) if lower_bin_ind == -1: lower_bin_ind = 0 upper_bin_ind = get_bin_on_value_1d(coord_range[1], edges[coord]) max_ind = len(edges[coord]) if upper_bin_ind == max_ind: upper_bin_ind -= 1 if lower_bin_ind >= max_ind or upper_bin_ind <= 0: # histogram edges are outside the range. return ranges.append((lower_bin_ind, upper_bin_ind)) if not ranges: ranges = ((None, None),) * hist.dim real_ind_ranges = [] for coord, coord_range in enumerate(ranges): low, up = coord_range if low is None: low = 0 else: # negative indices should not be supported if low < 0: raise lena.core.LenaValueError( "low must be not less than 0 if provided" ) max_ind = len(edges[coord]) - 1 if up is None: up = max_ind else: # huge indices should not be supported as well. if up > max_ind: raise lena.core.LenaValueError( "up must not be greater than len(edges)-1, if provided" ) real_ind_ranges.append(list(range(low, up))) indices = list(itertools.product(*real_ind_ranges)) for ind in indices: yield HistCell(get_bin_edges(ind, edges), get_bin_on_index(ind, bins), ind) def make_hist_context(hist, context): """Update a deep copy of *context* with the context of a :class:`.histogram` *hist*. .. deprecated:: 0.5 histogram context is updated automatically during conversion in :class:`~.output.ToCSV`. Use histogram._update_context explicitly if needed. """ # absolutely unnecessary. context = copy.deepcopy(context) hist_context = { "histogram": { "dim": hist.dim, "nbins": hist.nbins, "ranges": hist.ranges } } context.update(hist_context) # just bad. return context def unify_1_md(bins, edges): """Unify 1- and multidimensional bins and edges. Return a tuple of *(bins, edges)*. Bins and multidimensional *edges* return unchanged, while one-dimensional *edges* are inserted into a list. """ if hasattr(edges[0], '__iter__'): # if isinstance(edges[0], (list, tuple)): return (bins, edges) else: return (bins, [edges])
7dc25a1cdbe8aa1d3de6749ec46a7c6168102b60
niccolozy/Snake
/Snake.py
350
3.65625
4
#!/usr/bin/env python class Snake: def __init__(self,body): self.body = [] for i in body: self.body.append(i) def moveTo(self,position,food=False): self.body.append(position) if not food: self.body.pop(0) def getHead(self): return self.body[-1] def getTail(self): return self.body[0] def getBody(self): return self.body
a808a33c6adcb71bbd1d22c7eaf0c65def77fc2a
harrisonBirkner/PythonSP20
/Lab4/Lab4/PenniesForPay.py
497
3.84375
4
daysWorked = int(input('How many days did you work? ')) totalPennies = 1 print(' Salary/Day ') print('------------') print('1 . $ 0.01') for day in range(2, daysWorked + 1): if totalPennies == 1: totalPennies = 2 dailyPennies = 2 else: dailyPennies *= 2 totalPennies += dailyPennies print(day, '. $', format((dailyPennies / 100),'10,.2f')) print('\nTotal Salary') print('------------') print('$', format(((totalPennies + 1) / 100), '10,.2f'))
2bd57172eef759520b0ab7917d1d9bcd08fa554e
seungbin-lee0330/2021
/programmers_coding_test/72410.py
1,008
3.53125
4
def solution(new_id): #문자열은 리스트 함수 사용한 수정이 안되고 슬라이싱으로 새롭게 정의해주는게 좋다 answer = '' #1 new_id = new_id.lower() # .lower()는 원본에 영향을 미치지 않는다 #2 for c in new_id: if c.isalpha() or c.isdigit() or c in ['-','_','.']: answer += c #3 while '..' in answer: # 생각하기 어렵다 아니면 리스트로 바꿔서 적당히 손봐줘야 할듯 answer = answer.replace('..', '.') #4 if len(answer) > 1: if answer[0] == '.': answer = answer[1:] if answer[-1] == '.': answer = answer[:-1] else: if answer == '.': answer = '' #5 if answer == '': answer = 'a' #6 if len(answer) > 15: answer = answer[:15] if answer[-1] == '.': answer = answer[:-1] #7 while len(answer) < 3: answer += answer[-1] return answer
d1d9484d883502e4d2d5a706bc471f6c926e19d0
ElliottBarbeau/Leetcode
/Problems/Subarrays With Product Less than a Target.py
1,122
3.765625
4
from collections import deque ''' def find_subarrays(arr, target): result = [] curr_product = 1 window_start = 0 n = len(arr) for window_end in range(n): curr_product *= arr[window_end] while (curr_product >= target): curr_product /= arr[window_start] window_start += 1 temp_list = deque() for i in range(window_end, window_start-1, -1): temp_list.appendleft(arr[i]) result.append(list(temp_list)) return result ''' def find_subarrays(arr, target): result = [] curr_product = 1 window_start = 0 n = len(arr) for window_end in range(n): if arr[window_end] < target: result.append([arr[window_end]]) curr_product *= arr[window_end] while curr_product >= target: curr_product /= arr[window_start] window_start += 1 if curr_product < target and arr[window_start : window_end + 1] not in result: result.append(arr[window_start : window_end + 1]) return result print(find_subarrays([2, 5, 3, 10], 30))
de916963c4d73d0e8fabe103902b5d8e3c825629
verlisa/python-challenge
/PyBank/TotalRevenue.py
493
3.578125
4
# import modules import csv import os # Lists to store data date =[] revenue = [] # Open the CSV file and read the data with open('budget_data_1.csv', newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # Skip header row next(csvreader, None) # Add date from each row for row in csvreader: #Add revenue revenue.append(row[1]) print(revenue) Total = sum(int(i) for i in revenue) print("Total Revenue: " + "$" + str(Total))
7e3b38690652c5b9021b76b10fd6f05a51dd537b
wncowan/python2_algorithms
/merge_sort.py
2,718
4.1875
4
def merge(list1, list2): print "merge called", list1, list2 sorted_list = [] reps = len(list1) + len(list2) for i in range(0, reps): if list1 == []: sorted_list.append(list2[0]) elif list2 == []: sorted_list.append(list1[0]) elif list1[0] < list2[0]: sorted_list.append(list1[0]) list1.pop(0) else: sorted_list.append(list2[0]) list2.pop(0) print "sorted_list", sorted_list return sorted_list def merge_sort(_list): print _list if len(_list) < 2: print "got here" return _list else: return merge(merge_sort(_list[0:len(_list)/2]), merge_sort(_list[len(_list)/2:])) print merge_sort([8, 23, 15, 89, 42, 16, 99, 27]) # [8,23] a sorted list is returned # merge([8], [23]) # merge(merge_sort([8]), merge_sort([23])) ---when merge_sort input is 1 element, it returns that input. Other wise it will keep splitting the input. # merge(merge_sort([8, 23]), merge_sort([15, 89])) # merge(merge_sort([8, 23, 15, 89]), merge_sort([42, 16, 99, 27])) # merge_sort([8, 23, 15, 89, 42, 16, 99, 27]) # [15,89] a sorted list is returned # merge([15], [89]) # merge(merge_sort([15]), merge_sort([89])) ---when merge_sort input is 1 element, it returns that input. Other wise it will keep splitting the input. # merge([8, 23], merge_sort([15, 89])) # merge(merge_sort([8, 23, 15, 89]), merge_sort([42, 16, 99, 27])) # merge_sort([8, 23, 15, 89, 42, 16, 99, 27]) # [8, 15, 23, 89] sorted lit returned # merge([8, 23], [15, 89]) # merge(merge_sort([8, 23, 15, 89]), merge_sort([42, 16, 99, 27])) # merge_sort([8, 23, 15, 89, 42, 16, 99, 27]) # [16,42] a sorted list is returned # merge([42], [16]) # merge(merge_sort([42]), merge_sort([16])) ---when merge_sort input is 1 element, it returns that input. Other wise it will keep splitting the input. # merge(merge_sort([42, 16]), merge_sort([99, 27])) # merge([8, 15, 23, 89], merge_sort([42, 16, 99, 27])) # merge_sort([8, 23, 15, 89, 42, 16, 99, 27]) # [27,99] a sorted list is returned # merge([99], [27]) # merge(merge_sort([99]), merge_sort([27])) ---when merge_sort input is 1 element, it returns that input. Other wise it will keep splitting the input. # merge([16, 42], merge_sort([99, 27])) # merge([8, 15, 23, 89], merge_sort([42, 16, 99, 27])) # merge_sort([8, 23, 15, 89, 42, 16, 99, 27]) # [16, 27, 42, 99] a sorted lit is return # merge([16, 42], [27, 99]) # merge([8, 15, 23, 89], merge_sort([42, 16, 99, 27])) # merge_sort([8, 23, 15, 89, 42, 16, 99, 27]) # [8, 15, 16, 23, 27, 42, 89, 99] sorted list is returned # merge([8, 15, 23, 89], [16, 27, 42, 99]) # merge_sort([8, 23, 15, 89, 42, 16, 99, 27])
5a371ebd9e98be90fa34ecc5f22f5c2eae006ff6
dynnoil/diving-in-python
/week2/lists_and_tuple_example.py
446
3.71875
4
from random import randint import statistics numbers = [] numbers_size = randint(15, 20) for _ in range(numbers_size): numbers.append(randint(10, 20)) print(numbers) # mutates list numbers.sort() half_size = len(numbers) // 2 median = None if numbers_size % 2 == 1: median = numbers[half_size] else: median = sum(numbers[half_size - 1:half_size + 1]) / 2 print(f"Median: {median}") assert median == statistics.median(numbers)
8d51ceab384f4cd70413b73ff78e948408c22499
WhoisBsa/Curso-de-Python
/3 - Estruturas Compostas/desafio 75, tupla teclado.py
702
4.1875
4
""" Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em um tupla. No final, mostre: A - Quantas vezes apareceu o valor 9; B - Em que posição foi digitado o primeiro valor 3; C - Quais foram os números pares. """ n = (int(input('1º numero: ')), int(input('2º numero: ')), int(input('3º numero: ')), int(input('4º numero: '))) print(f'Voce digitou os valores {n}') print(f'O numero 9 apareceu {n.count(9)} vezes') if 3 in n: print(f'O numero 3 foi digitado na posiçao {n.index(3)+1}') else: print('O número 3 não está nessa sequencia') print('O números pares dessa sequencia são: ', end='') for i in n: if i%2 == 0: print(i, end=' ')
81fe87f856c5f74713dec24a8acb618ea3514edf
gitank007/python-assignmnet
/assgn5/pr2.py
169
3.921875
4
# table of user choice x=int(input("print of table of user choice by entering the intial of the table ")) print("The table is ") for i in range(1,11): print(x*i)
899a6a810897dbb5feafa9272a69208a183b6921
Jason0221/backup
/HOME/笔记/python/Python基础代码-T/Trangle-Area-F.py
451
3.703125
4
#!/usr/bin/python #coding=utf-8 ''' #输入三角形三条边求面积 先判断两边之和是否大于第三边,符合条件,进行运算 运算公式为 s=(a+b+c)/2 面积为 s*(a+b)*(b+c)*(a+c) 在进行开方 ''' import math a = input() b = input() c = input() if a + b < c or a + c < b or b + c < a: print "input error" exit() s = (a + b + c) / 2 area = math.sqrt(s * (s - a) * (s - b) * (s - c)) print "The area is %.2f"%area
0d310bf719a92cfb35a26e1b5b986ed99274b592
TDewayneH/CTI110
/CTI-110/M7-Functions/M7HW1_TestGrades_Hicks.py
1,136
4.15625
4
#A program to show the average test scores and give a grade #15NOV17 #CTI-110 M7HW1 Test Average and Grade #Dewayne Hicks def main(): totalTest = getGrade() grade = giveGrade(totalTest) print("You average of your test is", totalTest, ". Which gives you a"\ " grade score of", grade) def getGrade(): grade = 0 total = 0 number = 0 while grade >= 0: grade = int(input("Enter your test score (one at a time enter "\ "a neagtive number to exit): ")) if grade >= 0: total = grade + total number += 1 return total / number def giveGrade(totalTest): A_score = 90 B_score = 80 C_score = 70 D_score = 60 F_score = 50 if totalTest >= A_score: return "A" elif totalTest < A_score and totalTest >= B_score: return "B" elif totalTest < B_score and totalTest >= C_score: return "C" elif totalTest < C_score and totalTest >= D_score: return "D" else: return "F" main() input("\n\nPress enter to exit")
079b7f0f6b066a1832f636f01ea7d119d9d5571b
prakritii/python_practice
/random_number.py
941
4.625
5
# 1. When the game starts. Print the name of game and ask the user for his/her name. # 2. randomly generate a number between 1 to 10 and ask the user to guess the number # 3. If user's guess is correct print win message else print loss message import random game = "Random selection of Number" print(game) user = input("Please enter your name: ") print(f"Hello {user}, Welcome to the Game") def game(): number = random.randint(1,5) num = int(input("Guess the number between 1 to 5: ")) if num == number: print(f"Congratulation {user} You won the Game, {user} you choosed {num} and the random number is {number}") else: print(f"You loose the Game, {user} you choosed {num} and the random number is {number}") user_decision = input("Do you wanna play again?, type yes if you want to play again: ") if user_decision == "yes": game() else: print(f"Bye, Bye {user}") game()
658ea93f8e7a039dc7ad6e64ca44526e0584817d
Jeevan1351/Python_Bootcamp
/Activity_17.py
357
3.546875
4
def get_lot(): line = input()[2:-2] return [tuple(t[1:-1].split("\', \'")) for t in line.split('), (')] def lot_to_cs(listOfTuples): string = "" for (a, b) in listOfTuples: string += a+"="+b+";" return string def display(l): print(l) def main(): lot = get_lot() cs = lot_to_cs(lot) display(cs) main()
765b8c6ba0b7534ebf6a0dd82dbc90a439353a4b
CSant04y/holbertonschool-higher_level_programming
/0x02-python-import_modules/3-infinite_add.py
198
3.734375
4
#!/usr/bin/python3 if __name__ == "__main__": import sys length = len(sys.argv) num1 = 0 for i in range(1, length): num1 += int(sys.argv[i]) print("{:d}".format(num1))
87c3a2086dd1e5cf6b59a90e1f010b4ec7508d25
Arturogv15/Compilador
/Tabla LR1/TablaLR.py
3,224
3.5
4
from pila import Pila as pila from Lexico import Lexico as lexico from numpy import array class TablaLR: def __init__(self): self.aceptacion = False self.tabla = array([[2,0,0,1], [0,0,-1,0], [0,3,-3,0], [2,0,0,4], [0,0,-2,0]]) self.columna = '' self.fila = '' self.accion = 0 self.contador = 0 self.reglas = [] self.numero_elementos = [] def regresa_tipo(self,simbolo): if simbolo == 'Identificador': return 0 elif simbolo == 'Operador de Adicion' or simbolo == 1: return 1 elif simbolo == '$' or simbolo == 2: return 2 elif simbolo == 0: return 0 elif simbolo == 'E' or simbolo == 3: return 3 elif simbolo == 4: return 4 def inicializar_reglas(self): self.reglas.append('E') self.reglas.append('E') self.numero_elementos.append(3) self.numero_elementos.append(1) def recorrer_entrada(self,cadena,tipos,pila): self.inicializar_reglas() while self.aceptacion == False: print("Cadena: " + str(cadena[self.contador])) self.fila = self.regresa_tipo(pila.top()) self.columna = self.regresa_tipo(tipos[self.contador]) self.accion = self.tabla[self.fila, self.columna] print("Fila: " + str(self.fila) + " pila_top: " + str(pila.top())) print("Columna: " + str(self.columna) + " tipos__: " + str(tipos[self.contador])) print("Accion: " + str(self.accion)) if self.accion == -1: print("Cadena aceptada") self.aceptacion = True break if self.accion > 0: pila.push(tipos[self.contador]) pila.push(self.accion) self.contador = self.contador+1 pila.muestra() print("\n----------------\n\n") #if self.contador == 5: # self.aceptacion = True elif self.accion < 0: self.accion = -self.accion self.accion = self.accion-1 for i in range(self.numero_elementos[self.accion-1]*2): pila.pop() self.fila = pila.top() pila.push(self.reglas[self.accion-1]) self.columna = pila.top() self.accion = self.tabla[self.fila, self.regresa_tipo(self.columna)] pila.push(self.accion) print("=====") pila.muestra() print("=====") # self.aceptacion = True else: print("Cadena no valida") self.aceptacion = True LR = TablaLR() p = pila() lex = lexico def main(): entrada = lex.sig_simbolo(lex) tipo_entrada = lex.tipos p.push('$') p.push(0) LR.recorrer_entrada(entrada,tipo_entrada,p) if __name__ == '__main__': main()
a3b8aac905e52a4488b3bd26e70cd76f3ff2d626
Rahul7656/Coding
/GeeksforGeeks/BST/7.BinaryTreeToBST.py
1,343
4.09375
4
''' Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree ''' class Node: def __init__(self,data): self.data = data self.left = self.right = None def storeInorder(root,a): if root: storeInorder(root.left,a) a.append(root.data) storeInorder(root.right,a) def NumberOfNodes(root): if root is None: return 0 return NumberOfNodes(root.left) + NumberOfNodes(root.right) + 1 def arrayToBST(arr,root): if root is None: return arrayToBST(arr,root.left) root.data = arr[0] arr.pop(0) arrayToBST(arr,root.right) def BinaryTreeToBST(root): if root is None: return arr = [] n = NumberOfNodes(root) storeInorder(root,arr) arr.sort() arrayToBST(arr,root) def inOrder(root): if root: inOrder(root.left) print(root.data,end=" ") inOrder(root.right) if __name__=="__main__": root = Node(10) root.left = Node(30) root.right = Node(15) root.left.left = Node(20) root.right.right = Node(5) print("Inorder of Binary Tree: ") inOrder(root) print() BinaryTreeToBST(root) print("Inorder of BST: ") inOrder(root)
ca583f8d897b318b7e97ef9f99b2cee575896de0
mladmon/CtCI
/02-linked_lists/2.3-delete_mid.py
761
4.125
4
from linked_list import * # O(1) runtime, O(1) space - trick is it doesn't work at the end def delete_middle(node): if node is not None and node.next is not None: node.data = node.next.data node.next = node.next.next # Let's test it! foo = Node(5) foo.append(7) foo.append(9) foo.append(13) print_list(foo) print('Attempting to delete 13:', end=' ') delete_middle(foo.search(13)) print_list(foo) print('Attempting to delete 9: ', end=' ') delete_middle(foo.search(9)) print_list(foo) print('Attempting to delete 5: ', end=' ') delete_middle(foo) # foo is now 7 print_list(foo) print('Attempting to delete 7: ', end=' ') delete_middle(foo) # foo is now 13 print_list(foo) print('Attempting to delete 13:', end=' ') delete_middle(foo) print_list(foo)
2e9661559017fd1334f1aaf1eba1c5f97816a024
Densatho/Python-2sem
/aula13/usuarios.py
819
3.65625
4
class User: def __init__(self, fname, lname, rg1, cpf1, saudacao): self.first_name = fname self.last_name = lname self.rg = rg1 self.cpf = cpf1 self.saudacao = saudacao def describe_user(self): print(f'RG: {self.rg}') print(f'CPF: {self.cpf}') print(f'Name: {self.first_name} {self.last_name}') def greet_user(self): print(f'{self.saudacao}') usuario = [] while True: nome = input('Nome: ') if nome == '': break unome = input('Ultimo Nome: ') rg = input('RG: ') cpf = input('CPF: ') sauda = input('Saudação: ') usuario.append(User(nome, unome, rg, cpf, sauda)) for i in range(0, len(usuario)): usuario[i].describe_user() usuario[i].greet_user()
c7f2497c3722fd2c715a86a077aa8e6137c049c9
JIANZM/algorithm
/symmetricalTree.py
935
4.0625
4
""" 对称二叉树 实现一个函数判断是否是对称二叉树 if __name__ == "__main__": a = TreeNode('a') b1 = TreeNode('b') b2 = TreeNode('b') c1 = TreeNode('c') c2 = TreeNode('c') a.left = b1 a.right = b2 b1.left = c1 b2.right = c2 s = Solution() print(s.isSymmetrical(a)) """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetrical(self, tree): left = tree.left right = tree.right return self._isSymmetrical(left, right) def _isSymmetrical(self, left, right): if left == right == None: return True if left == None or right == None: return False if left.val != right.val: return False return self._isSymmetrical(left.left, right.right) or self._isSymmetrical(left.right, right.left)
9250848e6b11e5fc9e3eb7b01173a74a37afc3b4
joaopver10/Python-EstruturaDeDados
/Aula 12/aula12.py
435
4.03125
4
dicionarioAluno = {} for i in range(1,3): nome = input('Digite o nome do aluno: ') nota = float(input('Digite a nota do aluno: ')) dicionarioAluno[nome] = nota with open('texto.txt', 'w') as texto: for nome, nota in dicionarioAluno.items(): texto.write(f'{nome}, {nota}\n') with open('C:/Users/joaop/Documents/GitHub/Curso-Python/Aula 12/texto.txt') as texto2: for linha in texto2: print(linha)
88ee5c33f13d311343e09f6c38deef7e179d7f5c
murphsp1/ProjectEuler_Python
/p19.py
325
3.875
4
#Counting Sundays import calendar def main(): years = xrange(1901, 2001) months = xrange(1,13) count = 0 for y in years: for m in months: days = [calendar.weekday(y,m,d+1) for d in range(calendar.mdays[m])] if days[0]==6: count += 1 print(m,y) print(count) if __name__ == ('__main__'): main()
2698a17ae1ca8ec08044bf93e86b787c358c32de
slayers80/python-text-analysis
/WordSearch/code.py
1,789
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue May 15 21:05:15 2018 @author: lwang """ def exist(board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ def dfs(board, coord, subword, m, n): #print coord, subword, visited if len(subword) == 1: if board[coord[0]][coord[1]] == subword: return True else: return False if not (board[coord[0]][coord[1]] == subword[0]): return False else: board[coord[0]][coord[1]] = '#' if coord[0]>0: x = coord[0]-1 y = coord[1] if dfs(board, [x,y], subword[1:], m, n): return True if coord[0]<m-1: x = coord[0]+1 y=coord[1] if dfs(board, [x,y], subword[1:], m, n): return True if coord[1]>0: x = coord[0] y = coord[1]-1 if dfs(board, [x,y], subword[1:], m, n): return True if coord[1]<n-1: x = coord[0] y = coord[1]+1 if dfs(board, [x,y], subword[1:], m, n): return True board[coord[0]][coord[1]] = subword[0] m = len(board) if not m: return False n = len(board[0]) if not n: return False for i in range(m): for j in range(n): if dfs(board, [i,j], word, m, n): return True return False
212adc5337a2c8c1894d74468af4589518af94e5
andyjliang/HackerEarthProblems
/algorithms/graphs/problems/utkarsh_in_gardens.py
1,629
4
4
''' Utkarsh has recently put on some weight. In order to lose weight, he has to run on boundary of gardens. But he lives in a country where there are no gardens. There are just many bidirectional roads between cities. Due to the situation, he is going to consider any cycle of length four as a garden. Formally a garden is considered to be a unordered set of 4 roads {r0, r1, r2, r3} where ri and ri+1 mod 4 share a city. Now he wonders how many distinct gardens are there in this country. Input format: The first integer contains N, the number of cities in the country. It is followed by space separated elements of N*N binary matrix G. G[i][j] = 1 denotes there is a road between ith city and jth city. A pair of cities has atmost one road connecting them. No road connects a city to itself. G is symmetric. Output format: Print the total number of gardens. Constraints: 1 ≤ N ≤ 2000 ''' from numpy import zeros from collections import defaultdict from itertools import combinations gardens = 0 n = int(raw_input()) adj = zeros(shape=(n,n),dtype=int) # Create primary link adj list with set of cities for each city for i in range(n): for j,x in enumerate(raw_input().split()): if int(x): adj[i][j] = 1 lateral_paths = set() for x1, row1 in enumerate(adj): row_comb = list(combinations([i for i, x in enumerate(row1) if x == 1], 2)) row_comb = set([tuple(sorted(each_comb)) for each_comb in row_comb]) # print row_comb, lateral_paths print row_comb.intersection(lateral_paths) gardens += len(row_comb.intersection(lateral_paths)) lateral_paths = lateral_paths.union(row_comb) print gardens
d9b7adf8f2262425fbc6a90af04f90e94866df0c
imvivek71/Machine-Learning
/LinearRegression/SimpleLinearRegression.py
1,398
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 9 14:13:34 2019 @author: vivek """ # Importing the dataset import numpy as np import pandas as pd import matplotlib.pyplot as plt # Importing the dataset dataset = pd.read_csv('/home/vivek/Desktop/Salary_Data.csv') x = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values # Splitting the datset into training set and test set from sklearn.model_selection import train_test_split x_train,x_test,y_train, y_test = train_test_split(x,y, test_size = 1/3, random_state=0) # Feature Scaling """ from sklearn.preprocessing import StandardScaler sc_x = StandardScaler() x_train =sc_x.fit_transform(x_train) x_test = sc_x.transform(x_test) """ # Fitting simple linear regression from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(x_train,y_train) y_pred = regressor.predict(x_test) # Visulaising the training set results plt.scatter(x_train,y_train, color ='red') plt.plot(x_train,regressor.predict(x_train), color = 'blue') plt.title('Experience vs Salary(Training Set)') plt.xlabel('Experience') plt.ylabel('Salary') plt.show() # Visulaising the test set results plt.scatter(x_test,y_test, color ='red') plt.plot(x_train,regressor.predict(x_train), color = 'blue') plt.title('Experience vs Salary(Test Set)') plt.xlabel('Experience') plt.ylabel('Salary') plt.show()
8a7233739b5a00d9d7d0b065a3ccd05d0995df93
YeswanthRajakumar/LeetCode_Problems
/Easy/day-4/Maximum 69 Number.py
529
3.765625
4
''' 1. change input to string 2. iterate through string 3.change 6 to 9 (or) 9 to 6 4. store to max(output,curr val) 5 finally,return the output ''' num = 9669 output = num str_num = str(num) for i in range(len(str_num)): #'9 6 6 9 ' check_num = list(str(num)) if check_num[i] == '6': check_num[i] = '9' # print(i,check_num) else: check_num[i] = '6' # print(i,check_num) curr_val = int(''.join(check_num)) if curr_val > output: output = curr_val print(output)