blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
7e57fca9717e62dbba10ab777a34eeb005af248a
sahil-dhingra/Reinforcement-Learning
/Project 3/Soccer_game.py
4,854
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 10 23:06:41 2019 @author: sahil.d """ import random class soccer: # Board board = [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1]] # Eligible moves moves = [[0,-1], [-1,0], [0, 0], [1, 0], [0, 1]] # Goal positions goal_A =[[0, 0], [0, 1]] goal_B =[[3, 0], [3, 1]] def __init__(self, width=4, height=2): # Player & Ball initial positions self.player_A = [2, 1] self.player_B = [1, 1] self.position_ball = [1, 1] self.ball_with = 'B' self.position_players = {'A' : self.player_A, 'B' : self.player_A} self.is_over = None self.goal = None self.order = None # Random start self.ball_with = ['A','B'][random.randrange(2)] p_ball = 2+random.randrange(4) self.position_ball = self.board[p_ball] free_spots = list(range(2,p_ball)) + list(range(p_ball+1,6)) self.player_A = self.position_ball if self.ball_with == 'A' else self.board[random.choice(free_spots)] self.player_B = self.position_ball if self.ball_with == 'B' else self.board[random.choice(free_spots)] # Simulate actions for A & B def play(self, action_A_i, action_B_i): action_A = self.moves[action_A_i] action_B = self.moves[action_B_i] if random.randrange(2) == 0: self.order = ['A','B'] for i in range(1): self.move_player(self.player_A, self.player_B, action_A, 'A') if self.goal: self.is_over = 1 break self.move_player(self.player_B, self.player_A, action_B, 'B') if self.goal: self.is_over = 1 break else: self.order = ['B','A'] for i in range(1): self.move_player(self.player_B, self.player_A, action_B, 'B') if self.goal: self.is_over = 1 break self.move_player(self.player_A, self.player_B, action_A, 'A') if self.goal: self.is_over = 1 break # Execute actions and modify environment states def move_player(self, player, opp_player, action, player_tag): new_player = list(map(sum, zip(player, action))) valid_move = 0 collision = 0 # Collision check if new_player == opp_player: collision = 1 self.position_ball = opp_player if self.ball_with == 'B' and player_tag == 'B': self.ball_with = 'A' if self.ball_with == 'A' and player_tag == 'A': self.ball_with = 'B' # Bounds check if new_player in self.board: valid_move = 1 # Goal conditions if new_player in self.goal_A and self.ball_with == player_tag: self.goal = 'A' if new_player in self.goal_B and self.ball_with == player_tag: self.goal = 'B' # Updating player positions if player_tag == 'A' and valid_move == 1 and collision == 0: self.player_A = new_player self.position_ball = new_player if self.ball_with == 'A' else self.position_ball if player_tag == 'B' and valid_move == 1 and collision == 0: self.player_B = new_player self.position_ball = new_player if self.ball_with == 'B' else self.position_ball # Return current state of the game in int form def i_state(self): A = 2*self.player_A[0] + self.player_A[1] B = 2*self.player_B[0] + self.player_B[1] Ball = 0 if self.ball_with == 'A' else 1 return (A, B, Ball) # Return actions in int form def i_actions(self, action_A, action_B): aA = action_A[0] + 2*action_A[1] + 2 aB = action_B[0] + 2*action_B[1] + 2 return [aA, aB] # Return rewards for [A, B] def get_reward(self): reward = [0, 0] if self.goal: if self.goal == 'A': reward = [100, -100] if self.goal == 'B': reward = [-100, 100] return reward # Game state def game_state(self): return self.player_A, self.player_B, self.position_ball, self.is_over, self.ball_with, self.goal # Reset game def reset(self): self.__init__()
e2db1ca72b5571cf8936182d89a2fe90c5b94a63
BPCao/Assignments
/ACTIVITIES/python/Calculator/test_operator.py
869
3.953125
4
import unittest from calculator import Calculator class CalculatorTests(unittest.TestCase): def setUp(self): self.Calculator = Calculator() print("SETUP") def test_add_two_numbers(self): print("test_add_two_numbers") result = self.Calculator.addition(2, 3) self.assertEqual(5, result) def test_subtract_two_numbers(self): print("test_subtract_two_numbers") result = self.Calculator.subtraction(3, 2) self.assertEqual(1, result) def test_multiply_two_numbers(self): print("test_multiply_two_numbers") result = self.Calculator.multiply(2, 3) self.assertEqual(6, result) def test_divide_two_numbers(self): result = self.Calculator.divide(6, 3) self.assertEqual(2, result) def tearDown(self): print("TEARDOWN") unittest.main()
5a44fb4b82fa16813715db13e98c94ae3c46b338
maris205/secondary_structure_detection
/src/evaluate/get_svm_data.py
1,159
3.5
4
#!/usr/bin/env python #coding=utf-8 import math import sys #ȡngramǷǴʵlabel word_dict={} #װشʵ def load_dict(dict_file_name): #سʼʵ dict_file = open(dict_file_name, "r") word_dict_count = {} for line in dict_file: sequence = line.strip() key = sequence.split('\t')[0] value = float(sequence.split('\t')[1]) word_dict[key] = value #print key,value #feature fileӵ pre dict file֮ #ʼpre dict fileӦword + "\t" + label if __name__=="__main__": if len(sys.argv) != 4: print "please input feature file, pre dict file, feature id" sys.exit() #load dict load_dict(sys.argv[1]) #ȡµֵļ dict_file = open(sys.argv[2], "r") feature_id = sys.argv[3] for line in dict_file: sequence = line.strip() key = sequence.split('\t')[0] if word_dict.has_key(key): print sequence + " " + feature_id + ":" + str(word_dict[key]) else: #no this feature print sequence + " " + feature_id + ":0"
8cf049b369af25b8d38303b54823b9254fe944ad
jasonwee/asus-rt-n14uhp-mrtg
/src/lesson_dates_and_times/datetime_time.py
216
3.609375
4
import datetime t = datetime.time(1, 2, 3) print(t) print('hour :', t.hour) print('minute :', t.minute) print('second :', t.second) print('microsecond:', t.microsecond) print('tzinfo :', t.tzinfo)
37ade2db051a8a2f06430bbd2df5891db528c234
Vegadhardik7/DATA_STRUCTURES_AND_ALGO
/SORTING/Bubble.py
244
4.03125
4
def bubblesort(A): for i in range(len(A)-1, 0, -1): for j in range(i): if A[j] > A[j+1]: A[j], A[j+1] = A[j+1], A[j] A = [85,6,15,24,36] print("Before Sorting:",A) bubblesort(A) print("After Sorting:",A)
21790ed3b7639de7b24fd9071ea20e1f76450963
Tyler-Carter/100-Days-of-Code
/Day 17 - The Quiz Project/main(example).py
426
3.59375
4
class User: def __init__(self, user_id, username): self.id = user_id self.username = username self.followers = 0 self.following = 0 def follow(self, user): user.followers += 1 self.following += 1 user_1 = User("001","angela") user_2 = User("002", "not_angela") user_1.follow(user_2) print(user_1.followers, user_1.following) print(user_2.followers, user_2.following)
5b8007d8375f10761eb33541e2613fa84419c0bc
DarioBernardo/hackerrank_exercises
/tree_and_graphs/tree_level_avg_bfs_and_dfs.py
2,231
3.859375
4
""" Given a binary tree, get the average value at each level of the tree. Explained here: https://vimeo.com/357608978 pass fbprep """ import numpy as np class Node(object): def __init__(self, value): self.value = value # print(f"creating node with value {self.value}") self.children = [] def add_child(self, value): if len(self.children) == 2: raise Exception(f"Can't add more children here! {len(self.children)}") self.children.append(Node(value)) def get_children(self): return self.children def get_bfs_level_avg(tree_head: Node) -> dict: def _update_result(result, level, children): children_for_level = result.get(level, []) for child in children: children_for_level.append(child.value) result[level] = children_for_level result = {} level = 1 queue = [tree_head] while len(queue) != 0: _update_result(result, level, queue) new_queue = [] for elem in queue: new_queue.extend(elem.get_children()) queue = new_queue level += 1 avgs = {} for key, value in result.items(): avgs[key] = np.mean(value) return avgs def get_dfs_level_avg(tree_head: Node) -> dict: result = {} level = 1 def _update_result(result, level, child): children_for_level = result.get(level, []) children_for_level.append(child.value) result[level] = children_for_level def _collect(level: int, node: Node, result): for child in node.children: _collect(level+1, child, result) _update_result(result, level, node) _collect(level, tree_head, result) avgs = {} for key, value in result.items(): avgs[key] = np.mean(value) return avgs th = Node(4) th.add_child(7) th.add_child(9) th.get_children()[1].add_child(6) th.get_children()[0].add_child(10) th.get_children()[0].add_child(2) th.get_children()[0].get_children()[1].add_child(6) th.get_children()[0].get_children()[1].get_children()[0].add_child(2) avgs = get_bfs_level_avg(th) print(avgs) avgs = get_dfs_level_avg(th) s = sorted(avgs.items(), key=lambda x: x[0]) print(s) print(avgs)
c00ed09a70a60293af61e1c35966ebb5e7da419d
hypersport/LeetCode
/valid-palindrome-ii/valid_palindrome_ii.py
561
3.65625
4
class Solution: def validPalindrome(self, s: str) -> bool: left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return self.isPalindrome(s, left+1, right) or self.isPalindrome(s, left, right-1) or False left += 1 right -= 1 return True def isPalindrome(self, s: str, left: int, right: int) -> bool: while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True
a7e104da027ed59a1df6a02033541beaf7cda39a
CodeVeish/py4e
/Completed/ex_02_03/ex_02_03.py
173
3.9375
4
entry_hours = input("Enter Total Hours Worked: ") entry_rate = input("Enter Employee Pay Rate: ") total_pay = float(entry_hours) * float(entry_rate) print("Pay,",total_pay)
5676088e0bf4a67a00cbefad8cc4db2c8e5992fb
Submitty/Submitty
/sbin/get_version_details.py
6,625
3.578125
4
#!/usr/bin/env python3 """ Generate a list of active versions for students. Useful for when the database gets bad values for the active version and then you can just run this function to get the proper values to update the database with. Basic usage of this script is ./get_version_details.py <semester> <course> which will get all students and their submissions for that particular semester course. You can also pass in optional flag to not have any indentation in the JSON produced as well as to write the JSON to a file instead of printing it out to stdout. To see all options, use ./get_version_details.py --help """ import argparse from datetime import datetime import json import os CONFIG_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'config') with open(os.path.join(CONFIG_PATH, 'submitty.json')) as open_file: JSON = json.load(open_file) DATA_PATH = os.path.join(JSON['submitty_data_dir'], "courses") def get_all_versions(semester, course): """ Given a semester and course, generate a dictionary of every student, that then contains every homework for that student and then all versions (with condensed details) for the version. Additionally, we mark one of these versions as "active" based on the value in their user_assignment_settings.json file. :param semester: semester to use for the active versions :type semester: str :param course: course to examine for the active versions :type semester: str :return: a dictionary containing all students and their active versions for all assignments for the course and semester :rtype: dict """ versions = {} submission_path = os.path.join(DATA_PATH, semester, course, "submissions") results_path = os.path.join(DATA_PATH, semester, course, "results") build_path = os.path.join(DATA_PATH, semester, course, "config", "build") if not os.path.isdir(submission_path) or not os.path.isdir(results_path): raise SystemError("Could not find submission or results directory") for homework in os.listdir(submission_path): testcases = [] buildfile = os.path.join(build_path, "build_" + homework + ".json") if os.path.isfile(buildfile): with open(buildfile) as open_file: parsed = json.load(open_file) if parsed['testcases']: for testcase in parsed['testcases']: testcases.append({ "title": testcase['title'], "points": testcase['points'], "extra_credit": testcase['extra_credit'], "hidden": testcase['hidden'] }) homework_path = os.path.join(submission_path, homework) for student in os.listdir(homework_path): if student not in versions: versions[student] = {} versions[student][homework] = {} with open(os.path.join( homework_path, student, "user_assignment_settings.json" ), "r") as read_file: json_file = json.load(read_file) active = int(json_file["active_version"]) results_student = os.path.join(results_path, homework, student) for version in sorted(os.listdir(results_student)): versions[student][homework][version] = get_version_details( semester, course, homework, student, version, testcases, active ) return versions def get_version_details( semester, course, homework, student, version, testcases, active_version ): results_path = os.path.join( DATA_PATH, semester, course, "results", homework, student, version ) entry = { 'autograding_non_hidden_non_extra_credit': 0, 'autograding_non_hidden_extra_credit': 0, 'autograding_hidden_non_extra_credit': 0, 'autograding_hidden_extra_credit': 0, 'submission_time': None, 'active': False } if int(version) == active_version: entry['active'] = True results_json = os.path.join(results_path, "results.json") if not os.path.isfile(results_json): return False with open(results_json) as open_file: open_file = json.load(open_file) if testcases: if len(testcases) != len(open_file['testcases']): return False for i in range(len(open_file['testcases'])): testcase = testcases[i] points = float(open_file['testcases'][i]['points_awarded']) hidden = "hidden" if testcase['hidden'] else "non_hidden" ec = "extra_credit" if testcase['extra_credit'] else "non_extra_credit" entry['autograding_' + hidden + "_" + ec] += points with open(os.path.join(results_path, "history.json")) as open_file: json_file = json.load(open_file) if isinstance(json_file, list): a = datetime.strptime( json_file[-1]['submission_time'], "%a %b %d %H:%M:%S %Z %Y" ) entry['submission_time'] = '{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}' \ .format(a.year, a.month, a.day, a.hour, a.minute, a.second) return entry def main(): """ Main program execution. Pretty prints the generated dictionary for students and their active versions """ parser = argparse.ArgumentParser( description="Generate a list of students and their version " "details for all assignments" ) parser.add_argument("semester", type=str, help="What semester to look at?") parser.add_argument("course", type=str, help="What course to look at?") parser.add_argument( "-n", "--no-indent", dest="no_indent", action="store_true", default=False ) parser.add_argument("-o", "--outfile", dest="outfile", type=str, default=None) args = parser.parse_args() versions = get_all_versions(args.semester, args.course) indent = None if not args.no_indent: indent = 4 if args.outfile: with open(args.outfile, 'w') as open_file: json.dump(versions, open_file, indent=indent) else: print(json.dumps(versions, indent=indent)) if __name__ == "__main__": main()
d010f9ac5a0e794325476ad3f6b7e7d17e8e6706
Tahaa2t/Py-basics
/Conditions.py
1,231
4.34375
4
#-----------------------------simple if else ------------------------------------ #BMI calculator height = float(input("Enter height in cm: ")) weight = float(input("Enter weight in kg: ")) height = height/100 bmi = round(weight/(height**2)) #round = round off to nearest whole number if bmi < 18.5: print(f"{bmi}: Underweight") elif bmi < 25: #else if() <---cpp = elif <---Python print(f"{bmi}: Normal weight") elif bmi < 30: print(f"{bmi}: overweight") elif bmi < 35: print(f"{bmi}: obese") elif bmi >= 35: print(f"{bmi}: overweight") else: print("Enter correct weight") #------------------------------Nested if else--------------------------------------- #Roller coaster ride, # if heignt >= 120cm and age >= 10, charge 10$ # if heignt >= 120cm and age < 10, charge 7$ # if height < 120cm, not allowed print("Welcome to rollercoaster") height = int(input("Enter height in cm: ")) age = int(input("Enter age: ")) if height >= 120: #>=, <=, >, <, ==, != if age >= 10: print("You're good to go, 10$") elif age <10: print("You're good to go, 7$") else: print("nope...!") #for multiple conditions, use 'and'/'or' # eg: if age < 10 and age >= 5: ...
dab39dca767fd9c96b77482dbcdc9c10ba21cfb8
moore1474/public
/archive/Practice/Python_Leetcode_Solutions/019_Remove_Nth_Node_From_End_of_List.py
856
3.5625
4
from _Node_Tests_Util import * class Solution(object): def removeNthFromEnd(self, head, n): current = head #Find first n ahead i = 0 while i < n: current = current.next if current is None: return head.next if n == i+1 else head i += 1 #Go to the end n_minus_one_back = head while current.next is not None: n_minus_one_back = n_minus_one_back.next current = current.next n_minus_one_back.next = n_minus_one_back.next.next return head ll = create_linked_list((1,2,3,4,5)) ll = Solution().removeNthFromEnd(ll, 2) printll(ll)#1 -> 2 -> 3 -> 5 -> None print('') ll2 = create_linked_list((1,2)) ll2 = Solution().removeNthFromEnd(ll2, 2) printll(ll2)#2 -> None
6697269aaf11f377b22ef5ef5188e7ce15ac307e
joaofig/dublin-buses
/geomath.py
1,913
3.578125
4
import numpy as np import math def haversine_np(lat1, lon1, lat2, lon2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) All args must be of equal length. Taken from here: https://stackoverflow.com/questions/29545704/fast-haversine-approximation-python-pandas#29546836 """ lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1.0 - a)) meters = 6378137.0 * c return meters def delta_location(lat, lon, bearing, meters): """ Calculates a destination location from a starting location, a bearing and a distance in meters. :param lat: Start latitude :param lon: Start longitude :param bearing: Bearing (North is zero degrees, measured clockwise) :param meters: Distance to displace from the starting point :return: Tuple with the new latitude and longitude """ delta = meters / 6378137.0 theta = math.radians(bearing) lat_r = math.radians(lat) lon_r = math.radians(lon) lat_r2 = math.asin(math.sin(lat_r) * math.cos(delta) + math.cos(lat_r) * math.sin(delta) * math.cos(theta)) lon_r2 = lon_r + math.atan2(math.sin(theta) * math.sin(delta) * math.cos(lat_r), math.cos(delta) - math.sin(lat_r) * math.sin(lat_r2)) return math.degrees(lat_r2), math.degrees(lon_r2) def delta_degree_to_meters(lat, lon, delta_lat=0, delta_lon=0): return haversine_np(lon, lat, lon + delta_lon, lat + delta_lat) def x_meters_to_degrees(meters, lat, lon): _, lon2 = delta_location(lat, lon, 90, meters) return abs(lon - lon2) def y_meters_to_degrees(meters, lat, lon): lat2, _ = delta_location(lat, lon, 0, meters) return abs(lat - lat2)
18f842c23d1a4bdcf4918f0e34cb2815fd70ba0d
ronaldoedicassio/Pyhthon
/Arquivos Exercicios/Exercicios/Ex072.py
631
4.09375
4
'''' Exercício Python 72: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso. ''' extenso =('zero','um','dois','tres','quatro','cinco','seis','sete','oito','nove','dez','onze','doze','treze','quatorze','quinze','dezesseis','dezessete','dezoito','dezenove','vinte') while True: num = int(input("Digite um numero entre 0 e 20: ")) if 0 <= num <= 20: print(f'Numero digitado foi {extenso[num]}') break else: print('Tente novamnte,', end=' ')
8b4bcb6a35682462e659e512120a59b1c21d1553
Gabrielganchev/week2final
/whilelloops/count_to_user2.py
140
3.8125
4
a=int(input()) b=1 while b<=a: print(b) b+=1 if b==a: print("good facking logic my friend sorry for the cursing words")
bf7ee1a39aee2fad47a6eeb69b7bdd7e82c7c95e
Aarav6790/pst_to_ist.py
/psttoist.py
1,160
3.90625
4
time = input("enter time in pst(hh:mm am/pm): ") hours = int(time[0:2]) min = int(time[3:5]) if hours == 11 and min == 30 and time[-2].lower()=='a': print("12 midnight") elif hours == 11 and min == 30 and time[-2].lower()=='p': print("12 noon") elif hours>11 and min>=30 and time[-2].lower()=='a': hours+=12 min+=30 if min >= 60: min = min-60 hours+=1 if hours>12: hours-=12 print('Same day\n', hours,':', min, 'PM') elif hours<11 and min<=30 and time[-2].lower()=='a': hours+=12 min+=30 if min >= 60: min = min-60 hours+=1 if hours>12: hours-=12 print('Same Day\n', hours,':', min, 'PM') elif hours>11 and min>=30 and time[-2].lower()=='p': hours+=12 min+=30 if min >= 60: min = min-60 hours+=1 if hours>12: hours-=12 print('Next Day\n', hours,':', min, 'AM') elif hours<11 and min<=30 and time[-2].lower()=='p': hours+=12 min+=30 if min >= 60: min = min-60 hours+=1 if hours>12: hours-=12 print('Next Day\n', hours,':', min, 'AM')
5cb19cf17aa1c58a9bc7bead4c6e5e80806b6bea
Dayanand-Chinchure/assignments
/python/prog/number.py
58
3.609375
4
a=[1,2,3,4,5] if 2 in a: print 'yes' else: print 'no`'
3c8c98a0b54582dc1fb99b1ff64238304d78b178
KseniaMIPT/Adamasta
/graph/test/B1.py
309
3.875
4
def check(matrix): N = len(matrix) for i in range(N): for j in range(N): if matrix[i][j] != matrix[j][i]: return 'NO' return 'YES' N = int(input()) matrix = [] for i in range(N): data = str(input()).split() matrix.append(data) print(check(matrix))
fbe2cec4ed178b7b0eb736167549af2697ec9959
Seok-in/PythonCodingTest
/Solution/BinarySearch/BinarySearch01.py
664
3.890625
4
n = int(input()) array_n = list(map(int, input().split())) m = int(input()) array_m = list(map(int, input().split())) array_n.sort() array_m.sort() def binary_search(array, target, start, end): if start > end: return False mid = (start+end)//2 if target == array[mid]: return True elif target < array[mid]: return binary_search(array, target, start, mid-1) elif target > array[mid]: return binary_search(array, target, mid+1, end) for i in array_m: if binary_search(array_n, i, 0, n) == True: print("yes", end=" ") elif binary_search(array_n, i, 0, n) == False: print("no", end=" ")
d6b1fcc56424f573e53b46bd9195ff89dd536360
gaeun0516/python_projects
/Basic_grammer/class/Remove_the_same_word.py
683
3.703125
4
class find: def __init__(self): self.flag = 0 self.input_word = i_word self.list_word = l_word self.same_list = same_word def find_word(self, input_word, list_word, same_list): for i in range(0, len(input_word)): for o in range(0, len(list_word)): if (input_word[i] == list_word[o]): flag = 1 break if (flag == 1): same_list.append(input_word[i]) return input_word, list_word, same_list i_word = input() l_word = ['C', 'A', 'M', 'B', 'R', 'I', 'D', 'G', 'E'] same_word = [] find(i_word, l_word, same_word) print(same_word)
de1c68abe87136803a8f72457664e8196c708ecd
Rex7/PythonDemo
/hackerrank/Sets/SymmetricDifference.py
370
4.34375
4
""" Given sets of integers, m and n, print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both. """ m = input() a = set(map(int, input().split())) n = input() b = set(map(int, input().split())) c = sorted(a.symmetric_difference(b)) for element in c: print(element)
646823aebe61a3800d7fbb3a45c6cd00d3ce3fa7
dntandan/VTU-Lab-Programs
/SEM-6 (File Structures Laboratory)/4 RRN Records/student_record_using_rrn.py
1,911
3.703125
4
rrn = [-1] cnt = 0 class student: def __init__(self, usn, name, sem): self.usn = usn self.name = name self.sem = sem def display_data(self): print(f"\nUSN -> {self.usn} \nName -> {self.name} \nSem -> {self.sem} \n") def pack(self, file): global cnt pos = file.tell() buf = self.usn + "|" + self.name + "|" + self.sem + "|" buf += "\n" file.write(buf) cnt += 1 rrn.append(pos) def unpack(pos): with open("record.txt", "r") as fp: fp.seek(pos) line = fp.readline() fields = line.strip("\n").split("|")[:-1] s1 = student(fields[0], fields[1], fields[2]) s1.display_data() def find_rrn(): global cnt, pos, rrn pos = 0 try: with open("record.txt", "r+") as fp: line = fp.readline() while line: rrn.append(pos) pos = fp.tell() # for returning the location of the next line cnt += 1 line = fp.readline() except: pass find_rrn() while True: choice = input( "\n1.Insert a record\n2.Search for a record using RRN\n3.Exit\nEnter your choice ==>\t" ) if choice == "1": usn = input("Enter USN \t") name = input("Enter name \t") sem = input("Enter sem \t") new_student = student(usn, name, sem) with open("record.txt", "a+") as fp: new_student.pack(fp) elif choice == "3": break elif choice == "2": print(cnt) rrn_search = int(input("Enter the RRN to be found \t")) if rrn_search > cnt or rrn_search < 0: print("Invalid RRN Entered!") continue print("RRN Record Found") pos = rrn[rrn_search] with open("record.txt", "r") as fp: unpack(pos) else: print("Invalid Input")
1608302fa6f26b5dc2211cf5cfd923bc10b96ecd
IswaryaNidadavolu/python
/divisible.py
142
4.21875
4
x=int(input("enter the number")) y=int(input("enter the number")) if x%y==0: print("divisible") else: print("not divisible")
be288af37233916858ea687e4335a403eec28631
tanoabeleyra/algorithms.py
/searching/binary_search.py
473
3.96875
4
def binary_search(sorted_collection, target_elem): lo, hi = 0, len(sorted_collection) - 1 while lo <= hi: mid = (lo + hi) // 2 current_elem = sorted_collection[mid] if target_elem == current_elem: # Element found! return mid if target_elem < current_elem: # Search on the left side hi = mid - 1 else: # Search on the right side lo = mid + 1 return None # The element doesn't exist
423d9b5c9e1a9f1cf2c191b3e29cbfbf4952628b
Moerai/algorithm
/goorm/bitaalgo/temins_hobby.py
288
3.59375
4
# 고속거듭제곱 알고리즘 # def power(a,b,m): # result = 1 # while b > 0: # if b % 2 != 0: # result = (result * a) % m # b //= 2 # a = (a * a) % m # return result n = int(input()) answer = 0 for i in range(1, n+1): answer = answer + i*i*i print(answer%1000000007)
2102569e3fa88e0597ae8a091ffbe399f21e9afb
sillyCod/multiprocessing_demo
/condition.py
1,889
3.578125
4
# -*- coding: utf-8 -*- # time: 19-3-8 下午4:44 """ 多进程状态下的condition不可用 """ import multiprocessing from multiprocessing import Manager from multiprocessing.managers import BaseManager import time class Producer(multiprocessing.Process): def __init__(self, con): self.condition = con super().__init__() def run(self): global count while True: if self.condition.acquire(): print(count) if count > 700: self.condition.wait() else: count = count+100 msg = self.name+' produce 100, count=' + str(count) print(msg) self.condition.notify() self.condition.release() time.sleep(1) class Consumer(multiprocessing.Process): def __init__(self, con): self.condition = con super().__init__() def run(self): global count while True: if self.condition.acquire(): if count < 100: self.condition.wait() else: count = count-50 msg = self.name+' consume 50, count='+str(count) print(msg) self.condition.notify() self.condition.release() time.sleep(1) count = 500 # con = multiprocessing.Condition() class MyManager(BaseManager): pass def test(): # MyManager.register() with Manager() as manager: print("address", manager.address) print("connect", manager.connect()) con = manager.Condition() for i in range(2): p = Producer(con) p.start() for i in range(2): c = Consumer(con) c.start() if __name__ == '__main__': test()
4d482588627d326f54efd8e53ac72ed472015efd
daniela-mejia/Python-Net-idf19-
/PhythonAssig/4-24-19 Assigment4/4-24 Assigment5(Palindrom).py
592
4.28125
4
#Return the reversal of an integer in hexa, eg. reverse (456) returns 654 def reverse(number): reverse = 0 while number > 0: #this I took from GOOGLE endDigit = number % 10 reverse = (reverse*10) + endDigit number = number // 10 def isPalindrome(number): reverse(number) uno = number if uno == reverse: print("yep, it's a Palindrome") else: print("Not a Palindrome...Try again") def main(): number = eval(input("Please enter a number to check if Palindrome: ")) isPalindrome(number) main()
960e8264718ae5ae48d461e2de2e774f00df580c
suyeon-yang/CP1404practicals
/prac_01/loops.py
468
4
4
""" first loop """ for i in range(1, 21, 2): print(i, end=' ') print() """ second loop """ for j in range(0, 100, 10): print(j, end=' ') print() """ third loop """ for i in range(20, 0, -1): print(i, end=' ') print() """ fourth loop """ stars = int(input("Number of stars: ")) for j in range(stars): print('*', end=' ') print() """ fifth loop """ stars = int(input("Number of stars: ")) for i in range(1, stars + 1): print('*' * i) print()
58011fd09f64afe5b2a56118bfa131800b6039ec
aidangainor/Physics-97b-TTL-CPU
/src/microcoder/Instruction.py
5,019
3.609375
4
from MicroInstruction import MicroInstruction from Encoders import * class Instruction: """Corresponds to an instruction from the ISA level. It stores a sequence of up to 16 micro instructions needed to execute a programmer specified instruction. Default micro instructions are specified as class varialbes to deal with instruction fetch, reset, and interrupt routines. Micro instructions with "NoneType" in Python are unused, and will be written as 0xFF by EEPROM programmer. """ # Rest program counter and MAR, then do instruction fetch rst_micro_instructions = [MicroInstruction(inc_PC="0", clear_PC="0", clear_MAR="0", clear_condition_bit="0")] # Output ROM/RAM and clock in instruction register rst_micro_instructions.append(MicroInstruction(inc_PC="0", device_onto_db=DB_DEVICE_TO_BITSTRING["ROM/RAM"], device_onto_ab=AB_DEVICE_TO_BITSTRING["PC"], device_write_enable=DB_DEVICE_TO_BITSTRING["IR"])) # It is quite common to fetch two bytes from memory that are pointed to by PC + 1 and PC + 2 # These values are loading into PC in little endian format, so lets store this sequence of u-insts # Although we specify "PC_LOW" as our write target, the control unit actually writes into the PC low buffer so we can keep the original PC for next u-inst fetch_new_pc_instructions = [MicroInstruction(device_onto_db=DB_DEVICE_TO_BITSTRING["ROM/RAM"], device_onto_ab=AB_DEVICE_TO_BITSTRING["PC"], device_write_enable=DB_DEVICE_TO_BITSTRING["PC_LOW"], inc_PC="1")] # Now when we specify "PC_HIGH" as write target, the control unit actually specifies PC_HIGH to clock in data bus contents while PC_LOW clocks in PC buffer contents # This is done in parallel fetch_new_pc_instructions.append(MicroInstruction(inc_PC="0", device_onto_db=DB_DEVICE_TO_BITSTRING["ROM/RAM"], device_onto_ab=AB_DEVICE_TO_BITSTRING["PC"], device_write_enable=DB_DEVICE_TO_BITSTRING["PC_HIGH"])) # Auto generate instruction fetch, instruction fetch is always last micro instruction of an instruction # Program counter is incremented during instruction execution # Output ROM/RAM and clock in instruction register ir_fetch_instructions = [MicroInstruction(inc_PC="0", clear_condition_bit="0", device_onto_db=DB_DEVICE_TO_BITSTRING["ROM/RAM"], device_onto_ab=AB_DEVICE_TO_BITSTRING["PC"], device_write_enable=DB_DEVICE_TO_BITSTRING["IR"])] def __init__(self): self.instructions_added = 0 self.inst_micro_instructions = [None] * 16 # An instruction consists of 16 micro instructions # Note that only a subset of these 16 micro instructions will actually be used def add_u_instruction(self, u_inst): """Add a micro instruction to the instance of an instruction. """ self.inst_micro_instructions[self.instructions_added] = u_inst self.instructions_added += 1 def add_u_instructions(self, u_insts): """Add N micro instructions to instance of an instruction. """ for u_inst in u_insts: self.add_u_instruction(u_inst) def add_fetch_ir_sequence(self): """Append a sequence of micro instructions that fetch next instruction """ self.add_u_instructions(self.ir_fetch_instructions) def add_fetch_pc_sequence(self): """Append a sequence of micro instructions that swap the PC with 16 bit address operand stored in memory. """ self.add_u_instructions(self.fetch_new_pc_instructions) def add_def_instruction(self): """Append a sequence of 4 micro instructions that does nothing to the computers state """ self.add_u_instructions([MicroInstruction(inc_PC="0"), MicroInstruction(inc_PC="0"), MicroInstruction(inc_PC="0"), MicroInstruction(inc_PC="1")]) def add_skip_two_bytes_u_insts(self): self.add_u_instructions([MicroInstruction(inc_PC="1"), MicroInstruction(inc_PC="1")]) def generate_interrupt_sequence(self): """Return a constant interrupt handling routine (in microcode, of course!). Interrupt only occurs on next instruction cycle, this can be accomplished by checking if feedback register contains 4 0's """ pass def get_u_instructions(self): """Return all micro instructions that constitute an instruction """ return self.inst_micro_instructions def get_reset_sequence(self): """Returns a sequnce of u-insts that reset the CPU """ return self.rst_micro_instructions
4aa3552eaf65caf7d09f530a47b6105c3feb81c5
SoosX/python_study
/chapter3/3.2.py
535
3.828125
4
motorcycles =['honda','yamaha','suzuki'] print(motorcycles) motorcycles[2]='ducati' print(motorcycles) motorcycles.append('suzuki') print(motorcycles) motorcyclestwo =[] motorcyclestwo.append('1honda') motorcyclestwo.append('2yamaha') motorcyclestwo.append('3suzuki') print(motorcyclestwo) motorcyclestwo.insert(1,'ducati') print(motorcyclestwo) del motorcyclestwo[0] print(motorcyclestwo) fruits = ['apple','pear','banana'] print(fruits) poppedfruit=fruits.pop(1) print(poppedfruit) print(fruits) fruits.remove('apple') print(fruits)
208dfefa977b9d6c31755038161ddc592f01c2c3
Zzpecter/Coursera_AlgorithmicToolbox
/week2/6_last_digit_sum_of_fib_numbers.py
948
4.09375
4
# Created by: René Vilar S. # Algorithmic Toolbox - Coursera 2021 import time global start MAX_TIME = 9.9 def get_fibonacci_rene(n): pisano_period = get_pisano_period(10) remainder_n = n % pisano_period if remainder_n == 0: return 0 previous, current = 0, 1 for _ in range(remainder_n - 1): if time.time() - start > MAX_TIME: raise TimeoutError previous, current = current, previous + current return current % 10 def get_pisano_period(m): previous, current = 0, 1 for i in range(m ** 2): previous, current = current, (previous + current) % m # Pisano Period always starts with 01 if (previous == 0 and current == 1): return i + 1 def get_last_digit_of_sum(n): return (get_fibonacci_rene(n + 2) - 1)%10 if __name__ == '__main__': n = int(input()) start = time.time() print(get_last_digit_of_sum(n)) end = time.time()
d12e6e1c9d63dde4e5f2b96e80eb491680d55c0e
cpiehl/Project-Euler
/python/092-Square_digit_chains/euler092.py
1,759
3.53125
4
#!/usr/bin/env python from Euler import sum_squared_digits, timing # A number chain is created by continuously adding the square of the digits # in a number to form a new number until it has been seen before. # For example, # 44 → 32 → 13 → 10 → 1 → 1 # 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 # Therefore any chain that arrives at 1 or 89 will become stuck in an # endless loop. What is most amazing is that EVERY starting number # will eventually arrive at 1 or 89. # How many starting numbers below ten million will arrive at 89? # Answer: 8581146 # Still takes ~24s to solve, needs a better algorithm @timing def main(): #~ cyclical = {1, 4, 10, 13, 16, 20, 32, 37, 42, 44, 58, 89, 145} cyclical = {'1', '4', '01', '13', '16', '02', '23', '37', '24', '44', '58', '89', '145'} #~ happy = {44, 32, 13, 10, 1} #~ unhappy = {4, 16, 37, 58, 89, 145, 42, 20} unhappy = {'4', '16', '37', '58', '89', '145', '24', '02'} L = 7 # limit expressed as 10**L count = 0 for i in range(1,10**L): j = i chain = set() # All numbers in the chain, for if we come across them later while True: jstr = ''.join(sorted(str(j))) if jstr in cyclical: break #~ while j not in cyclical: #~ print([int(c)**2 for c in str(j)], j) #~ j = sum([int(c)**2 for c in str(j)]) # sum squares of digits #~ j = sum([int(c)*int(c) for c in str(j)]) # mult is faster than pow #~ j = sum((int(c)*int(c) for c in str(j))) # generator is faster j = sum_squared_digits(j) # pure ints is even faster chain.add(jstr) #~ chain.add(j) cyclical |= chain # 2x faster than cyclical = cyclical | chain if jstr in unhappy: unhappy |= chain count += 1 print(count) if __name__ == "__main__": main()
7144e90bf618377c31e00c4e60496d8e028034db
NarayanS321/Selenium-Project
/code cha10.py
446
4.34375
4
def isPalindrome(str): # ABCBA reverse_str = reverse(str) #print(reverse_str) result = False if reverse_str == str: #print("true") result = True else: # print("false") result = False return result # Python code to reverse a string # using extended slice syntax # Function to reverse a string def reverse(string): string = string[::-1] return string print(isPalindrome("wow"))
b5a9ba7cd6fa97d3990c7c70465c87af837c1dc3
txcavscout/tempConversion
/temp.py
796
4.34375
4
# Temp conversion print('Temperature Conversion Tool.') try: convert_type = int(input("Enter 1 for Celsius to Fareheit. Enter 2 for Farenheit to Celsius: ")) if convert_type == 1: temp = int(input('Enter the temp in celsius to convert: ')) converted = temp * 9/5 + 32 print(f'{temp} celsius is {converted} degrees farenheit.\n') if convert_type == 2: temp = int(input('Enter the temp in farenheit to convert: ')) converted = (temp - 32) * 5/9 converted = int(round(converted, 0)) print(f'{temp} degrees farenheit is {converted} degree celsius.') if convert_type > 2 or convert_type < 1: print("You must enter 1 or 2.") except ValueError: val = int print("You must enter 1 or 2.")
157aa0f7db30f8bd33f617c6ae49188d35793dfa
vierbergenlars/Informatica
/HC 2/types.py
685
3.671875
4
# Negeer al die try en except zever, dat is gewoon om effe fouten te vermijden # invoer = raw_input("Tekst voor de invoer > ") print "Invoer: " print invoer, "type: ", print type(invoer) # Welk is het type van deze variabele? # Omzetten naar een int try: print "Omzetten naar int: " omgezet = int(invoer) print omgezet, "type: ", print type(omgezet) # // Negeer onderstaand except ValueError: print "Oké, dat kan duidelijk geen int zijn!" # Of naar een float try: print "Omzetten naar float: " omgezet = float(invoer) print omgezet, "type: ", print type(omgezet) # // Negeer onderstaand except ValueError: print "Oké, dit is geen float"
51f8261cf381af3ba214ec0f410c25ddb98363e7
ccacoba/cmsc117project
/dmcspy/numdiff/second.py
1,702
3.703125
4
#credits: PAALAN import numpy as np from matplotlib import pyplot as plt #plt.rc('text', usetex=True) plt.rc('font', family='serif') #machine epsilon eps = np.finfo('float').eps #4/3 # stepsizes h = np.array([0.1/(1.1**k) for k in range(500)]) #takes stepsizes greather than eps #h = h[h>eps] from time import time def second_derivative(): start = time() """ This function shows the graph of the Second Derivative Formula f"(x) = [f(x+h) - 2f(x) + f(x-h)]/(h^2). The truncation error is -(h^2/12)f""(eps). Variables: - eps machine epsilon equal to np.finfo('float').eps - h step size Output: 1. Graph of Second Derivative Formula with line truncation error, predicted optimal h, and horizontal line(for reference) """ error = np.abs(1 - ( np.exp(h) - 2 + np.exp(-h) )/(h**2)) fig = plt.figure() plt.loglog(h, error, color='blue', linewidth = 2.0, label = r'$|1 - (e^h - 2 + e^{-h} )/h^2|$') plt.xlabel(r'$h$', fontsize=12) plt.title('Second Derivative Formula') plt.loglog(h, h**2/12, color='red', linestyle = '--', linewidth = 2.0, label = r'$h^2/12$') plt.loglog(h, 24*eps/(h**2), color = 'green', linestyle = '--', linewidth = 2.0, label = r'$24\epsilon/h^{1/2}$') plt.loglog([6.*(eps)**0.25, 6.*(eps)**0.25], [0.0,1.5], linewidth=2.0, label=r'predicted optimal $h$',linestyle= '--') plt.plot([0,10**-1],[10**-10,10**-10], label=r'horizontal line $y=10^{-10}$') plt.ylim(bottom=1e-12, top=2.0) plt.legend(loc = 'best', fontsize = 15) plt.xticks(fontsize = 14) plt.yticks(fontsize = 14) plt.gca().autoscale(enable = True, axis='x', tight =True) end = time() plt.show() return end-start #second_derivative()
8c736003b6f4ab0d32850552dadb2d7cede55fb7
Gromy4/Site
/Site/test_4.py
506
3.515625
4
import unittest import re import app class Test_test4(unittest.TestCase): def test_phone_True(self): phone = ["8-931-233-49-72"] for i in range (len(phone)): regex=re.search(r'^([+]?\d{1,2}[-\s]?|)\d{3}[-\s]?\d{3}[-\s]?\d{2}[-\s]?\d{2}$',phone[i]) if (regex == None): a=False if (regex != None): a=True self.assertTrue(a) if __name__ == '__main__': unittest.main()
6f088fd9ff8670f0006f28e3a8a01ec6d1a02709
nagireddy96666/Interview_-python
/COMPANIES/pracice.bangalur/numpy/nump.py
153
3.703125
4
import numpy as np x=np.array([[1,2],[3,4]]) y=np.array([[5,6],[7,8]]) print x+y print np.add(x,y) print x*y print np.multiply(x,y) print np.reversed(x)
861e7381eee1b427bb306709c4af71c9a75c2e41
suton5/partia-flood-warning-system
/test_flood.py
2,164
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 26 16:25:50 2017 @author: limyiheng """ import pytest from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.flood import stations_highest_rel_level, stations_level_over_threshold #stations = build_station_list() #update_water_levels(stations) #new_list = stations_level_over_threshold(stations, 0.2) #print(new_list) #test for 2B def test_stations_level_over_threshold(): """check if the elements in the list are ranked in desceding order according to their relative water level, check if each element in the list is a tuple of 2""" stations = build_station_list() update_water_levels(stations) new_list = stations_level_over_threshold(stations, 0.2) for i in new_list: #check if they are tuples assert type(i) == tuple #check if the tuples have 2 items assert len(i) == 2 for i in range(len(new_list)-1): #check if the order is correct if new_list[i][1] > new_list[i+1][1]: True else: False assert True if new_list[i][1] <= 0.2: False else: True assert True #test for 2C def test_stations_highest_rel_level(): """check if the elements in the list are ranked in desceding order according to their relative water level, check if each element in the list is a tuple of 2, check if the length of the list is N""" stations = build_station_list() update_water_levels(stations) new_list_2 = stations_highest_rel_level(stations, 10) assert len(new_list_2) == 10 for i in new_list_2: #check if they are tuples assert type(i) == tuple #check if the tuples have 2 items assert len(i) == 2 for i in range(len(new_list_2)-1): #check if the order is correct if new_list_2[i][1] > new_list_2[i+1][1]: True else: False assert True
4393b13e151064175366d0d3a7dfcf2914506dda
lclong728/Daily-Coding-Problem
/problem #1-#20/dailyCoding#10.py
469
3.734375
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 26 19:55:12 2018 @author: lenovo """ """ DailyCodingProblem #10 26/07/2018 Asked by: Apple Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds """ import time def delay_function(function, sleep_time): print('delay function start!') time.sleep(sleep_time) return function def function(): return 'after delay' print(delay_function(function(), 10))
a0dd69ff5d72d041c1ed2cf297fe89924b8ac161
ioam/featuremapper
/featuremapper/distribution.py
41,156
3.5
4
""" Distribution class """ # To do: # # - wrap bins for cyclic histograms # - check use of float() in count_mag() etc # - clarify comment about negative selectivity # # - function to return value in a range (like a real histogram) # - cache values # - assumes cyclic axes start at 0: include a shift based on range # # - is there a way to make this work for arrays without mentioning # "array" anywhere in here? # - should this be two classes: one for the core (which would be # small though) and another for statistics? import numpy as np import param import cmath import math unavailable_scipy_optimize = False try: from scipy import optimize except ImportError: param.Parameterized().debug("scipy.optimize not available, dummy von Mises fit") unavailable_scipy_optimize = True def wrap(lower, upper, x): """ Circularly alias the numeric value x into the range [lower,upper). Valid for cyclic quantities like orientations or hues. """ #I have no idea how I came up with this algorithm; it should be simplified. # # Note that Python's % operator works on floats and arrays; # usually one can simply use that instead. E.g. to wrap array or # scalar x into 0,2*pi, just use "x % (2*pi)". axis_range = upper - lower return lower + (x - lower + 2.0 * axis_range * (1.0 - math.floor(x / (2.0 * axis_range)))) % axis_range def calc_theta(bins, axis_range): """ Convert a bin number to a direction in radians. Works for NumPy arrays of bin numbers, returning an array of directions. """ return np.exp( (2.0 * np.pi) * bins / axis_range * 1.0j ) class Distribution(object): """ Holds a distribution of the values f(x) associated with a variable x. A Distribution is a histogram-like object that is a dictionary of samples. Each sample is an x:f(x) pair, where x is called the feature_bin and f(x) is called the value(). Each feature_bin's value is typically maintained as the sum of all the values that have been placed into it. The feature_bin axis is continuous, and can represent a continuous quantity without discretization. Alternatively, this class can be used as a traditional histogram by either discretizing the feature_bin number before adding each sample, or by binning the values in the final Distribution. Distributions are bounded by the specified axis_bounds, and can either be cyclic (like directions or hues) or non-cyclic. For cyclic distributions, samples provided outside the axis_bounds will be wrapped back into the bound range, as is appropriate for quantities like directions. For non-cyclic distributions, providing samples outside the axis_bounds will result in a ValueError. In addition to the values, can also return the counts, i.e., the number of times that a sample has been added with the given feature_bin. Not all instances of this class will be a true distribution in the mathematical sense; e.g. the values will have to be normalized before they can be considered a probability distribution. If keep_peak=True, the value stored in each feature_bin will be the maximum of all values ever added, instead of the sum. The distribution will thus be a record of the maximum value seen at each feature_bin, also known as an envelope. """ # Holds the number of times that undefined values have been # returned from calculations for any instance of this class, # e.g. calls to vector_direction() or vector_selectivity() when no # value is non-zero. Useful for warning users when the values are # not meaningful. undefined_vals = 0 def __init__(self, axis_bounds, axis_range, cyclic, data, counts, total_count, total_value, theta): self._data = data self._counts = counts # total_count and total_value hold the total number and sum # (respectively) of values that have ever been provided for # each feature_bin. For a simple distribution these will be the same as # sum_counts() and sum_values(). self.total_count = total_count self.total_value = total_value self.axis_bounds = axis_bounds self.axis_range = axis_range self.cyclic = cyclic self._pop_store = None # Cache busy data self._keys = list(data.keys()) self._values = list(data.values()) self._theta = theta if self.cyclic: # Cache the vector sum self._vector_sum = self._fast_vector_sum(self._values, theta) else: self._vector_sum = None def data(self): """ Answer a dictionary with bins as keys. """ return self._data def pop(self, feature_bin): """ Remove the entry with bin from the distribution. """ if self._pop_store is not None: raise Exception("Distribution: attempt to pop value before outstanding restore") self._pop_store = self._data.pop(feature_bin) self._keys = list(self._data.keys()) self._values = list(self._data.values()) def restore(self, feature_bin): """ Restore the entry with bin from the distribution. Only valid if called after a pop. """ if self._pop_store is None: raise Exception("Distribution: attempt to restore value before pop") self._data[feature_bin] = self._pop_store self._pop_store = None self._keys = list(self._data.keys()) self._values = list(self._data.values()) def vector_sum(self): """ Return the vector sum of the distribution as a tuple (magnitude, avgbinnum). Each feature_bin contributes a vector of length equal to its value, at a direction corresponding to the feature_bin number. Specifically, the total feature_bin number range is mapped into a direction range [0,2pi]. For a cyclic distribution, the avgbinnum will be a continuous measure analogous to the max_value_bin() of the distribution. But this quantity has more precision than max_value_bin() because it is computed from the entire distribution instead of just the peak feature_bin. However, it is likely to be useful only for uniform or very dense sampling; with sparse, non-uniform sampling the estimates will be biased significantly by the particular samples chosen. The avgbinnum is not meaningful when the magnitude is 0, because a zero-length vector has no direction. To find out whether such cases occurred, you can compare the value of undefined_vals before and after a series of calls to this function. This tries to use cached values of this. """ if self._vector_sum is None: # There is a non cyclic distribution that is using this. # Calculate and then cache it # First check if there is a cached theta. If not derive it. if self._theta is None: self._theta = calc_theta(np.array(self._keys), self.axis_range) self._vector_sum = self._fast_vector_sum(self._values, self._theta) return self._vector_sum def _fast_vector_sum(self, values, theta): """ Return the vector sum of the distribution as a tuple (magnitude, avgbinnum). This implementation assumes that the values of the distribution needed for the vector sum will not be changed and depends on cached values. """ # vectors are represented in polar form as complex numbers v_sum = np.inner(values, theta) magnitude = abs(v_sum) direction = cmath.phase(v_sum) if v_sum == 0: self.undefined_vals += 1 direction_radians = self._radians_to_bins(direction) # wrap the direction because arctan2 returns principal values wrapped_direction = wrap(self.axis_bounds[0], self.axis_bounds[1], direction_radians) return (magnitude, wrapped_direction) def get_value(self, feature_bin): """ Return the value of the specified feature_bin. (Return None if there is no such feature_bin.) """ return self._data.get(feature_bin) def get_count(self, feature_bin): """ Return the count from the specified feature_bin. (Return None if there is no such feature_bin.) """ return self._counts.get(feature_bin) def values(self): """ Return a list of values. Various statistics can then be calculated if desired: sum(vals) (total of all values) max(vals) (highest value in any feature_bin) Note that the feature_bin-order of values returned does not necessarily match that returned by counts(). """ return self._values def counts(self): """ Return a list of values. Various statistics can then be calculated if desired: sum(counts) (total of all counts) max(counts) (highest count in any feature_bin) Note that the feature_bin-order of values returned does not necessarily match that returned by values(). """ return list(self._counts.values()) def bins(self): """ Return a list of bins that have been populated. """ return self._keys def sub_distr( self, distr ): """ Subtract the given distribution from the current one. Only existing bins are modified, new bins in the given distribution are discarded without raising errors. Note that total_value and total_count are not affected, and keep_peak is ignored, therefore analysis relying on these values should not call this method. """ for b in distr.bins(): if b in self.bins(): v = distr._data.get(b) if v is not None: self._data[b] -= v def max_value_bin(self): """ Return the feature_bin with the largest value. Note that uses cached values so that pop and restore need to be used if want with altered distribution. """ return self._keys[np.argmax(self._values)] def weighted_sum(self): """Return the sum of each value times its feature_bin.""" return np.inner(self._keys, self._values) def value_mag(self, feature_bin): """Return the value of a single feature_bin as a proportion of total_value.""" return self._safe_divide(self._data.get(feature_bin), self.total_value) def count_mag(self, feature_bin): """Return the count of a single feature_bin as a proportion of total_count.""" return self._safe_divide(float(self._counts.get(feature_bin)), float(self.total_count)) # use of float() def _bins_to_radians(self, bin): """ Convert a bin number to a direction in radians. Works for NumPy arrays of bin numbers, returning an array of directions. """ return (2*np.pi)*bin/self.axis_range def _radians_to_bins(self, direction): """ Convert a direction in radians into a feature_bin number. Works for NumPy arrays of direction, returning an array of feature_bin numbers. """ return direction * self.axis_range / (2 * np.pi) def _safe_divide(self, numerator, denominator): """ Division routine that avoids division-by-zero errors (returning zero in such cases) but keeps track of them for undefined_values(). """ if denominator == 0: self.undefined_vals += 1 return 0 else: return numerator/denominator class Pref(dict): """ This class simply collects named arguments into a dictionary the main purpose is to make pretty readable the output of DistributionStatisticFn functions. In addition, trap missing keys """ def __init__(self, **args): dict.__init__(self, **args) def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return None class DistributionStatisticFn(param.Parameterized): """ Base class for various functions performing statistics on a distribution. """ value_scale = param.NumericTuple((0.0, 1.0), doc=""" Scaling of the resulting value of the distribution statistics, typically the preference of a unit to feature values. The tuple specifies (offset, multiplier) of the output scaling""") # APNOTE: previously selectivity_scale[ 1 ] used to be 17, a value suitable # for combining preference and selectivity in HSV plots. Users wishing to keep # this value should now set it when creating SheetViews, in commands like that # in command/analysis.py selectivity_scale = param.NumericTuple((0.0, 1.0), doc=""" Scaling of the resulting measure of the distribution peakedness, typically the selectivity of a unit to its preferred feature value. The tuple specifies (offset, multiplier) of the output scaling""") __abstract = True def __call__(self, distribution): """ Apply the distribution statistic function; must be implemented by subclasses. Subclasses sould be called with a Distribution as argument, return will be a dictionary, with Pref objects as values """ raise NotImplementedError class DescriptiveStatisticFn(DistributionStatisticFn): """ Abstract class for basic descriptive statistics """ def vector_sum(self, d): """ Return the vector sum of the distribution as a tuple (magnitude, avgbinnum). Each bin contributes a vector of length equal to its value, at a direction corresponding to the bin number. Specifically, the total bin number range is mapped into a direction range [0,2pi]. For a cyclic distribution, the avgbinnum will be a continuous measure analogous to the max_value_bin() of the distribution. But this quantity has more precision than max_value_bin() because it is computed from the entire distribution instead of just the peak bin. However, it is likely to be useful only for uniform or very dense sampling; with sparse, non-uniform sampling the estimates will be biased significantly by the particular samples chosen. The avgbinnum is not meaningful when the magnitude is 0, because a zero-length vector has no direction. To find out whether such cases occurred, you can compare the value of undefined_vals before and after a series of calls to this function. This is a slow algorithm and should only be used if the contents of the distribution have been changed by the statistical function. If not, then the cached value in the distribution should be used. """ # vectors are represented in polar form as complex numbers h = d.data() theta = calc_theta(np.array(list(h.keys())), d.axis_range) return d._fast_vector_sum(list(h.values()), theta) def _weighted_average(self, d ): """ Return the weighted_sum divided by the sum of the values """ return d._safe_divide(d.weighted_sum(), sum(d.values())) def selectivity(self, d): """ Return a measure of the peakedness of the distribution. The calculation differs depending on whether this is a cyclic variable. For a cyclic variable, returns the magnitude of the vector_sum() divided by the sum_value() (see _vector_selectivity for more details). For a non-cyclic variable, returns the max_value_bin()) as a proportion of the sum_value() (see _relative_selectivity for more details). """ if d.cyclic == True: return self._vector_selectivity(d) else: return self._relative_selectivity(d) # CEBHACKALERT: the definition of selectivity for non-cyclic # quantities probably needs some more thought. # Additionally, this fails the test in testfeaturemap # (see the comment there). def _relative_selectivity(self, d): """ Return max_value_bin()) as a proportion of the sum_value(). This quantity is a measure of how strongly the distribution is biased towards the max_value_bin(). For a smooth, single-lobed distribution with an inclusive, non-cyclic range, this quantity is an analog to vector_selectivity. To be a precise analog for arbitrary distributions, it would need to compute some measure of the selectivity that works like the weighted_average() instead of the max_value_bin(). The result is scaled such that if all bins are identical, the selectivity is 0.0, and if all bins but one are zero, the selectivity is 1.0. """ # A single feature_bin is considered fully selective (but could also # arguably be considered fully unselective) if len(d.data()) <= 1: return 1.0 proportion = d._safe_divide(max(d.values()), sum(d.values())) offset = 1.0/len(d.values()) scaled = (proportion-offset) / (1.0-offset) # negative scaled is possible # e.g. 2 bins, with values that sum to less than 0.5 # this probably isn't what should be done in those cases if scaled >= 0.0: return scaled else: return 0.0 def _vector_selectivity(self, d): """ Return the magnitude of the vector_sum() divided by the sum_value(). This quantity is a vector-based measure of the peakedness of the distribution. If only a single feature_bin has a non-zero value(), the selectivity will be 1.0, and if all bins have the same value() then the selectivity will be 0.0. Other distributions will result in intermediate values. For a distribution with a sum_value() of zero (i.e. all bins empty), the selectivity is undefined. Assuming that one will usually be looking for high selectivity, we return zero in such a case so that high selectivity will not mistakenly be claimed. To find out whether such cases occurred, you can compare the value of undefined_values() before and after a series of calls to this function. """ return d._safe_divide(d.vector_sum()[0], sum(d.values())) __abstract = True class DescriptiveBimodalStatisticFn(DescriptiveStatisticFn): """ Abstract class for descriptive statistics of two-modes distributions """ def second_max_value_bin(self, d): """ Return the feature_bin with the second largest value. If there is one feature_bin only, return it. This is not a correct result, however it is practical for plotting compatibility, and it will not mistakenly be claimed as secondary maximum, by forcing its selectivity to 0.0 """ if len(d.bins()) <= 1: return d.bins()[0] k = d.max_value_bin() d.pop(k) m = d.max_value_bin() d.restore(k) return m def second_selectivity(self, d): """ Return the selectivity of the second largest value in the distribution. If there is one feature_bin only, the selectivity is 0, since there is no second peack at all, and this value is also used to discriminate the validity of second_max_value_bin() Selectivity is computed in two ways depending on whether the variable is a cyclic, as in selectivity() """ if len( d._data ) <= 1: return 0.0 if d.cyclic == True: return self._vector_second_selectivity(d) else: return self._relative_second_selectivity(d) def _relative_second_selectivity(self, d): """ Return the value of the second maximum as a proportion of the sum_value() see _relative_selectivity() for further details """ k = d.max_value_bin() d.pop(k) m = max(d.values()) d.restore(k) proportion = d._safe_divide(m, sum(d.values())) offset = 1.0 / len(d.data()) scaled = (proportion - offset) / (1.0 - offset) return max(scaled, 0.0) def _vector_second_selectivity(self, d): """ Return the magnitude of the vector_sum() of all bins excluding the maximum one, divided by the sum_value(). see _vector_selectivity() for further details """ k = d.max_value_bin() d.pop(k) s = self.vector_sum(d)[0] d.restore(k) return self._safe_divide(s, sum(d.values())) def second_peak_bin(self, d): """ Return the feature_bin with the second peak in the distribution. Unlike second_max_value_bin(), it does not return a feature_bin which is the second largest value, if laying on a wing of the first peak, the second peak is returned only if the distribution is truly multimodal. If it isn't, return the first peak (for compatibility with numpy array type, and plotting compatibility), however the corresponding selectivity will be forced to 0.0 """ h = d.data() l = len(h) if l <= 1: return d.keys()[0] ks = list(h.keys()) ks.sort() ik0 = ks.index(d.keys()[np.argmax(d.values())]) k0 = ks[ik0] v0 = h[k0] v = v0 k = k0 ik = ik0 while h[k] <= v: ik += 1 if ik >= l: ik = 0 if ik == ik0: return k0 v = h[k] k = ks[ik] ik1 = ik v = v0 k = k0 ik = ik0 while h[k] <= v: ik -= 1 if ik < 0: ik = l - 1 if ik == ik0: return k0 v = h[k] k = ks[ik] ik2 = ik if ik1 == ik2: return ks[ik1] ik = ik1 m = 0 while ik != ik2: k = ks[ik] if h[k] > m: m = h[k] im = ik ik += 1 if ik >= l: ik = 0 return ks[im] def second_peak_selectivity(self, d): """ Return the selectivity of the second peak in the distribution. If the distribution has only one peak, return 0.0, and this value is also usefl to discriminate the validity of second_peak_bin() """ l = len(d.keys()) if l <= 1: return 0.0 p1 = d.max_value_bin() p2 = self.second_peak_bin(d) if p1 == p2: return 0.0 m = d.get_value(p2) proportion = d._safe_divide(m, sum(d.values())) offset = 1.0 / l scaled = (proportion - offset) / (1.0 - offset) return max(scaled, 0.0) def second_peak(self, d): """ Return preference and selectivity of the second peak in the distribution. It is just the combination of second_peak_bin() and second_peak_selectivity(), with the advantage of avoiding a duplicate call of second_peak_bin(), if the user is interested in both preference and selectivity, as often is the case. """ l = len(d.keys()) if l <= 1: return (d.keys()[0], 0.0) p1 = d.max_value_bin() p2 = self.second_peak_bin(d) if p1 == p2: return (p1, 0.0) m = d.get_value(p2) proportion = d._safe_divide(m, sum(d.values())) offset = 1.0 / l scaled = (proportion - offset) / (1.0 - offset) return (p2, max(scaled, 0.0)) __abstract = True class DSF_MaxValue(DescriptiveStatisticFn): """ Return the peak value of the given distribution """ def __call__(self, d): p = self.value_scale[1] * (d.max_value_bin() + self.value_scale[0]) s = self.selectivity_scale[1] * (self.selectivity(d)+self.selectivity_scale[0]) return {"": Pref(preference=p, selectivity=s)} class DSF_WeightedAverage(DescriptiveStatisticFn): """ Return the main mode of the given distribution The prefence value ia a continuous, interpolated equivalent of the max_value_bin(). For a cyclic distribution, this is the direction of the vector sum (see vector_sum()). For a non-cyclic distribution, this is the arithmetic average of the data on the bin_axis, where each feature_bin is weighted by its value. Such a computation will generally produce much more precise maps using fewer test stimuli than the discrete method. However, weighted_average methods generally require uniform and full-range sampling, which is not always feasible. For measurements at evenly-spaced intervals over the full range of possible parameter values, weighted_averages are a good measure of the underlying continuous-valued parameter preference, assuming that neurons are tuned broadly enough (and/or sampled finely enough) that they respond to at least two of the tested parameter values. This method will not usually give good results when those criteria are not met, i.e. if the sampling is too sparse, not at evenly-spaced intervals, or does not cover the full range of possible values. In such cases max_value_bin should be used, and the number of test patterns will usually need to be increased instead. """ def __call__(self, d): p = d.vector_sum()[1] if d.cyclic else self._weighted_average(d) p = self.value_scale[1] * (p + self.value_scale[0]) s = self.selectivity_scale[1] * (self.selectivity(d) + self.selectivity_scale[0]) return {"": Pref(preference=p, selectivity=s)} class DSF_TopTwoValues(DescriptiveBimodalStatisticFn): """ Return the two max values of distributions in the given matrix """ def __call__(self, d): r = {} p = self.value_scale[1] * (d.max_value_bin() + self.value_scale[0]) s = self.selectivity_scale[1] * (self.selectivity(d) + self.selectivity_scale[0]) r[""] = Pref(preference=p, selectivity=s) p = self.second_max_value_bin(d) s = self.second_selectivity(d) p = self.value_scale[1] * (p + self.value_scale[0]) s = self.selectivity_scale[1] * (s + self.selectivity_scale[0]) r["Mode2"] = Pref(preference=p, selectivity=s) return r class DSF_BimodalPeaks(DescriptiveBimodalStatisticFn): """ Return the two peak values of distributions in the given matrix """ def __call__(self, d): r = {} p = self.value_scale[1] * (d.max_value_bin() + self.value_scale[0]) s = self.selectivity_scale[1] * (self.selectivity(d) + self.selectivity_scale[0]) r[""] = Pref(preference=p, selectivity=s) p, s = self.second_peak(d) p = self.value_scale[1] * (p + self.value_scale[0]) s = self.selectivity_scale[1] * (s + self.selectivity_scale[0]) r["Mode2"] = Pref(preference=p, selectivity=s) return r class VonMisesStatisticFn(DistributionStatisticFn): """ Base class for von Mises statistics """ # values to fit the maximum value of k parameter in von Mises distribution, # as a function of the number of bins in the distribution. Useful for # keeping selectivity in range 0..1. Values derived offline from distribution # with a single active feature_bin, and total bins from 8 to 32 vm_kappa_fit = (0.206, 0.614) # level of activity in units confoundable with noise. Used in von Mises fit, # for two purposes: if the standard deviation of a distribution is below this # value, the distribution is assumed to lack any mode; it is the maximum level # of random noise added to a distribution before the fit optimization, for # stability reasons noise_level = 0.001 # exit code of the distribution fit function. Codes are function-specific and # each fit function, if provide exit codes, should have corresponding string translation fit_exit_code = 0 user_warned_if_unavailable = False __abstract = True def _orth(self, t): """ Return the orthogonal orientation """ if t < 0.5 * np.pi: return t + 0.5 * np.pi return t - 0.5 * np.pi def _in_pi(self, t): """ Reduce orientation from -pi..2pi to 0..pi """ if t > np.pi: return t - np.pi if t < 0: return t + np.pi return t def von_mises(self, pars, x): """ Compute a simplified von Mises function. Original formulation in Richard von Mises, "Wahrscheinlichkeitsrechnung und ihre Anwendungen in der Statistik und theoretischen Physik", 1931, Deuticke, Leipzig; see also Mardia, K.V. and Jupp, P.E., " Directional Statistics", 1999, J. Wiley, p.36; http://en.wikipedia.org/wiki/Von_Mises_distribution The two differences are that this function is a continuous probability distribution on a semi-circle, while von Mises is on the full circle, and that the normalization factor, which is the inverse of the modified Bessel function of first kind and 0 degree in the original, is here a fit parameter. """ a, k, t = pars return a * np.exp(k * (np.cos(2 * (x - t)) - 1)) def von2_mises(self, pars, x): """ Compute a simplified bimodal von Mises function Two superposed von Mises functions, with different peak and bandwith values """ p1 = pars[: 3] p2 = pars[3:] return self.von_mises(p1, x) + self.von_mises(p2, x) def von_mises_res(self, pars, x, y): return y - self.von_mises(pars, x) def von2_mises_res(self, pars, x, y): return y - self.von2_mises(pars, x) def norm_sel(self, k, n): m = (self.vm_kappa_fit[0] + n * self.vm_kappa_fit[1])**2 return np.log(1 + k) / np.log(1 + m) def fit_vm(self, distribution): """ computes the best fit of the monovariate von Mises function in the semi-circle. Return a tuple with the orientation preference, in the same range of axis_bounds, the orientation selectivity, and an estimate of the goodness-of-fit, as the variance of the predicted orientation preference. The selectivity is given by the bandwith parameter of the von Mises function, modified for compatibility with other selectivity computations in this class. The bandwith parameter is transposed in logaritmic scale, and is normalized by the maximum value for the number of bins in the distribution, in order to give roughly 1.0 for a distribution with one feature_bin at 1.0 an all the other at 0.0, and 0.0 for uniform distributions. The normalizing factor of the selectivity is fit for the total number of bins, using fit parameters computed offline. There are conditions that prevents apriori the possibility to fit the distribution: * not enough bins, at least 4 are necessary * the distribution is too flat, below the noise level and conditions of aposteriori failures: * "ier" flag returned by leastsq out of ( 1, 2, 3, 4 ) * no estimated Jacobian around the solution * negative bandwith (the peak of the distribution is convex) Note that these are the minimal conditions, their fulfillment does not warrant unimodality, is up to the user to check the goodness-of-fit value for an accurate acceptance of the fit. """ if unavailable_scipy_optimize: if not VonMisesStatisticFn.user_warned_if_unavailable: param.Parameterized().warning("scipy.optimize not available, dummy von Mises fit") VonMisesStatisticFn.user_warned_if_unavailable=True self.fit_exit_code = 3 return 0, 0, 0 to_pi = np.pi / distribution.axis_range x = to_pi * np.array(distribution.bins()) n = len(x) if n < 5: param.Parameterized().warning("No von Mises fit possible with less than 4 bins") self.fit_exit_code = -1 return 0, 0, 0 y = np.array(distribution.values()) if y.std() < self.noise_level: self.fit_exit_code = 1 return 0, 0, 0 rn = self.noise_level * np.random.random_sample(y.shape) p0 = (1.0, 1.0, distribution.max_value_bin()) r = optimize.leastsq(self.von_mises_res, p0, args=(x, y + rn), full_output=True) if not r[-1] in ( 1, 2, 3, 4 ): self.fit_exit_code = 100 + r[-1] return 0, 0, 0 residuals = r[2]['fvec'] jacobian = r[1] bandwith = r[0][1] tuning = r[0][2] if bandwith < 0: self.fit_exit_code = 1 return 0, 0, 0 if jacobian is None: self.fit_exit_code = 2 return 0, 0, 0 error = (residuals**2).sum() / (n - len(p0)) covariance = jacobian * error g = covariance[2, 2] p = self._in_pi(tuning) / to_pi s = self.norm_sel(bandwith, n) self.fit_exit_code = 0 return p, s, g def vm_fit_exit_codes(self): if self.fit_exit_code == 0: return "succesfull exit" if self.fit_exit_code == -1: return "not enough bins for this fit" if self.fit_exit_code == 1: return "flat distribution" if self.fit_exit_code == 2: return "flat distribution" if self.fit_exit_code == 3: return "missing scipy.optimize import" if self.fit_exit_code > 110: return "unknown exit code" if self.fit_exit_code > 100: return "error " + str(self.fit_exit_code - 100) + " in scipy.optimize.leastsq" return "unknown exit code" def fit_v2m(self, distribution): """ computes the best fit of the bivariate von Mises function in the semi-circle. Return the tuple: ( orientation1_preference, orientation1_selectivity, goodness_of_fit1, orientation2_preference, orientation2_selectivity, goodness_of_fit2 ) See fit_vm() for considerations about selectivity and goodness_of_fit """ null = 0, 0, 0, 0, 0, 0 if unavailable_scipy_optimize: if not VonMisesStatisticFn.user_warned_if_unavailable: param.Parameterized().warning("scipy.optimize not available, dummy von Mises fit") VonMisesStatisticFn.user_warned_if_unavailable=True self.fit_exit_code = 3 return null to_pi = np.pi / distribution.axis_range x = to_pi * np.array(distribution.bins()) n = len(x) if n < 9: param.Parameterized().warning( "no bimodal von Mises fit possible with less than 8 bins" ) self.fit_exit_code = -1 return null y = np.array(distribution.values()) if y.std() < self.noise_level: self.fit_exit_code = 1 return null rn = self.noise_level * np.random.random_sample(y.shape) t0 = distribution.max_value_bin() p0 = (1.0, 1.0, t0, 1.0, 1.0, self._orth(t0)) r = optimize.leastsq(self.von2_mises_res, p0, args=(x, y + rn), full_output=True) if not r[-1] in ( 1, 2, 3, 4 ): self.fit_exit_code = 100 + r[-1] return null residuals = r[2]['fvec'] jacobian = r[1] bandwith_1 = r[0][1] tuning_1 = r[0][2] bandwith_2 = r[0][4] tuning_2 = r[0][5] if jacobian is None: self.fit_exit_code = 2 return null if bandwith_1 < 0: self.fit_exit_code = 1 return null if bandwith_2 < 0: self.fit_exit_code = 1 return null error = (residuals ** 2).sum() / (n - len(p0)) covariance = jacobian * error g1 = covariance[2, 2] g2 = covariance[5, 5] p1 = self._in_pi(tuning_1) / to_pi p2 = self._in_pi(tuning_2) / to_pi s1 = self.norm_sel(bandwith_1, n) s2 = self.norm_sel(bandwith_2, n) self.fit_exit_code = 0 return p1, s1, g1, p2, s2, g2 def __call__(self, distribution): """ Apply the distribution statistic function; must be implemented by subclasses. """ raise NotImplementedError class DSF_VonMisesFit(VonMisesStatisticFn): """ Return the main mode of distribution in the given matrix, by fit with von Mises function. """ worst_fit = param.Number(default=0.5, bounds=(0.0, None), softbounds=(0.0, 1.0), doc=""" worst good-of-fitness value for accepting the distribution as monomodal""") # default result in case of failure of the fit null_result = {"": Pref(preference=0, selectivity=0, goodness_of_fit=0), "Modes": Pref(number=0)} def __call__(self, distribution): f = self.fit_vm(distribution) if self.fit_exit_code != 0 or f[-1] > self.worst_fit: return self.null_result results = {} p, s, g = f p = self.value_scale[1] * (p + self.value_scale[0]) s = self.selectivity_scale[1] * (s + self.selectivity_scale[0]) results[""] = Pref(preference=p, selectivity=s, goodness_of_fit=g) results["Modes"] = Pref(number=1) return results class DSF_BimodalVonMisesFit(VonMisesStatisticFn): """ Return the two modes of distributions in the given matrix, by fit with von Mises function The results of the main mode are available in self.{preference,selectivity,good_of_fit}, while the second mode results are in the first element of the self.more_modes list, as a dictionary with keys preference,selectivity,good_of_fit. """ worst_fit = param.Number(default=0.5, bounds=(0.0, None), softbounds=(0.0, 1.0), doc=""" Worst good-of-fitness value for accepting the distribution as mono- or bi-modal""") # default result in case of failure of the fit null_result = { "": Pref(preference=0, selectivity=0, goodness_of_fit=0), "Mode2": Pref(preference=0, selectivity=0, goodness_of_fit=0), "Modes": Pref(number=0) } def _analyze_distr(self, d): """ Analyze the given distribution with von Mises bimodal fit. The distribution is analyzed with both unimodal and bimodal fits, and a decision about the number of modes is made by comparing the goodness of fit. It is a quick but inaccurate way of estimating the number of modes. Return preference, selectivity, goodness of fit for both modes, and the estimated numer of modes, None if even the unimodal fit failed. If the distribution is unimodal, values of the second mode are set to 0. The main mode is always the one with the largest selectivity (von Mises bandwith). """ no1 = False f = self.fit_vm(d) if self.fit_exit_code != 0: no1 = True p, s, g = f f2 = self.fit_v2m(d) if self.fit_exit_code != 0 or f2[2] > self.worst_fit: if no1 or f[-1] > self.worst_fit: return None return p, s, g, 0, 0, 0, 1 p1, s1, g1, p2, s2, g2 = f2 if g1 > g: return p, s, g, 0, 0, 0, 1 if s2 > s1: return p2, s2, g2, p1, s1, g1, 2 return p1, s1, g1, p2, s2, g2, 2 def __call__(self, distribution): f = self._analyze_distr(distribution) if f is None: return self.null_result results = {} p, s, g = f[: 3] p = self.value_scale[1] * (p + self.value_scale[0]) s = self.selectivity_scale[1] * (s + self.selectivity_scale[0]) results[""] = Pref(preference=p, selectivity=s, goodness_of_fit=g) p, s, g, n = f[3:] p = self.value_scale[1] * (p + self.value_scale[0]) s = self.selectivity_scale[1] * (s + self.selectivity_scale[0]) results["Mode2"] = Pref(preference=p, selectivity=s, goodness_of_fit=g) results["Modes"] = Pref(number=n) return results
dfebfce2e9601d9d33effa74ee361a9b9f00456f
soyal/py-gs
/src/data-struct/ds_using_tuple.py
263
3.765625
4
zoo = ('dog', 'cat', 'elephant') new_zoo = ('monkey', 'camel', zoo) print('zoo length: ',len(zoo)) print('the last animal about old zoo is', new_zoo[2][2]) # len == 1的元组 tuple_len1 = ('a',) print(type(tuple_len1)) print('len: ', len(tuple_len1)) # len, 1
6256050dedd92c725048cbca550062cdf87db3d0
Sudhanva1999/AllCodesPython
/Sorting/MergeSort.py
713
4
4
def merge_sort(arr): if len(arr)>1: middle=len(arr)//2 arr1=arr[0:middle] arr2=arr[middle:len(arr)] merge_sort(arr1) merge_sort(arr2) i=0 j=0 k=0 while i<len(arr1) and j<len(arr2): if(arr1[i]<arr2[j]): arr[k]=arr1[i] i+=1 else: arr[k]=arr2[j] j+=1 k+=1 while i < len(arr1): arr[k]=arr1[i] i+=1 k+=1 while j < len(arr2): arr[k]=arr2[j] j+=1 k+=1 print('Enter space separated Elements.') arr=list(map(int,input().split())) merge_sort(arr) print(arr)
27d88ddac1d1fff0cd486a33ce2c8c559ed6447b
fabiannoda/PythonTutorial
/hashmap.py
226
3.8125
4
stra=hash("hola123.") str2=hash(input()) lista=["hola123/", "angel15/"] flag=True while flag: if stra==str2: print(lista) flag=False else: print("contraseña erronea") str2=hash(input())
e82b007daaa309b967e893cace158d45ca137ffc
programmeremmanuel586/investment_and_inflation_calculator
/investment_and_inflation_calculations.py
1,531
3.828125
4
import math # finding the value from investment def investment_value(investment, growth_rate, num_of_compounds, years): # converts growth rate to a decimal growth_rate = growth_rate/100 # exponential function equation value = investment * (1 + growth_rate/num_of_compounds) ** (num_of_compounds * years) # rounds value to nearest cent value = round(value, 2) msg = "Your current investment value is now: $" + str(value) print(msg) # finding investment compounded continuously def continuous_investment_value(investment, growth_rate, years): # converts growth rate to a decimal growth_rate = growth_rate/100 # continuous compounded function equation value = investment * math.e ** (growth_rate * years) # rounds value to nearest cent value = round(value, 2) msg = "Your continuous investment value is now: $" + str(value) print(msg) # solving for inflation def inflation_calculation(inflation_cost, growth_rate, years): # converts growth rate to a decimal growth_rate = growth_rate/100 # continuous compounded function equation value = inflation_cost * (1 + growth_rate) ** years # rounds value to nearest cent value = round(value, 2) msg = "The inflation value is: $" + str(value) print(msg) # finding the value from investment investment_value(5100, 5.3, 1, 6.5) # finding investment compounded continuously continuous_investment_value(9600, 3.1, 4) # solving for inflation inflation_calculation(131500, 2.5, 14)
a97c234c714fefea8a9fe93f11a4ceecf13c5fda
yash161/jeniknsdemo8-10
/jenkins.py
59
3.5625
4
a=100 b=30 c=a+b print(f"The sum of Two numbers is:{c}")
ed1379a2c5324d04bc3623d8c9645b5f125102c3
jetbrains-academy/introduction_to_python
/File input output/What next/main.py
712
3.890625
4
def print_heart(n): for i in range(n // 2, n, 2): for j in range(1, n - i, 2): print(end=" ") for j in range(1, i + 1): print("*", end=" ") if (j == 1 or j == i) else print(end=" ") for j in range(1, n - i + 1): print(end=" ") for j in range(1, i + 1): print("*", end=" ") if (j == 1 or j == i) else print(end=" ") print() for i in range(n, 0, -1): for j in range(i, n): print(end=" ") for j in range(1, i * 2): print("*", end=" ") if (j == 1 or j == i * 2 - 1 or (i == n and j == i)) else print(end=" ") print() if __name__ == '__main__': print_heart(5)
d3f1a4c1806d0532404a4cbd6273fd84614338d6
farrowking37/CSI260Repo
/Week 5/Library Project 1/main.py
6,403
3.796875
4
"""Implements the functions created in library_catalog.py and allows you to add/remove items to a catalog, print catalog contents, and search for specific catalog items. Author: John Shultz Class: CSI-260-03 Assignment: Library Project Part 1 Due Date: 2/26/2019 12:30 PM Certification of Authenticity: I certify that this is entirely my own work, except where I have given fully-documented references to the work of others. I understand the definition and consequences of plagiarism and acknowledge that the assessor of this assignment may, for the purpose of assessing this assignment: - Reproduce this assignment and provide a copy to another member of academic - staff; and/or Communicate a copy of this assignment to a plagiarism checking - service (which may then retain a copy of this assignment on its database for - the purpose of future plagiarism checking) """ from library_catalog import LibraryItem, DVDMovie, MusicCD, Book, Catalog # Create a catalog named catalog that we will work with. catalog = Catalog("Champlain College Library Catalog") def search_catalog(): """UI for searching the catalog""" filter_text = str(input("Enter in some text to search for (name, author, director, tag, etc.): ")) while True: print("1. Book\n2. DVD Movie\n3. Music CD") type_filter = input("Enter in one of the above choices to filter by item or nothing to show all items: ") if type_filter in ["1", "2", "3", ""]: break else: print("Please only enter in a valid choice or no input.") print('Searching the catalog') filter_dict = {"1": "Book", "2": "DVD", "3": "Music CD"} # Call the Catalog.search_items function which returns a list of matching items if type_filter: found_items = catalog.search_items(filter_text, filter_dict[type_filter]) else: found_items = catalog.search_items(filter_text) print("Here are your results!") print("---------------------") # Check to see if any items were found. If any were, print each found item to screen if found_items: for item in found_items: print(item) def print_catalog(): print("Here all all the items in the library catalog!") print("----------------------------------------------") for item in catalog._all_items: print(item) def add_item(): """Adds a list of items to the catalog :return: No return value, but appends a list of items to catalog._all_items """ new_items = [] while True: print("1. Book") print("2. DVD Movie") print("3. Music CD") try: item_choice = int(input("Enter a number to select the type of item you want to add: ")) if item_choice == 1: # Make a book name = str(input("Enter the name of the book: ")) isbn = str(input("Enter the ISBN of the book: ")) author = str(input("Enter the author of the book: ")) tags = [] while True: new_tag = str(input("Enter in a tag describing the book, or nothing to quit: ")) if new_tag: tags.append(new_tag) else: break new_book = Book(name, isbn, author, tags) new_items.append(new_book) elif item_choice == 2: # Make a DVD movie name = str(input("Enter the name of the DVD: ")) isbn = str(input("Enter the ISBN of the DVD: ")) director = str(input("Enter in the director of the movie: ")) actor = str(input("Enter in the lead actor in the movie: ")) tags = [] while True: new_tag = str(input("Enter in a tag describing the movie, or nothing to quit: ")) if new_tag: tags.append(new_tag) else: break new_dvd = DVDMovie(name, isbn, director, actor, tags) new_items.append(new_dvd) elif item_choice == 3: # Make a Music CD name = str(input("Enter the name of the CD: ")) isbn = str(input("Enter the ISBN of the CD: ")) artist = str(input("Enter in the recording artist of the CD: ")) while True: try: num_discs = int(input("Please enter in the number of discs: ")) break except ValueError: print("That's not a valid number!") tags = [] while True: new_tag = str(input("Enter in a tag describing the CD, or nothing to quit: ")) if new_tag: tags.append(new_tag) else: break new_cd = MusicCD(name, isbn, artist, num_discs, tags) new_items.append(new_cd) else: print("Please enter one of the above numbers") run_again = str(input("Would you like to add another item (Y/N): ")) if run_again.lower() not in ['y', 'yes']: catalog.add_items(new_items) break except ValueError: print("Please enter one of the above numbers") def remove_item(): """Takes an item with a given name and removes it from the catalog :return: nothing. Removes entries from catalog._all_items """ remove_name = str(input("Enter the name of the item you wish to remove: ")) for item in catalog._all_items: if item.name.lower() == remove_name.lower(): print(f'Removing a {item.resource_type} named {item.name}') catalog.remove_items([item]) catalog_menu = """Library Catalog Menu 1. Search catalog 2. Print the entire catalog 3. Add items to catalog 4. Remove items from catalog Choose an option: """ menu_options = {'1': search_catalog, '2': print_catalog, '3': add_item, '4': remove_item} while True: user_choice = input(catalog_menu) if user_choice in menu_options: menu_options[user_choice]() else: print('That option is not recognized')
5c4a743c57ae6c19cf75b9a79b81d2b09fe47175
cocacolabe/TechInterviewProblems
/hackerrank/quicksort.py
1,043
3.90625
4
''' https://www.hackerrank.com/challenges/quicksort1 divide-and-conquer algorithm divide: choose some pivot element, p, and partition your unsorted array into left, right, and equal, left < p, right > p, equal = p If partition is then called on each sub-array, the array will now be split into four parts. This process can be repeated until the sub-arrays are small. When partition is called on just one of the numbers, they end up being sorted. ''' def partition(ar): p = ar[0] left = [] equal = [p] right = [] for i in range(1, len(ar)): if ar[i] < p: left.append(ar[i]) elif ar[i] == p: equal.append(ar[i]) else: right.append(ar[i]) return (left, equal, right) def sort(arr): if len(arr) < 2: return arr if len(arr) == 2: if arr[0] > arr[1]: arr[0], arr[1] = arr[1], arr[0] return arr else: return arr if len(arr) > 2: left, p, right = partition(arr) final = sort(left) + p + sort(right) return final m = input() ar = [int(i) for i in raw_input().strip().split()] print sort(ar)
5dfe77f140c84b2daa3e8db9ebf59124491ed0ed
Yulionok2/Netologia
/1.Fundamentals Python/Python.Знакомство с консолью/DZ_2.py
641
4.375
4
# Пользователь вводит длину и ширину фигуры.Программа выводит их периметр и площадь. square=int(input("Введите длину стороны квадрата:")) P=square*4 S=square**2 print("Вывод: ") print("Периметр:", P) print("Площадь:", S) rectangle_a=int(input("Введите длину прямоугольника:")) rectangle_b=int(input("Введите ширину прямоугольника:")) P=(rectangle_a+rectangle_b)*2 S=rectangle_a*rectangle_b print("Вывод: ") print("Периметр:", P) print("Площадь:", S)
786d331aacfac82a4900cb3929fda7e001a8d1ab
MohamedMagdyOmar/Arabic-Diacritization
/NN/tensorflow/5- combine 2, 3, 4.py
6,349
3.734375
4
import os import tensorflow as tf import pandas as pd from sklearn.preprocessing import MinMaxScaler os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Load training data set from CSV file training_data_df = pd.read_csv("sales_data_training.csv", dtype=float) # Load testing data set from CSV file testing_data_df = pd.read_csv("sales_data_test.csv", dtype=float) # Pull out columns for X (data to train with) and Y (value to predict) X_training = training_data_df.drop("total_earnings", axis=1).values Y_training = training_data_df[["total_earnings"]].values # Pull out columns for X (data to train with) and Y (value to predict) X_testing = testing_data_df.drop("total_earnings", axis=1).values Y_testing = testing_data_df[["total_earnings"]].values # All data needs to be scaled to a small range like 0 to 1 for the neural # network to work well. Create scalers for the inputs and outputs. X_scaler = MinMaxScaler(feature_range=(0, 1)) Y_scaler = MinMaxScaler(feature_range=(0, 1)) # Scale both the training inputs and outputs X_scaled_training = X_scaler.fit_transform(X_training) Y_scaled_training = Y_scaler.fit_transform(Y_training) # It's very important that the training and test data are scaled with the same scaler. X_scaled_testing = X_scaler.transform(X_testing) Y_scaled_testing = Y_scaler.transform(Y_testing) print(X_scaled_testing.shape) print(Y_scaled_testing.shape) print("Note: Y values were scaled by multiplying by {:.10f} and adding {:.4f}".format(Y_scaler.scale_[0], Y_scaler.min_[0])) # define model parameters learning_rate = 0.001 training_epochs = 100 display_step = 5 # define how many input and output neurons number_of_inputs = 9 number_of_outputs = 1 # define how many neurons in each layer layer_1_nodes = 50 layer_2_nodes = 100 layer_3_nodes = 50 # section one: define the layers of the neural network itself # input layer # we put each layer in its "variable scope" # any variables we create within this scope will automatically get a prefix of "input" to their name internally in tf # "None" tells tf that our NN can mix up batches of any size # "number_of_inputs" tells tf to expect nine values for each record in the batch with tf.variable_scope('input'): x = tf.placeholder(tf.float32, shape=(None, number_of_inputs)) # layer 1 # each fully connected layer has the following 3 parts # "weights" is the value for each connection between each node and the node in previous layer # "bias" value for each node # "activation function" that outputs the result of the layer with tf.variable_scope('layer_1'): # "shape", we want to have one weight for each node's connection to each node in the previous layer. # "initializer" a good choice for initializing weights is an algorithm called "Xavier Initialization" weights = tf.get_variable(name="weights1", shape=[number_of_inputs, layer_1_nodes], initializer=tf.contrib.layers.xavier_initializer()) # we need "variables" to store bias value for each node # this will be a "variable" instead of a "placeholder", because we want tf to remember the value over time # there is one bias value for each node in this layer, so the shape should be the same as the number of nodes in the # ... layer # we need also to define "initial value" for this variable, so we can pass one of the built-in initializer functions # we want the bias values for each node to default to zero biases = tf.get_variable(name="biases1", shape=[layer_1_nodes], initializer=tf.zeros_initializer) # "activation function", multiplying "weights" by "inputs" layer_1_output = tf.nn.relu(tf.matmul(x, weights) + biases) # layer 2 with tf.variable_scope('layer_2'): weights = tf.get_variable(name="weights2", shape=[layer_1_nodes, layer_2_nodes], initializer=tf.contrib.layers.xavier_initializer()) biases = tf.get_variable(name="biases2", shape=[layer_2_nodes], initializer=tf.zeros_initializer) layer_2_output = tf.nn.relu(tf.matmul(layer_1_output, weights) + biases) # layer 3 with tf.variable_scope('layer_3'): weights = tf.get_variable(name="weights3", shape=[layer_2_nodes, layer_3_nodes], initializer=tf.contrib.layers.xavier_initializer()) biases = tf.get_variable(name="biases3", shape=[layer_3_nodes], initializer=tf.zeros_initializer) layer_3_output = tf.nn.relu(tf.matmul(layer_2_output, weights) + biases) # Output Layer with tf.variable_scope('output'): weights = tf.get_variable(name="weights4", shape=[layer_3_nodes, number_of_outputs], initializer=tf.contrib.layers.xavier_initializer()) biases = tf.get_variable(name="biases4", shape=[number_of_outputs], initializer=tf.zeros_initializer) prediction = tf.nn.relu(tf.matmul(layer_3_output, weights) + biases) # section 2: define the "cost function" of the NN that will measure prediction with tf.variable_scope('cost'): # expected value, it will be "placeholder" node, because it will feed in a new value each time Y = tf.placeholder(tf.float32, shape=[None, 1]) # "cost" function or "loss" function, tells us how wrong the neural network is when trying to predict the correct output # mean square of what we expected and the actual(calculated) # we want to get avg value of that difference, so we will use "reduce_mean" cost = tf.reduce_mean(tf.squared_difference(prediction, Y)) # section 3: define the optimization function that will be run to optimize the neural network with tf.variable_scope('train'): # we will use here adam optimizer, that tells tf that whenever we tell it to execute the optimizer, it should run # one iteration of AdamOptimizer to make the cost function smaller optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) with tf.Session() as session: # run the global variable initializer to initialize all variables and layers to their default values session.run(tf.global_variables_initializer()) # here we run our optimizer function over and over, either for a certain number of iterations # ... or until it hits an accuracy level we want for epoch in range(training_epochs): # feed in the training data and do one step of neural network training session.run(optimizer, feed_dict={x: X_scaled_training, Y: Y_scaled_training}) print("Training pass: {}".format(epoch)) print("Training is complete")
2ac360e3c1a07e7657a216f587f807b055f1111c
oulenz/fuzzy-rough-learn
/examples/data_descriptors/one_class_classification.py
3,139
3.796875
4
""" ======================== One class classification ======================== Data descriptors generalise knowledge about a target class of data to the whole attribute space. This can be used to predict whether new data instances belong to the target class or not, or to identify which new instances should be subjected to further inspection. This type of binary classification is known as *one-class classification*, *semi-supervised outlier detection*, *semi-supervised anomaly detection*, or *novelty detection*. In principle, there is no good or bad way to generalise the target class, this can only be evaluated empirically. In practice, we want a good balance between variance and bias. The following graphs illustrate the behaviour of the data descriptors in fuzzy-rough-learn, with their default hyperparameter values as established in [1]_. Note that the predicted scores have been converted to quantiles to obtain clear contour lines that illustrate how the predicted scores taper off. References ---------- .. [1] `Lenz OU, Peralta D, Cornelis C (2021). Average Localised Proximity: A new data descriptor with good default one-class classification performance. Pattern Recognition, vol 118, no 107991. doi: 10.1016/j.patcog.2021.107991 <https://www.sciencedirect.com/science/article/abs/pii/S0031320321001783>`_ """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from frlearn.data_descriptors import ALP, CD, IF, MD, NND, LNND, LOF, SVM # Sample attribute space, to use as test data xx, yy = np.meshgrid(np.linspace(-6, 6, 300), np.linspace(-6, 6, 300)) # Generate training data rng = np.random.default_rng(0) X = rng.standard_normal((100, 2)) X_train = np.r_[1 * X + 2, 0.75*X, 0.5 * X - 2] # Initialise data descriptors to include data_descriptors = [ ('ALP', ALP()), ('CD', CD()), ('IF', IF()), ('LNND', LNND()), ('LOF', LOF()), ('MD', MD()), ('NND', NND()), ('SVM', SVM()), ] # Calculate number of rows cols = 3 rows = (len(data_descriptors) + (cols - 1)) // cols # Create plot layout with square subplots fig, axs = plt.subplots(rows, cols, figsize=(3*cols, 3*rows), subplot_kw=dict(box_aspect=1), ) # Iterate over data descriptors for i, (name, clf) in enumerate(data_descriptors): ax = axs[i // cols][i % cols] # Create model and query for scores model = clf(X_train) Z = model(np.c_[xx.ravel(), yy.ravel()]) # Transform scores into their respective centile centiles = np.quantile(Z, np.linspace(0, 1, 101)) Z = np.searchsorted(centiles, Z)/100 Z = Z.reshape(xx.shape) # Plot contours ax.contourf(xx, yy, Z, levels=np.linspace(0, 1, 12), cmap=plt.cm.PuBu) # Plot training data c = ax.scatter(X_train[:, 0], X_train[:, 1], c='white', s=10, edgecolors='k') # Set axis limits and delete ticks and legends plt.xlim((-6, 6)) plt.ylim((-6, 6)) c.axes.get_xaxis().set_visible(False) c.axes.get_yaxis().set_visible(False) ax.set_title(name) # Delete spare subfigures for i in range((-len(data_descriptors)) % cols): fig.delaxes(axs[-1, -(i + 1)]) fig.tight_layout() plt.show()
a034799bb4e91d1ea630adf405a7611ff0ccf7d7
Naushikha/Old-Projects
/Python/Simple Tutorials/The All-in-One Converter/Chunked functions/deci_to_hexa_f.py
469
3.765625
4
#17 Feb 2017 #Converts a decimal into hexadecimal #Coded by _xXHun3rXx_ def dec_hexa(): res="" while n!=0: q=n//16 r=n%16 if r==10: r="A" elif r==11: r="B" elif r==12: r="C" elif r==13: r="D" elif r==14: r="E" elif r==15: r="F" else: r=str(r) n=q res = r + res return (res)
b8e8f37db75c0cbcb81e83c8cf531f9dcef21b5f
mm-uddin/HackerRankSolutions
/second_lowest.py
769
4.09375
4
''' Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. Input: students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] Output: Berry Harry ''' student_with_marks = [] marks = [] for i in range(int(input())): name = input() score = float(input()) student_with_marks.append([name, score]) marks.append(score) marks = sorted(set(marks)) second_lowest_num = marks[1] for i, j in sorted(student_with_marks): if j == second_lowest_num: print(i)
edf0ae5da9ddd499bfcf752e0e1a76fa8f1ea0e3
krisgrav/IN1000
/1. oblig/dato.py
1,473
3.796875
4
#Oppgave 3 #1 dag_1 = input("Skriv inn en dato med bruk av tall. Forst dag:") maaned_1 = input(", deretter maaned.:") dag_2 = input("Skriv så inn en annen dato. Forst dag:") maaned_2 = input(", deretter maaned.:") dato_1 = (dag_1 + maaned_1) dato_2 = (dag_2 + maaned_2) '''Her ber programmet brukeren om to datoer, og lagrer svarene som fire forskjellige variabler, to for dag og to for måned. Det lager også to variabler der dag og måned er slått sammen til en hel dato.''' if maaned_1 < maaned_2: print("Riktig rekkefølge!") if maaned_1 > maaned_2: print("Feil rekkefølge!") elif maaned_1 == maaned_2 and dag_1 > dag_2: print("Feil rekkefølge!") elif maaned_1 == maaned_2 and dag_1 < dag_2: print("Riktig rekkefølge!") elif maaned_1 == maaned_2 and dag_1 == dag_2: print("Samme dato!") '''Videre bruker programmet variabelene og if-statements til å sjekke hvilken av datoene som kommer først. Er maaned_2 større enn maaned_1 vil "Riktig rekkefølge!" printes, men om det er omvendt vil "feil rekkefølge" printes. Videre bruker programmet til linjer med elif i tilfellene der måneden er lik. Linje 21 og 23 er skrevet slik at programmet først vil finne ut om variablene for maaned_1 og maaned_2 er like, og deretter vurdere hvilken av dagene som kommer først, for å gi to forskjellige svar i output. Er datoene like vil programmet i linjer 23 først se om måneden er lik, og deretter dag, før det da evt printer "samme dato!"'''
d552fa3a40bbdce489293961a8059c723730bd35
ravi4all/PythonApril_21
/functions/12-func.py
466
3.53125
4
def temp_convert(c): return 9/5 * c + 32 def min_to_sec(m): return m * 60 def km_to_m(km): return km * 1000 def myMap(func, iter): data = [] for i in range(len(iter)): data.append(func(iter[i])) return data temps = [34.5,45.3,42.3,39.8,29.4,28.5,33.6] mins = [5,6,12,45,60,1,2.5,5.5] kms = [2,2.3,5.4,5,3.8,10,120] print(myMap(temp_convert, temps)) print(myMap(min_to_sec, mins)) print(myMap(km_to_m, kms))
9df0c805a58ec4efb7b40b1cb158ef761b150bd4
renlei-great/git_window-
/python数据结构/python黑马数据结构/链表/single_link_list.py
7,206
3.78125
4
"""重要的就是要考虑周全,普通情况和特殊情况""" class BaseLinkList(object): """链表基板""" def is_empty(self): """链表是否为空""" return self.head is None def length(self): """链表长度""" cur = self.head count = 0 while cur: count += 1 cur = cur.next return count def travel(self): """遍历整个链表""" cur = self.head if cur is None: return cur print('- ', end='') while cur: print(cur.item, end=',') cur = cur.next print(' -') def search(self, item): """查找节点是否存在""" # 将每一个节点的值拿出来进行比对,如果找到,返回true如果没有找到返回false cru = self.head while cru != None: if cru.item == item: return True cru = cru.next return False class SingleNode(object): def __init__(self, item): self.item = item self.next = None class SingleLinkList(BaseLinkList): """单链表""" def __init__(self, node=None): self.head = node def add(self, item): """链表头部添加元素""" node = SingleNode(item) node.next = self.head self.head = node def append(self, item): """链表尾部添加元素""" cur = self.head if cur == None: node = SingleNode(item) self.head = node else: while cur.next: cur = cur.next node = SingleNode(item) cur.next = node def insert(self, pos, item): """指定位置添加元素""" if pos <= 0: self.add(item) elif pos > self.length(): self.append(item) else: node = SingleNode(item) cur = self.head count = 0 while count < (pos - 1): cur = cur.next count += 1 node.next = cur.next cur.next = node def remove(self, item): """删除节点""" # 将每一个节点的值拿出来进行比对,如果相同,执行删除操作,如果判断完所有数据都没有相同,什么都不做 # 特殊情况 cru = self.head while cru != None: # 只有一个节点 if cru.item == item: self.head = cru.next break if cru.next: if cru.next.item == item: cru.next = cru.next.next break cru = cru.next def is_loop(self): """ 判断是否有环路 解题思想1:分出两个指针一个指针P每次前进一,后一个指针PP,然后有一个计数器, P每走一步,计数器加1,PP指针每次从头来走,走到P的前一个步长停 结论:如果没有环路,那么循环正常退出,如果有环路PP指针一定会和P指针重合,有重合返回True 参考文档:https://zhuanlan.zhihu.com/p/31401474 """ cur = self.head.next # 1, 1, 1, 2, 1, 2 # 0, 0, 1, 1 count = 1 while cur is not None: is_cur = self.head for i in range(count): if cur == is_cur: return True is_cur = is_cur.next cur = cur.next count += 1 return False def reverse_index(self, index): """查看倒数第index 的数是什么""" try: if self.is_empty(): return None le = self.length() n = le - index if n >= 0: cur = self.head for i in range(n): cur = cur.next return cur.item else: return None except AttributeError: return None def reverse_star_end(self): """反转第一个和最后一个节点""" if self.head and self.head.next: cur_p = self.head cur_n = self.head.next # 找到前一个和最后一个节点 while cur_n.next: cur_p = cur_n cur_n = cur_n.next if self.length() == 2: cur_p.next = None cur_n.next = cur_p self.head = cur_n else: cur_n.next = self.head.next cur_p.next = self.head self.head.next = None self.head = cur_n else: pass def reverse(self): """反转列表 单链表反转的思想: 1. 创建一个新列表 2. 从旧链表中依次往出取数据 3. 然后将这个数据每次都插入到新列表的头部 4. 反转完成 """ if self.head.next is None: return cur = self.head ll = SingleLinkList() while True: cur = self.head if cur is None: break ll.add(self.head.item) self.head = self.head.next self.head = ll.head def reverse_print(self): """反向输出""" if self.head is None: return cur = self.head stack = list() while cur is not None: """遍历每个节点,压入在中,这里用列表实现栈的功能""" stack.insert(0, cur.item) cur = cur.next for item in stack: print(item, end=" ") def pop(self): """弹出头结点位置的元素""" if self.head is None: return None ret = self.head.item self.head = self.head.next return ret def p_pop(self): if self.head is None: return None ret = self.head.item return ret def merge_single(l1:SingleLinkList, l2:SingleLinkList): """合并两个有序集合""" if l1.is_empty() and l2.is_empty(): """对两个链表进行判空""" return new_l = SingleLinkList() l1_val = l1.pop() l2_val = l2.pop() while l1_val is not None and l2_val is not None: if int(l1_val) <= int(l2_val): new_l.append(l1_val) l1_val = l1.pop() else: new_l.append(l2_val) l2_val = l2.pop() if not l1.is_empty(): l1_val = l1.pop() while l1_val is not None: new_l.append(l1_val) l1_val = l1.pop() elif not l2.is_empty(): l2_val = l2.pop() while l2_val is not None: new_l.append(l2_val) l2_val = l2.pop() return new_l if __name__ == "__main__": l1 = SingleLinkList() l1.append(1) l1.append(5) l1.append(9) l1.append(15) l1.append(26) l1.append(32) l2 = SingleLinkList() l2.append(2) l2.append(7) l2.append(16) l2.append(17) l2.append(21) l2.append(34) new_l = merge_single(l1, l2) new_l.travel()
37257970bf8e9ad211d6a33f656265c508c70ac4
otisgbangba/python-lessons
/simple/todo.py
128
3.859375
4
items = [] while True: item = input('Item? ') if item: items.append(item) else: break print(items)
a0313dec7265e25f84b7be1ef3a67262c4a0cf22
Gabicolombo/Python-exercicios
/Dictionaries/exercicio 3.py
551
3.9375
4
''' 3. At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had 45 medals, Russia had 30 medals, and Germany had 17 medals. Create a dictionary assigned to the variable medal_count with the country names as the keys and the number of medals the country had as each key’s value. ''' medal_count = {'United States' : 70, 'Great Britain': 38, 'China': 45, 'Russia': 30, 'Germany': 17} print(medal_count) # {'United States': 70, 'Great Britain': 38, 'China': 45, 'Russia': 30, 'Germany': 17}
92da246f3db0c5a0c39773fc1e7fe2dfe75a2a1f
imolina218/Practica
/Login_system/validation.py
1,282
3.859375
4
class Authentication(object): def __init__(self, input_value=''): self.input_value = input_value def __lower(self): lower = any(c.islower() for c in self.input_value) return lower def __upper(self): upper = any(c.isupper() for c in self.input_value) return upper def __digit(self): digit = any(c.isdigit() for c in self.input_value) return digit def validate(self): lower = self.__lower() upper = self.__upper() digit = self.__digit() value_len = len(self.input_value) report_name = lower and upper and digit and value_len >= 6 if report_name: print("Username and password validated.") return True elif not lower: print("You didn't use a lower case letter.") return False elif not upper: print("You didn't use a upper case letter.") return False elif value_len < 6: print("Your username and password should have at least 6 characters") return False elif not digit: print("You didn't use a digit") return False else: pass
c283c3a0fe5848138890eb4499ac0fa675cc3448
Cr1s1/bfsutechlab-1week-python
/学习笔记/代码笔记/Day2/4.1_lists.py
2,598
3.84375
4
# 4.1 列表 # 4.1.1 定义一个列表 names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] # 用方括号定义一个列表,字符串元素需要用引号括起来 print(names) ''' 运行结果: ------------------------------------------ ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] ------------------------------------------ ''' # 4.1.2 列表中单个元素的索引 # 相关知识点:可复习2.2字符串的索引 names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] print(names[0]) # 用索引来访问单个元素(0索引第一项) print(names[2]) # 2索引第(2+1)项 print(names[-1]) # -1索引最后一项 print(names[-2]) # -2索引倒数第二项 ''' 运行结果: ---------- John Mosh Mary Sarah ---------- ''' # 4.1.3 列表中对一系列元素的索引 names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] print(names[2:]) # 只指定开始索引,就默认一直访问到末尾 print(names[2:4]) # 只访问开始索引所指项,不访问结束索引所指项 print(names[:4]) # 只指定结束索引,就默认从第一项开始访问 print(names[:]) # 开始和结束索引都不指定,默认访问所有项 print(names[0:]) # 默认访问所有项 print(names) # 字符串的索引语句不会修改最初的列表 ''' 运行结果: ------------------------------------------- ['Mosh', 'Sarah', 'Mary'] ['Mosh', 'Sarah'] ['John', 'Bob', 'Mosh', 'Sarah'] ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] -------------------------------------------- ''' print('\n') # 4.1.4 修改原列表中的单个元素 names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] names[0] = 'Jon' # 直接使用索引和赋值语句修改其值 print(names) ''' 运行结果: ---------------------------------------------- ['Jon', 'Bob', 'Mosh', 'Sarah', 'Mary'] ---------------------------------------------- ''' print('\n') # 4.1.5 小练习:找出列表中的最大元素 # 注:本练习需要用到for循环、if语句的知识,可以待学完第五章相关知识后再回看本练习 numbers =[3, 6, 2, 10, 8, 4] max = numbers[0] # 存放最大值,初始化为列表第一项的值(假设第一项最大) # 需要遍历这个列表,获取其中每一项的值,每一次迭代进行一次比较 for number in numbers: if number > max: max = number print(max) ''' 运行结果:10 '''
548e9536380b869da7fa727e49cc631dba03399a
jay6413682/Leetcode
/Merge_k_Sorted_Lists_23.py
6,442
3.984375
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: """ 顺序合并: https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/ """ def merge_two_lists(self, node_a: ListNode, node_b: ListNode) -> ListNode: if not node_a: return node_b if not node_b: return node_a merged_dummy_head = ListNode() merged_pointer = merged_dummy_head pointer_a = node_a pointer_b = node_b while pointer_a is not None and pointer_b is not None: if pointer_a.val < pointer_b.val: merged_pointer.next = pointer_a pointer_a = pointer_a.next else: merged_pointer.next = pointer_b pointer_b = pointer_b.next merged_pointer = merged_pointer.next if pointer_a is not None: merged_pointer.next = pointer_a elif pointer_b is not None: merged_pointer.next = pointer_b return merged_dummy_head.next def mergeKLists(self, lists: List[ListNode]) -> ListNode: m = None for l in lists: m = self.merge_two_lists(m, l) return m class Solution2: """ My own solution, not efficient """ def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists: return None merged_list_dummpy_head = ListNode(-10**4 - 1) for l in lists: if not l: continue pointer = l while pointer is not None: merged_list_pointer_slow = merged_list_dummpy_head merged_list_pointer_fast = merged_list_pointer_slow.next nxt = pointer.next while merged_list_pointer_slow is not None: if (merged_list_pointer_fast is not None and pointer.val >= merged_list_pointer_slow.val and pointer.val <= merged_list_pointer_fast.val) or (merged_list_pointer_fast is None): pointer.next = merged_list_pointer_fast merged_list_pointer_slow.next = pointer break merged_list_pointer_slow = merged_list_pointer_slow.next if merged_list_pointer_fast is not None: merged_list_pointer_fast = merged_list_pointer_fast.next pointer = nxt return merged_list_dummpy_head.next class Solution3: """ 堆/优先序列;use heapq : to represent priority queue: https://www.geeksforgeeks.org/heap-queue-or-heapq-in-python/ working solution: https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/python-c-you-xian-dui-lie-zui-xiao-dui-onlogk-by-m/ not working in python 3: https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/duo-tu-yan-shi-23-he-bing-kge-pai-xu-lian-biao-by-/ """ def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists: return n = len(lists) if n == 1: return lists[0] import heapq q = [] dummpy_head = ListNode(-1) merged_pointer = dummpy_head for i, l in enumerate(lists): if l: heapq.heappush(q, (l.val, i)) while q: val, i = heapq.heappop(q) # why cannot i use pointer = lists[i] here???? # because the next node needs to be saved to the lists; so in one of next loops, we can access it. merged_pointer.next = lists[i] merged_pointer = merged_pointer.next lists[i] = lists[i].next if lists[i]: heapq.heappush(q, (lists[i].val, i)) return dummpy_head.next """ # my latest try. easier to understand if not lists: return heap = [] for i, root in enumerate(lists): while root: heapq.heappush(heap, (root.val, i)) root = root.next #print(heap) root = None if heap: val, i = heapq.heappop(heap) node = lists[i] #print(node) root = curr = node lists[i] = node.next while heap: val, i = heapq.heappop(heap) node = lists[i] #print(node) curr.next = node curr = curr.next lists[i] = node.next return root """ class Solution4: """ 归并/merge 法: https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/ 归并排序最好的解释: https://zhuanlan.zhihu.com/p/44656243 归并排序复杂度解析:https://blog.csdn.net/YuZhiHui_No1/article/details/44223225 (也可用master theorem) https://zhuanlan.zhihu.com/p/124356219 """ def merge_two_lists(self, node_a: ListNode, node_b: ListNode) -> ListNode: if not node_a: return node_b if not node_b: return node_a merged_dummy_head = ListNode() merged_pointer = merged_dummy_head pointer_a = node_a pointer_b = node_b while pointer_a is not None and pointer_b is not None: if pointer_a.val < pointer_b.val: merged_pointer.next = pointer_a pointer_a = pointer_a.next else: merged_pointer.next = pointer_b pointer_b = pointer_b.next merged_pointer = merged_pointer.next if pointer_a is not None: merged_pointer.next = pointer_a elif pointer_b is not None: merged_pointer.next = pointer_b print(4) return merged_dummy_head.next def merge(self, lists, left, right): print(2) if left == right: return lists[left] mid = (left + right) // 2 l1 = self.merge(lists, left, mid) l2 = self.merge(lists, mid + 1, right) print(3) return self.merge_two_lists(l1, l2) def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists: return n = len(lists) if n == 1: return lists[0] print(1) return self.merge(lists, 0, n - 1)
9c957cc382445c1747af3d99c90da18e44068934
KojiNagahara/Python
/TextExercise/13-2/binaryTree.py
1,326
3.8125
4
"""動的計画法に使用するRooted Binary Treeのpython実装をclass化したもの。 関数バージョンだとキャッシュの初期化を明示的に書かないといけないので、class化することでその問題を解消する""" class CachedBinaryTree(): """キャッシュを考慮したRooted Binary Treeクラス""" def __init__(self): """sourceはツリーを生成するための元になるItemのList""" self._cache = {} def max_value(self, source, avail): if (len(source), avail) in self._cache: result = self._cache[(len(source), avail)] elif source == [] or avail == 0: result = (0, []) elif source[0].weight > avail: # 右側の分岐のみを探索する result = self.max_value(source[1:], avail) else: next_item = source[0] # 左側の分岐を探索する with_value, with_to_take = self.max_value(source[1:], avail - next_item.weight) with_value += next_item.value # 右側の分岐を探索する without_value, without_to_take = self.max_value(source[1:], avail) if with_value > without_value: result = (with_value, with_to_take + [next_item,]) else: result = (without_value, without_to_take) self._cache[(len(source), avail)] = result return result
4710d526b1c43bd18e7e4f7077c823043f36d94d
dmitryzhurkovsky/stepik
/python_profiling/euler_7.py
1,873
3.546875
4
"""Project euler problem 7 solve""" from __future__ import print_function import math import sys import cProfile def profile(func): """Decorator for run function profile""" def wrapper(*args, **kwargs): profile_filename = func.__name__ + '.prof' profiler = cProfile.Profile() result = profiler.runcall(func, *args, **kwargs) profiler.dump_stats(profile_filename) return result return wrapper def is_prime(num): """ Checks if num is prime number. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(4) False >>> is_prime(5) True >>> is_prime(41) True >>> is_prime(42) False >>> is_prime(43) True """ for i in range(2, int(math.sqrt(num) + 1)): if num % i == 0: return False return True @profile def get_prime_numbers(count): """ Get 'count' prime numbers. >>> get_prime_numbers(1) [2] >>> get_prime_numbers(2) [2, 3] >>> get_prime_numbers(3) [2, 3, 5] >>> get_prime_numbers(6) [2, 3, 5, 7, 11, 13] >>> get_prime_numbers(9) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> get_prime_numbers(19) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] """ prime_numbers = [2] next_numbers = 3 while len(prime_numbers) < count: if is_prime(next_numbers): prime_numbers.append(next_numbers) next_numbers += 1 return prime_numbers if __name__ == '__main__': try: count = int(sys.argv[1]) except (TypeError, ValueError, IndexError): sys.exit("Usage: euler_7.py number") if count < 1: sys.exit("Error: number must be greater than zero") prime_numbers = get_prime_numbers(count) print(f'Answer: {prime_numbers[-1]}')
f793319b2d63ca0fbf6b4a286dedcab3d66b1a33
elsantodel90/cses-problemset
/concert_tickets.py
2,832
3.671875
4
# MAGIC CODEFORCES PYTHON FAST IO import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) # END OF MAGIC CODEFORCES PYTHON FAST IO import random NOT_FOUND = (-1,-1) class EmptyNode(object): def insert(self, val): return BSTNode(val) def findAndRemove(self, upper): return self, NOT_FOUND def merge(self, right): return right def empty(self): return True def depth(self): return 0 # Notar que no necesitamos balancear porque tenemos todos los datos que insertamos al comienzo: # basta un random_shuffle al comienzo para tener un arbol balanceado. # NOTA: Asumiendo que no hay repetidos!!! Por eso tuve un WA, y hubo que desempatar cosas. class BSTNode(object): def __init__(self, val): self.left = EmptyNode() self.right = EmptyNode() self.val = val def empty(self): return False def insert(self, val): if val <= self.val: self.left = self.left.insert(val) else: self.right = self.right.insert(val) return self # Sabemos que todo el arbol right es mayor estricto que todo nuestro arbol def merge(self, right): parent, largest = None, self while not largest.right.empty(): parent , largest = largest, largest.right if parent is not None: parent.right = largest.left largest.left = self largest.right = right return largest def findAndRemove(self, upper): if upper >= self.val: self.right, ret = self.right.findAndRemove(upper) if ret == NOT_FOUND: return self.left.merge(self.right), self.val else: return self, ret else: self.left , ret = self.left.findAndRemove(upper) return self, ret def depth(self): return 1+max(self.left.depth(), self.right.depth()) class BinarySearchTree(object): def __init__(self): self.root = EmptyNode() def insert(self, val): self.root = self.root.insert(val) def insertAll(self, values): for val in values: self.insert(val) def findAndRemove(self, upper): self.root, ret = self.root.findAndRemove(upper) return ret def readLineInts(): return map(int,input().split()) n,m = readLineInts() h = [(x,i) for i,x in enumerate(readLineInts())] random.shuffle(h) bst = BinarySearchTree() bst.insertAll(h) print(bst.root.depth(), file=sys.stderr) t = readLineInts() for customer in t: val, index = bst.findAndRemove((customer, n)) print(val)
f6812ed3e0a165dd0bed8726d65bbcdf37de5b82
lightening0907/algorithm
/SwapTwoNodeInPair.py
522
3.875
4
# Given a linked list, swap every two adjacent nodes and return its head. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head N1 = head.next N2 = head N2.next = self.swapPairs(N1.next) N1.next = N2 return N1
fe1fead1b6716947dbb093a5d955a31b3f8fd44e
AdamZhouSE/pythonHomework
/Code/CodeRecords/2936/60634/250951.py
1,239
3.59375
4
table = ['2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','#','7','7','8','8','8','9','9','9','#'] def transform(phoneNum): result = "" for x in phoneNum: if x <= 'Z' and x >= 'A': result += table[ord(x) - ord('A')] elif x >= '0' and x <= '9': result += x return result def equal(phone1, phone2): if len(phone1) != len(phone2): return False for x in range(len(phone1)): if ord(phone1[x]) != ord(phone2[x]): return False return True num = int(input()) phoneBook = [] for x in range(num): phoneBook.append(transform(input())) diff = True i = 0 while i < len(phoneBook) - 1: count = 1 j = i + 1 while j < len(phoneBook): if equal(phoneBook[i],phoneBook[j]): diff = False count += 1 phoneBook.remove(phoneBook[j]) j -= 1 j += 1 if count > 1: k = 0 while k < len(phoneBook[i]): print(phoneBook[i][k],end = "") if k == 2: print('-',end = "") k += 1 print(end = " ") print(count) i += 1 if diff: print("No duplicates.",end = "")
1c75a2f4f0e1689a7eca3b528d4221f1073c3d4e
tapachec0/Algorithms-Data-Structures
/Monitoring Activities/List #3/DoublyLinkedList.py
10,902
3.921875
4
''' Univesidade Federal de Pernambuco -- UFPE (http://www.ufpe.br) Centro de Informatica -- CIn (http://www.cin.ufpe.br) Bacharelado em Sistemas de Informacao IF969 -- Algoritmos e Estruturas de Dados Autor: Talyta Maria Rosas Pacheco Email: [email protected] Data: 2018-09-07 Descricao: Implementação de uma lista duplamente encadeada Copyright(c) 2018 Talyta Pacheco ''' class Node: def __init__(self, item = None, previous = None, after = None): self.item = item self.prev = previous self.after = after def __str__(self): return str(self.item) def __repr__(self): return repr(self.item) class DoublyLinkedList: def __init__(self, iterable = None): ''' Construtor recebe iteráveis. Por padão é None, que é uma lista vazia ''' self.head = Node() if(iterable == None): self.tail = self.head else: aux = self.head for element in iterable: #construindo a lista, começando pelo próximo elemento da cabeça aux.after = Node(element, aux) aux = aux.after #o fim é o último elemento adicionado self.tail = aux def isEmpty(self): if(self.head == self.tail): return True else: return False def append(self, item): ''' Adicionar um item no fim da lista ''' #o proximo elemento do outro --> Nó self.tail.after = Node(item, self.tail) #atualização do último elemento self.tail = self.tail.after def insertByIndex(self, item, index): ''' Insere um elemento na lista, em um índice desejado. Caso o índice seja maior que o tamanho da lista, adiciona na última posição ''' if(index < self.__len__()): cont = 0 aux = self.head.after while(cont != index): aux = aux.after cont += 1 aux.prev = Node(item, aux.prev, aux) aux.prev.prev.after = aux.prev else: return self.append(item) def pop(self, index = None): ''' Remove o elemento de um índice desejado. Sendo por padrão, o último índice ''' if(index == None): index = self.__len__()-1 if(self.isEmpty()): print("List is empty") elif(index > (self.__len__()-1)): raise IndexError("Index out of Range") else: aux = self.head.after cont = 0 while(cont != index): aux = aux.after cont += 1 aux.prev.after = aux.after #caso o elemento que foi removido seja o ultimo, altera a ligação do último para o anterior do último if(aux.after == None): self.tail = aux.prev else: aux.after.prev = aux.prev valueReturn = aux del aux #devolve o valor retirado return valueReturn def remove(self, item): ''' Remove o nó que contém o item passado pelo usuario. Caso haja mais de um nós com esse elemento, remove apenas o primeiro ''' if(self.isEmpty()): print("List is empty") elif(self.__contains__(item) == False): raise ValueError("Item not found") else: aux = self.head.after while(aux.item != item): aux = aux.after aux.prev.after = aux.after if(aux.after == None): self.tail = aux.prev else: aux.after.prev = aux.prev del aux def eliminate(self, item): ''' Retira da lista, todos os nós os nós que possuem o valor passado pelo usuario ''' if(self.isEmpty()): print("List is empty") elif(self.__contains__(item) == False): raise ValueError("Item not found") else: cont = 0 tam = self.__len__() aux = self.head.after while(cont < tam): keepFinding = aux if(aux.item == item): if(aux.after == None): aux.prev.after = aux.after self.tail = aux.prev else: aux.prev.after = aux.after aux.after.prev = aux.prev del keepFinding aux = aux.after cont += 1 def research(self, item): ''' Devolve para o usuário o índice do valor desejado na lista ''' if(self.__contains__(item) == False): raise ValueError("Item not found") else: cont = 0 aux = self.head.after found = False while(found == False): if(aux.item == item): found = True return "Index de %s é "%(item) + str(cont) aux = aux.after cont += 1 def copy(self): ''' Faz uma cópia de uma lista duplamente encadeada ''' #novo objeto do tipo lista encadeada self.newObject = DoublyLinkedList() cont = 0 aux = self.head.after #tamanho da lista que será copiada tam = int(self.__len__()) while(cont < tam): #construção da lista por vários appends, até chegar ao tamanho da lista original self.newObject.append(aux.item) aux = aux.after cont += 1 self.tail = aux #devolve a cópia return self.newObject def extend(self, iterable): ''' Põe ao final da lista, um objeto iteravel ''' for item in iterable: self.append(item) def switch(self, index1, index2): ''' Troca os nós de uma lista que possui os indices passados pelo usuario: o primerio e segundo indices que deseja trocar de posição na lista ''' if(index1 > (self.__len__()-1) or index2 > (self.__len__()-1)): raise IndexError("Index out of range") else: cont = 0 aux = self.head.after self.secondValue = self.firstValue = 0 while(cont != index1): aux = aux.after cont += 1 #get o valor do primeiro indice do usuario self.firstValue = aux.item #reseta o auxiliar e cont para encontrar o valor do segundo índice cont = 0 aux = self.head.after while(cont != index2): aux = aux.after cont += 1 self.secondValue = aux.item #utiliza a função setitem para trocar de posição. O primerio indice recebe o segundo, e o outro o inverso self.__setitem__(index1, self.secondValue) self.__setitem__(index2, self.firstValue) def __iter__(self): #torna o objeto da lista duplamente encadeada iteravel return DoublyLinkedListIterator(self) def __contains__(self, item): ''' Verifica se há um elemento passado pelo usuario na lista ''' aux = self.head.after #tag para auxiliar o encontro found = False while(found == False): #caso o aux seja None, significa que chegou ao final, já que não há, agr, nenhum valor guardado. Logo, não encontrou o elemento if(aux == None): return False if(aux.item == item): found = True return True aux = aux.after def __getitem__(self, index): ''' Retorna o valor de um indice. Implementa a seguinte chamada: lista[indice] ''' if(self.isEmpty()): print("List is empty") elif(index > (self.__len__()-1)): raise IndexError("Index out of Range") else: found = False cont = 0 aux = self.head.after while(found == False): if(cont == index): found = True return aux aux = aux.after cont += 1 def __setitem__(self, index, item): ''' Troca o valor de um indice. Implementa a seguinte chamada: lista[indice] = valor ''' if(index > (self.__len__()-1)): raise IndexError("Index out of Range") else: cont = 0 aux = self.head.after while(cont != index): aux = aux.after cont += 1 aux.item = item def __len__(self): cont = 0 aux = self.head while(aux.after != None): aux = aux.after cont += 1 return cont def __str__(self): string = "[" cont = 0 aux = self.head while(cont < self.__len__()): if(aux.after.after == None): string += repr(aux.after) else: string += repr(aux.after) + "," + " " cont += 1 aux = aux.after string += "]" return string def __repr__(self): string = "DoublyLinkedList([" cont = 0 aux = self.head while(cont < self.__len__()): if(aux.after.after == None): string += repr(aux.after) else: string += repr(aux.after) + "," + " " cont += 1 aux = aux.after string += "])" return string class DoublyLinkedListIterator: def __init__(self, doublyLinkedList): self.firstPosition = doublyLinkedList.head def __iter__(self): return self def __next__(self): self.firstPosition = self.firstPosition.after if(self.firstPosition == None): raise StopIteration return self.firstPosition.item def concanate(list1, list2): ''' Junta duas listas. O princípio é ligar como o proximo elemento do ultimo da primeira lista ao primeiro elemento da segunda lista. ''' list1.tail.after = list2.head.after list2.head.after.prev = list1.tail return list1
1c532103db2d814eb3a9250454ea9abb99b94838
Suzie-to/Python_Data_Structures
/Stacks_Tuples_Sets/04.Honey.py
3,407
4.34375
4
''' Worker-bees collect nectar. When a worker-bee has found enough nectar, she returns to the hive to drop off the load. The worker-bees pass the nectar to waiting bees so they can really start the honey-making process. You will receive 3 sequences: • a sequence of integers, representing working bees, • a sequence of integers, representing nectar, • a sequence of symbols – "+", "-", "*" or "/", representing the honey-making process. Your task is to check if the bee has collected enough nectar to return to the hive and to keep track of the total honey waiting bees have made with the collected nectar. Step one: you should check if the bee has collected enough nectar. You should take the first bee and try to match it with the last nectar: • If the nectar value is more or equal to the value of the bee, it is considered collected, and the bee returns to the hive to drop off the load (step two). • If the nectar value is less than the value of the bee, you should remove the nectar and try to match the bee with the next nectar's value. Step two: you should calculate the honey made with the passed nectar. When you find a bee and nectar that have matched (step one), you should take the first symbol in the sequence of symbols ("+", "-", "*" or "/") and make the corresponding calculation as follows: "{matched bee} {symbol} {matched nectar}" The result represents the honey that is made from the passed nectar. The calculation should always return the absolute value of the result. After the calculation, remove the bee, the nectar, and the symbol. Stop making honey when you are out of bees or nectar. There always will be enough symbols in the sequence of symbols Input • On the first line, you will be given the values of bees - integers, separated by a single space • On the second line, you will be given the nectar's values - integers, separated by a single space • On the third line, you will be given symbols - "+", "-", "*" or "/", separated by a single space Output • On the first line - print the total honey made: ◦ "Total honey made: {total honey}" • On the next two lines print the bees or the nectar that are left, if there are any, otherwise skip the line: ◦ "Bees left: {bee1}, {bee2}, … {beeN}" ◦ "Nectar left: {nectar1}, {nectar2}, … {nectarN}" ''' from collections import deque bees = deque([int(x) for x in input().split()]) # FIFO tail nectar = [int(x) for x in input().split()] # LIFO stack signs = deque(input().split()) # honey making process total_honey = 0 while bees and nectar: curr_bee = bees.popleft() curr_nectar = nectar.pop() if curr_nectar >= curr_bee: sign = signs.popleft() if sign == '+': total_honey += abs(curr_bee + curr_nectar) elif sign == '*': total_honey += abs(curr_bee * curr_nectar) elif sign == '/': if curr_nectar > 0: total_honey += abs(curr_bee / curr_nectar) elif sign == '-': total_honey += abs(curr_bee - curr_nectar) else: bees.appendleft(curr_bee) print(f"Total honey made: {total_honey}") if bees: print(f"Bees left: {', '.join([str(bee) for bee in bees])}") if nectar: print(f"Nectar left: {', '.join([str(x) for x in nectar])}")
c59d063724dc0114126740c1af759c3f84d9c945
tgspacelabs/Dev
/PythonApplication1/PythonApplication1/PythonApplication1.py
312
4.03125
4
def Test(n): print('Function called with ', n) print('This is python...') for i in range(10): print('For loop value: ', i) Test(i) # Python 3: Fibonacci series up to n def Fibonacci(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() Fibonacci(10000)
479e714f12fb49b3e410d29e5ea9b811f3e990c5
Master-of-moyu/sh_and_md
/python/array.py
462
3.546875
4
import matplotlib.pyplot as plt import numpy as np a = [1, 2] print(a) for x in a: print(x) a.append(3) print(a) b = np.arange(0, 1, 0.1) print("np.arange: ") print(b) c = np.linspace(1, 10, num= 5, endpoint = True) print("np.linspace: ") print(c) arr = [] l = len(arr) print(l) arr.append(100) l = len(arr) print(l) d = np.array([1, 2, 3, 4, 5]) print(d) print("np.zeros: ") e = np.zeros((2,3)) print(e) print("np.ones: ") f = np.ones((2,4)) print(f)
2fe8c28fbad8a712b5f57c72dfabe82ec7812a80
williamsyb/mycookbook
/algorithms/BAT-algorithms/The beauty of programming/chapter-3/3-计算字符串的相似度.py
982
3.890625
4
def calculate_string_distance(str_a, start_a, end_a, str_b, start_b, end_b): if start_a > end_a: if start_b > end_b: return 0 else: return end_b - start_b + 1 if start_b > end_b: if start_a > end_a: return 0 else: return end_a - start_a + 1 if str_a[start_a] == str_b[start_b]: return calculate_string_distance(str_a, start_a + 1, end_a, str_b, start_b + 1, end_b) else: t1 = calculate_string_distance(str_a, start_a + 1, end_a, str_b, start_b, end_b) t2 = calculate_string_distance(str_a, start_a, end_a, str_b, start_b + 1, end_b) t3 = calculate_string_distance(str_a, start_a + 1, end_a, str_b, start_b + 1, end_b) return min(t1, t2, t3) + 1 if __name__ == '__main__': str_a = "aaee" str_b = "aac" if calculate_string_distance(str_a, 0, len(str_a) - 1, str_b, 0, len(str_b) - 1) == 1: print(1) else: print(0)
dad93ea293a3adc68ba3f6b01e86c0dea9e01fe6
qnadeem/solutions_to_some_programming_puzzles
/six/PrA.py
347
3.8125
4
x = str(raw_input()) def printt(a): r = "" if a ==0: print "0" else: while a>0: i = a%2 a = a/2 r = str(i) + r print r while( x!= "#"): N = int(x, 2) ans = 17*N printt(ans) x = raw_input()
854ff732f61fbcc1b089b25bb40050aedef1ffd8
fran757/battles
/model/factory.py
1,547
3.578125
4
"""Army-oriented Unit factory, using generic stats stored in json file.""" from dataclasses import dataclass, field as dfield from typing import List import json from tools import tools from .unit import Unit, UnitBase, UnitField, Strategy from .army import Army @dataclass class Factory: """Interface to build units for an army. Army side is provided at instanciation. Each call providing unit type and position will use loaded stats to add a new unit to the underlying army. """ side: int units: List[Unit] = dfield(default_factory=list) _registery = {} @classmethod @tools(log="registered {name}") def register(cls, name, prototype): """Register prototype for given unit type name.""" cls._registery[name] = prototype @property def army(self): """Provide army built from created units.""" return Army(self.units) def __call__(self, name, coords, strategy, is_centurion=False): try: base = self._registery[name] except KeyError: tools(log=f"Unregistered name: {name}")() base = UnitBase(0, 0, 0, 0) field = UnitField(self.side, coords, is_centurion) strat = Strategy(*strategy) self.units.append(Unit(base, field, strat)) return self.units[-1] def load(file_name): """Load unit type stats from json file.""" with open(file_name) as file: data = json.load(file) for name, attrs in data.items(): Factory.register(name, UnitBase(*attrs))
1e05ea0ebf34f5310ce37f6c34d5a90b7f304f86
7vgt/CSE
/Andrew Esparza - Programmer.py
629
3.765625
4
class Person(object): def __init__(self, name, age): self.name = name self.age = age def work(self): print("%s gose to work" % self.name) class Employee(Person): def __init__(self, name, age, length): super(Employee, self).__init__(name, age) self.length = length def name_tag(self): print("Tells Us All of your information") class Programmer(Employee): def __init__(self, name, age, length, weight): super(Programmer, self).__init__(name, age, length) self.weight = weight def experience_recemmended(self): print("10 years")
843409930b29c9cea6952dda33839169afa3b059
As4klat/Tutorial_Python
/Tanda 1/04.py
234
3.84375
4
def fahrenheit_celsius(f): return (f - 32)*5/9 print("Grados Fahrenheit Grados Celsius") print("================= ==============") for f in range(0, 121, 10): print(" ", f, " ", fahrenheit_celsius(f))
fe6f13e1e74686b068e8fa8dd7a1a28dc6b0ee72
janmlam/TDT4110
/oving1/messages.py
559
3.5625
4
counter = 1 def logg(name, time, msg): global counter print ("MSG", counter, ", " + name + " sent this message: " + msg + " at " + time + " o'clock.") counter = counter + 1 return def main(): logg("Mr. Y", "23:59", "Har du mottatt pakken?") logg("Mdm. Evil", "0:00", "Ja. Pakken er mottatt.") logg("Dr. Horrible", "0:03", "All you need is love!") logg("Mr. Y", "0:09", "Dr. Horrible, Dr. Horrible , calling Dr. Horrible .") logg("Mr. Y", "0:09", "Dr. Horrible, Dr. Horrible wake up now.") logg("Dr. Horrible", "0:09", "Up now!") return main()
39a99861d4f0a4c068fcacd0a886d95cfd004fc4
spacemanlol/Python-DataStructures-Reference
/SinglyLinkedList.py
6,077
4.21875
4
# Singly Linked List class Node: def __init__(self, data=None): self.data = data self.next = None class SinglyLinkedList: # Default Constructor def __init__(self): self.head = None self.tail = None self.length = 0 # Add to end of linked list def push(self, data): # Create a new node using the value passed to the function newNode = Node(data) # if there is no head property, set the # head and the tail to be the newly created node if not self.head: self.head = newNode self.tail = self.head # Otherwise set the next property on the tail to be the # new node and set the tail property on the list # to be the newly created node else: self.tail.next = newNode self.tail = newNode # Increment length self.length += 1 return SinglyLinkedList # Pop last element in linked list def pop(self): # If there are no nodes in the list, return undefined if not self.head: return None # Case if theres only 1 item in the array if self.head == self.tail: self.__init__() return None current = self.head # Loop through the entire list until you reach the tail while(current.next != self.tail): current = current.next # set the next property of the 2nd to last node to be null current.next = None self.tail = current # Decrement Length By One self.length -= 1 # Remove node from the beginning of the linked list def display_list(self): # Print List to Console current = self.head toString = "[ " while(current): toString += current.data + " " current = current.next print(toString + "]") # Remove node from the beginning of the linked list def shift(self): if self.length == 0: return None current = self.head if not self.head.next: self.__init__() return current # Remove node from the beginning of the linked list self.head = current.next self.length -= 1 return # Adding a new node to the beginning of the linked list def unshift(self, data): newNode = Node(data) # if there is no head property on the list, set the head # and tail to be the newly created node if not self.head: self.head = newNode self.tail = newNode # Otherwise set the newly created node's next # property to be the current head property on the list else: newNode.next = self.head # Set the head property on the list to be that newly created node self.head = newNode return SinglyLinkedList # Get value at specific index within linked list def get(self, index): if index > self.length or index < 0: return None current = self.head for i in range(index): current = current.next return current # Set Value at specific index within the linked list def set(self, index, value): getVal = self.get(index) if(getVal): getVal.data = value return getVal # Adding a node to the linked list at a specific position def insert(self, index, data): # if the index less than zero or greater than the length, return false if index < 0 or index > self.length: return False # if the index is the same as the length, push a new node to the end of the list if index == self.length: self.push(data) return True # if the index is 0, unshift a new node to the start of the list if index == 0: self.unshift(data) return True # Create new node newNode = Node(data) # Otherwise, using the get method, access the node at the [index - 1] getValue = self.get(index - 1) # Set the next property on that node to be the new node next = getValue.next getValue.next = newNode # Set the property on the new node to be the previous next newNode.next = next # Increment Length self.length += 1 return True # Removing a node from the Linked List at a specific index def remove(self, index): # Value to be removed toRemove = None # If the index is less than zero or greater than the length, return undefined if index < 0 or index >= self.length: return toRemove # If the index is the same as the length-1, pop if index == self.length - 1: toRemove = self.pop() # If the index is 0, use shift elif index == 0: toRemove = self.shift() else: # Otherwise, using the get method, access the node at index - 1 getValue = self.get(index - 1) # Value to be removed toRemove = getValue.next # Set the next property on that node to be the next of the next node getValue.next = getValue.next.next self.length -= 1 return toRemove # Reversing Linked List In Place def reverse(self): # Initialize node variable node = self.head # Swap head and tail self.head, self.tail = self.tail, self.head # We need prev to be null because we need to make sure the end of the list is null prev = None next = None # Rebuild list in backwards order for i in range(self.length): next = node.next node.next = prev prev = node node = next return SinglyLinkedList newList = SinglyLinkedList() newList.push("1") newList.push("2") newList.push("3") newList.push("4") newList.display_list() newList.reverse() newList.display_list()
4442ed29b6b1ae736e7c53fa7a956a934468234c
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/without_level/314/to_columns.py
335
3.765625
4
from typing import List # not needed when we upgrade to 3.9 from itertools import zip_longest def print_names_to_columns(names: List[str], cols: int = 2) -> None: names = list(map(lambda x: f'| {x:10}', names)) groups = zip_longest(*[iter(names)] * cols, fillvalue='') for group in groups: print(''.join(group))
185e897df5f1b45edbfb88d72a94638ef9ee33e1
shubham2441/movierental
/BackEnd.py
1,644
3.515625
4
import sqlite3 def connect(): conn=sqlite3.connect("Movie.db") cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS rental (id INTEGER PRIMARY KEY, name text, title text, time integer, phone integer, address text)") conn.commit() conn.close() def insert(name, title, time, phone, address): conn=sqlite3.connect("Movie.db") cur = conn.cursor() cur.execute("INSERT INTO rental VALUES(NULL,?,?,?,?,?)", (name, title, time, phone, address)) conn.commit() conn.close() def view(): conn = sqlite3.connect("Movie.db") cur = conn.cursor() cur.execute("SELECT * FROM rental") rows=cur.fetchall() conn.commit() conn.close() return rows def search(name="", title="", time="", phone="", address=""): conn = sqlite3.connect("Movie.db") cur = conn.cursor() cur.execute("SELECT * FROM rental WHERE name=? OR title=? OR time=? OR phone=? OR address=?", (name, title, time, phone, address)) rows=cur.fetchall() conn.commit() conn.close() return rows def delete(id): conn=sqlite3.connect("Movie.db") cur=conn.cursor() cur.execute("DELETE FROM rental WHERE id=?", (id,)) conn.commit() conn.close() def update(id, name, title, time, phone, address): conn = sqlite3.connect("Movie.db") cur = conn.cursor() cur.execute("UPDATE rental SET name=?, title=?, time=?, phone=?, address=? WHERE id=?", (name, title, time, phone, address, id)) conn.commit() conn.close() def calculate(cost, time): amount = int(cost) + (int(time)*10) return amount connect()
2ccdf66e29855c0dac9d70c1781cd9d16fd2b5e7
SuryamitraAkkipeddi/Codility
/Nesting.py
295
3.828125
4
def solution(S): parentheses = 0 for element in S: if element == "(": parentheses += 1 else: parentheses -= 1 if parentheses < 0: return 0 if parentheses == 0: return 1 else: return 0
a568db684e331b7d6353ee7ba251c566ad4f5731
zhjw8086/MagikCode
/第二季/tkinterProjectS02TEST/paddleGame1~9/paddolGame5/paddleGame5.py
2,898
3.65625
4
""" 12.5 让球拍移动 """ from tkinter import * import time import random tk = Tk() tk.title('paddle game') tk.resizable(0, 0) # 设置窗口的大小是否可以调整, (0, 0)的意思是在水平和垂直方向上都不能改变 tk.wm_attributes("-topmost", 1) # 窗口置顶(无条件记住该方法和括号内的选项) canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=5) # 指定高亮边框的宽度 canvas.pack() tk.update() # 刷新页面,为我们的游戏动画做好初始化 class Ball: def __init__(self, main_canvas, color): # 创建 Ball 的类,它有两个参数:画布·main_canvas、球的颜色·color self.canvas = main_canvas # 将参数 main_canvas 赋值给变量 canvas self.ID = main_canvas.create_oval(0, 0, 20, 20, fill=color) # 在画布上画一个用颜色参数作为填充颜色的小球 self.canvas.move(self.ID, 240, 190) # 将tkinter画小球时所返回的ID保存起来 start_x = [-3, -2, -1, 1, 2, 3] random.shuffle(start_x) self.x = start_x[0] self.y = -3 self.canvas_height = self.canvas.winfo_height() self.canvas_width = self.canvas.winfo_width() def draw(self): self.canvas.move(self.ID, self.x, self.y) pos = self.canvas.coords(self.ID) # print(pos) if pos[1] <= 0: self.y = 10 if pos[3] >= self.canvas_height: self.y = -10 if pos[0] <= 0: self.x = 10 if pos[2] >= self.canvas_width: self.x = -10 class Paddle: def __init__(self, main_canvas, color): self.canvas = main_canvas self.ID = main_canvas.create_rectangle(0, 0, 100, 10, fill=color) self.canvas.move(self.ID, 200, 300) """step1: 增加对象变量 self.x""" self.x = 0 """step2:调取画布的宽度赋值给 self.canvas_width""" self.canvas_width = self.canvas.winfo_width() """step4:将对应的按键的方向绑定在step3中生成的函数上""" self.canvas.bind_all("<KeyPress-Left>", self.turn_left) self.canvas.bind_all("<KeyPress-Right>", self.turn_right) def draw(self): """pass""" """step5:修改 draw 的移动条件""" self.canvas.move(self.ID, self.x, 0) ball_pos = self.canvas.coords(self.ID) if ball_pos[0] <= 0: self.x = 0 elif ball_pos[2] >= self.canvas_width: self.x = 0 """step3: 创建两个函数来改变向左(turn_left)向右(turn_right)的方向""" def turn_left(self, evt): self.x = -3 def turn_right(self, evt): self.x = 3 paddle = Paddle(canvas, "LightSteelBlue") ball = Ball(canvas, "Royalblue") while True: ball.draw() paddle.draw() tk.update_idletasks() tk.update() time.sleep(0.01)
946bcb5c8016c99c844b5f4a4e1525f2b5042bde
vv31415926/python_lesson_08_UltraLite
/main.py
1,163
3.953125
4
''' 1. Написать свой генератор последовательностей, свой тернарный оператор 2. Написать свой декоратор ''' # тернарный оператор f = lambda x: 'дед' if x > 50 else 'пацан' print( f(30), f(60)) # Генератор последовательностей *************************************************** lst = [ [x,x**3] for x in range( 10 ) if x%2 == 0 ] print('списки:',type(lst)) for v in lst: print( v[0], v[1]) dic = { x : x**3 for x in range( 10 ) if x%2 == 0 } print('словарь:',type(dic)) for k,v in dic.items(): print( k, v ) set = { x**3 for x in range( 10 ) if x%2 == 0 } print('Множество:',type(set)) for v in set: print( v ) # Декоратор ******************************************************************** def show(f): def wrapper( *args, **kwargs ): print( '*' * (len(args[0])+4) ) print( '* '+f( *args, **kwargs )+' *' ) print('*' * (len(args[0])+4) ) return wrapper @show def getName( s ): return s getName('Валерий') getName('Вика')
d47727cbec4aed19ba134225be452d3953dc7046
s0m35h1t/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
379
4.28125
4
#!/usr/bin/python3 """ append text to file """ def append_write(filename="", text=""): """append a string to a text file (UTF8) and returns the number of characters written Args: filename (str): file name text (int): text to write Returns: (int) """ with open(filename, "a", encoding="utf-8") as f: return f.write(text)
5599c3504e3ba15bb055e7e4d9632065c096fcb4
Nadim-Nion/Python-Programming
/xargs.py
528
4.21875
4
''' xargs is used to print multiple numbers of arguments for the same number of parameter. if we change the numbers of argument , the function still can print the output. Note: xargs works like Tuples. ''' def add(*details):# syntax: def function_name(*text) print(details) print(details[1]) add(101,"Physics") add(102,"Chemistry","Ch 1st paper") def summation(*numbers): sum=0 for x in numbers: sum= sum+x print("Summation is =",sum) summation(10,20) summation(10,20,50) summation(10,20,50,70)
7ad417ac25510689517f115ae6fa0a2d3f8797e5
pbinneboese/CD_Python
/fundamentals/stars.py
797
3.75
4
# stars, part 1 # def convertToChars(num, chr): # return string with num characters of chr str = "" for i in range(0,num): str += chr return str # def draw_stars(arr, chr): for i in arr: str1 = convertToChars(i, chr) print (str1) return # starArray = [4,6,1,3,5,7,25] print "stars part 1" draw_stars(starArray,"*") # # stars, part 2 def draw_stars2(wordList): for i in wordList: if type(i) is int: chr = "*" num = i elif type(i) is str: chr = i[0].lower() num = len(i) # print chr, num str1 = convertToChars(num, chr) print (str1) # draw_stars(starArray,chr) return # x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] print "stars part 2" draw_stars2(x)
d0812a2f6a355269748f065b0252463a8b64b6f7
TanishTaneja/Python-Questions
/Coding Ninjas/Conditionals & Loops/Q4_Fahrenheit_to_Celsius.py
985
4.15625
4
# Given Given three values - Start Fahrenheit Value (S), End Fahrenheit value (E) and Step Size (W), you need to # convert all Fahrenheit values from Start to End at the gap of W, into their corresponding Celsius values and print # the table. Input Format : 3 integers - S, E and W respectively Output Format : Fahrenheit to Celsius conversion # table. One line for every Fahrenheit and corresponding Celsius value. On Fahrenheit value and its corresponding # Celsius value should be separate by tab ("\t")version table. One line for every Fahrenheit and corresponding # Celsius value. On Fahrenheit value and its corresponding Celsius value should be separate by tab ("\t") # Read input as specified in the question # Print output as specified in the question # (°F − 32) × 5/9 = °C # C = (F-32)*5//9 S = int(input()) E = int(input()) W = int(input()) F = S # C = (F-32)*5//9 # print(C) for F in range(S, E + 1, W): C = int((F - 32) * 5 / 9) print(F, "", C)
6b6562c63a3a05dbaf728b3d767b1c76b6e986b3
Akshaya-Dhelaria-au7/coding-challenges
/coding-challenges/week02/day3/alphabet_rangoli.py
410
3.5
4
size=3 for i in range(1,size+1): print ("-"*(2*(size-i)),end="") s=chr(96+size) for j in range(1,i): s+=("-"+chr(96+size-j)) s2= s[::-1] print (s+s2[1::],end="") print ("-"*(2*(size-i))) for i in range(size-1,0,-1): print ("-"*(2*(size-i)),end="") s=chr(96+size) for j in range(1,i): s+=("-"+chr(96+size-j)) s2= s[::-1] print (s+s2[1::],end="") print ("-"*(2*(size-i)))
bb15928f8b089b749025ffedc10b3c9e20a26c78
nyirweb/python-t
/Exam2.py
836
3.890625
4
#Üzenet a napokra válaszként nap = int(input("Add meg hanyadik napja van a hétnek?\n")) if(nap == 1): print("Hétfő - Work hard live hard - Éld túl ezt is!") elif(nap == 2): print("Kedd! Akkor még egy kis erő maradt a hétvégéből?") elif(nap == 3): print("Szerda! A nap végén több telt el a hétből, mint ami hátra van! ;) ") elif(nap == 4): print("Csütörtök! Akkor ez azt jelenti, hogy holnap végre pééééntek!") elif(nap == 5): print("Péntek! A nap végén vége a hétnek, már ami a munkát illeti!") elif(nap == 6): print("Szombat! A hétvége ma kezdődik! Programok és programozások!") elif(nap == 7): print("Vasárnap! Holnap meló, örülsz!?") else: print("Helytelen számot adtál meg! Futtatsd újra a szoftvert és 1 és 7 között válassz!")
0d791c5333b25bef3a1a47451243b2e594f65434
whime/dataStructure-algorithm
/剑指offer/左旋转字符串.py
413
3.953125
4
""" 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务, 就是用字符串模拟这个指令的运算结果。 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。 """ # -*- coding:utf-8 -*- class Solution: def LeftRotateString(self, s, n): # write code here tmpstr=s[0:n] s=s[n:]+tmpstr return s
2b9d56106fa73e6b8a1ac114d9d611c0bd71bcc2
BumbarG/Hex-Tournament
/hex/libs/disjoint_set.py
838
3.703125
4
class DisjoinSet: def __init__(self): self.parents = {} self.ranks = {} def find(self, a): if a not in self.parents: self.parents[a] = a self.ranks[a] = 0 return a while self.parents[a] != a: prev = a a = self.parents[a] self.parents[prev] = self.parents[a] return a def union(self, a, b): aroot = self.find(a) broot = self.find(b) if aroot == broot: return # already connected if self.ranks[aroot] < self.ranks[broot]: aroot, broot = broot, aroot self.parents[broot] = aroot if self.ranks[aroot] == self.ranks[broot]: self.ranks[aroot] += 1 def are_connected(self, a, b): return self.find(a) == self.find(b)
ef0cb1cc84ca2f43073d090ea9ca691894556d6d
RonaldoLira/Mision_02
/cuenta.py
308
3.9375
4
# Autor: Ronaldo Estefano Lira Buendia # Programa donde calcula el total de la cuenta c=int(input("Introduce el total de la comida: ")) p=c*.13 i=c*.16 t=c+p+i print("Costo de su comida: {0:.2f}".format(c)) print("Propina: {0:.2f}".format(p)) print("IVA: {0:.2f}".format(i)) print("Total a pagar: {0:.2f}".format(t))
822b005755d4a0bc72e2ad1f383366a5a41d6350
fatimahammouri/HB_Restaurant_rating_lab
/ratings.py
930
3.9375
4
"""Restaurant rating lister.""" def Restaurant_scoring(file_name): opened_file = open(file_name) rating_dict = {} for line in opened_file: line = line.rstrip("\n") data = line.split(":") #print(data) rating_dict[data[0]] = data[1] # print(rating_dict) user_restaurant_name = input("What is the restaurant name? > ") user_restaurant_score = input("What is the restaurant score? > ") while int(user_restaurant_score) > 5 or int(user_restaurant_score) < 1: user_restaurant_score = input("Score must be between 1 and 5. What is the restaurant score? > ") rating_dict[user_restaurant_name.title()] = user_restaurant_score restaurants = rating_dict.items() restaurants = sorted(restaurants) # print(restaurants) for ratings_set in restaurants: print(f"{ratings_set[0]} is rated at {ratings_set[1]}.")
18fa6677f3e607cb74d2681f7ba5b80dec931f55
UncleBob2/MyPythonCookBook
/data and variable types.py
967
3.828125
4
''' Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range(6) range x = {"name" : "John", "age" : 36} dict x = {"apple", "banana", "cherry"} set x = frozenset({"apple", "banana", "cherry"}) frozenset x = True bool x = b"Hello" bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview ''' my_integer =3 my_float = 3.141592 my_string = "hello" print(type(my_integer)) print(type(my_float)) print(type(my_string)) my_integer = 'some text' print(type(my_integer))
27544b52d9865f27d4a5780b09f11b59b38da578
binghe2402/learnPython
/刷题/Leetcode/p938 二叉搜索树的范围和.py
671
3.578125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __init__(self): self.s = 0 def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int: def travalTree(node): if node is None: return if low <= node.val <= high: self.s += node.val if node.val >= low: travalTree(node.left) if node.val <= high: travalTree(node.right) travalTree(root) return(self.s)
c189d4dd818de4d56557c01aca4d87f8139a0056
eagletusk/PythonADS
/Trees/nodeTree.py
1,465
3.765625
4
class BT(object): def __init__(self,rootObj): self.key =rootObj self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BT(newNode) else: t = BT(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self,newNode): if self.rightChild == None: self.rightChild = BT(newNode) else: t = BT(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): return self.rightChild def getLeftChild(self): return self.leftChild def setRootVal(self,obj): self.key = obj def getRootVal(self): return self.key def preorder(self): if self.key: print(self.key) if self.leftChild: self.leftChild.preorder() if self.rightChild: self.rightChild.preorder() r = BT('a') # print(r.getRootVal()) # print(r.getRightChild()) r.insertLeft(3) r.insertLeft(2) r.insertRight(4) # print(r.getLeftChild().getRootVal()) r.preorder() def preorder(tree): if tree: print(tree.getRootVal()) preorder(tree.getLeftChild()) preorder(tree.getRightChild()) def postorder(tree): if tree: postorder(tree.getLeftChild()) postorder(tree.getRightChild()) print(tree.getRootVal()) def inorder(tree): if tree: postorder(tree.getLeftChild()) print(tree.getRootVal()) postorder(tree.getRightChild())
6c5327e6dab0ae0a5df388deaa7a904a59991edd
acaciooneto/cursoemvideo
/ex_aulas/ex.aula12-036.py
836
3.953125
4
print('Você quer alugar uma casa? Primeiro terá que se adequar a nossos critérios.') casa = int(input('Digite o valor da casa que você quer comprar: ')) salario = int(input('Diga o valor do seu salário: ')) tempo = int(input('Agora diga em quantos anos você pretende pagar: ')) parcelas = tempo * 12 prestação = casa / parcelas if prestação <= (salario*30) / 100: print('Em {} parcelas, a prestação da casa fica {:.2f} R$ por mês.' .format(parcelas, prestação)) print('Como você se enquadra em nossos requisitos, seu crédito será aprovado.') elif prestação > (salario*30) / 100: print('Do jeito que você quer, as prestações ficam {:.2f} R$, o que está acima de 30% do seu salário.'.format(prestação)) print('Então infelizmente não podemos aprovar seu crédito.') print('Tenha um bom dia.')
106e4f7b4330a226c54f85051ad29239f8938600
PrivateVictory/Leetcode
/src/ziyi/Tree/MaximumDepthofBinaryTree.py
876
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-01-05 13:18:43 # @Author : Alex Tang ([email protected]) # @Link : http://t1174779123.iteye.com ''' description: ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 else: return self.iterDepth(0,[root]) def iterDepth(self, depth, nodeList): if len(nodeList) == 0: return depth else: newNodes = [] for node in nodeList: if node.left: newNodes.append(node.left) if node.right: newNodes.append(node.right) return self.iterDepth(depth+1, newNodes)
b99c49f96c2697a56f2c9197b6039891466417ef
DonValino/Python
/practice1/Conditionals.py
632
4.15625
4
import random import sys import os # if else elif == != > >= <= age = 21 if age >= 21 : print("You Are Old Enough To Drive A Bus") elif age >= 16 : print("You Are Old Enough To Drive A Car or Motorcycle") else : print("You Are Not Old Enough To Drive") # Combining conditions with logical operators # Logical operators: and, or, not print("\n") if((age >= 1) and (age <= 18)) : print("You are aged between 1 and 18") elif((age == 21) or (age >= 65)) : print("You are a senior of working age") elif not (age == 30) : print("You are not yet considered a fully growned adult") else : print("Don't know")
89ba15aa0fe4605c09afe376d402ac7c9ac3daff
sifirib/yoo
/src/Games/connect4/Board.py
2,141
3.625
4
from enum import Enum class Board: def __init__(self, height=6, width=7): self.width = width self.height = height self.board = [[Piece.EMPTY for _ in range(width)] for _ in range(height)] # 6 x 7 def getPiece(self, x, y): return self.board[y][x] def addPiece(self, col, peice): for i in range(self.height): if self.board[self.height - i - 1][col] == Piece.EMPTY: self.board[self.height - i - 1][col] = peice return col, self.height - i - 1 return False def checkWin(self, x, y, piece): """ Check if the move is a winning move :param x: :param y: :return: """ count = 0 # Check rows for i in range(max(x - 4, 0), min(x + 4, self.width)): if self.board[y][i] == piece: count += 1 else: count = 0 if count >= 4: return True # Check cols for i in range(max(y - 4, 0), min(y + 4, self.height)): if self.board[i][x] == piece: count += 1 else: count = 0 if count >= 4: return True # Check diag drc = 0 dlc = 0 for i in range(-3, 4): if x + i < self.width and y + i < self.height and x + i >= 0 and y + i >= 0 and self.board[y + i][ x + i] == piece: drc += 1 else: drc = 0 if x + i < self.width and y - i < self.height and x + i >= 0 and y - i >= 0 and self.board[y - i][ x + i] == piece: dlc += 1 else: dlc = 0 if dlc >= 4 or drc >= 4: return True return False def __repr__(self): return "\n".join((["|" + "|".join( ["O" if y == Piece.RED else ("X" if y == Piece.BLACK else "_") for y in x]) + "|" for x in self.board])) + "\n" class Piece(Enum): EMPTY = 0 RED = 1 BLACK = 2