blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
f5e20b542289e708891d558541397436047b6f47
Giorc93/PythonCourse
/Exceptions/exception3.py
302
4.03125
4
import math def sqrtFunc(a): if a < 0: raise ValueError('Number should be grater than 0') else: return math.sqrt(a) op1 = (int(input('Insert a number: '))) try: print(sqrtFunc(op1)) except ValueError as NegativeNumber: print(NegativeNumber) print('Program ended')
84604c70398644841b5e0ef1e707b52647dc7437
thiagosouzalink/my_codes-exercices-book-curso_intensivo_de_python
/Capitulo_09/exercise9_11/exercise9_11.py
472
3.734375
4
""" 9.11 – Importando Admin: Comece com seu programa do Exercício 9.8 (página 241). Armazene as classes User, Privileges e Admin em um módulo. Crie um arquivo separado e uma instância de Admin e chame show_privileges() para mostrar que tudo está funcionando de forma apropriada. 9.12 – Vários módulos: Armazene a classe User em um """ from user import User, Privileges, Admin admin = Admin('João', 'Pereira', 40, 'joao@mail.com') admin.privilege.show_privileges()
236bd6bc2224c6400286a2e8c4e61562df776335
shalommita/PrakAlpro-Lab-10
/LAB-10-DICTIONARY.py
1,442
3.546875
4
# SHALOMMITA P # 71200640 # LAB 10 DICTIONARY # INPUT # OPSI PILIHAN # BARANG YANG AKAN DITAMBAH/DIHAPUS # JUMLAH BARANG YG AKAN DITAMBAH # PROSES # UBAH KE DALAM DICT # LAKUKAN PERCABANGAN dan Perulangan While # OUTPUT import sys keranjang={} def utama(): print(""" Keranjang Stok Toko Syahdu 5.5 Big Sale ======================================== 1. Menambahkan Barang 2. Menghapus Barang 3. Melihat Keranjang 4. Keluar """) def pil(): opsi=int(input("Pilihan Anda (1/2/3/4): ")) while opsi != 0: if opsi == 1: inp=int(input("Jumlah barang yang akan ditambahkan: ")) for i in range(inp): barang=input("Tambahkan barang: ") jml=int(input("Jumlah: ")) keranjang[barang]=jml utama() pil() elif opsi == 2: barang=input("Barang yang akan dihapus: ") del(keranjang[barang]) utama() pil() elif opsi == 3: for barang in keranjang: print(barang,": ",keranjang[barang]) utama() pil() elif opsi == 4: print("Anda sudah keluar dari Keranjang Toko Syahdu") sys.exit() else: print("Pilihan Anda tidak tersedia \nSilakan cek ulang.") utama() pil() utama() pil()
2117665327969dfe4c5c918a8dcc56820207adbf
nebofeng/python-study
/01python-base/Dictionary.py
445
3.578125
4
#coding=utf-8 #{} 是字典 。字典可以覆盖修改。删除可以删除单个元素 del 还可以 删除整个词典 。 .clear() 方法 mydict1 = dict(([1, 'a'], [2, 'b'])) print(mydict1) mydict2 = dict.fromkeys((1,2,3),'a') print(mydict2) str1 = ['import','is','if','for','else','exception'] a={key:val for key,val in enumerate(str1)} print(a) M = [[1,2,3],[4,5,6],[7,8,9]]#求m中3,6,9组成的列表 b=[x[2] for x in M] print(b)
23b2d6d241628b0dc2648272fbc7b771cbf64233
intothedeep/Project-Euler
/problem009.py
726
4.125
4
#!/bin/python3 #suppose a<b<c, then a<n/3. a**2 = c**2-b**2 = (c-b)(c+b) = (c-b)(n-a) def find_biggest_pythagorean_set(n): pt_set = [] for a in range(n // 3, 1, -1): if (a ** 2) % (n - a) == 0: k = (a ** 2) / (n - a) if (n - a - k) % 2 == 0: b = (n - a - k) / 2 c = (n - a + k) / 2 pt_set.append(int(a * b * c)) if len(pt_set) == 0: return -1 else: return max(pt_set) num = [] t = int(input().strip()) for a0 in range(t): num.append(int(input().strip())) pyth_result = [] for i in range(max(num)): pyth_result.append(find_biggest_pythagorean_set(i + 1)) for n in num: print(pyth_result[n - 1])
a6f6425e658750cdf619bae954c2340a56458592
sanidhyamangal/interviews_prep
/code_prep/abstract_structures/queue_stack/stack_min.py
1,575
3.703125
4
# Implement a stack with a function that returns the current minimum item. __author__ = 'tchaton' import unittest import numpy as np from collections import defaultdict import numpy as np class Node: def __init__(self, value, prev=None, next=None, cnt=1): self.value = value self.prev = prev self.next = next self.cnt = cnt class StackwMin: def __init__(self): self.arr = [] self.tail = Node(np.inf) def push(self, item): self.arr.append(item) if item < self.tail.value: n = Node(item, prev=self.tail) self.tail = n def pop(self): last_value = self.arr[-1] self.arr = self.arr[:-1] if last_value <= self.tail.value: self.tail = self.tail.prev return last_value def min(self): return self.tail.value class Test(unittest.TestCase): def test_min_stack(self): min_stack = StackwMin() self.assertEqual(min_stack.min(), np.inf) min_stack.push(7) self.assertEqual(min_stack.min(), 7) min_stack.push(6) min_stack.push(5) self.assertEqual(min_stack.min(), 5) min_stack.push(10) self.assertEqual(min_stack.min(), 5) self.assertEqual(min_stack.pop(), 10) self.assertEqual(min_stack.pop(), 5) self.assertEqual(min_stack.min(), 6) self.assertEqual(min_stack.pop(), 6) self.assertEqual(min_stack.pop(), 7) self.assertEqual(min_stack.min(), np.inf) if __name__ == "__main__": unittest.main()
c65fd5984f97e22f995f3c7894ec555464b86506
FirdavsSharapov/PythonLearning
/Python Course/Learning Python/LeetCode Exercises/remove_duplicate.py
1,525
4.25
4
from datetime import date, timedelta def count_digits(text: str) -> int: count = 0 for char in text: if char.isnumeric(): count += 1 return count # def days_diff(a, b): # start_date = date(*a) # end_date = date(*b) # return timedelta(end_date - start_date) # print(days_diff((1982, 4, 19), (1982, 4, 22))) def backward_string_by_word(text: str) -> str: words = text.split(" ") # Reversing each word and creating # a new list of words # List Comprehension Technique new_words = [word[::-1] for word in words] # Joining the new list of words # to for a new Sentence new_sentence = " ".join(new_words) return new_sentence print(backward_string_by_word('Hello world')) if __name__ == '__main__': print("Example:") print(count_digits('This picture is an oil on canvas ' 'painting by Danish artist Anna ' 'Petersen between 1845 and 1910 year')) # These "asserts" are used for self-checking and not for an auto-testing assert count_digits('hi') == 0 assert count_digits('who is 1st here') == 1 assert count_digits('my numbers is 2') == 1 assert count_digits('This picture is an oil on canvas ' 'painting by Danish artist Anna ' 'Petersen between 1845 and 1910 year') == 8 assert count_digits('5 plus 6 is') == 2 assert count_digits('') == 0 print("Coding complete? Click 'Check' to earn cool rewards!")
76d7b528c45a1025ebcf66f7574e661bd0a03604
Boyko03/Python101
/week_6/decorators/test_accepts.py
1,585
3.78125
4
import unittest from accepts import accepts class TestAccepts(unittest.TestCase): def test_function_accepts_args_of_type_str_and_given_str(self): @accepts(str) def say_hello(name): pass exc = None try: say_hello(name='Boyko') except Exception as e: exc = e self.assertIsNone(exc) def test_function_accepts_args_of_type_str_should_raise_error_if_arg_of_type_int(self): @accepts(str) def say_hello(name): pass exc = None try: say_hello(name=1) except TypeError as e: exc = e self.assertIsNotNone(exc) self.assertEqual(str(exc), 'Argument "name" of say_hello is not str!') def test_function_accepts_multiple_arguements_of_different_types_returns_true_if_correct(self): @accepts(str, int) def deposit(name, money): pass exc = None try: deposit(name="Marto", money=10) except Exception as e: exc = e self.assertIsNone(exc) def test_function_accepts_multiple_arguements_of_different_types_returns_false_if_not_correct(self): @accepts(str, int) def deposit(name, money): pass exc = None try: deposit(name="Marto", money=(1, 5)) except Exception as e: exc = e self.assertIsNotNone(exc) self.assertEqual(str(exc), 'Argument "money" of deposit is not str or int!') if __name__ == '__main__': unittest.main()
4675b61d2907150b03a9b12ed936346c1727390c
weston100721/python-demo
/fundemental/Condition.py
1,639
4.3125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- x = int(raw_input("please input an integer:")) # 单分支的条件判断。 if x > 0: print x # 双分支的条件判断。 if x > 0: print x else: print x * 2 # 多分支的条件判断。 if x < 0: x = 0 print "Negative changed to zero" elif x == 0: print "zero" elif x == 1: print "Single" else: print "more" # 三元操作符。 x = True e = "x is True." y = "x is False" var = x if e else y # 判断相等 == num = 5 if num == 3: # 判断num的值 print 'boss' elif num == 2: print 'user' elif num == 1: print 'worker' elif num < 0: # 值小于零时输出 print 'error' else: print 'roadman' # 条件均不成立时输出 # 操作符 >= <= and or num = 9 if num >= 0 and num <= 10: # 判断值是否在0~10之间 print 'hello' if 0 <= num <= 10: # 判断值是否在0~10之间 print 'hello' if num < 0 or num > 10: # 判断值是否在小于0或大于10 print 'hello' else: print 'undefined' num = 8 # 判断值是否在0~5或者10~15之间 # 此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。 if (0 <= num <= 5) or (10 <= num <= 15): print 'hello' else: print 'undefined' # 操作符:不等于 != var = 100 if var != 100: print "变量 var 的值为100" print "Good bye!" # in 和 not in 操作符。 a = "Hello" if "H" in a: print "H 在变量 a 中" else: print "H 不在变量 a 中" if "M" not in a: print "M 不在变量 a 中" else: print "M 在变量 a 中"
8995cb03d9852910ac8d19772f1b6754580b558d
m2be-igg/neurorosettes
/examples/rosette_formation.py
1,207
3.59375
4
"""Script to simulate the formation of Homer-Wright rosettes.""" import numpy as np from neurorosettes.simulation import Simulation, Container def create_tissue(container: Container) -> None: """Creates and registers new neurons in the simulation world.""" radius = 24.0 number_of_cells = 9 t = np.linspace(0, 2*np.pi, number_of_cells, endpoint=False) x = radius * np.cos(t) y = radius * np.sin(t) for x_coord, y_coord in zip(x, y): neuron = container.create_new_neuron(coordinates=[x_coord, y_coord, 0]) neuron.set_outgrowth_axis(np.subtract(np.zeros(3), neuron.cell.position)) def main(): # Initialize simulation objects sim_world = Simulation.from_file("config/config.yml") # Create initial configuration create_tissue(sim_world.container) # Plot the current state of the simulation sim_world.container.animator.set_camera(height=400.0) sim_world.container.animator.show() # Run the simulation to check if springs work sim_world.run() # Plot the results (mark interactive as False to automatically close the window) sim_world.container.animator.show(interactive=True) if __name__ == "__main__": main()
b00afd394497e210b4387d90cc5e95586e924b30
Lorenzo97/tests
/fun.py
332
3.515625
4
def sum2(a,b): '''sums 2 numbers''' return a+b def power(a,b): '''a^b''' c = a**b return c def fwrite(file, L): channel=open(file, 'w') for i in L: channel.write(i+ '\n') channel.close() return 0 ''' fwrite('intro',['hi, ','myname is Lorenzo ','and I am ','a farmer ']) '''
876bcaf26cc1a7c6e5ac7a330b00d37044ed6158
zz-tracy/hello_python
/python_dictionaries/dictionaries.py
3,417
3.671875
4
# 访问字典中的值 alien = {'color': 'green'} print(alien['color']) # 向字典中添加键-值对 alien_0 = {'color': 'green', 'points': 5} print(alien_0) alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) # 修改字典中的值 alien_0 = {'color': 'green'} print('The alien is ' + alien_0['color'] + '.') alien_0['color'] = 'yellow' print('The alien is now ' + alien_0['color'] + '.') # 删除键值-对 alien_0 = {'color': 'green', 'opions': 5} print(alien_0) del alien_0['opions'] print(alien_0) # 遍历字典 user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi', } for key, value in user_0.items(): print('\nkey: ' + key) print('value: ' + value) # 遍历字典中的所有键 favorite_language = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in favorite_language.keys(): print(name.title()) for name in favorite_language: # 遍历字典时,会默认遍历所有的键,所以不需要加keys()输出效果一样 print(name.title()) # 使用sorted()方法按顺序遍历字典中所有的键 favorite_language = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in sorted(favorite_language.keys()): print(name.title() + ', thank you for taking the poll') # 遍历字典中所有的值: favorite_language = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for language in favorite_language.values(): print(language.title()) # 使用集合set()方法找出列表中独一无二的元素 favorite_language = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for language in set(favorite_language.values()): print(language.title()) # 嵌套:将一系列字典存储在列表中, 或将列表作为值存储在字典中 alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 15} aliens = ['alien_0', 'alien_1', 'alien_2'] for alien in aliens: print(alien) # 使用range()方法自动生成一些列数字 # 创建一个空列表用来存储生成的数字 aliens = [] for alien_number in range(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) for alien in alien[:5]: # 显示前五个生成的信息 print(alien) print('...') # 显示创建了多少个数字 print('Toal number of aliens: ' + str(len(aliens))) # 字典中存储列表 favorite_languages = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } for name, languages in favorite_languages.items(): print('\n' + name.title() + '\'s favorite languages are: ') for language in languages: print('\t' + language.title()) # 在字典中存储字典 users = { 'asinstein' : { 'first': 'albert', 'last': 'einstein', 'location': 'princeton', }, 'mcurie': { 'first': 'marie', 'last': 'curie', 'location': 'paris', } } for username, user_info in users.items(): print('\nUsername: ' + username) full_name = user_info['first'] + ' ' + user_info['last'] location = user_info['location'] print('\tFull name: ' + full_name.title()) print('\tLocation: ' + location.title())
1f0f7962f3e527fc31e6a425b8a9d63c1ad7bd16
NestY73/Algorythms_Python_Course
/Lesson_3/max_between_min.py
1,050
4.03125
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: Homework - Lesson 3_Algorythms # # Author: Yuri Nesterovich # # Created: 31.03.2019 # Copyright: (c) Fujitsu 2019 # Licence: <your licence> #------------------------------------------------------------------------------- #Находим макс. элемент среди мин. элементов столбцов #Кол-во столбцов и строк вводит пользователь from random import random col = int(input()) row = int(input()) a = [] for i in range(row): b = [] for j in range(col): n = int(random()*200) b.append(n) print('|{:4d}|'.format(n),end='') a.append(b) print() max_elem = -1 for j in range(col): min_elem = 200 for i in range(row): if a[i][j] < min_elem: min_elem = a[i][j] if min_elem > max_elem: max_elem = min_elem print("Максимальный среди минимальных: ", max_elem)
8ea1d7f6b8c02b6548ca590fb343bc1c72322603
seanxyuan/TSP_Robot_Path_Planning
/ArtificialNodes/artificial_nodes.py
1,010
3.59375
4
import input, basic_graph, add_nodes, deposition_cost class ArtiticialNodes(object): def __init__(self): pass def readFile(self): # Reading the graph from the input file self.graphInput = input.Input() self.graphInput.readFile('input.json') def makeGraph(self): # Construction the graph from the input self.graph = basic_graph.BasicGraph(self.graphInput.data) self.graph.createBasicGraph() def addAdditionalNodes(self): # Adding the extra nodes in the graph depending upon the degree of the node. self.graph = add_nodes.AddingNodes(self.graph) self.graph.addNodes() def addDepositionCost(self): # Assigning the deposition costs self.graph = deposition_cost.DepositionCost(self.graph) self.graph.assignDepositionCost() def main(self): self.readFile() self.makeGraph() self.addAdditionalNodes() self.addDepositionCost() return self.graph
9160b4654c0e1d0e95fb99c6e9c6cd07dae76b75
Eldalote/CDP-Component-Database-Program
/Component-Database/.ipynb_checkpoints/Component_Database-checkpoint.py
1,249
3.515625
4
from tkinter import * import tkinter.messagebox import sqlite3 from sqlite3 import Error import db_handler import Resistors def get_screen_size(): """ Hack to get the resolution of the active monitor :return: x, y, tuple with resolution in pixels. """ test = Tk() test.update_idletasks() test.attributes('-fullscreen', True) test.state('iconic') x = test.winfo_width() y = test.winfo_height() test.destroy() return x, y def main(): #Get screen resolution of the active monitor screensize = get_screen_size() #create database object db = db_handler.component_database(r"db/components.db") #create the resistor window object resistor_window = Resistors.resistor_window(screensize, db) #build the main window mainWindow = Tk() mainWindow.geometry(f'{300}x{300}+{int(screensize[0]*0.4)}+{int(screensize[1]*0.4)}') #add the Resistor button resistor_button = Button(mainWindow, text= "Resistors", command=resistor_window.display_main) resistor_button.grid(row=0, column=0) #main windown main loop mainWindow.mainloop() #Stuff to do when closing program #close db connection db.close() if __name__ == "__main__": main()
6bb8a8105ee0f76f8541b5974777715845058476
nathruby/adventofcode_2019
/Day_4/part1.py
748
3.859375
4
INPUT = '146810-612564' def find_passwords_in_input_range(input): input_array = INPUT.split('-') start = int(input_array[0]) end = int(input_array[1]) password_count = 0 for password in range(start, end+1): if is_password_valid(password): password_count+=1 print(password_count) def is_password_valid(password): current_digit = str(password)[:1] is_valid = False for next_digit in str(password)[1:]: if int(next_digit) < int(current_digit): return False if int(next_digit) == int(current_digit): is_valid = True current_digit = next_digit return is_valid if __name__ == "__main__": find_passwords_in_input_range(INPUT)
1641604d1e919298728150ec6bc05c1060252a57
PDXDevCampJuly/michael_devCamp
/python/sorting_algorithms/sorting_algorithms.py
3,373
4.53125
5
# Implementation of various sorting algorithms for lists ########################## from sys import argv import time filename = (argv[1]) # python sorting algorithm def python_sort(our_list): return sorted(our_list) def list_swap(our_list, low, high): """ Uses simultaneous assignment to swap it with the one we are moving. """ our_list[low], our_list[high] = our_list[high], our_list[low] return our_list def selection_sort(our_list): """ Look through the list. Find the smallest element. Swap it to the front. Repeat. """ # first for-loop grabs the zero index declares it lowest # we set the range to perform the calculates for the length of the list minus the last spot of the range because there is nothing to compare to. it will be the largest value of the list # begin the first for-loop, declare variables for start_index in range(len(our_list) - 1): lowest_index = start_index # second for-loop grabs the next_index to compare for next_index in range(start_index + 1, len(our_list)): if our_list[next_index] < our_list[lowest_index]: # values lowest_index = next_index list_swap(our_list, start_index, lowest_index) return our_list def insertion_sort(our_list): """ Insert (via swaps) the next element in the sorted list of the previous elements. """ # we want to begin at the first index and compare to the index before it. if the index is -1, break out of the loop. we first declare our minimum to the index[1] to test backwards. this is opposite from the selection_sort because we know that the last index is the highest so we do not need to run it for start_index in range(1, len(our_list)): min_value = our_list[start_index] # declare smallest value position_index = start_index while position_index > 0 and our_list[position_index - 1] > min_value: our_list[position_index], position_index = our_list[position_index - 1], position_index - 1 print(our_list) our_list[position_index] = min_value return our_list def merge_sort(our_list): """ Our first recursive algorithm. Divide and conquer """ # base case, single item list if len(our_list) == 1: return our_list # integer division //, floor middle = len(our_list) // 2 list1 = merge_sort(our_list[:middle]) list2 = merge_sort(our_list[middle:]) list3 = [] while len(list1) > 0 and len(list2) > 0: if list1[0] < list2[0]: list3.append(list1.pop(0)) else: list3.append(list2.pop(0)) list3 += list1 + list2 return list3 def linear_search(x, our_list): """ Searching through the list of items one by one until the target value is found. """ for i in range(len(our_list)): if our_list[i] == x: # item found, return the index value return i return -1 # loop finished, item was not in list # retrieve a file if __name__ == '__main__': with open(filename, "r") as f: our_list = eval(f.read()) # print(selection_sort(our_list)) # print(insertion_sort(our_list)) print(merge_sort(our_list)) # print(linear_search(8, our_list))
56f71e003b6e8796c625c43def8562a16b0b4f53
GalyaBorislavova/SoftUni_Python_Advanced_May_2021
/4_Comprehensions/06. Word Filter.py
122
3.8125
4
words = input().split() even_len_words = [word for word in words if len(word) % 2 == 0] print(*even_len_words, sep="\n")
1be3f688ec9fc28ee183ef8f10711f934be395de
shen-huang/selfteaching-python-camp
/exercises/1901100064/1001S02E05_stats_text.py
2,910
4
4
import string text = '''The Zen of Python , by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambxiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ''' print(text) # 拆分text text_chaifen = text.split() #拆分字符串 print('输出拆分字符串的结果-列表:') print(text_chaifen) #对字符串使用split()方法的结果,是返回一个列表。 # 去掉两端空格 text_chaifen = [word.strip() for word in text_chaifen] # 去掉单词两端的空格。可以直接赋值给表表 print('去掉两端空格:') print(text_chaifen) # 去掉单词两端的标点符号。可以直接赋值给原数组 text_chaifen = [word.strip(string.punctuation) for word in text_chaifen] print('去掉单词两端的标点符号:') print(text_chaifen) # 纯粹的标点符号将被strip()成''(空)——什么都没有。 # 应将除去列表中的空元素,使用filter()方法 text_notnone= list(filter(lambda x: len(x)>0 ,text_chaifen)) # filter()函数只能返回一个迭代器对象,不能返回列表 # 或者使用tuple()转换成元组,然后也可以打印输出 print('去掉单词列表中的空元素:') print(text_notnone) # 为避免将同一个单词的大小写识别为两个单词 # 现在,全部转换成大写单词 text_notnone = [wrod.upper() for wrod in text_notnone] print('大写的单词-单词的总量为:',text_notnone) # 忽略重复的单词,统计单词的净量。使用set()函数 text_set = set(text_notnone) print('单词的净量为:') print(text_set) # 用字典统计单词的个数 text_dict = {} # 定义一个字典 # 使用字典的推导式来生成字典的元素 text_dict = {word:text_notnone.count(word) for word in text_set} # 使用sorded()函数,按频率从大到小排序 list_new = sorted(text_dict,key=lambda x:text_dict[x],reverse=True) # sorted()函数只能返回这个字典的key——返回值是只有key的列表 # 想要得到{单词:频数}的字典,必须利用原来的字典text_dict重新生成字典 text_newdict = {word:text_dict[word] for word in list_new} print('从大到小输出单词及次数:\n',text_newdict)
204ef6b76ca5902fc4e5e1a239245f63804c4ab0
TommyX12/vim-smart-completer
/plugin/sc/completion_results.py
4,452
3.96875
4
# import vim import heapq class UniqueValuedMaxHeap(object): """ A priority queue where all values are unique. Data format: (value, priority) """ def __init__ (self, max_entries = 0): self.data = [] self.indices = {} self.max_entries = max_entries def set_max_entries(self, max_entries): self.max_entries = max_entries def clear (self): """ Clears the heap. """ self.data = [] self.indices = {} def update (self, value, priority, take_max = False): """ Updates a certain value with given priority. If take_max is True, only update when priority is greater than previous. """ if value in self.indices: old_priority = self.data[self.indices[value]][1] if take_max and priority <= old_priority: return self.data[self.indices[value]] = (self.data[self.indices[value]][0], priority) if priority > old_priority: self.float_up(self.indices[value]) else: self.float_down(self.indices[value]) else: if self.max_entries > 0 and len(self.data) >= self.max_entries: del self.indices[self.data[len(self.data) - 1][0]] self.data[len(self.data) - 1] = (value, priority) else: self.data.append((value, priority)) self.indices[value] = len(self.data) - 1 self.float_up(len(self.data) - 1) def float_down (self, i): """ Pushes the i-th entry downward on the heap when necessary. """ i_value = self.data[i][0] i_priority = self.data[i][1] j = i while j < len(self.data) - 1: l = 2 * i + 1 r = 2 * i + 2 if l < len(self.data) and self.data[l][1] > self.data[j][1]: j = l if r < len(self.data) and self.data[r][1] > self.data[j][1]: j = r if j == i: break self.indices[self.data[j][0]] = i self.indices[i_value] = j self.data[i], self.data[j] = self.data[j], self.data[i] i = j def float_up (self, i): """ Pushes the i-th entry upward on the heap when necessary. """ i_value = self.data[i][0] i_priority = self.data[i][1] j = i while j > 0: j = (i - 1) // 2 if i_priority <= self.data[j][1]: break self.indices[self.data[j][0]] = i self.indices[i_value] = j self.data[i], self.data[j] = self.data[j], self.data[i] i = j class CompletionResults(object): """ Container and helpers for completion candidates. """ def __init__ (self, max_entries = None): super(CompletionResults, self).__init__() self.heap = UniqueValuedMaxHeap(max_entries) def set_max_entries(self, max_entries): self.heap.set_max_entries(max_entries) def clear (self): """ Clears the results. """ self.heap.clear() def add (self, text, priority, take_max = True): """ Add a single result. If take_max is True, only update when priority is greater than previous. """ self.heap.update(text, priority, take_max) def get_strings (self): """ Returns the data array as strings. """ return [item[0] for item in self.heap.data] def is_empty(self): """ Returns True iff there are no results. """ return len(self.heap.data) == 0 if __name__ == "__main__": cr = CompletionResults(3) cr.add('a', 4) print(cr.heap.data) cr.add('b', 1) print(cr.heap.data) cr.add('d', 6) print(cr.heap.data) cr.add('w', 2) print(cr.heap.data) cr.add('t', 9) print(cr.heap.data) cr.add('s', 54) print(cr.heap.data) cr.add('s', 0) print(cr.heap.data) cr.add('b', 34) print(cr.heap.data)
9ee6c23d9799d1cf56be67e8711ac18106f6a981
GoingMyWay/LeetCode
/82-remove-duplicates-from-sorted-list-ii/solution.py
707
3.6875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(None) dummy.next, prev = head, dummy while (prev.next): curr = prev.next flag = False while (curr and curr.next and curr.val == curr.next.val): curr = curr.next flag = True if flag: prev.next = curr.next else: prev = prev.next return dummy.next
d618291d69e419b5a5ac49d9f6b35524d9650a0b
thenger/combCheck
/combinations_RAW.py
454
3.625
4
def do(s): print (s) def spin(s, sNew): if (len(s) == 2): do (sNew + s[0] + s[1]) do (sNew + s[1] + s[0]) else: for char in s: srl = s.replace (char, "", 1) spin (srl, sNew + char) def combine(s): if (len(s) > 1): spin (s,"") else: do(s) def main(): combine ("boop") main()
4bb71b9104207dead1ae3e07fd59abc14cac50d3
jdamato41/python4e
/chap2_ex2.py
192
4.09375
4
#this program converts a farenheit temperature to celius print ('welcone to the Temperature Converter') farh=input("enter a temperature in degrees fareheit \n") farh= int(farh) print (farh*2)
86cca3e6766ed771b7d5fb73ef79d89107e39286
dpica21/STEP-2017
/gameloops.py
191
3.828125
4
tries = 5 counter = 0 while counter < tries : guess = int(input("guess a number between 0 and 10:")) counter = counter + 1 if guess == 4: print("right") else: print("wrong")
e94713b450d2be3c4ac7c67c8d972cb97ebd1852
bmoyles0117/codeeval
/38-string-list/test.py
733
3.5
4
import sys def base_convert(val, n, chars): s = '' total_chars = len(chars) while val > 0: s = chars[val % total_chars] + s val /= total_chars if len(s) < n: s = chars[0] * (n - len(s)) + s return s def get_possibilities(n, chars): chars = list(set(chars)) possibilities = [] for i in xrange(len(chars) ** n): possibilities.append(base_convert(i, n, chars)) return possibilities # for i in xrange(2 ** 3): # print base(i, 3, ['p', 'o']) test_cases = open(sys.argv[1], 'r') for test in test_cases: line = test.strip() total_chars, chars = line.split(',') total_chars = int(total_chars) print get_possibilities(total_chars, chars)
f4313f19b87034af96387c154a00dc3038376d38
PolinaSergeevna/Lesson4
/Lesson4_HW7.py
235
4.03125
4
def my_func(n): temp = 1 for i in range(1, n + 1): temp *= i yield temp n = int(input("Просьба указать число для расчета факториала? ")) for _ in my_func(n): print(_)
701228f404f5d39d1160f5a82e39acd15743ca61
deepabalan/googles_python_class
/sorting/9.py
97
3.828125
4
strs = ['hello', 'and', 'goodbye'] shouting = [s.upper() + '!!!' for s in strs] print shouting
4cddc981e0be0bf25d367ed79163053124997acb
huageyiyangdewo/learn_algorithm
/test/breadth_first_seatch_test.py
487
3.703125
4
from graph.breadth_first_search import BreadthFirstSearch from graph.graph import Graph g = Graph(13) g.add_edge(0, 5) g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(0, 6) g.add_edge(5, 3) g.add_edge(5, 4) g.add_edge(3, 4) g.add_edge(4, 6) g.add_edge(7, 8) g.add_edge(9, 11) g.add_edge(9, 10) g.add_edge(9, 12) g.add_edge(11, 12) # 准备广度优先搜索对象 s = BreadthFirstSearch(g, 0) c = s.get_count() print(c) m1 = s.get_marked(1) print(m1) m7 = s.get_marked(8) print(m7)
d28792bacfaf19069b63678289f7919dcf153588
Sarkanyolo/AdventOfCode
/AoC2019-python/Day4/day4.py
1,093
3.78125
4
from typing import List, Tuple, Dict def getLines(filename: str) -> List[str]: with open(filename) as file: return [line.strip() for line in file] def manhattan(point: Tuple[int, int]) -> int: return abs(point[0]) + abs(point[1]) def getPath(steps: List[str]) -> Dict[Tuple[int, int], int]: x, y = 0, 0 line = {} i = 0 for s in steps: dir = s[0] length = int(s[1:]) for _ in range(length): i += 1 if dir == "R": x += 1 elif dir == "L": x -= 1 elif dir == "D": y += 1 else: y -= 1 line[x, y] = i return line lines = getLines("input.txt") l1: List[str] = lines[0].split(",") l2: List[str] = lines[1].split(",") l1_path = getPath(l1) l2_path = getPath(l2) intersect = set(l1_path) & set(l2_path) result = {manhattan(p): l1_path[p] + l2_path[p] for p in intersect} print("Part 1: ", min(result.keys())) print("Part 2: ", min(result.values()))
da656c7b187d415acfe8ebe2f8180d42582bed8a
weiyuyan/LeetCode
/每日一题/March/面试题 10.01. 合并排序的数组.py
2,114
4.3125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:ShidongDu time:2020/3/3 ''' 给定两个排序后的数组 A 和 B,其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法,将 B 合并入 A 并排序。 初始化 A 和 B 的元素数量分别为 m 和 n。 示例: 输入: A = [1,2,3,0,0,0], m = 3 B = [2,5,6], n = 3 输出: [1,2,2,3,5,6] ''' from typing import List # 第一种方法:直接拼接到A的尾部然后使用sort()方法排序 # class Solution: # def merge(self, A: List[int], m: int, B: List[int], n: int) -> None: # """ # Do not return anything, modify A in-place instead. # """ # A[m:] = B # A.sort() pass # 第二种方法,使用额外数组空间 # class Solution: # def merge(self, A: List[int], m: int, B: List[int], n: int) -> None: # """ # Do not return anything, modify A in-place instead. # """ # if not A or not B: return # sorted = [] # pa=pb=0 # while pa<=m and pb<=n: # if pa==m: sorted[pa+pb:]=B[pb:]; break # if pb==n: sorted[pa+pb:]=A[pa:m]; break # if A[pa]<=B[pb]: sorted.append(A[pa]); pa+=1 # else: sorted.append(B[pb]); pb+=1 # A[:] = sorted pass # 第三种方法,利用A后面的额外空间,从大到小倒序排列 class Solution: def merge(self, A: List[int], m: int, B: List[int], n: int) -> None: """ Do not return anything, modify A in-place instead. """ tail= m+n-1 pa, pb = m-1, n-1 while pa>=0 or pb>=0: if pa==-1: A[tail]=B[pb] pb -= 1 elif pb == -1: A[tail] = A[pa] pa -= 1 elif A[pa] > B[pb]: A[tail] = A[pa] pa -= 1 else: A[tail] = B[pb] pb -= 1 tail -= 1 A = [1,2,3,0,0,0]; m = 3 B = [2,5,6]; n = 3 # A = [2, 0]; m = 1 # B = [1]; n = 1 solution = Solution() solution.merge(A, m, B, n) print(A)
f3177ee8917784ab7e84d57cba3cd22978f4dd5a
t3eHawk/pepperoni
/pepperoni/record.py
4,826
3.78125
4
"""Elements used for record preparation and creation.""" import datetime as dt import os import sys import threading class Record(): """Represents a particular logging record as an object. This class describes the record. Record is an entity that is going to be send to the output as a single and separated string. Main purpose of the record is to return formatted string based on two level string templates and set of the forms - variables used in string formatting. First level string template presents a whole record formatting including message. Second level string template present only message format. Also there are two types of forms. First one is predifined dynamic forms which are the variablse that automatically defined by class during the instance construction. Second one is user defined forms which are passed to class constructor as kwargs. List of predefined dynamic forms available by now: +---------+----------------------------------------------------+ | Name | Description | +=========+====================================================+ |rectype |Type of the record | +---------+----------------------------------------------------+ |datetime |Datetime object at the time of record construction | +---------+----------------------------------------------------+ |isodate |Date string form of the time of record construction | +---------+----------------------------------------------------+ |objname |Name of the object from which record was initiated | +---------+----------------------------------------------------+ |flname |Script file name from which record was initiated | +---------+----------------------------------------------------+ |thread |Current thread name | +---------+----------------------------------------------------+ |div |Border element | +---------+----------------------------------------------------+ |message |Input text message | +---------+----------------------------------------------------+ Parameters ---------- logger : Logger That is a Logger object that owns the output for that record. rectype : str Name of the record type item from the Logger.rectypes dictionary. message : str Input message that must be printed with that record. error : bool, optional That is True or False to indicate that record include error information. format : str, optional String template of the whole record. error_format : str or bool, optional String template of the error message. **kwargs The keyword arguments that is used for additional variables in record and message formatting. """ def __init__(self, logger, rectype, message, error=False, format=None, error_format=None, **kwargs): self.logger = logger # Get the record string template. self.format = format or logger.formatter.record # Get the presentation of record type. self.rectype = logger.rectypes[rectype] # Date forms. self.datetime = dt.datetime.now() self.isodate = self.datetime.isoformat(sep=' ', timespec='seconds') # Execution forms. frame = self.__catch_frame() f_code = frame.f_code flname = f_code.co_filename objname = f_code.co_name self.objname = objname if objname != '<module>' else 'main' self.flname = os.path.splitext(os.path.basename(flname))[0] self.thread = threading.current_thread().name # Styling forms. self.div = logger.formatter.div # Store formatted message as instance attribute. message = str(message if error is False else logger.formatter.error) try: self.message = message.format(**self.__dict__, **kwargs) except KeyError: self.message = message pass def __str__(self): """Create record string.""" return self.create() __repr__ = __str__ def create(self, css=False): """Create and return string representation of the record.""" string = self.format.format(**self.__dict__) return string def __catch_frame(self): """Catch the frame from file where methods of module was called.""" frame = sys._getframe() module_dir = os.path.dirname(__file__) while True: if module_dir != os.path.dirname(frame.f_code.co_filename): return frame else: frame = frame.f_back
232967c03f3c81b93cbfbfac36dc1d3fb8cda304
snehilk1312/Python-Progress
/Timedelta.py
1,363
3.765625
4
#HACKERRANK QUESTION #You are given 2 timestamps in the format given below: #Day dd Mon yyyy hh:mm:ss +xxxx #Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between #them. #Input Format #The first line contains , the number of testcases. #Each testcase contains lines, representing time and time . #Constraints #Input contains only valid timestamps #. #Output Format #Print the absolute difference in seconds. #Sample Input 0 #2 #Sun 10 May 2015 13:54:36 -0700 #Sun 10 May 2015 13:54:36 -0000 #Sat 02 May 2015 19:54:36 +0530 #Fri 01 May 2015 13:54:36 -0000 #Sample Output 0 #25200 #88200 #!/bin/python3 import math import os import random import re import sys import datetime # Complete the time_delta function below. def time_delta(t1, t2): t1=datetime.datetime.strptime(t1,'%a %d %b %Y %H:%M:%S %z' ) t2=datetime.datetime.strptime(t2,'%a %d %b %Y %H:%M:%S %z' ) #t1.replace(tzinfo=timezone.utc) #t1.replace(tzinfo=timezone.utc) t_delta=abs(t1-t2) return str(int(t_delta.total_seconds())) #print(t_delta.total_seconds()) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): t1 = input() t2 = input() delta = time_delta(t1, t2) fptr.write(delta + '\n') fptr.close()
422a14e76828c3584a68df4eeed1dfc9872115ea
geekquad/al-go-rithms
/data_structures/linked_list/python/double_linked_list.py
1,667
4.28125
4
class Node(object): def __init__(self, value): self.value=value self.next=None self.prev=None class List(object): def __init__(self): self.head=None self.tail=None def insert(self,n,x): #Not actually perfect: how do we prepend to an existing list? if n!=None: x.next=n.next n.next=x x.prev=n if x.next!=None: x.next.prev=x if self.head==None: self.head=self.tail=x x.prev=x.next=None elif self.tail==n: self.tail=x def display(self): values=[] n=self.head while n!=None: values.append(str(n.value)) n=n.next print ("List: ",",".join(values)) def removeNode(self, node_delete): """This function recieves a node and is responsible for deleting it and reconecting the nodes before and after it.""" prev = node_delete.prev nxt = node_delete.next if(prev != None): prev.next = nxt if(nxt != None): nxt.prev = prev def removeRepeated(self): """this function uses a nested while loop to find the repeated values. every time one is found the method removeNode is called to remove the repeated node""" aux = self.head while(aux != None): aux2 = aux.next #needs to be .next otherwise it will compare the value on aux with itself while (aux2 != None): if(aux2.value == aux.value): self.removeNode(aux2) aux2 = aux2.next aux = aux.next return self def toNativeList(self): """This method creates a list with all the nodes to use in the unit testing""" n = self.head out = [] while(n != None): out += [n.value] n = n.next return out
c818e1d0cf4c0b070bd489ea9919d36e6d658113
khangesh9420/CARD-VALIDATION
/main.py
918
4.25
4
# Enter the card number by User and use .strip() for unwanted spaces card_number = list(input("Enter the card number :").strip()) # Remove the last digit i.e check digit check_digit =(card_number.pop()) #Reverse the card_number card_number.reverse() # make an empty list future_use = [] #check for the even index and odd Index for index,digit in enumerate (card_number) : if index % 2 == 0 : # make an even value double double_digit = int(digit) * 2 #if double digit is greater than 9 then substract it from 9 if double_digit > 9 : double_digit = double_digit - 9 future_use.append(double_digit) else : # odd number value remains same future_use.append(int(digit)) total = int(check_digit) + sum(future_use) print(total) # check the number is divisible by 10 or not if total % 10 == 0 : print(" The card number valid") else : print("The card number invalid")
fee9e78b8cf3a99214d35d7b901bedb81f344c11
JKChang2015/Python
/w3resource/List_/Q013.py
185
3.625
4
# -*- coding: UTF-8 -*- # Q013 # Created by JKChang # Thu, 31/08/2017, 16:35 # Tag: # Description: 13. Write a Python program to generate a 3*4*6 3D array whose each element is *.
e2ea5161ae19e2d50f23f36667316907034bbb26
traore18/python_academy
/exo.py
352
3.71875
4
def print_list(number_list): for i in number_list: if i > 20: print "Big Number" else: print "Small Number" my_list = [1, 3, 10, 24, 400, 4, 100000] print_list(my_list) def keep_printing(number_list): i = 0 while i < len(number_list): print "Index at %d" % i print number_list[i] i = i + 1 keep_printing(my_list)
5e5bc3fe23e851bbb54a84dc9a22309d5f8db3e6
daisy037/ProjectEuler
/problem1.py
145
3.9375
4
sum = 0 n = int(input("Enter limit : ")) print (n) for i in range (1,n) : if ((i % 3 == 0) or (i % 5 == 0)):sum += i print("sum = " +str(sum))
1afb3a48641f0f6007e432efc09a24b7d01c1967
deltaint-project/deltaint
/INTPath-DINT/system/controller/device.py
1,988
3.59375
4
# -*- coding:utf-8 -*- class Port(object): """ Describe a switch port it contains the num of this port and the name of device which contains this port """ def __init__(self, portNum, deviceName): self.portNum = portNum self.deviceName = deviceName class Table(object): """ Describe a flow table in a switch it contains a name ,an action, a key and a value """ def __init__(self, name, action, key, value): self.name = name self.action = action self.key = key self.value = value class Device(object): """ Describe a device in a network it contains a name, port list and the count of port """ def __init__(self, name): self.name = name self.ports = [] self.portSum = 0 def addLink(self, deviceName): self.portSum = self.portSum + 1 # Start from 1 port = Port(self.portSum, deviceName) self.ports.append(port) class Switch(Device): """ Describe a switch in a network (inherit the Device class) it contains tables, thrift port and thrift Runtime it has 2 actions: add table and clear table """ def __init__(self, name, thriftPort=9090, runtime=None): super(Switch, self).__init__(name) self.tables = [] self.thriftPort = thriftPort self.runtime = runtime def addTable(self, name, action, key, value): self.tables.append(Table(name, action, key, value)) def clearTable(self): self.tables = [] class Host(Device): """ Describe a host in a netwrok (interit the Device class) it contains a MAC address, an IP address and an OpenVSwitch Ip address """ def __init__(self, name, mac='', ip='', ovsIp=''): super(Host, self).__init__(name) self.macAddress = mac self.ipAddress = ip self.ovsIpAddress = ovsIp if __name__ == '__main__': device = Host('hahah') print(device.name)
742263358edd71e0225a725f25e11e86ac515456
FutureSeller/TIL
/ps/baekjoon/1676.py
84
3.6875
4
N = int(input()) answer = 0 while N: answer += N // 5 N = N // 5 print(answer)
cb27ea051352d805e0bab0c5f93924c9b9db0ab2
avijeetsingh1988/CodingPractice
/Python/Basics Exercises/squaringlist.py
654
4.40625
4
def squaringlist(list): for i in list: print(i**2) a=[4,5,6] squaringlist(a) #ALTERNATE WAYS TO DISPLAY THE SQUARES IN A LIST# #1 Using append b=[] for number in a: b.append(number**2) print(b) #2 Using Map d=map(lambda n:n*n,a) print(list(d)) #3 Using for numbers = [1, 2, 3, 4, 5] squared_numbers = [number ** 2 for number in numbers] print(squared_numbers) #by creating higher order function which takes another function as its argument. def square(x): return x**2 def mymap(func,arg): result=[] for i in arg: result.append(func(i)) return result squares= mymap(square,[1,2,3,4]) print(squares)
1de64f8231559f59598ebabc5ad2c8a5e0773ead
jharna-dohotia/my_Repo
/knight.py
2,797
3.984375
4
# Python3 code for minimum steps for # a knight to reach target position # initializing the matrix. dp = [[0 for i in range(8)] for j in range(8)]; def getsteps(x, y, tx, ty): # if knight is on the target # position return 0. if (x == tx and y == ty): return dp[0][0]; # if already calculated then return # that value. Taking absolute difference. elif(dp[abs(x - tx)][abs(y - ty)] != 0): return dp[abs(x - tx)][abs(y - ty)]; else: # there will be two distinct positions # from the knight towards a target. # if the target is in same row or column # as of knight than there can be four # positions towards the target but in that # two would be the same and the other two # would be the same. x1, y1, x2, y2 = 0, 0, 0, 0; # (x1, y1) and (x2, y2) are two positions. # these can be different according to situation. # From position of knight, the chess board can be # divided into four blocks i.e.. N-E, E-S, S-W, W-N . if (x <= tx): if (y <= ty): x1 = x + 2; y1 = y + 1; x2 = x + 1; y2 = y + 2; else: x1 = x + 2; y1 = y - 1; x2 = x + 1; y2 = y - 2; elif (y <= ty): x1 = x - 2; y1 = y + 1; x2 = x - 1; y2 = y + 2; else: x1 = x - 2; y1 = y - 1; x2 = x - 1; y2 = y - 2; # ans will be, 1 + minimum of steps # required from (x1, y1) and (x2, y2). dp[abs(x - tx)][abs(y - ty)] = min(getsteps(x1, y1, tx, ty), getsteps(x2, y2, tx, ty)) + 1; # exchanging the coordinates x with y of both # knight and target will result in same ans. dp[abs(y - ty)][abs(x - tx)] = dp[abs(x - tx)][abs(y - ty)] return dp[abs(x - tx)][abs(y - ty)]; # Driver Code if __name__ == '__main__': # size of chess board n*n n = 8; # (x, y) coordinate of the knight. # (tx, ty) coordinate of the target position. x = 0; y = 0; tx = 0; ty = 1; # (Exception) these are the four corner points # for which the minimum steps is 4. if ((x == 1 and y == 1 and tx == 2 and ty == 2) or (x == 2 and y == 2 and tx == 1 and ty == 1)): ans = 4; elif ((x == 1 and y == n and tx == 2 and ty == n - 1) or (x == 2 and y == n - 1 and tx == 1 and ty == n)): ans = 4; elif ((x == n and y == 1 and tx == n - 1 and ty == 2) or (x == n - 1 and y == 2 and tx == n and ty == 1)): ans = 4; elif ((x == n and y == n and tx == n - 1 and ty == n - 1) or (x == n - 1 and y == n - 1 and tx == n and ty == n)): ans = 4; else: # dp[a][b], here a, b is the difference of # x & tx and y & ty respectively. dp[1][0] = 3; dp[0][1] = 3; dp[1][1] = 2; dp[2][0] = 2; dp[0][2] = 2; dp[2][1] = 1; dp[1][2] = 1; ans = getsteps(x, y, tx, ty); print(ans); # This code is contributed by PrinciRaj1992
a8c1927e45577400e8af79fea48f5708eeea0601
MichalBrzozowski91/algorithms
/Algorithms_and_Data_Structures/bubble_sort.py
394
3.984375
4
def bubble_sort(nums): flag = True no_of_swaps = 0 while flag: flag = False for i in range(len(nums)-1): if nums[i] > nums[i+1]: nums[i], nums[i+1] = nums[i+1], nums[i] no_of_swaps += 1 print('Swap',no_of_swaps,':',nums) flag = True # There was a swap, so we must run again return nums
f5da8ad77fde88a2f30c3e30ea026d0762eee448
payalgupta1204/Data_Structure_Algorithms
/quick_select.py
1,276
3.984375
4
import random def inputnumber(message): while True: try: userInput = int(input(message)) except ValueError: print("Not an integer, enter int value") continue else: return userInput def partition(arr, low, high): wall = low - 1 pivot = arr[high] for j in range(low, high): if arr[j] <= pivot: wall += 1 arr[j], arr[wall] = arr[wall], arr[j] arr[wall + 1], arr[high] = arr[high], arr[wall + 1] return wall + 1 def quick_select(arr, low, high, k): if low < high: pivot_idx = random.randint(low, high) arr[high], arr[pivot_idx] = arr[pivot_idx], arr[high] pi = partition(arr, low, high) if k < pi: return quick_select(arr, low, pi - 1, k) elif k > pi: return quick_select(arr, pi + 1, high, k) else: return arr[pi] n = inputnumber("enter number of elements in array:") k = inputnumber("enter the element position required") arr = [] for i in range(n): a = inputnumber("enter element of array") arr.append(a) len_arr = len(arr) result = quick_select(arr, 0 , len_arr -1,k) print("The element at {}th position is {}".format(k, result))
d31683e7457304c7d446eec406780637caf9ce77
fatezy/Algorithm
/datastructure/work2/进制转换.py
823
3.578125
4
# 十进制转换为八进制 class Solution: def ten_to_eight(self,num): if not num: return 0 res = [] while num: num,remainder = num // 8, num % 8 res.append(remainder) return ''.join(str(x) for x in res[::-1]) def ten_to_eight2(self,num): res = '' # if not num: # return res if num // 8 == 0: res += str(num) return res res += self.ten_to_eight2(num//8) res += str(num % 8) return res if __name__ == '__main__': while True: val = input('请输入需要转换的十进制数,输入#键结束') if val == '#': break print(Solution().ten_to_eight(int(val))) print(Solution().ten_to_eight2(int(val)))
d48d01022509348f889e164e74b8de7f45396ee7
BrandiCook/cs162project2
/StoreTester.py
4,083
3.671875
4
# Author: Brandi Cook # Date: 10/5/2020 # Description: This program is to test a simulated store, named Store.py # Store.py has members, grocery items, and keeps track of items in cart as # well as price. StoreTester.py ensures functions and classes are working properly. import unittest import uuid from cs162project2.Store import Product from cs162project2.Store import Customer from cs162project2.Store import Store class ProductTest(unittest.TestCase): """ This is a class made in order to test the Product class from Store.py """ def setUp(self): """ Creates example/test specifications for the product """ self.product_id = uuid.getnode() self.product_title = "Test Title" self.product_desc = "Test Description" self.product_price = 102.38 self.product_quant = 1 self.product = Product(self.product_id, self.product_title, self.product_desc, self.product_price, self.product_quant) def test_get_product_id(self): """ Tests whether or not Store.py successfully gets product id """ self.assertEqual(self.product_id, self.product.get_id_code()) def test_get_product_title(self): """ Tests whether or not Store.py successfully gets product title """ self.assertEqual(self.product_title, self.product.get_title()) def test_decrement_quantity(self): """ Tests whether or not Store.py successfully decrements quantity available """ self.assertEqual(self.product.get_quantity_available(), 1) class CustomerTest(unittest.TestCase): """ This is a class made in order to test the Customer class from Store.py """ def setUp(self): """ Sets up test specifications for a customer object """ #note to self *** UUID is universal unique id*** self.customer_id = uuid.uuid1() self.customer_name = "Billy Bob" self.customer_premium = True #Testing 2 customers because there's not a lot to test with Product #Testing customer 2 premium false while 1 is true self.customer2_id = uuid.uuid1() self.customer2_name = "Sally Jane" self.customer2_premium = False self.customer1 = Customer(self.customer_name, self.customer_id, self.customer_premium) self.customer2 = Customer(self.customer2_name, self.customer2_id, self.customer2_premium) def test_is_premium_member(self): """ Checks whether or not the premium member checker from Store.py works correctly """ self.assertTrue(self.customer1.is_premium_member()) self.assertFalse(self.customer2.is_premium_member()) class StoreTest(unittest.TestCase): """ This is a class made in order to test the Store class from Store.py """ def setUp(self): """ Sets up test specifications for a Store """ self.first_member = Customer("John Doe", uuid.uuid1(), True) self.second_member = Customer("Tony Hawk", uuid.uuid1(), False) self.store = Store() self.inventory = dict() self.members = dict() def test_add_member(self): """ Tests whether or not the member adding function from Store.py functions correctly """ self.store = Store() self.store.add_member(self.first_member) self.assertIsNotNone(self.store.get_member_from_id(self.first_member.get_account_ID())) def test_add_member_none(self): self.store = Store() self.assertIsNone(self.store.get_member_from_id(self.first_member.get_account_ID())) self.store.add_member(self.first_member) self.assertIsNotNone(self.store.get_member_from_id(self.first_member.get_account_ID())) self.assertIsNone(self.store.get_member_from_id(self.second_member.get_account_ID())) if __name__ == '__main__': unittest.main()
3222c164ae7c0392b5962f24ee5803b7dfa37e33
yangruihan/raspberrypi
/python/les8/les8_2.py
1,295
3.734375
4
#!/usr/bin/env python3 def sanitize(time_string): if '-' in time_string: spliter = '-' elif ':' in time_string: spliter = ':' else: return(time_string) (mins, secs) = time_string.split(spliter) return(mins+'.'+secs) class AthleteList(list): def __init__(self, a_name, a_dob, a_times): list.__init__([]) self.name = a_name self.dob = a_dob self.extend(a_times) def top3(self): return (sorted(set([sanitize(f) for f in self]))[0:3]) def show_top3(self): print(self.name + "'s fastest times are : " + str(self.top3())) def get_coach_data(filename): try: with open(filename) as f: data = f.readline().strip().split(',') return (AthleteList(data.pop(0), data.pop(0), data)) except IOError as io_err: print("The IOError : " + str(io_err)) return(None) if __name__ == '__main__': james = get_coach_data('james2.txt') julie = get_coach_data('julie2.txt') mikey = get_coach_data('mikey2.txt') sarah = get_coach_data('sarah2.txt') james.show_top3() julie.show_top3() mikey.show_top3() sarah.show_top3() print('------------------------------') james.extend(['1.00', '1.23']) james.show_top3()
97b5b9e2fb538a4d392b086e91eaff974a4a5f97
jarulsamy/Edge-Detection
/src/Theory.py
1,015
3.53125
4
from Myro import * from Graphics import * import math setX = [1, 2, 3, 4] setY = [1, 2, 3, 4] devSumX = 0 devSumY = 0 sumX = 0 sumY = 0 # Calc Avg X for i in range(len(setX)): sumX += setX[i] avgX = sumX / len(setX) # Calc Avg Y for j in range(len(setY)): sumY += setY[j] avgY = sumY / len(setY) # Stdev Equation for i in range(len(setX)): devSumX += (pow(setX[i] - avgX, 2)) for j in range(len(setY)): devSumY += (pow(setY[j] - avgY, 2)) needRootX = devSumX / (len(setX) - 1) needRootY = devSumY / (len(setY) - 1) devX = math.sqrt(needRootX) devY = math.sqrt(needRootY) ### sumAB = 0 sumAA = 0 sumBB = 0 for i in range(len(setX)): # A or B = point - avg x or y corresponding a = setX[i] - avgX b = setY[i] - avgY # Sum of A * B sumAB += a * b # Sum of A Squared sumAA += a * a # Sum of B Squared sumBB += b * b r = sumAB / (math.sqrt(sumAA * sumBB)) print("R:", r) print("stdDevX:", devX) print("stdDevY:", devY) m = r * (devY / devX) print("Slope:", m)
e39ff1bb39484479840c146c2b50cbd2e2d6b10c
caringtiger/battleships
/main.py
4,555
4.0625
4
#!/bin/python import random if user_difficult == "4": gridsize_x = 11 gridsize_y = 11 else: gridsize_x = 7 gridsize_y = 6 # Game difficulty torpedo count. 0 = Easy, 1 = medium etc. game_difficulty_torpedos = [15,10,5,10] def main(): user_difficulty = get_user_difficulty() user_play_again = True while user_play_again == True: game_map = init_game_map(gridsize_x,gridsize_y) #call the subroutine to set up the game # Set the total user torpedos based on the difficulty user_total_torpedos = game_difficulty_torpedos[user_difficulty] user_curr_torpedos = user_total_torpedos game_won = False print("Welcome to BattleShips!") print("An enemy ship is hidden somewhere at sea") print("We have no idea what a radar is so GEUSS!") print("you only have",user_total_torpedos," torpedoes to hit it.") while user_curr_torpedos > 0: print() draw_grid(game_map,gridsize_x,gridsize_y) #Call the subroutine to draw the current state of the game print() print("you have ", user_curr_torpedos, "torpedoes left") print("Enter the row and column seperatly to aim your torpedo.") user_target_x = int(input("Row?")) user_target_y = int(input("Column?")) if game_map[user_target_x][user_target_y] == "M": print("Holy fork you are dumb") elif game_map[user_target_x][user_target_y] == ".": game_map[user_target_x][user_target_y] = "M" elif game_map[user_target_x][user_target_y] == "S": game_map[user_target_x][user_target_y] = "X" game_won = True draw_grid(game_map,gridsize_x,gridsize_y) print("You won the game!") break user_curr_torpedos -= 1 if game_won == True: print("You won the game with ", user_curr_torpedos, "out of ", user_total_torpedos, " torpedos left") score = user_curr_torpedos * game_difficulty_torpedos[user_difficulty] print(score) save_game(score) else: print("YOU ARE USELESS YOU COULDNT EVEN FIGURE OUT HOW TO USE RADAR YOU JUST GEUSSED YOU IDIOT") print("TRY ANOTHER MODE IF YOU WANT") user_difficulty_str = input("Do you want to play again? (y/n)") if user_difficulty_str.lower() == "n": print("Thank you for playing!") exit() def save_game(score): with open('highscore.txt', 'r') as read_file: file_buffer = [int(x) for x in read_file.read().splitlines()] file_buffer.append(score) file_buffer.sort() with open('highscore.txt', 'w') as write_file: write_file.write('\n'.join(str(line) for line in file_buffer)) def get_user_difficulty(): while True: print("[1]. Easy") print("[2]. Medium") print("[3]. Hard") print("[4]. DEATH") # take's the user's desired difficulty as a string user_difficulty_str = input("Please enter 1,2,3 or 4: ") if user_difficulty_str == "1" or user_difficulty_str == "2" or user_difficulty_str == "3" or user_difficulty_str == "4": print("Correct Conditions") # Converts the string to an integer if it matches the variables return int(user_difficulty_str) - 1 break else: print("stop it. get some help.") #Setup the game def init_game_map(gridsize_x,gridsize_y): game_map = [["." for y in range(gridsize_y) ] for x in range(gridsize_x)] #Hide a ship at a random position game_ship_location_x = random.randrange(gridsize_x) game_ship_location_y = random.randrange(gridsize_y) print("shipx", game_ship_location_x, "shipY", game_ship_location_y) game_map[game_ship_location_x][game_ship_location_y] = "S" return game_map #Draw Grid for other difficulties def draw_grid(game_map,gridsize_x,gridsize_y): grid = " " for x in range(gridsize_x - 1): grid = grid+str(x)+" " print(grid) for x in range(gridsize_x - 1): print(x, end=" ") for y in range(gridsize_y): if game_map[x][y] == "S": print(".", end=" ") if game_map[x][y] == "M": print("M", end=" ") if game_map[x][y] == "X": print("X", end=" ") if game_map[x][y] == ".": print(".", end=" ") print() main()
61a77776a79c7866a806b871c9a796f46151d963
zeal2end/LogicCodes
/Pypy/combinations.py
638
3.796875
4
from itertools import combinations def backtrack(arr,i,n,cur=[]): if i==n: print(cur) else: backtrack(arr,i+1,n,cur); cur.append(arr[i]) backtrack(arr,i+1,n,cur) cur.pop() def main(): Array = [int(a) for a in input("Enter the Array here: ").split()] length = len(Array) print("Combinations Using Recursion :") backtrack(Array,0,length) print("Combinations Using Itertools :") combi(Array) def combi(arr): for i in range(1,len(arr)+1): comb = combinations(arr,i) for a in list(comb): print(a) if __name__ == "__main__": main()
3e93f3697284dd3e74241292da68c5430e48095e
gandrewstone/chainsim
/simEmergentConsensus.py
5,261
3.546875
4
from chainsim import * def runChainSplitSbyL(MinerClass, smallPct, largePct,preforktime=6000, postforktime=1000000): """ Returns the number of chain tips in the final full blockchain. There is one tip per chain fork. """ random.seed() # 1) chain = Blockchain() # Create a group of miners with EB=1MB, AD=4, and generate size = 1MB miner = MinerClass(smallPct, 1000000, 4, 1000000, chain) # Create a 2nd group of miners with EB=2MB, AD=4, and generate size = 2MB minerb = MinerClass(largePct, 2000000, 4, 2000000, chain) for i in range(1,preforktime): # Everyone is mining smaller blocks. miner.mine() # So just let "miner" mine for i in range(1,postforktime): # Now its time to mine big and smaller blocks miner.mine() # so let both mine minerb.mine() # this call order doesn't matter because successful mining is random #chain.p() #chain.printChain(chain.start,0) forkLens = chain.getForkLengths() height = 0 for tip in chain.tips: # find the max height if tip.height > height: height = tip.height return (len(chain.tips), forkLens, height) def runChainSplit2(MinerClass,s,l,iterations=100): """Run many iterations of a 2-way chain split, where a group of miners start producing and accepting larger blocks. Pass the small block hashpower as a fraction of 1, the large block hashpower as a fraction of 1, and the number of iterations to run. This routine prints out data in the following format: 0.950000/0.050000: {0: 97, 1: 3, ...} ^ largeblk ^small ^ 97 runs had no fork ^ 3 runs had one fork """ results = [] maxForkLen=0 orphans=[] numblocks=[] blockHeights = [] for i in range(0,iterations): (numForks, forkLengths, blockheight) = runChainSplitSbyL(MinerClass,s,l) numForks -= 1 # Because the main chain isn't a fork results.append(numForks) forkLengths.sort(reverse=True) logging.info("%f/%f.%d: fork lengths: %s" % (l,s, i, str(forkLengths))) orphan = 0 if len(forkLengths) > 1: # because main chain is forkLengths[0] if maxForkLen < forkLengths[1]: maxForkLen = forkLengths[1] for fl in forkLengths[1:]: orphan += fl orphans.append(orphan) numblocks.append(sum(forkLengths)) blockHeights.append(blockheight) if numblocks: maxNumBlocks = max(numblocks) avgNumBlocks = sum(numblocks)/len(numblocks) if orphans: maxOrphan = max(orphans) avgOrphan = sum(orphans)/len(orphans) else: maxOrphan = 0 avgOrphan = 0 maxBlockHeight = max(blockHeights) rd = {} for r in results: t = rd.get(r,0) rd[r] = t+1 print "%f/%f (%d, %d, %d): %d, %d, %d, %s" % (l,s, maxBlockHeight, maxNumBlocks, avgNumBlocks, maxForkLen, maxOrphan, avgOrphan, str(rd)) def Test(): random.seed() # 1) # runChainSplit2(0.00,1) # runChainSplit2(0.0001,.999) its = 1000 print "BUIP041" print " SPLIT (block height, max blocks, avg blocks): max fork depth, max orphans, avg orphans, { X:Y where Y runs had X forks }" runChainSplit2(Miner,0.50,0.50,iterations=its) runChainSplit2(Miner,0.40,0.60,iterations=its) runChainSplit2(Miner,0.333,0.667,iterations=its) runChainSplit2(Miner,0.25,0.75,iterations=its) runChainSplit2(Miner,0.20,0.80,iterations=its) runChainSplit2(Miner,0.10,0.90,iterations=its) runChainSplit2(Miner,0.05,0.95,iterations=its) print "BUIP001 + trailing fix" print " SPLIT (block height, max blocks, avg blocks): max fork depth, max orphans, avg orphans, { X:Y where Y runs had X forks }" runChainSplit2(Miner,0.50,0.50,iterations=its) runChainSplit2(Miner,0.40,0.60,iterations=its) runChainSplit2(Miner,0.333,0.667,iterations=its) runChainSplit2(Miner,0.25,0.75,iterations=its) runChainSplit2(Miner,0.20,0.80,iterations=its) runChainSplit2(Miner,0.10,0.90,iterations=its) runChainSplit2(Miner,0.05,0.95,iterations=its) print "Original BUIP001 commit (does not move to the chain tip if EB/AD is exceeded)" print " SPLIT (block height, max blocks, avg blocks): max fork depth, max orphans, avg orphans, { X:Y where Y runs had X forks }" runChainSplit2(MinerTrailingBug,0.50,0.50,iterations=its) runChainSplit2(MinerTrailingBug,0.40,0.60,iterations=its) runChainSplit2(MinerTrailingBug,0.333,0.667,iterations=its) runChainSplit2(MinerTrailingBug,0.25,0.75,iterations=its) runChainSplit2(MinerTrailingBug,0.20,0.80,iterations=its) runChainSplit2(MinerTrailingBug,0.10,0.90,iterations=its) runChainSplit2(MinerTrailingBug,0.05,0.95,iterations=its) def Testthreaded(): t=[] t.append(threading.Thread(target=runChainSplit2, args=(0.50,0.50))) t.append(threading.Thread(target=runChainSplit2, args=(0.40,0.60))) t.append(threading.Thread(target=runChainSplit2, args=(0.333,0.667))) t.append(threading.Thread(target=runChainSplit2, args=(0.25,0.75))) t.append(threading.Thread(target=runChainSplit2, args=(0.20,0.80))) t.append(threading.Thread(target=runChainSplit2, args=(0.10,0.90))) t.append(threading.Thread(target=runChainSplit2, args=(0.05,0.95))) for th in t: th.start() for th in t: th.join()
71b3fdf1ad46224f18c041c462e38dd753821a09
Joel1210/CodingDojo
/python_stack/python/fundamentals/complete/functions_basic_I.py
1,237
3.984375
4
print("1.") def a(): return 5 print(a()) print("2.") def b(): return 5 print(b()+b()) print("3.") def c(): return 5 return 10 print(c()) print("4.") def d(): return 5 print(10) print(d()) print("5.") def e(): print(5) x = e() print(x) print("6.") def f(b,c): print(b+c) print(f(1,2) + f(2,3)) print("7.") def g(b,c): return str(b)+str(c) print(g(2,5)) print("8.") def h(): b = 100 print(b) if b < 10: return 5 else: return 10 return 7 print(h()) print("9.") def i(b,c): if b<c: return 7 else: return 14 return 3 print(i(2,3)) print(i(5,3)) print(i(2,3) + i(5,3)) print("10.") def j(b,c): return b+c return 10 print(j(3,5)) print("11.") b = 500 print(b) def k(): b = 300 print(b) print(b) k() print(b) print("12.") b = 500 print(b) def l(): b = 300 print(b) return b print(b) l() print(b) print("13.") b = 500 print(b) def m(): b = 300 print(b) return b print(b) b=m() print(b) print("14") def n(): print(1) o() print(2) def o(): print(3) n() print("15.") def p(): print(1) x = q() print(x) return 10 def q(): print(3) return 5 y = p() print(y)
0b5b6611619ccc95edeade796d164282ef22be5d
franciszxlin/pythonlearn
/Exercises/ch8e5.py
360
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 30 16:40:40 2017 @author: zil20 """ fname = input('Enter a file name: ') fhand = open(fname) fcount = 0 for line in fhand: if not line.startswith('From'): continue fcount += 1 words = line.split() print(words[1]) print('There were', fcount, 'lines in the file with From as the first word')
9666c3ed9dac42fe46aaaa16afed2c85661daaae
hmd1996/Python-Learning
/Python_600课/py_07_逻辑运算符应用.py
252
3.78125
4
age = int(input('请您输入您的年龄')) if age <0 or age > 120: print('怪胎?') elif age >= 0 and age <=18: print('您还不能进网吧哟') else: print('网吧欢迎您!') is_vip = False if not is_vip : print('不是VIP')
6e1eeebda39b66a62c9eb423e30bbeb9d31edf1c
ensarbaltas/14.Hafta-Odevler
/14.hafta 3.odev.py
1,941
3.9375
4
""" 14.Hafta 3.odev @author: ensarbaltas """ import random #oyuncu sayisi random.randint ile secildi oyuncusayisi=random.randint(2,4) #print('oyuncusayisi ',oyuncusayisi) scores=[] count1=0 while count1<oyuncusayisi: scores+=[random.randrange(5,120,5)] scores.append(random.randrange(5,120,5)) scores.sort() scores.reverse() count1+=1 print('Bu dongude oyuncu puanlari random ile rastgele secildi \n') n=len(scores) #print('n ',n) print('General scores :',scores,'\n') #oyun sayisi random.randint ile secildi. oyunsayisi=random.randint(2,oyuncusayisi) #print('oyunsayisi ',oyunsayisi) #Alice'nin puanlari random.randrange ile secildi alice=[] count2=0 while count2<oyunsayisi: alice+=[random.randrange(5,120,5)] alice.append(random.randrange(5,120,5)) alice.sort() alice.reverse() count2+=1 #Bu dongude Alice'nin puanlari rastgele secildi m=len(alice) #print('m ',m) print('Alice scores :',alice,'\n') #Burada oyuncu siralamasi yapildi oyuncusirasi=[] sira1=[] for i in scores: if i not in oyuncusirasi: oyuncusirasi+=[i] sira1+=[len(oyuncusirasi)] #print('oyuncusirasi ',oyuncusirasi) #print('sira1',sira1) #Burada oyun puanlari ile alice nin puanlari birlestirildi toplamsira=scores+alice toplamsira.sort() toplamsira.reverse() tekrarsizliste=[] sira2=[] #Asil siralama icin tekrarsiz liste olusturuldu for i in toplamsira: if i not in tekrarsizliste: tekrarsizliste+=[i] sira2+=[len(tekrarsizliste)] sira2.reverse() #print('toplamsira ',toplamsira) #print('tekrarsizliste ',tekrarsizliste) #print('sira2',sira2) #Tekrarsiz listeden hareketle alice nin sirasi tesbit edildi. sonuc=[] aliceninsirasi=[] count3=0 for i in alice: if i in tekrarsizliste: sonuc+=[tekrarsizliste.index(i)] for i in sonuc: i+=1 aliceninsirasi+=[i] aliceninsirasi.reverse() print("Alice'in sirasi : \n",*aliceninsirasi, sep='\n')
8537f95be7e7a9e685d6ef6ef1c3011a19bb429e
vargheseashik/python
/Languagefundamentals/sumpattern.py
118
3.9375
4
num=int(input("enter the number")) sum=0 for i in range(1,num+1): data=str(num)*i sum=sum+int(data) print(sum)
9b6193cce636516ed273129490dd53f55696d9f1
PullBack993/Python-Advanced
/5. Functions Advanced - Exercise/3.Min Max and Sum.py
271
3.703125
4
# input # 2 4 6 # output # The minimum number is 2 # The maximum number is 6 # The sum number is: 12 nums = list(map(int, input().split())) print(f"The minimum number is {min(nums)}") print(f"The maximum number is {max(nums)}") print(f"The sum number is: {sum(nums)}")
369b6deda986697894141aaed5d4ee114c8ff2fc
WuZhiT/xtpython
/xt18.py
494
4
4
#this oneis like oyur script with argv def print_two(*args): arg1,arg2 = args print(f"arg1: {arg1}, arg2: {arg2}.") #ok,that *args is actually pointless, we can just do it def print_two_again(arg1,arg2): print(f"arg1: {arg1}, arg2: {arg2}.") #this just takes one argument def print_one(arg1): print(f"arg1: {arg1}") #this one takes no arguments def print_none(): print("I got none.") print_two("Zed","Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none()
2e11bb22a151f8c2473ea0adacd84103d034ca07
spettigrew/pythonII-guided-practice
/online-store/store-guided.py
3,122
4.03125
4
#OOP - object oriented programming or design. ''' Take a complicated topic and make it into a modular application. Objects or classes O - blueprints / prototype; creating and grouping data. Holds data - attributes of a prototype of a blueprint. Uses methods - functions. You pass arguments, a function receives parameters C - Instance of a class - take a blueprint and create on instance of the objects and have it interact with other objects. Class naming convention is capitalization. Ex. pets Pet blueprint(class) attributes in a pet: name, height, size, kind/breed, gender, species, diet, leg number, etc. Dog (object) - ("rover", "40'",) Function - feed_pet, pet_pet, play_pet, walk_pet, etc. ''' from category import Category class Store: # attributes # name # categories (departments) # constructor - the function that runs every time you create a new instance. def __init__(self, name, categories): self.name = name self.categories = categories #dunder function uses double __ (underscores) def __str__(self): #str - allows us to transform the store object into a string. A built-in function. # return a stirng representing the store. Build a string class.\n = new line output = f"Welcome to {self.name}!" i = 1 for category in self.categories: output += f'\n {i}. {str(category)}' i += 1 # return f"Welcome to {self.name}! Here are the categories: {self.categories}" def __repr__(self): # also returns a string. # helps developers debug and understand how object is structured. datenow(). Repr classes, represents underlying classes or sub-classes. return f"self.name = {self.name} : self.categories = {self.categories}" running_category = Category("Running", "All equipment available", []) biking_category = Category("Biking", "Mountain bikes only", []) fishing_category = Category("Fishing", "Outdoor only", []) hiking_category = Category("Hiking", "Outdoor/Mountains only", []) # sports_store = Store("Gander Mountain", ["Running", "Biking", "Fishing", "Hiking"]) # produce_store = Store("Kroger", ["Dairy", "Produce", "Deli", "Bakery" ]) #create an instance of existing code. #str(sports_store) #print(sports_store) #print(produce_store) #print(repr(sports_store)) #print(running_category) sports_store = Store("Gander Mountain", [running_category, biking_category, fishing_category]) choice = -1 # REPL <- Read, Evaluate, Print, Loop. print(sports_store) print("type q to quit") while True: # Read choice = input("Please choose a category (#): ") try: # Evaluate if (choice == "q"): break choice = int(choice) - 1 if choice >= 0 and choice < len(sports_store.categories): chosen_category = sports_store.categories[choice] # Print print(chosen_category) else: print("The number is out of range.") except ValueError: print("Please enter a valid number.") #except Exception: which works as a "catch all" for errors
6482219b4a67da9104c1eef987646ad75e001f36
theokott/txt-combiner
/txtcombiner.py
1,887
4.21875
4
import glob filetype = raw_input("What is the file extension to be combied?: ") #Asks the user for the extension used by files to be combined filetype = "*." + filetype #Adds a wildcard and . to the filetype to be used by the glob function filenameList = glob.glob(filetype) #Returns a list of all txt files in the directory the program is in print filenameList cFilename = raw_input("What should the combined file be called?: ") #Asks the user for what the combined filename should be combFile = open(cFilename, "w") #Creates and opens a file called whatever the user entered and sets the open mode to write for x in filenameList: #Goes through the list of files and opens each one, adds its contents to combFile and closes it copyFile = open(x, "r") lineStr = copyFile.readline() #Gets the first line from the file to be copied and sets the value of lineStr to it while lineStr != "": #Loops through the file until a line that is empty #lineStr = lineStr[:-1] #Removes the endline character from the line combFile.write(lineStr) #Writes the line to be copied to the new file lineStr = copyFile.readline() #Gets the new line to be copied copyFile.close() #Closes the file once it has been fully copied combFile.write("\n") #Adds a newline character to the first line of the next file is copied onto a new line combFile.close() #Closes the combined file
1fc7843da2c664aca96d20efb6593c7ff2c2ebaf
seonghyeon555/Python_Project2.0
/test1.py
100
3.5
4
a=input().split(' ') x=int(a[0]) y=int(a[1]) print(x+y) print(x-y) print(x*y) print(x//y) print(x%y)
9ce14a8fe4897117b7eb2e077fd8b8d91c48f3f5
RandyHodges/Self-Study
/Java/Machine Learning/LinearRegression.py
1,316
3.671875
4
import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_diabetes from statistics import mean def best_fit_slope_and_intercept(xs, ys): m = (((mean(xs)*mean(ys)) - mean(xs*ys)) / ((mean(xs)*mean(xs)) - mean(xs*xs))) b = mean(ys) - m*mean(xs) return m, b def simply(originalarray): tmparr = [] for arr in originalarray: for arr1 in arr: tmparr.append(arr1) return tmparr # Load the diabetes dataset diabetes = load_diabetes() # Use only one feature diabetes_X = diabetes.data[:, np.newaxis, 2] # Split the data into training/testing sets diabetes_X_train = np.array(simply(diabetes_X[:-20])) diabetes_X_test = np.array(simply(diabetes_X[-20:])) # Split the targets into training/testing sets diabetes_y_train = np.array(diabetes.target[:-20]) diabetes_y_test = np.array(diabetes.target[-20:]) m, b = best_fit_slope_and_intercept(diabetes_X_train, diabetes_y_train) test_Y = [] for x in diabetes_X_test: test_Y.append((m*x)+b) # Plot outputs plt.scatter(diabetes_X_train, diabetes_y_train, color='red', label='Train Data') plt.scatter(diabetes_X_test, diabetes_y_test, color='green', label='Test Data') plt.plot(diabetes_X_test, test_Y, color='blue', linewidth=3, label='Line of best fit') plt.legend(loc=4) plt.show()
b2c9a1c2682aa8661d589cb00d2ab1ca936438c2
KurinchiMalar/DataStructures
/DynamicProgramming/LongestPalindromicSubsequence.py
2,057
3.59375
4
__author__ = 'kurnagar' ''' ''' # Time Complexity : O(n*n) # Space Complexity : O(n*n) ''' Algorithm: 1) Fill all diagonal to 1. lcps[i][i] = 1 # meaning single letter palindrome (lvl = 1) 2) if Ar[i] == Ar[j]: lcps[i][j] = lcps[i+1][j-1] + 2 # 2 means, say i corresponds to a , then j also will be a .. so we have a a else: lcps[i][j] = max(lcps[i][j-1],lcps[i+1][j]) # take the max 3) lcps[0][n-1] is the answer. ''' def get_length_of_longest_palindromic_subsequence(Ar): n = len(Ar) lcps = [[0] * n for x in range(len(Ar))] lvl = 1 for i in range(0,n): lcps[i][i] = 1 lvl = 2 while lvl <= n: print "---------------------------" for i in range(0, n-lvl+1): j = i + lvl - 1 print "lvl :"+str(lvl)+" i = "+str(i)+" j = "+str(j) if Ar[i] == Ar[j]: lcps[i][j] = lcps[i+1][j-1] + 2 else: lcps[i][j] = max(lcps[i][j-1],lcps[i+1][j]) lvl = lvl + 1 max_pali_seq_len = lcps[0][n-1] result = [0]* max_pali_seq_len i = 0 j = n-1 start = 0 end = max_pali_seq_len - 1 for list in lcps: print list while i < n and j >= 0: if lcps[i][j] == 0: break if lcps[i+1][j] == lcps[i][j-1]: # Move diagonal #if lcps[i+1][j] != lcps[i][j]: # if not equal then it should have a +2 from diagonal, so append to result and move diagonal.. if Ar[i] == Ar[j]: result[start] = Ar[i] result[end] = Ar[j] start = start + 1 end = end - 1 i = i + 1 j = j - 1 else: if lcps[i+1][j] > lcps[i][j-1]: i = i + 1 else: j = j -1 return lcps[0][n-1],result mystr = "agbdba" length,result = get_length_of_longest_palindromic_subsequence(list(mystr)) print "Longest palindromic subseq : "+str(result) print "Length of longest palindromic subseq : "+str(length)
fbc04177f13ad32239b9540bfc1427b6985e13dc
AmitBaanerjee/Data-Structures-Algo-Practise
/leetcode problems/704.py
906
3.875
4
# 704. Binary Search # # Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. # # # Example 1: # # Input: nums = [-1,0,3,5,9,12], target = 9 # Output: 4 # Explanation: 9 exists in nums and its index is 4 # # Example 2: # # Input: nums = [-1,0,3,5,9,12], target = 2 # Output: -1 # Explanation: 2 does not exist in nums so return -1 class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ low=0 high=len(nums)-1 while low<=high: mid=(low+high)//2 if target==nums[mid]: return mid elif target<nums[mid]: high-=1 else: low+=1 return -1
2c2813c88325e3cb5fdc274056de85ecfc312c92
KeyoungLau/lazy4power
/ncre-py/chapter6/元组.py
243
3.78125
4
s = list() for i in range(11): s.append(i) # 用tuple()函数把列表s转换为元组 s = tuple(s) print("原元组为:", s) # 对列表s进行切片,步长为2 print("从第四个开始对元组进行切片,步长为2: ",s[3::2])
0bc7f0d1c200033ccdb72f6f59a6d4dfadf765d6
netletic/pybites
/121/password_no_regex.py
995
3.71875
4
MIN_LENGTH = 8 def _has_lower_upper(password): return any([c.islower() for c in password]) and any([c.isupper() for c in password]) def _has_number_and_char(password): return any([c.isdigit() for c in password]) and any([c.isalpha() for c in password]) def _has_special(password): return not password.isalnum() def _is_long_enough(password): return len(password) >= MIN_LENGTH def _is_long_enough_without_repetition(password): if not _is_long_enough(password): return False previous = "" for c in password: if c == previous: return False previous = c return True def password_complexity(password): score = 0 if _has_lower_upper(password): score += 1 if _has_number_and_char(password): score += 1 if _has_special(password): score += 1 if _is_long_enough(password): score += 1 if _is_long_enough_without_repetition(password): score += 1 return score
73dfbcd2caa3537ff0ca44f2b66a742b51d5d94c
imarevic/psy_python_course
/notebooks/Chapter8/instblock.py
1,811
3.53125
4
# import pygame modules import pygame, os import TextPresenter # initialize pygame pygame.init() # create screen screen = pygame.display.set_mode((700, 700)) pygame.display.set_caption("Solution Rendering Multiline Text") # create a font object # parameters are 'system font type' and 'size' font = pygame.font.SysFont("Arial", 28) # === loading instructions text === # # get path absPath = os.path.abspath(os.curdir) instPath = os.path.join(absPath, "instructions/") # defining instructions loading function def load_instructions(filename): """loads instructions from a text file""" with open(instPath + filename, 'r') as file: infile = file.read() return infile # ===================================================== # # === section that creates the rendered text object === # # create a text string, text color, background color, and a rendered text object # params of the render method are 'text', anti-aliasing, color and background color text = load_instructions("welcome.txt") textColor = (0, 0, 0) # text is black bgColor = (160, 160, 160) # bgColor will be light grey screenRect = screen.get_rect() # get screen rect # define width and height of text textwidth = screenRect.width - (screenRect.width//10) textheight = screenRect.height - (screenRect.height//10) # create instruction block object instWelcome = TextPresenter.text_object(text, font, textwidth, textheight) # ===================================================== # # change color of screen and draw everything screen.fill(bgColor) # blit text with the textRect as positional argument screen.blit(instWelcome, (screenRect.centerx - (textwidth // 2), screenRect.centery - (textheight // 2))) # flip to foreground pygame.display.flip() # wait for 8 seconds pygame.time.wait(8000)
d81efd82d060436d1ce4b932f8c966f0a9324c26
sunnyhyo/Problem-Solving-and-SW-programming
/lab9-6.py
209
3.59375
4
#Lab9-6 (문자열 -> 숫자변환) x = input("숫자1: ") y = input("숫자2: ") z = input("숫자3: ") #문자열을 숫자로 변환하여 덧셈 연산 result = int(x) + int(y) + int(z) print(result)
dc372bc2d35f5ab669a74fa9d20f6def00b79908
Crone1/College-Python
/Year One - Semester Two/Week Three/numcomps_031.py
789
4.125
4
import sys n = int(sys.argv[1]) + 1 def is_prime(n): i = 2 while i < n and n % i != 0: i = i + 1 return n == i print('Multiples of 3: {}'.format([num for num in range(1, n) if not num % 3])) print ('Multiples of 3 squared: {}'.format([num * num for num in range(1, n) if not num % 3])) print ('Multiples of 4 doubled: {}'.format([num * 2 for num in range(1, n) if not num % 4])) print ('Multiples of 3 or 4: {}'.format([num for num in range(1, n) if not num % 3 or not num % 4])) print ('Multiples of 3 and 4: {}'.format([num for num in range(1, n) if not num % 3 and not num % 4])) print ('Multiples of 3 replaced: {}'.format(['X' if not num % 3 else num for num in range(1, n)])) print ('Primes: {}'.format([num for num in range(1, n) if is_prime(num)]))
2e4350f4729246eb92b64dc5809b2fea645eeadd
chensuim/leetcode
/trie.py
469
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/12/17 下午1:40 # @Author : Sui Chen class Trie(object): def __init__(self, words): self.data = [None] * 27 for word in words: layer = self.data for char in word: index = ord(char) - ord('a') if layer[index] is None: layer[index] = [None] * 27 layer = layer[index] layer[-1] = True
7ce5cc030d2e8e3593f9877361311e90ca136b82
Guitarboyjason/PythonExercise
/baekjoon/11729-하노이 탑 이동 순서.py
289
4.03125
4
from queue import LifoQueue N = int(input()) def hanoi(stack_1,stack_2,stack_3): if stack_3.size == N: return 1 if stack_1 != stack_1 = LifoQueue(maxsize = N) stack_2 = LifoQueue(maxsize = N) stack_3 = LifoQueue(maxsize = N) for i in range(N,0,-1): arr_1.append(i)
be8863b3895f790910ca839e1c010c84ec0923f1
SharonReginaSutio99/Python-basic
/prac_07/KivyDemos-master/dynamic_labels.py
880
3.53125
4
""" Name: Sharon Regina Sutio Link: https://github.com/SharonReginaSutio99/cp1404practicals """ from kivy.app import App from kivy.lang import Builder from kivy.uix.label import Label class DynamicLabelsApp(App): """Main program - Kivy app to make dynamic labels.""" def __init__(self, **kwargs): """Construct main app.""" super().__init__(**kwargs) self.names = ["Alan", "Jack", "Bob", "Sarah"] def build(self): """Build Kivy GUI.""" self.title = 'Dynamic Labels' self.root = Builder.load_file('dynamic_labels.kv') self.create_labels() return self.root def create_labels(self): """Create labels from list entries and add them to GUI.""" for name in self.names: temp_label = Label(text=name) self.root.ids.labels_box.add_widget(temp_label) DynamicLabelsApp().run()
be846e0932bf068348083e1cdf350d75e3e17b7e
yordanivh/intro_to_cs_w_python
/chapter05/Chapter5ExcersicesPart2.py
2,666
3.734375
4
Python 3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> ph=2 >>> if ph < 3.0: print(ph, "is VERY acidic! Be careful.") elif ph < 7.0: print(ph, "is acidic. SyntaxError: EOL while scanning string literal >>> if ph < 3.0: print(ph, "is VERY acidic! Be careful.") elif ph < 7.0: print(ph, "is acidic.") 2 is VERY acidic! Be careful. >>> ph = float(input("Enter the ph level: ")) Enter the ph level: 6.4 >>> if ph < 7.0: print("It's acidic!") elif ph < 4.0: print("It's a strong acid!") It's acidic! >>> ph = float(input("Enter the ph level: ")) Enter the ph level: 3.6 >>> if ph < 7.0: print("It's acidic!") elif ph < 4.0: print("It's a strong acid!") It's acidic! >>> if ph < 7.0: print("It's acidic!") if ph < 4.0: print("It's a strong acid!") SyntaxError: invalid syntax >>> if ph < 7.0: print("It's acidic!") if ph < 4.0: print("It's a strong acid!") SyntaxError: expected an indented block >>> if ph < 7.0: print("It's acidic!") if ph < 4.0: print("It's a strong acid!") It's acidic! It's a strong acid! >>> young = age < 45 Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> young = age < 45 NameError: name 'age' is not defined >>> age =23 >>> young = age < 45 >>> heavy = bmi >= 22.0 Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> heavy = bmi >= 22.0 NameError: name 'bmi' is not defined >>> bmi = 23 >>> heavy = bmi >= 22.0 >>> if young ​and not heavy: ​ risk = ​'low'​ ​elif​ young ​and​ ​heavy: ​ risk = ​'medium'​ ​​elif​ ​not​ young ​and​ not heavy: ​ risk = ​'medium'​ ​​elif​ ​not​ young ​and​ ​heavy: ​ risk = ​'high' SyntaxError: invalid character in identifier >>> sk = ​'low'​ ​elif​ young ​and​ ​heavy: ​ risk = ​'medium'​ ​​elif​ ​not​ young ​and​ not heavy: ​ risk = ​'medium'​ ​​elif​ ​not​ young ​and​ ​heavy: ​ risk = ​'high' KeyboardInterrupt >>> ​​if young ​and​ not heavy: ​ risk = ​'low'​ ​elif​ young ​and​ ​heavy: ​ risk = ​'medium'​ ​​elif​ ​not​ young ​and​ not heavy: ​ risk = ​'medium'​ ​​elif​ ​not​ young ​and​ ​heavy: ​ risk = ​'high' SyntaxError: invalid character in identifier >>> if young and not heavy: risk = 'low' elif young and heavy: risk = 'medium' elif not young and not heavy: risk = 'medium' elif not young and heavy: risk = 'high' >>> risk 'medium' >>>
ae50317ea13b4058734e05c13761d90830d1d054
Johnny-kiv/sheduler
/test/time 3.py
1,545
4.03125
4
#Это напоминальщик #версия 3 #Автор: johnny-kiv import time a2 = int(input("Введите минуты работы: ")) b2 = int(input("Введите минуты отдыха: ")) с2 = int(input("Введите часы нахождения в школе: ")) if a2 == 0: a4 = 60*20 if b2 == 0: b4 = 20*60 if с2 == 0: с4 = с2*(60*60) else: a4 = a2*60 b4 = b2*60 с4 = с2*(60*60) print("\a Работаем на компьютере") time.sleep(a4) print("\a \n \t Идём в школу") time.sleep(с4) print("\a Работаем на компьютере") time.sleep(a4) print("\a \n \t Делаем уроки ") time.sleep(b4) print("Работаем на компьютере") time.sleep(a4) print("\a \n \t Английский язык") time.sleep(b4) print("\a Работаем на компьютере") time.sleep(a4) print("\a \n \t Cольфеджио ") time.sleep(b4) print("\a Работаем на компьютере") time.sleep(a4) print("\a \n \t Спорт ") time.sleep(b4) print("\a Работаем на компьютере") time.sleep(a4) print("\a \n \t Чтение") time.sleep(b4) print("\a Работаем на компьютере ") time.sleep(a4) print("\a \n \t Фортепиано ") time.sleep(b4) print("\a Работаем на компьютере") time.sleep(a4) print("\a \n \t Гитара ") time.sleep(b4) print("\a Работаем на компьютере") time.sleep(a4) print("\a \n \t А теперь спать ")
e289ad2877356c1ce5bfc65a0cd6147a3a2e43a5
RobinXYuanBlog/PythonAlgorithm
/recursion/Hanoi.py
493
4.25
4
# def hanoi(steps, left='left', right='right', middle='middle'): # if steps: # hanoi(steps - 1, left, middle, right) # print(left, '=>', right) # hanoi(steps - 1, middle, right, left) # # 3 0 0 # 2 0 1 # 1 1 1 # 1 2 0 # 0 2 1 # 1 1 1 # 1 0 2 # 0 0 3 def hanoi(steps, left='left', middle='middle', right='right'): if steps: hanoi(steps - 1, left, right, middle) print(left, '=>', right) hanoi(steps - 1, middle, left, right) hanoi(3)
7d1e7d5cff060ae621fb0147b8ca142a87032266
quentin-lipeng/python-first
/less2/less2-1/part2-5.py
570
3.796875
4
count = 0 while count < 5: print('凉凉一首') count += 1 pass print('over') def one_hun(): num1 = 0 flag = 1 while flag <= 100: num1 += flag flag += 1 else: print(num1) pass pass # 2550 def dou_sum(): num = 0 end = 100 start = 0 flag = 1 while flag <= end/2: flag += 1 if end or start % 2 == 0: num += end + start end -= 2 start += 2 print(num) else: num += end print(num) pass pass dou_sum()
15d8c86cc6cf85f0f8ebcf1e5e22c2b127ddd8e1
Tayl1989/WordReferenceAutoSort
/venv/Include/back_up.py
451
3.703125
4
# 注意: 需要安装python-docx库 from docx import Document import re import copy # file_path = input("请输入文档的绝对路径地址: ") file_path = r'D:\Development\python\docx-quotes-sort\venv\Include\test.docx' document = Document(file_path) for p in document.paragraphs: flag = re.match(r"^(\[\d+\])", p.text) if flag: # print("size: ",p.runs[0].font.size) for run in p.runs: print(run.font.name)
a347e9f3015e70d46c0804cd81ace26864706c58
diegoscolnik/ClaseAbiertaSelenium
/principiante.py
299
3.71875
4
#Programa de principiantes de la clase abierta de automation a = 1+5 b = 8 print(a+b) print(a-b) print(a*b) print(a/b) print(a**b) print(a%b) print(8//3) print(8/3) c = "Hola Mundo" d = 'Hola Mundo' print(c) print(d) e = 1.4648646468 f = 68616158616 print(f/e) g = True h = False print(g) print(h)
0164c5eab11adb9ceb9081fd66b8388278bfbab0
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/3197.py
2,651
3.5
4
import itertools with open('A-small-attempt1.in', 'r') as f: prob1 = f.readlines() total = int(prob1[0]) happy = 0 down = 0 case = 0 flips = 0 total_pancakes = 0 answer = [] # run through the rest of the lines for x in range(1, total+1): # 1,total+1 # per run format contained at this level success_runs = [] case = case + 1 x = prob1[x].rstrip() # pancake_line string, remove newline pancake_line = x[:len(x)-2].strip() # remove K number total_pancakes = len(pancake_line) # find number of pancakes we are workin with k = int(x[len(x)-2:]) # number of pancakes that flipper can handle line_members = [] for p in x[:len(x)-2]: line_members.append(p) if p == '-': down = down + 1 elif p == '+': happy = happy + 1 ################## Set the shortcut conditions? # Now find all possibilities max_flips_possible = total_pancakes - (int(k) - 1) flip_path = [] # first flip assignment, label by the starting index flip for u in range(max_flips_possible): if int(k) <= (total_pancakes-u): flip_path.append(u) original = line_members # permutations of all places to start trying to flip for n in list(itertools.permutations(flip_path)): pancake_line_try = [p for p in x[:len(x)-2]] # flip that section num_flips_done = 0 for position in n: num_flips_done = num_flips_done + 1 flip_tracker = 0 for pancake in pancake_line_try[position:position + k]: if pancake == '-': pancake_line_try[position+flip_tracker] = '+' elif pancake == '+': pancake_line_try[position+flip_tracker] = '-' flip_tracker = 1 + flip_tracker # check if the flip means all smiley #print(pancake_line_try) check = 0 for n in pancake_line_try: if n == '+': check = check + 1 # if all smiles then , good! if check == total_pancakes: success_runs.append(num_flips_done) if len(success_runs) == 0: string = 'Case #' + str(case) + ': IMPOSSIBLE' + '\n' if(happy == total_pancakes): success = 0 string = 'Case #' + str(case) + ': ' + str(success) + '\n' else: success = min(success_runs) if(happy == total_pancakes): success = 0 string = 'Case #' + str(case) + ': ' + str(success) + '\n' #print(string) # reset per run happy = 0 down = 0 total_pancakes = 0 answer.append(string) with open('result1.txt', 'w')as k: for a in answer: k.write(a) # Easy shortcuts: # if k = 1, min flips = down pancakes # if k = 0, impossible # if k > num pancakes, impossible? # if happy = total # pancakes # import itertools # n = itertools.permutations([1,2,3]) # list(n)
39bcbe9d664219f56608744cc6e2b0e88261fa2a
carriehe7/bootcamp
/IfStatementBasics.py
1,118
4.125
4
# if statements basics part 1 salary = 8000 if salary < 5000: print('my salary is too low, need to change my job') else: print('salary is above 5000, okay for now') age = 30 if age > 50: print('you are above 50. you are a senior developer for sure') elif age > 40: print('your age is bigger than 40. you are a developer for some time, but if not, better late than never') elif age > 35: print('so you are more than 35yo, I might guess you are a developer') else: print("doesn't matter what age you are. let's code python") # if statements basic part 2 age = 30 name = 'James' # logical operator - 'and' if age > 20 and name == 'James': print('my name is James and I am over 20') else: print('default exit point') # logical operator - 'or' if age > 20 or name == 'James': print('my name is James and I am over 20') else: print('default exit point') # nested 'if' statement married = True if age > 20 and name == 'James': if married == True: print("good luck, it's gonna be a long happy ride") else: print('nested else') else: print('parent else')
ed51c7733c5c43339625e26a53329df0e2c05fbe
rodolforicardotech/pythongeral
/pythonparazumbis/Lista01/PPZ01.py
208
3.8125
4
# 1) Faça um programa que peça dois # números inteiros e imprima a soma desses dois números n1 = int(input('Informe o primeiro número: ')) n2 = int(input('Informe o segundo número: ')) print(n1 + n2)
a36ada6c22eefff15d9ddff7175229ff46c77810
vitor251093/SimuladorAD.2018-1
/simulador/models/pacote.py
1,251
3.640625
4
""" Classe Pacote que guardara todas as informacoes pertinentes ao Pacote, do momento que chega, ate o momento que sai do sistema. """ class Pacote(object): def __init__(self, id, tempoChegadaNoSistema, indiceDaCor, canal=-1, indiceEmCanal=0, servico=0): self.id = id self.indiceDaCor = indiceDaCor self.canal = canal # Usado apenas por pacotes de voz (0 a 29) self.indiceEmCanal = indiceEmCanal self.servico = servico self.tempoChegadaFila = tempoChegadaNoSistema self.tempoChegadaServico = 0.0 self.tempoServico = 0.0 self.tempoTerminoServico = 0.0 ############### ## Getters ############### ### Getters para calculos estatisticos def getTempoEsperaFila(self): # W1/2 return self.tempoChegadaServico - self.tempoChegadaFila def getTempoTotalServico(self): # X1/2 return self.tempoTerminoServico - self.tempoChegadaServico def getTempoTotalSistema(self): # T1/2 return self.tempoTerminoServico - self.tempoChegadaFila def getVarianciaTempoEsperaFila(self, esperancaTempoEsperaFila): # VW1/2 return ((self.tempoChegadaServico - self.tempoChegadaFila) - esperancaTempoEsperaFila) ** 2
58bd4d11754b4193b021bbb1287a1b2bd5ced61f
IshaBharti/python_list_loop_ifelse_fun
/menue.py
443
3.921875
4
day=input("enter day") meal=input("enter time") if day=="monday" and meal=="breakfast": print("poori sbji") elif day=="monday" and meal=="lunch": print("daal chawal") elif day=="monday" and meal=="dinner": print("chicken rice") elif day=="tuesday" and meal=="breakfast": print("tea and toast") elif day=="tuesday" and meal=="lunch": print("sambhar rice") elif day=="tuesday" and meal=="dinner": print("manchuriyan")
422c14c8b99277984dc7d141fe6cb2ab2670a43f
HG-Dev/OrthoTurtleSim
/__main__.py
1,061
3.75
4
''' Main executable for the 2D turtle moving simultor. ''' import time from turtlesim.world_render import WorldDrawer from turtlesim.turtle import Turtle from turtlesim.datatypes import Coord from turtlesim.exceptions import ExitInterrupt def main(): """ Main body for starting up and updating simulation """ # pylint: disable=no-member try: world = WorldDrawer() turtle = Turtle(world, Coord(0, 0)) assert WorldDrawer.TURTLE in world.world_data[0] check_time = start_time = time.time() while True: #Tick check if time.time() - check_time > 1: check_time = check_time + 1 if world.has_changed: WorldDrawer.clear_screen() print(int(check_time - start_time)) world.draw() turtle.update() if not turtle.moving: raise ExitInterrupt except (KeyboardInterrupt, ExitInterrupt): print("Exiting") if __name__ == "__main__": main()
b73d0ffff7aeccc54f72afdd3833fffb25b838dc
Ronak912/Programming_Fun
/hashmap/CheckIfListCandivideIntoPairs.py
921
3.96875
4
# http://www.geeksforgeeks.org/check-if-an-array-can-be-divided-into-pairs-whose-sum-is-divisible-by-k/#disqus_thread # https://ideone.com/IO9hw2 # Input: arr[] = {9, 7, 5, 3}, k = 6 # Output: True # We can divide array into (9, 3) and (7, 5). # Sum of both of these pairs is a multiple of 6. # # Input: arr[] = {92, 75, 65, 48, 45, 35}, k = 10 # Output: True # We can divide array into (92, 48), (75, 65) and # (45, 35). Sum of all these pairs is a multiple of 10. # # Input: arr[] = {91, 74, 66, 48}, k = 10 # Output: False def isArrayDividable(lst, k): if len(lst) % 2 != 0: return False newset = set() for val in lst: remainder = val % k if (k - remainder) in newset: newset.remove(k-remainder) else: newset.add(remainder) return len(newset) == 0 if __name__ == "__main__": lst = [5, 4, 6, 3, 10, 8] print isArrayDividable(lst, 9)
5a0a0dabeb19145957a028c41819e9c19b54f6a1
Sayam753/semester-3
/adsa/S20180010158_karger.py
1,505
3.546875
4
# Karger's algorithm implementation by Sayam Kumar - S20180010158 import random # Merge Utility def merge(graph, u, v): # Adding all connections of v to u for vertex in graph[v]: graph[vertex].remove(v) if vertex!=u: # Removing self edges graph[u].append(vertex) graph[vertex].append(u) del graph[v] # Karger utility def karger(graph): while(len(list(graph))>2): # Getting one vertex randomly u = random.choice(list(graph)) # Getting one edge from u randomly v = random.choice(graph[u]) merge(graph, u, v) mincut_length = len(graph[list(graph)[0]]) return mincut_length graph = dict() print("Enter the number of edges") edges = int(input()) print("Enter an edge by giving two vertices") for _ in range(edges): [a, b] = list(map(int, input().split())) if a in graph: graph[a].append(b) else: graph[a] = [b, ] if b in graph: graph[b].append(a) else: graph[b] = [a, ] print("Running karger algorithm 10000 times") result = dict() for i in range(10000): # Creating temp graph temp = dict() for j in graph: temp[j] = graph[j].copy() length = karger(temp) if length in result: result[length] = result[length]+1 else: result[length] = 1 print("Mincut Length:\tNumber of times") for i in result: print("\t", i, "\t", result[i]) """ Test Case 14 1 2 1 3 1 4 2 3 2 4 3 4 2 5 4 5 5 6 6 7 7 8 8 5 5 7 6 8 """
3ab75b8c4ff05816fbe8db2751667704c06c2408
xionghhcs/algorithm
/剑指offer/34_UglyNumber.py
1,445
3.5625
4
# -*- coding:utf-8 -*- class Solution: def GetUglyNumber_Solution(self, index): # write code here if index <=0: return None ugly_numbers = [0] * index ugly_numbers[0] = 1 p1, p2, p3 = 0,0,0 ugly_cnt = 1 while ugly_cnt < index: min_ugly = min(ugly_numbers[p1] * 2, ugly_numbers[p2] * 3, ugly_numbers[p3] * 5) ugly_numbers[ugly_cnt] = min_ugly while ugly_numbers[p1] * 2 <= ugly_numbers[ugly_cnt]: p1 += 1 while ugly_numbers[p2] * 3 <= ugly_numbers[ugly_cnt]: p2 += 1 while ugly_numbers[p3] * 5 <= ugly_numbers[ugly_cnt]: p3 += 1 ugly_cnt += 1 return ugly_numbers[-1] pass # -*- coding:utf-8 -*- class Solution2: def GetUglyNumber_Solution(self, index): # write code here def isUgly(number): while number % 2 == 0: number = number // 2 while number % 3 == 0: number = number // 3 while number % 5 == 0: number = number // 5 return True if number == 1 else False if index <= 0: return 0 number = 0 uglyCnt = 0 while uglyCnt < index: number += 1 if isUgly(number): uglyCnt += 1 return number
edd626dd420df7e1c4125503d136c2414bb61992
pioella/Study
/7list_ex.py
790
3.984375
4
# 지하철 칸별로 10명, 20명, 30명 # subway1 = 10 # subway2 = 20 # subway3 = 30 subway = [10, 20, 30] print(subway) subway = ["유재석", "조세호", "박명수"] print(subway) print(subway.index("조세호")) print(subway[1]) subway.append("하하") print(subway) subway.insert(1, "정형돈") print(subway) print(subway.pop()) print(subway) # print(subway.pop()) # print(subway) # # print(subway.pop()) # print(subway) subway.append("유재석") print(subway) print(subway.count("유재석")) subway.sort() print(subway) subway.reverse() print(subway) subway.clear() print(subway) num_list = [5, 2, 4, 3, 1] num_list.sort() print(num_list) num_list.reverse() print(num_list) mix_list = ["조세호", 20, True] print(mix_list) num_list.extend(mix_list) print(num_list)
e4cf002451e6a3eb109ed6405875d66ab4b24e14
iyuangang/pycode
/swap.py
235
3.546875
4
#!/usr/bin/python # coding:utf-8 a = [] for i in range(10): a.append(input("entert the num:")) print a for i in range(9): for j in range(i+1,10): if a[i] > a[j]: a[i],a[j] = a[j],a[i] print a
f62fb8762a3a217067fe79e18924ed3b7b4ab8b2
mogalaxy64/Schedule-maker
/scheduleMaker.py
686
3.890625
4
def lineCounter():#This finds the total amount of lines in the doc to show the num of classes file = open("Schedule Example.txt") lines = 0 for line in file: line = line.strip("\n") lines += 1 return lines def main(): classNum = lineCounter() f = open("Schedule Example.txt") s = f.readline() for i in range(classNum): s +=f.readline() f.close() #print(s) #Now I need to parse the string to get all the values needed for each class #Can either store each class info into a single array and iterate through #Or can create array for each data type I need to get and iterate through those for each line main()
d2ca186a106557665c70df1065371fb46fc72cf2
Amutha-4/amjo
/set2,1.py
129
4.09375
4
n=int(input("enter a number:")) sum1=0 while(n>0): sum1=sum1+n n=n-1 print("the sum of first n natural number is",sum1)
531d448d7e55ec3e3719f35b68a94674cf900ce7
bopopescu/Projects-1
/1/1_1/默写测试/用户基双分支础判断.py
618
4.09375
4
""" _username = "kevin" _password = '123456' username = input("username: ") password = input("password: ") if username == _username and password == _password : print("welcome" , _username) else: print("wrong username or password") """ name = input("name: ") sex = input("sex: ") age = int(input("age: ")) #if ex == 'f': #1如果 是女生 # 1.1 如果年龄 小于28 # 1.1.1 打印喜欢女生 # 1.2 打印姐弟恋 # 2 如果是男生 打印搞基 if sex == "f": if age <28 : print("I love girls") else : print("姐弟恋很好") else: print ("一起来搞基")
f7c5ae4ca4fb62d8374725b4c52884cb530d1000
JavaRod/SP_Python220B_2019
/students/rfelts/lesson04/assignment/tests/test_unit.py
4,554
3.546875
4
#!/usr/bin/env python3 # Russell Felts # Assignment 4 - Unit Tests """ Unit test for the basic_operations """ from unittest import TestCase import logging from peewee import DoesNotExist from customer_model import DATABASE, Customer from basic_operations import add_customer, search_customer, delete_customer, \ update_customer_credit, list_active_customers, list_active_customer_names, add_customers logging.basicConfig(level=logging.INFO) LOGGER = logging.getLogger(__name__) def set_up_db(): """ Set up routine needed for all tests to make sure the db is in a known/empty state """ DATABASE.drop_tables([Customer]) DATABASE.close() DATABASE.create_tables([Customer]) DATABASE.close() class BasicOperationsUnitTest(TestCase): """ Unittests for verifying the basic_operations functionality """ test_customers = [[1, "Bruce", "Wayne", "1007 Mountain Drive, Gotham", "228-626-7699", "b_wayne@gotham.net", True, 200000.00], [2, "Clark", "Kent", None, "228-626-7899", "ckent@dailyplanet.com", True, 200.00], [3, "Diana", "Prince", None, "587-8423", "ww@justiceleague.net", False, 100.00]] def test_add_customer(self): """ Test adding a valid customer record to the DB """ set_up_db() add_customer(*self.test_customers[0]) test_customer = Customer.get_by_id(1) self.assertEqual("Bruce", test_customer.name) self.assertEqual("Wayne", test_customer.last_name) self.assertEqual("1007 Mountain Drive, Gotham", test_customer.home_address) self.assertEqual("228-626-7699", test_customer.phone_number) self.assertEqual("b_wayne@gotham.net", test_customer.email) self.assertEqual(True, test_customer.status) self.assertEqual(200000.00, test_customer.credit_limit) def test_add_customers(self): """ Test adding a valid customer records to the DB """ set_up_db() add_customers(self.test_customers) test_customer = Customer.get_by_id(1) self.assertEqual(self.test_customers[0][1], test_customer.name) test_customer = Customer.get_by_id(2) self.assertEqual(self.test_customers[1][1], test_customer.name) test_customer = Customer.get_by_id(3) self.assertEqual(self.test_customers[2][1], test_customer.name) def test_search_customer(self): """ Test that search_customer returns a dict containing name, last name, email address and phone number """ expected_result = {"name": "Bruce", "last_name": "Wayne", "email": "b_wayne@gotham.net", "phone_number": "228-626-7699"} set_up_db() add_customer(*self.test_customers[0]) self.assertDictEqual(expected_result, search_customer(1)) def test_search_no_customer(self): """ Test the search_customer returns an empty dict when the customer is not found """ set_up_db() self.assertEqual({}, search_customer(1)) def test_delete_customer(self): """ Tests that a customer can be deleted """ set_up_db() add_customer(*self.test_customers[0]) delete_customer(1) try: Customer.get_by_id(1) except DoesNotExist: LOGGER.info("Customer was deleted.") def test_update_customer(self): """ Tests that customer can be updated """ set_up_db() add_customer(*self.test_customers[0]) update_customer_credit(1, 500000.00) self.assertEqual(500000.00, Customer.get_by_id(1).credit_limit) def test_update_no_customer(self): """ Test that a ValueError is raised when trying to update a customer that doesn't exist """ set_up_db() with self.assertRaises(ValueError): update_customer_credit(2, 5.50) def test_list_active_customers(self): """ Test that the correct number of active customers is returned """ set_up_db() add_customer(*self.test_customers[0]) add_customer(*self.test_customers[1]) add_customer(*self.test_customers[2]) self.assertEqual(2, list_active_customers()) def test_list_active_customer_names(self): """ Test that the correct names of active customers is returned """ set_up_db() add_customer(*self.test_customers[0]) add_customer(*self.test_customers[1]) add_customer(*self.test_customers[2]) self.assertEqual(['Bruce Wayne', 'Clark Kent'], list_active_customer_names())
bdaf541814e9d9a7fcf15ffd76bc966a7ae9d4de
gyuhwanhwang/algorithm
/LeetCode/lc_21.py
1,396
4
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # l1에 항상 작은 값이 오도록 if (not l1) or (l2 and l1.val > l2.val): l1, l2 = l2, l1 if l1: l1.next = self.mergeTwoLists(l1.next, l2) return l1 """ if not l1 and not l2: return None result = ListNode() start = result while l1 and l2: if l1.val <= l2.val: # l1 이 작거나 같을 때 result.val = l1.val result.next = ListNode() l1 = l1.next result = result.next else: # l2가 작을 때 result.val = l2.val result.next = ListNode() l2 = l2.next result = result.next # l1이 남았음 while l1: result.val = l1.val l1 = l1.next if l1: result.next = ListNode() result = result.next # l2 남았음 while l2: result.val = l2.val l2 = l2.next if l2: result.next = ListNode() result = result.next return start """
d3de501361b16e0c19b9c7e274a4169c48938a11
ragamandali/pythonlabs
/classexamples/variables.py
155
3.71875
4
myname = "Raga" # nameofvariable = valueofvariable print(f"My name is {myname}") print(f"{myname} goes to high school") print(f"{myname} likes to read")
25c4832b2ca591d190a98cc4c5951b2f31984a01
ratchanon-dev/solution_py
/GradeII.py
553
3.953125
4
"""GradeII""" def main(): """grade cal""" grade = float(input()) if 95 <= grade <= 100: print("A") elif grade > 100 or grade <= 0: print('ERR') elif 90 <= grade < 95: print("B+") elif 85 <= grade < 90: print('B') elif 80 <= grade < 85: print('C+') elif 75 <= grade < 80: print('C') elif 70 <= grade < 75: print('D+') elif 65 <= grade < 70: print('D') elif 60 <= grade < 65: print('F+') elif 0 < grade < 60: print('F') main()
00b9f46e41de29693a515d315e7cf79ccd429905
ApurvaKunkulol/REST-APIs-with-Flask
/functions/code.py
275
3.859375
4
__author__ = 'LENOVO' # Most basic form of a function. def hello(): print("hello") def user_age_in_seconds(): age = int(input("Please enter your age(in years): ")) print("Age in seconds: ", age * 365 * 24 *3600) print("Good Bye!!") user_age_in_seconds()
13375b0a0fd83deb90a2214bac12c360db5e076a
ralphplumley/coursera
/algo-toolbox/week4_divide_and_conquer/1_binary_search/binary_search.py
898
3.984375
4
# Uses python3 import sys import math # 8 1 3 5 5 7 9 11 13 # 1 9 def binary_search(arr, target): minIndex, maxIndex = 0, len(arr) - 1 while maxIndex >= minIndex: midIndex = math.floor((minIndex + maxIndex) / 2) if arr[midIndex] == target: return midIndex elif arr[midIndex] < target: minIndex = midIndex + 1 else: maxIndex = midIndex - 1 return -1 def linear_search(a, target): for i in range(len(a)): if a[i] == target: return i return -1 if __name__ == '__main__': input = sys.stdin.read() # for Coursera submission data = list(map(int, input.split())) n = data[0] m = data[n + 1] arr = data[1 : n + 1] for target in data[n + 2:]: # replace with the call to binary_search when implemented print(binary_search(arr, target), end = ' ')
b48e924693ac1d8c7eb70fcf62303a5779f03969
sasha-n17/python_homeworks
/homework_3/task_5.py
659
3.953125
4
def calc_sum(): """Возвращает сумму чисел из введённых строк. Q - спецсимвол для выхода.""" result = 0 flag = True while flag: s = input('Введите строку из чисел, разделённых пробелом: ').split() if 'Q' not in s: numbers = [float(el) for el in s] result += sum(numbers) else: pos = s.index('Q') numbers = [float(el) for el in s[:pos]] result += sum(numbers) flag = False print(f'Сумма чисел: {result}') return result calc_sum()
421264e11e1c77b5ecf34accd17b72c252846b64
HackerSchool/HS_Recrutamento_Python
/Ielga_Oliveira/Projeto.py
2,524
3.75
4
import MenuAPP def ler(id): ficheiro = open('Registo.txt','r') password = "" for linha in ficheiro: id2= linha.split('-')[0] if id==id2: password = linha.split('-')[1] break ficheiro.close() return password def escrever(username,password): ficheiro = open('Registo.txt','a') ficheiro.write(username+ '-' + password + '\n') ficheiro.close() def registar(): username = input("username:\n") leitura = ler(username) if leitura != "": print("Este usuario ja se encontra registado") else: password = input("cont:\n") escrever(username,password) print("Registo efetuado com sucesso!") def apagaLinha(id): ficheiro = open('Registo.txt') output = [] for line in ficheiro: if not id in line: output.append(line) ficheiro.close() ficheiro2 = open('Registo.txt', 'w') ficheiro2.writelines(output) ficheiro2.close() def mudarPassword(): username = input("username:\n") apagaLinha(username) leitura = ler(username) if leitura != "": print("Este usuario ja se encontra registado") else: password = input("password:\n") escrever(username,password) print("Palavra-Passe alterada com Sucesso!") def menuLogin(): while True: print('''\nEscolhe a tua opcao 1 - Calculadora 2 - Mudar Password 3 - Logout ''') opcao = input("opcao:\n") if opcao == 1: MenuAPP.calculadora() elif opcao == 2: mudarPassword() elif opcao == 3: main() else: print("Introduza uma opcao que conste no Menu") def login(): username = input("username:\n") password_file = ler(username) password_input = input("password:\n") if password_file == "": print("Este usuario nao esta registado") elif password_file == password_input+'\n': print("Login efetuado") menuLogin() else: print("Credenciais incorretas") def main(): while True: print('''\nEscolhe a tua opcao 1 - Login 2 - Registar 3 - Sair ''') opcao = input("opcao:\n") if opcao == 1: print("Menu de Login") login() elif opcao == 2: registar() elif opcao == 3: exit() else: print("Introduza uma opcao que conste no Menu") main()
6271371810fa5337ec52db0a30b373f831913ead
fis-jogos/ep1-shape
/actors/meteor.py
641
3.59375
4
class Meteor: """ This class represents the aircraft controlled by the user. """ def __init__(self, actor, positionX, positionY,mass, speed, gravity=100): self.actor = actor self.positionX = positionX self.positionY = positionY self.mass = mass self.speed = speed self.gravity = gravity self.acceleration = 0 self.area = self.actor.width * self.actor.height def draw(self): """ Draw the aircraft in the screen. """ self.actor.x = self.positionX self.actor.y = World.HEIGHT - self.positionY self.actor.draw()