blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
9ae11d8cc57f5cf243312e80a71757398a2b1ed9
Mengeroshi/python-tricks
/2.Efective-Functions/2.1lambda.py
413
4.0625
4
""" Lambda are single statement anonymous function """ add = lambda x, y: x + y print(add(5, 3)) print((lambda x, y: x + y)(10, 20)) """Sorting iterables with alt key """ tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')] tuples.sort(key=lambda x: x[1]) print(tuples) """ this are the same""" lel = list(range(-5, 6)) lel.sort(key=lambda x: x * x) print(lel) print(sorted(range(-5, 6), key=lambda x: x*x))
edfe6a185579a75050b43f778ced88e263e092e1
Mengeroshi/python-tricks
/1.Patterns-For-Clear-Python/2.1.with.py
186
3.75
4
with open('hello.txt', 'w') as f: f.write("hello, world!") #another way to write same code of with f = open('hello.txt', 'w') try: f.write('hello world') finally: f.close()
c0d0697f27c61f5800d36abcd0a9f38991e2773e
Mengeroshi/python-tricks
/2.Efective-Functions/1.6_objects_behave_like_func.py
177
3.515625
4
class Adder: def __init__(self, n): self.n = n def __call__(self, x): return self.n + x plus_3 = Adder(3) print(plus_3(4)) print(callable(plus_3))
10f120dc49d89ee274e6f0258bffcfe0a2a8d711
Mengeroshi/python-tricks
/4.1.3.defaultdict.py
347
3.6875
4
""" default dict is dict subclass that returns a callable if the key cannot be found """ from collections import defaultdict dd = defaultdict(list) dd['dogs'].append('Rufus') # <---accessing to missimg key creates it and initializes it using default factory dd['dogs'].append('Kathrin') dd['dogs'].append('Mr Sniffles') print(dd['dogs']) print(dd)
c562dc0f6d4ab184c8a3b273567eeea000046026
hagmanen/aoc2019
/day21.py
1,120
3.71875
4
from intcomputer import intcomputer, input_ctrl def main(): filename = 'day21_input.txt' with open(filename, 'r') as f: text = f.read() program = [int(numeric_string) for numeric_string in text.split(",")] imp_str = 'NOT A J\nNOT C T\nOR T J\nAND D J\nWALK\n' comp_input = [ord(c) for c in imp_str] computer = intcomputer(program, comp_input) while True: (m_exit, m_out) = computer.run() if m_exit == 99: break if m_out < 255: print(chr(m_out), end = '') else: print('WALK Result: %i' % m_out) imp_str = 'NOT A J\nNOT B T\nOR T J\nNOT C T\nOR T J\nAND D J\nNOT E T\nNOT T T\nOR H T\nAND T J\nRUN\n' comp_input = [ord(c) for c in imp_str] computer = intcomputer(program, comp_input) while True: (m_exit, m_out) = computer.run() if m_exit == 99: break if m_out < 255: print(chr(m_out), end = '') else: print('RUN Result: %i' % m_out) #19354392 #1139528802 if __name__ == "__main__": main()
31da991ff741554de4a9e5e5f06be538f9a45fe1
TPIOS/Small-Python-exercise
/nltk_exercise/chapter 1/lx01.py
478
3.8125
4
import re mystring = "Monty Python ! And the holy Grail ! \n" # print(mystring.split()) # print(mystring.strip()) # print(mystring.upper()) # print(mystring.replace('!','''''')) # if re.search('Python', mystring): # print("We found Python") # else: # print("No") # print(re.findall('!',mystring)) word_freq = {} for tok in mystring.split(): if tok in word_freq: word_freq[tok] += 1 else: word_freq[tok] = 1 print(word_freq)
37edc4cb5cf76bb72b008ae6fd73d227f74cc59a
byteford/cx-interview-questions
/shopping_basket/shopping_basket/offers.py
2,514
3.796875
4
from . import utility #To be implemented by other offers to add diffrent funcionality with each offer class offer(): _multi = False #sets up the offer def __init__(self, **kwargs): pass #returns a float of the discount def discount(self,**kwargs): pass #returns if the offer is for multiple products or just one type def isMulti(self): return self._multi #for offers where you get an amount for the pice of a diffrent amount, ie 3 for 2 class xfory(offer): _x = _y = 0 #kwargs = (x:int,y:int) #x being the amount needed for the discount and the y being the amout the customor pays for. #ie. 3 for 2 , x would be 3 and y would be 2 def __init__(self, **kwargs): self._x = kwargs["x"] self._y = kwargs["y"] self._multi = False #kwargs = (amount:int,cost:float) #amount is the amount being bought #cost is cost per item #returns a float def discount(self, **kwargs): amount = kwargs["amount"] cost = kwargs["cost"] dif = (self._x-self._y) saving = amount / self._x return round(int(saving) *(cost*dif),2) class percent(offer): _percent = 0 #kwarfgs = percent:int #percent is a whole number > 0 def __init__(self, **kwargs): self._percent = kwargs["percent"] self._multi = False #kwargs = (amount:int,cost:float) #amount is the amount being bought #cost is cost per item #returns a float def discount(self, **kwargs): amount = kwargs["amount"] cost = kwargs["cost"] saving = cost * (self._percent /100) return round(saving*amount,2) class buyxGetCheap(offer): _amount = 0 #kwarfgs = amount:int #amount if how many to get one free def __init__(self, **kwargs): self._amount = kwargs["amount"] self._multi = True #works out whats the most amount of money the could be saved #kwargs = (catalog:Dict[string, float] (name, cost),items:Dict[string,int] (name, amount)) #returns a float def discount(self,**kwargs): arr = [] discount = 0 cat = kwargs["catalog"] items= kwargs["items"] totalAmount = sum(items.values()) if(totalAmount< self._amount): return 0 amountFree = int(totalAmount/self._amount) arr = utility.sortItems(cat, utility.DicToList(items)) for i in range(amountFree): discount += cat[arr[i*self._amount+self._amount-1]] return discount
54cdd55e67935f57596fe4d3c2945b504e665daf
Bladesmc/python-calculator
/factorial.py
268
3.875
4
def main(): print "the number of possible arrangements for a deck of cards is:\n" + str(factorial(52)) def factorial(n): if n < 1: return 1 else: rN = n*factorial(n-1) return rN if __name__ == "__main__": main()
1c77967940f1f8b17e50f4f2632fb34a13b3daf0
sweetysweat/EPAM_HW
/homework1/task2.py
692
4.15625
4
""" Given a cell with "it's a fib sequence" from slideshow, please write function "check_fib", which accepts a Sequence of integers, and returns if the given sequence is a Fibonacci sequence We guarantee, that the given sequence contain >= 0 integers inside. """ from typing import Sequence def check_fibonacci(data: Sequence[int]) -> bool: seq_len = len(data) fib1 = 0 fib2 = 1 if seq_len == 0 or seq_len == 1: return False if data[0] == 0 and data[1] == 1: for i in range(2, seq_len): fib1, fib2 = fib2, fib1 + fib2 if not fib2 == data[i]: return False return True else: return False
d10cd2ab04df7e4720f72bf2f5057768e8bfad3f
sweetysweat/EPAM_HW
/homework8/task_1.py
1,745
4.21875
4
""" We have a file that works as key-value storage, each line is represented as key and value separated by = symbol, example: name=kek last_name=top song_name=shadilay power=9001 Values can be strings or integer numbers. If a value can be treated both as a number and a string, it is treated as number. Write a wrapper class for this key value storage that works like this: storage = KeyValueStorage('path_to_file.txt') that has its keys and values accessible as collection items and as attributes. Example: storage['name'] # will be string 'kek' storage.song_name # will be 'shadilay' storage.power # will be integer 9001 In case of attribute clash existing built-in attributes take precedence. In case when value cannot be assigned to an attribute (for example when there's a line 1=something) ValueError should be raised. File size is expected to be small, you are permitted to read it entirely into memory. """ import re from typing import Union class KeyValueStorage: def __init__(self, path: str): self.storage = dict() self.create_class_attributes(path) def create_class_attributes(self, path: str): with open(path, 'r') as f: for line in f: key, value = line.strip().split('=') if not re.search(r'^[a-zA-z_][\w]*$', key, re.ASCII): raise ValueError("The key can only contain ASCII symbols and can't starts with numbers!") value = int(value) if value.isdigit() else value self.storage[key] = value def __getattr__(self, attr_name: str) -> Union[str, int]: return self.storage[attr_name] def __getitem__(self, attr_name: str) -> Union[str, int]: return self.storage[attr_name]
e13c26d81818de3cf64ed616d2371ae084552d4e
sweetysweat/EPAM_HW
/homework2/task5.py
933
4
4
""" Some of the functions have a bit cumbersome behavior when we deal with positional and keyword arguments. Write a function that accept any iterable of unique values and then it behaves as range function: assert = custom_range(string.ascii_lowercase, 'g') == ['a', 'b', 'c', 'd', 'e', 'f'] assert = custom_range(string.ascii_lowercase, 'g', 'p') == ['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'] assert = custom_range(string.ascii_lowercase, 'p', 'g', -2) == ['p', 'n', 'l', 'j', 'h'] """ from typing import Any, Iterable, List def custom_range(iterable: Iterable, start, stop=None, step=1) -> List[Any]: result = [] start = iterable.index(start) if stop is None: for i in range(0, start, step): result.append(iterable[i]) return result else: stop = iterable.index(stop) for i in range(start, stop, step): result.append(iterable[i]) return result
1606b576295949aba9086faa032f3f551f804029
xzhacker123/JsonTools
/json_utils/run_new.py
3,513
3.5625
4
# -*- coding: utf8 -*- __author__ = 'Alex.xu' import sys class Stack(): def __init__(self): self.stack = [] self.top = -1 def push(self, x): self.stack.append(x) self.top = self.top + 1 def pop(self): '''''' if self.is_empty(): raise exception("stack is empty") else: self.top = self.top - 1 self.stack.pop() def is_empty(self): return self.top == -1 def peek(self): ''' :return:栈顶元素 ''' if self.stack is not []: return self.stack[self.top] else: return None class Bracket(): @classmethod def is_right_bracket(self, ch): ''' 判断是否为右括号 :return: boolean ''' # if ch == ')' or ch == ']' or ch == '}': if ch == '}': return True; else: return False; @classmethod def is_left_bracket(self, ch): ''' 判断是否为左括号 :return: boolean ''' # if ch == '(' or ch == '[' or ch == '{': if ch == '{': return True; else: return False; @classmethod def is_peek(self, peek, c): # brackets = ['{', '[', '(', ')', ']', '}'] brackets = ['{', '}'] temp = 0 for i in brackets[len(brackets)/2:]: if c == i: if peek == brackets[temp]: return True temp += 1 return False def substr(str, start, end): return str[str.index(start) + len(start):str.index(end, str.index(start))] def getPeek(str, flag=None): ''' 返回字符串指定括号匹配内容 :param flag: :return: ''' s = Stack() temp = False start = 0 for index, c in enumerate(str): if Bracket.is_left_bracket(c): if temp is False: start = index temp = True s.push(c) elif Bracket.is_right_bracket(c): if s.is_empty(): raise exception("peek fail!") elif Bracket.is_peek(s.peek(), c) is not None: s.pop() if temp is True:# if s.is_empty(): return str[start:index+1] def my_split(flag, s): ''' 分割字符串,不分割${}里面的 :param flag: 根据什么字符分割 :param s: 要分割的字符串 :return: ''' data = s.split(flag) a = [] stack = Stack() temp = '' for d in data: if stack.is_empty(): temp += d else: temp = temp+','+d if '${' in d or not stack.is_empty(): # temp = ',' + d for c in d: if Bracket.is_left_bracket(c): stack.push(c) elif Bracket.is_right_bracket(c): if stack.is_empty(): raise exception("peek fail!") elif Bracket.is_peek(stack.peek(), c) is not None: stack.pop() if stack.is_empty(): a.append(temp) temp = '' else: a.append(d) temp = '' return a if __name__ == "__main__": s = '${ab,c[]},b,c,d,${a,b,c,d}abc,${[a,b,c,d]},' for i in my_split(',', s): print i
dee8d17c68e2dc2e4e7514efab1cbfc6012bbbd8
BasilArackal/TCSCodeVita
/CodeVita2016/Round1/CodeVita2016-2/solns/c.py
322
3.78125
4
def funk(mom): totSweets = 0 for no in mom: totSweets = totSweets + int(no) return totSweets def countThree(mom): count = 0 for no in mom: if(int(no)%3==0): count = count + 1 return count+1 n = int(input()) mom = input().split() if(funk(mom)%3==0): print("Yes " + str(countThree(mom))) else: print("No")
0682dad3b4bf3825a68203cfba3e44dac8717bf9
BasilArackal/TCSCodeVita
/CodeVita2016/Round1/CodeVita2016-2/solns/b.py
207
3.578125
4
import math def nCr(n,r): f = math.factorial return f(n) / f(r) / f(n-r) N, K = input().split() N= int(N) K = int(K) res = 0 for k in range(0, K+1, 2): res = res + int(nCr(N,k)) print( str(res) )
9c77241329e3d8e15dfdafb978272844f1697b0d
AT-Fieldless/python
/daily_exercise/0011.py
463
3.734375
4
# -*- coding: utf-8 -*- # 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。 s = set() def define(): file = open("filtered_words.txt") for eachline in file: s.add(eachline.rstrip('\n')) if __name__ == '__main__': define() temp = raw_input() if temp in s: print 'Freedom' else: print 'Human Rights'
4209cfd3b879e1c02531a7e8dae52dee26d2cce0
bahadirsensoz/PythonCodes
/fahrenheit.py
266
4.28125
4
while(True): print("CELSIUS TO FAHRENHEIT CONVERTER") celsius = float(input("Please enter your degree by celcius:")) #Ali Bahadır Şensöz fahr=1.8*celsius+32 print("Your temperature " +str(celsius) + " Celsius is " +str(fahr) + " in Fahrenheit.")
d8aa4ae8c2cee23df820c18d73109975a079a027
EmilioMuniz/ops-401d2-challenges
/class42.py
1,870
3.6875
4
#!/usr/bin/env python3 # Script: ops-401d2-challenge-class42.py # Author: Emilio Muniz # Date of latest revision: 6/02/2021 # Purpose: Attack tools Part 2 of 3. # Import libraries: import nmap # Declare variables: scanner = nmap.PortScanner() print("Nmap Automation Tool") print("--------------------") ip_addr = input("IP address to scan: ") print("The IP you entered is: ", ip_addr) type(ip_addr) resp = input("""\nSelect scan to execute: 1) SYN ACK Scan 2) UDP Scan 3) OPEN PORT Scan \n""") ### TODO: Select what your third scan type will be print("You have selected option: ", resp) range = '1-50' ### TODO: Prompt the user to type in a port range for this tool to scan port_scanner = input("Enter a port range to scan: ") print("The port range is: ", port_scanner) if resp == '1': print("Nmap Version: ", scanner.nmap_version()) scanner.scan(ip_addr, range, '-v -sS') print(scanner.scaninfo()) print("Ip Status: ", scanner[ip_addr].state()) print(scanner[ip_addr].all_protocols()) print("Open Ports: ", scanner[ip_addr]['tcp'].keys()) elif resp == '2': print("Nmap Version: ", scanner.nmap_version()) scanner.scan(ip_addr, range, '-v -sS') print(scanner.scaninfo()) print("Ip Status: ", scanner[ip_addr].state()) print(scanner[ip_addr].all_protocols()) print("Open Ports: ", scanner[ip_addr]['tcp'].keys()) elif resp == '3': print("Nmap Version: ", scanner.nmap_version()) scanner.scan(ip_addr, range, '-v -sS') print(scanner.scaninfo()) print("Ip Status: ", scanner[ip_addr].state()) print(scanner[ip_addr].all_protocols()) print("Open Ports: ", scanner[ip_addr]['tcp'].keys()) elif resp >= '4': print("Please enter a valid option")
9508589a5b285805d6cc8d80d6c3a8a7732b3dc0
bangdasun/leetcode-bangdasun
/2017/Algorithms/252-easy-MeetingRooms.py
1,032
3.9375
4
""" LeetCode 252 Easy Meeting Rooms Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. For example, Given [[0, 30],[5, 10],[15, 20]], return false. """ def meeting_rooms(intervals): """ Sort the meetings by start time, then compare the last meeting's end time and next meeting's start time Parameters ---------- intervals: list of interval [start_time, end_time] Return ------ True / False """ lst = intervals.copy() if not lst or len(lst) == 0: return False # sort by the start time, this would take O(nlogn) time lst.sort() end = lst[0][1] for it in lst[1:]: # compare the start time of next meeting with the end time of current meeting if it[0] < end: return False end = max(end, it[1]) return True # test intervals = [[0, 13], [5, 10], [15, 20]] meeting_rooms(intervals)
50e50015e425e4ba5a924775ded68b79cba31edc
sawall/advent2017
/advent_6.py
2,729
4.21875
4
#!/usr/bin/env python3 # memory allocation # #### part one # # The debugger would like to know how many redistributions can be done before a blocks-in-banks # configuration is produced that has been seen before. # # For example, imagine a scenario with only four memory banks: # # The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen # for redistribution. # Starting with the next bank (the fourth bank) and then continuing to the first bank, the second # bank, and so on, the 7 blocks are spread out over the memory banks. The fourth, first, and second # banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 # 1 2. # Next, the second bank is chosen because it contains the most blocks (four). Because there are four # memory banks, each gets one block. The result is: 3 1 2 3. # Now, there is a tie between the first and fourth memory banks, both of which have three blocks. # The first bank wins the tie, and its three blocks are distributed evenly over the other three # banks, leaving it with none: 0 2 3 4. # The fourth bank is chosen, and its four blocks are distributed such that each of the four banks # receives one: 1 3 4 1. # The third bank is chosen, and the same thing happens: 2 4 1 2. # At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite # loop is detected after the fifth block redistribution cycle, and so the answer in this example is # 5. # # Given the initial block counts in your puzzle input, how many redistribution cycles must be # completed before a configuration is produced that has been seen before? def day6(): inp = '4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5' memory = [int(i) for i in inp.strip().split()] past_states = [] num_banks = len(memory) cycles = 0 while (hash(tuple(memory)) not in past_states): past_states.append(hash(tuple(memory))) realloc_blocks = max(memory) realloc_cursor = memory.index(max(memory)) memory[realloc_cursor] = 0 while realloc_blocks > 0: realloc_cursor += 1 memory[(realloc_cursor) % num_banks] += 1 realloc_blocks -= 1 cycles += 1 print('-= advent of code DAY SIX =-') print(' part one: total cycles until loop detected = ' + str(cycles)) #### part two # # Out of curiosity, the debugger would also like to know the size of the loop: starting from a state # that has already been seen, how many block redistribution cycles must be performed before that # same state is seen again? loop_start = past_states.index(hash(tuple(memory))) print(' part two: loop size = ' + str(cycles - loop_start)) day6()
3f20d400e5da5a21660eda19a5cb456888367074
Kevinskwk/ILP
/Midterm/Midterm-Ma Yuchen-2.py
174
3.703125
4
i=1 a=0 b=1 while b<=10**999: a,b=b,a+b i+=1 print ("The "+str(i)+"th term is the first term to have 1000 digits.\n") print ("The number is:\n"+str(b))
65c1080bcbaf60e4d4bfab7d33d8f18a796dd42d
Kevinskwk/ILP
/week3/week3 6.py
227
3.609375
4
lista=[1,2,3,4,5,6,7,8,8] l=len(lista) n=False for x in range(l): for y in range(l): if x!=y and lista[y]==lista[x]: n=True if n==True: print ('Yes') else: print('No')
b7254172d3a752293aa0314c38e5f627509ebc67
aymhh/School
/conditional-statements/numberSeries.py
814
3.984375
4
import time x = input("What number do you want to start the count from?\n") while not x.isnumeric(): x = input("That is not a number...\nWhat number do you want to start the count from?\n") xInt = int(x) y = input("What number do you want to end the count on?\n") while not y.isnumeric(): y = input("What number do you want to end the count on?\n") yInt = int(y) + 1 numberRange = list(range(xInt, yInt)) print("calculating...") time.sleep(1) evenNumbers = [] oddNumbers = [] for calculatedNumbers in numberRange: if(calculatedNumbers%2 == 0): evenNumbers.append(calculatedNumbers) else: oddNumbers.append(calculatedNumbers) print(evenNumbers) print(f"Number of even numbers: {str(len(evenNumbers))}") print(oddNumbers) print(f"Number of odd numbers: {str(len(oddNumbers))}")
910db0a0156d0f3c37e210ec1931fd404f1357e9
aymhh/School
/Holiday-Homework/inspector.py
1,095
4.125
4
import time print("Hello there!") print("What's your name?") name = input() print("Hello there, " + name) time.sleep(2) print("You have arrived at a horror mansion!\nIt's a large and spooky house with strange noises coming from inside") time.sleep(2) print("You hop out of the car and walk closer...") time.sleep(2) print("You tread carefully onto the rotten woodpath porch.") time.sleep(2) print("You trip over a loose plank of wood and fall over") time.sleep(2) print("Your knee hurts. But you notice something under the porch...") time.sleep(2) print("It's a box...") time.sleep(2) print("Inside it was a blooded hand!") time.sleep(2) print("You wonder wether to go inside or leave...") question = input("What is your next move?\n - Type in `inside` to go inside the house\n - Type in `leave` to leave away!\n") if question == "inside": print("you pick yourself up and head inside the house and only to be greated with a mysterious character, the door slams behind you and you are trapped!") if question == "leave": print("you rush back into your car and drift away, very far!")
24d025d8a89380a8779fbfdf145083a9db64fc07
shahad-mahmud/learning_python
/day_16/unknow_num_arg.py
324
4.15625
4
def sum(*nums: int) -> int: _sum = 0 for num in nums: _sum += num return _sum res = sum(1, 2, 3, 5) print(res) # Write a program to- # 1. Declear a funtion which can take arbitary numbers of input # 2. The input will be name of one or persons # 3. In the function print a message to greet every one
78c20cf1465a7b633372c8635ae011b2d2db84df
shahad-mahmud/learning_python
/day_3/even_odd.py
151
4.40625
4
# even if -> number % 2 == 0 number = int(input('Enter a number: ')) if number % 2 == 1: print('Odd') else: print('Even') # -3 / 2 = -2, 1
c20d7062f3a08c081d7c38a35da3963ef553421e
shahad-mahmud/learning_python
/day_5/tricks.py
109
3.890625
4
while True: number = int(input('Enter a number (-1 to stop): ')) if number == -1: break
b7109f030f7149817c937e569dd19a58fbeda29e
shahad-mahmud/learning_python
/day_14/uri_1013.py
525
3.640625
4
def max_num(a, b): if a > b: return a return b def abs(x): if x >= 0: return x return -x inp = input() inp = inp.split() a, b, c = int(inp[0]), int(inp[1]), int(inp[2]) m_num = max_num(a, max_num(b, c)) # s_m = max_num(b, c) if m_num == a else max_num( # c, a) if m_num == b else max_num(a, b) if m_num == a: s_m = max_num(b, c) elif m_num == b: s_m = max_num(c, a) else: s_m = max_num(a, b) res = (m_num + s_m + abs(m_num - s_m)) / 2 print(f"{int(res)} eh o maior")
382a8a2f5c64f0d3cd4c1c647b97e19e2c137fda
shahad-mahmud/learning_python
/day_3/if.py
417
4.1875
4
# conditional statement # if conditon: # logical operator # intendation friend_salary = float(input('Enter your salary:')) my_salary = 1200 if friend_salary > my_salary: print('Friend\'s salary is higher') print('Code finish') # write a program to- # a. Take a number as input # b. Identify if a number is positive # sample input 1: 10 # sample output 1: positive # sample inout 2: -10 # sample output:
ec55765f79ce87e5ce0f108f873792fecf5731f6
shahad-mahmud/learning_python
/day_7/python_function.py
347
4.3125
4
# def function_name(arguments): # function body def hello(name): print('Hello', name) # call the funciton n = 'Kaka' hello(n) # Write a program to- # a. define a function named 'greetings' # b. The function print 'Hello <your name>' # c. Call the function to get the message # d. Modify your function and add a argument to take your name
f26bfae29250589012708c5fbee61d598acc3e02
rewatevijaykumar/python-webscrap-beautifulsoup
/deadly-earthquake.py
1,106
3.59375
4
# Web Scrapping Using BeautifulSoup # List of deadly earthquakes since 1900 from bs4 import BeautifulSoup import requests url = 'https://en.wikipedia.org/wiki/List_of_deadly_earthquakes_since_1900' r = requests.get(url) html_content = r.text html_soup = BeautifulSoup(html_content, 'html.parser') earthquakes_table = html_soup.find_all('table', class_='wikitable') earthquakes = [] for table in earthquakes_table: headers = [] rows = table.find_all('tr') for header in table.find('tr').find_all('th'): headers.append(header.text) for row in table.find_all('tr')[1:]: values = [] for col in row.find_all(['th','td']): values.append(col.text) if values: earthquake_dict = {headers[i]: values[i] for i in range(len(values))} earthquakes.append(earthquake_dict) for earthquake in earthquakes: print(earthquake) print(len(earthquakes)) import pandas as pd df = pd.DataFrame.from_dict(earthquakes) df.head() df.columns df.info() df.to_csv('deadly_earthquake.csv', index=False)
b0824befae2b1d672ac6ec693f97e7c801366c0c
srinivasdasu24/regular_expressions
/diff_patterns_match.py
1,534
4.53125
5
""" Regular expression basics, regex groups and pipe character usage in regex """ import re message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.' phoneNum_regex = re.compile( r'\d\d\d-\d\d\d-\d\d\d\d') # re.compile to create regex object \d is - digit numeric character mob_num = phoneNum_regex.search(message) # print(phoneNum_regex.findall(message)) # findall returns a list of all occurences of the pattern print(mob_num.group) # regex object has group method which tells the matching pattern # pattern with different groups - groups are created in regex strings using parentheses phoneNum_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') # this pattern will have twwo groups mob_num = phoneNum_regex.search(message) mob_num.group() # gives entire match mob_num.group(1) # gives first 3 digits 1 is first set of parentheses , 2 is second and so on mob_num.group(2) # gives remaining pattern # o/p is : '415-555-1011' # :'415' # : '555-1011' # pattern with matching braces( () ) phoneNum_regex = re.compile(r'\(\d\d\d\) \d\d\d-\d\d\d\d') mo = phoneNum_regex.search('My number is (415) 555-4243') mo.group() # o/p is : '(415) 555-4243 # matching multiple patterns bat_regx = re.compile(r'Bat(man|mobile|copter|bat)') # pipe | symbol used to match more than one pattern mo = bat_regx.search('I like Batman movie') mo.group() # o/p is 'Batman' # if search method doesn't find pattern it returns None mo = bat_regx.search('Batmotorcycle lost a wheel') mo == None # prints True
9d422749ea092c68345a08d83a7d6f49878d4a36
missile777/learning
/lesson2.py
447
3.828125
4
import unittest def reverse(n: list): # do this function return list(reversed(n)) class TestListMethod(unittest.TestCase): def test_get_reverse1(self): nums = [10, 20, 40, 80] self.assertListEqual(reverse(nums), [80, 40, 20, 10]) def test_get_reverse2(self): nums = [10, 20, 40, 40, 80] self.assertListEqual(reverse(nums), [80, 40, 40, 20, 10]) if __name__ == '__main__': unittest.main()
100afd225a0be3eb88af57181652a24805db3080
igor-rufino/C214-unittest
/tests/test_lances.py
2,354
3.5
4
import unittest from src.dominio import Cliente, Lance, Leilao class TestLances(unittest.TestCase): def setUpClass(): # SetUp antes de todos os testes da classe pass def setUp(self): # SetUp antes de cada testes da classe self.phyl = Cliente("Phyl") self.lance_do_phyl = Lance(self.phyl, 150.0) self.leilao = Leilao("1 Saco de Arroz de 5kg") def test_maior_e_menor_valor_de_um_lance_quando_adicionados_ordem_crescente(self): igor = Cliente("Igor") lance_do_igor = Lance(igor, 100.0) self.leilao.propoe(lance_do_igor) self.leilao.propoe(self.lance_do_phyl) menor_valor_esperado = 100.0 maior_valor_esperado = 150.0 self.assertEqual(menor_valor_esperado, self.leilao.menor_lance) self.assertEqual(maior_valor_esperado, self.leilao.maior_lance) def test_maior_e_menor_valor_de_um_lance_quando_adicionados_ordem_decrescente(self): luana = Cliente("Luana") lance_do_luana = Lance(luana, 80.0) self.leilao.propoe(self.lance_do_phyl) self.leilao.propoe(lance_do_luana) menor_valor_esperado = 80.0 maior_valor_esperado = 150.0 self.assertEqual(menor_valor_esperado, self.leilao.menor_lance) self.assertEqual(maior_valor_esperado, self.leilao.maior_lance) def test_mesmo_valor_para_o_maior_e_menor_lance_quando_leilao_tiver_um_lance(self): self.leilao.propoe(self.lance_do_phyl) self.assertEqual(150.0, self.leilao.menor_lance) self.assertEqual(150.0, self.leilao.maior_lance) def test_maior_e_menor_valor_quando_o_leilao_tiver_tres_lances(self): igor = Cliente("Igor") lance_do_igor = Lance(igor, 10.0) sarah = Cliente("Sarah") lance_da_sarah = Lance(sarah, 200.0) self.leilao.propoe(lance_do_igor) self.leilao.propoe(self.lance_do_phyl) self.leilao.propoe(lance_da_sarah) menor_valor_esperado = 100.0 maior_valor_esperado = 200.0 self.assertEqual(menor_valor_esperado, self.leilao.menor_lance) self.assertEqual(maior_valor_esperado, self.leilao.maior_lance) def tearDown(self): # TearDown depois de cada teste pass def tearDownClass(): # TearDown depois de todos os testes da classe pass
f14563d83628511d21cd06a2d8799f8405549747
asya5/code-analyse-klas-1e
/no.py
795
3.625
4
#does the user give an input to num? #assignment analyse case 1 to 5 checked and correct #CASE 1 num = 123456786 x = [int(a) for a in str(num)] n = x.pop() z = (sum(x)) if z%10== n: print('VALID') else: print ('INVALID') #CASE 2 num = 123456789 x = [int(a) for a in str(num)] n = x.pop() z = (sum(x)) if z%10== n: print('VALID') else: print ('INVALID') #CASE 3 num = 123 x = [int(a) for a in str(num)] n = x.pop() z = (sum(x)) if z%10== n: print('VALID') else: print ('INVALID') #CASE 4 num = 321 x = [int(a) for a in str(num)] n = x.pop() z = (sum(x)) if z%10== n: print('VALID') else: print ('INVALID') #CASE 5 num = 12 x = [int(a) for a in str(num)] n = x.pop() z = (sum(x)) if z%10== n: print('VALID') else: print ('INVALID')
3865e404fdf198c9b8a6cb674783aa58af2c8539
rehul29/QuestionOfTheDay
/Question8.py
561
4.125
4
# minimum number of steps to move in a 2D grid. class Grid: def __init__(self, arr): self.arr = arr def find_minimum_steps(self): res = 0 for i in range(0, len(self.arr)-1): res = res + self.min_of_two(self.arr[i], self.arr[i+1]) print("Min Steps: {}".format(res)) def min_of_two(self, first, second): x1, y1 = first x2, y2 = second return max(abs(x2-x1), abs(y2-y1)) if __name__ == "__main__": arr = [(0,0),(1,1),(1,2)] sol = Grid(arr) sol.find_minimum_steps()
0a95bf073d27303f600b76a53cb2ad616a757407
hamiltonmneto/College
/Pesquisa_Ordenação_de_Dados/selection_sort.py
615
3.75
4
def select_max(A, left, right): max_pos = left i=left while i<= right: if A[i] > A[max_pos]: max_pos = i i = i + 1 return max_pos def selection_sort(A): for i in range (len(A) - 1, 0, -1): max_pos = select_max(A,0,i) if max_pos !=i: tmp = A[i] A[i] = A[max_pos] A[max_pos] = tmp print (i,A) sequence = [12,4,3,20,6] selection_sort(sequence) def best_case(n): r = range(n) return list(r) def worst_case(n): r = rage(n) array = list(r) return array[:: - 1] worst_case(5)
5b8c4351f132c0695d521ed31ede600e6689d453
sfyc23/KotlinWeeklyBuilder
/common/add_spaces.py
1,309
3.75
4
import sys import functools # Some characters should not have space on either side. def allow_space(c): ''' :param c: str :return: Bool True 允许加空格,False 不允许加空格 ''' return not c.isspace() and not (c in ',。;「」:《》『』、[]()*_') def is_latin(c): ''' 判断是否为英文字符,或者是数字 :param c: str :return: Bool True 允许加空格,False 不允许加空格 ''' return ord(c) < 256 def add_space_at_boundry(prefix, next_char): ''' 通过前后字符判断,是否加上空格 :param prefix: str 前面的字符 :param next_char: str 后面的一个字符 :return:str 返回当前位置已加空格(或不加)的 str ''' if not prefix: return next_char if is_latin(prefix[-1]) != is_latin(next_char) and allow_space(next_char) and allow_space(prefix[-1]): return prefix + ' ' + next_char else: return prefix + next_char def add_space(str_): ''' 为中英文之间加中空格。 :param c: srt 文字 :return: str 已处理的文字 ''' outstr = functools.reduce(add_space_at_boundry, str_, '') return outstr if __name__ == '__main__': TEXT_HELLO = "I'm Chin中e牛se" print(add_space(TEXT_HELLO))
6bb8df8f913d958ec9f6d4d18972cba9c1b53dfb
hashmand/Python_Programs
/Tkinter GUI Program/Login.py
792
3.671875
4
import tkinter as tk from tkinter import messagebox def hello(): l1 = tk.Label(win, bg="yellow",text=msg, width=20) l1.place(x = 50, y = 250) win = tk.Tk() win.geometry("500x500+50+50") l2 = tk.Label(win, bg="yellow",text="username", width=20) l2.place(x = 50, y = 50) l3 = tk.Label(win, bg="yellow",text="password", width=20) l3.place(x = 50, y = 100) e1 = tk.Entry(win, bg="yellow",width=20) e1.place(x = 250, y = 50) e2 = tk.Entry(win, bg="yellow",width=20) e2.place(x = 250, y = 100) b1 = tk.Button(win, text = "Login ", command=hello, bg="red", fg="yellow", activebackground="green", width=10) b1.place(x = 70, y = 150) b2 = tk.Button(win, text = "Cancel ", command=hello, bg="red", fg="yellow", activebackground="green", width=10) b2.place(x = 270, y = 150) win.mainloop()
7736a04d75a89f40c01f912cdd8c50b6399243e7
hashmand/Python_Programs
/Tkinter GUI Program/button.py
446
3.671875
4
import tkinter as tk from tkinter import messagebox def hello(): msg = e1.get() l1 = tk.Label(win, bg="yellow",text=msg, width=20) l1.place(x = 50, y = 250) win = tk.Tk() win.geometry("500x500+50+50") e1 = tk.Entry(win, bg="yellow",width=20) e1.place(x = 50, y = 50) b1 = tk.Button(win, text = "Click Me", command=hello, bg="red", fg="yellow", activebackground="green", height=5, width=20) b1.place(x = 50, y = 100) win.mainloop()
525e3c9b48be4b2e2320c38a0712e84e716050a4
hhayoung/python-basic
/day02_print.py
1,020
3.9375
4
# 기본 출력 print('hello python') print("hello python") print() print('''hello python''') print("""hello python""") # saparator 옵션 print('T','E','S','T',sep='/') # separator를 이용해서 TEST 출력 print('T','E','S','T',sep='') # 2020-07-14 출력 print('2020','07','14',sep='-') # test@naver.com print('test','naver.com',sep='@') print('------------- end 옵션 ---------------') # end 옵션의 default 값은 \n print('welcome To',end='\n') print('welcome To',end='') print('Test') # format 사용 print('{} and {}'.format('You','Me')) print('{0} and {1} and {0}'.format('You','Me')) print('{var1} and {var2}'.format(var1='You',var2='Me')) # %d, $f, $s print("%s의 나이는 %d" %('홍길동', int(33))) print('Test1: %5d, Price: %4.2f' %(766,543.123)) print('Test1: {a:5d}, Price: {b:4.2f}'.format(a=766,b=6543.123)) ''' Escape 코드 \n : 개행 \t : xoq \\ : \ \' : ' \" : " ''' print('국어 \t 영어 \t 수학') print('국어 \' 영어 \' 수학')
a9130f9ff185e788be9908f75a0594ec89ebbcbe
missdavid7/LPTHW
/ex5.py
755
3.53125
4
my_name = 'Zed A.Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = int(180) #lbs my_eyes = 'blue' my_teeth = "white" my_hair = "brown" print "Let's talk about %r." % my_name print "He's %r inches tall." % my_height print "He's %d lbs heavy." % my_weight print "Actually that's too heavy." print "He's got %s eyes and %s hair" % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth print "If I add %d, %d, and %d I get %d." %( my_age, my_height, my_weight,my_age+my_weight+my_height) metric_height = my_height * 2.54 metric_weight = my_weight * 0.453592 print "To the rest of the world, %s is %2.2f cm tall." % (my_name, metric_height) print "And they would say he is %2.4f kg heavy." % metric_weight
2b5896a2583a6e84dd7ca815ae87ef3059647f0e
Ashi-s/coding_problems
/FT_Coding/Akuna/almostequivalent.py
1,538
3.515625
4
# def almost(s,t): # if len(s) != len(t): # return ["NO"] # s_d = {} # t_d = {} # for i, j in zip(s,t): # if i not in s_d: # s_d[i] = 1 # else: # s_d[i] += 1 # if j not in t_d: # t_d[j] = 1 # else: # t_d[j] += 1 # print(s_d, t_d) # for i in s_d: # if i not in t_d: # if s_d[i] <= 3: # continue # else: # return ["NO"] # else: # if abs(s_d[i] - t_d[i]) <= 3: # continue # else: # return ["NO"] # for i in t_d: # if i not in s_d and t_d[i] > 3: # return ["NO"] # return ["YES"] def almost(s,t): hash_s = {} hash_t = {} ## Creating Hashmap for S & T for i, j in zip(s,t): if i not in hash_s: hash_s[i] =1 else: hash_s[i] += 1 if j not in hash_t: hash_t[j] = 1 else: hash_t[j] += 1 ## Updating hash_t with the sustraction from hash_s ## if any key not in hash_t then append it in hash_t for i in hash_s: if i in hash_t: hash_t[i] = abs(hash_s[i] - hash_t[i]) else: hash_t[i] = hash_s[i] ## Comparing if each of Hash_t values are upto 3 for i in hash_t: if hash_t[i] <= 3: continue else: return "NO" return "YES" print(almost('aacccdwwjjj', 'abbbddzzkkk'))
639cb33ebaaedf49bc3ae027c66b067d83ed435c
Ashi-s/coding_problems
/FT_Coding/nutanix/primeString.py
826
3.78125
4
import math def isPrime(n): for i in range (2,int(math.sqrt(n))+1): if n%i==0: return False return True def primeString(string): res = [] for i in string: ascii = ord(i) if isPrime(ascii): res.append(i) else: s = True j = ascii k = ascii while s: if isPrime(j-1) and j-1 >= 65: res.append(chr(j-1)) s = False elif isPrime(k+1) and k+1 <= 122: res.append(chr(k+1)) s = False j -= 1 k += 1 return ''.join(res) print(primeString('zex')) # print([ord(c) for c in 'asdkbjhiUHIOubdaiwudblASjhdblIQ']) # print([ord(c) for c in primeString('asdkbjhiUHIOubdaiwudblASjhdblIQ')])
a61490294c12a1362f591338340ca251a09c6f0a
Ashi-s/coding_problems
/DevPost/letterOnlyOccursOnce.py
1,485
3.828125
4
''' Input: "eeeeffff" Output: 1 Why? We can delete one occurence of e or one occurence of 'f'. Then one letter will occur four times and the other three times. Input: "aabbffddeaee" Output: 6 Why: For example, we can delete all occurences of 'e' and 'f' and one occurence of 'd' to obtain the word "aabbda". Note that both 'e' and 'f' will occur zero times in the new word, but that's fine, since we only care about the letter that appear at least once. Input: "llll" Output: 0 Why? There is no need to delete any character. ''' def occursOnlyOnce(string): d = {} l = [] count = 0 for i in string: if i not in d: d[i] = 1 else: d[i] += 1 if len(d) == 1: return 0 aSet = set(d.values()) print(aSet) for key in d: if d[key] in aSet: print(d[key], aSet) aSet.remove(d[key]) l.append(d[key]) #print('l -----', l) else: j = d[key] while j >= 0: if j-1 not in aSet and j-1 not in l: count += 1 if j-1 != 0: aSet.add(j-1) #l.append(j-1) break else: j -= 1 count += 1 print('====', aSet,"li ----", l) print(d, aSet) return count #print(d,val) print(occursOnlyOnce('aabbffddeaee'))
568f7b406b12c5d04875290d51d3da935ddf8801
kaitlynning/String-Concatenating
/0229.py
1,125
3.953125
4
row =int(input('Insert num: ')) for i in range(row): for _ in range(i + 1): #end=add space no newline print('*', end = '') #wrap text print() for i in range(row): for j in range(row): if j < row -i - 1: print(' ', end = '') else: print('*', end = '') print() for i in range(row): for j in range(row): if j < row -i - 1: print('', end = ' ') else: print('*', end = ' ') print() for i in range(row): for j in range(row): if j <= i - 1: print('', end = ' ') else: print('*', end = ' ') print() for i in range(row): for _ in range(row - i - 1): print(' ', end = '') for _ in range(i*2 + 1): print('*', end = '') print() ''' Insert num: 8 * ** *** **** ***** ****** ******* ******** * ** *** **** ***** ****** ******* ******** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *** ***** ******* ********* *********** ************* *************** '''
06a6612ce00ab2fb58911d9e06ab1f3a39f07021
Rohika379/-Ridge-Regression-and-Lasso-Regression
/computer new.py
7,969
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 13 20:41:32 2021 @author: USER """ import pandas as pd #loading the dataset computer = pd.read_csv("D:/BLR10AM/Assi/25.lasso ridge regression/Datasets_LassoRidge/Computer_Data (1).csv") #2. Work on each feature of the dataset to create a data dictionary as displayed in the below image #######feature of the dataset to create a data dictionary #######feature of the dataset to create a data dictionary description = ["Index row number (irrelevant ,does not provide useful Informatiom)", "Price of computer(relevant provide useful Informatiom)", "computer speed (relevant provide useful Informatiom)", "Hard Disk space of computer (relevant provide useful Informatiom)", "Random axis momery of computer (relevant provide useful Informatiom)", "Screen size of Computer (relevant provide useful Informatiom)", "Compact dist (relevant provide useful Informatiom)", "Multipurpose use or not (relevant provide useful Informatiom)", "Premium Class of computer (relevant provide useful Informatiom)", "advertisement expenses (relevant provide useful Informatiom)", "Trend position in market (relevant provide useful Informatiom)"] d_types =["Count","Ratio","Ratio","Ratio","Ratio","Ratio","Binary","Binary","Binary","Ratio","Ratio"] data_details =pd.DataFrame({"column name":computer.columns, "data types ":d_types, "description":description, "data type(in Python)": computer.dtypes}) #3. Data Pre-computercessing #3.1 Data Cleaning, Feature Engineering, etc #details of computer computer.info() computer.describe() #droping index colunms computer.drop(['Unnamed: 0'], axis = 1, inplace = True) #dummy variable creation from sklearn.preprocessing import LabelEncoder LE = LabelEncoder() computer['cd'] = LE.fit_transform(computer['cd']) computer['multi'] = LE.fit_transform(computer['multi']) computer['premium'] = LE.fit_transform(computer['premium']) #data types computer.dtypes #checking for na value computer.isna().sum() computer.isnull().sum() #checking unique value for each columns computer.nunique() """ Exploratory Data Analysis (EDA): Summary Univariate analysis Bivariate analysis """ EDA ={"column ": computer.columns, "mean": computer.mean(), "median":computer.median(), "mode":computer.mode(), "standard deviation": computer.std(), "variance":computer.var(), "skewness":computer.skew(), "kurtosis":computer.kurt()} EDA # covariance for data set covariance = computer.cov() covariance # Correlation matrix co = computer.corr() co # according to correlation coefficient no correlation of Administration & State with model_dffit #According scatter plot strong correlation between model_dffit and rd_spend and #also some relation between model_dffit and m_spend. ####### graphicomputer repersentation ##historgam and scatter plot import seaborn as sns sns.pairplot(computer.iloc[:, :]) #boxplot for every columns computer.columns computer.nunique() computer.boxplot(column=['price','ads', 'trend']) #no outlier #for imputing HVO for Price column """ # here we can see lVO For Price # Detection of outliers (find limits for RM based on IQR) IQR = computer['Price'].quantile(0.75) - computer['Price'].quantile(0.25) upper_limit = computer['Price'].quantile(0.75) + (IQR * 1.5) ####################### 2.Replace ############################ # Now let's replace the outliers by the maximum and minimum limit #Graphical Representation import numpy as np import matplotlib.pyplot as plt # mostly used for visualization purposes computer['Price']= pd.DataFrame( np.where(computer['Price'] > upper_limit, upper_limit, computer['Price'])) import seaborn as sns sns.boxplot(computer.Price);plt.title('Boxplot');plt.show()""" # Q-Q Plot from scipy import stats import pylab import matplotlib.pyplot as plt stats.probplot(computer.price, dist = "norm", plot = pylab) plt.show() stats.probplot(computer.ads, dist = "norm", plot = pylab) plt.show() stats.probplot(computer.trend, dist = "norm", plot = pylab) plt.show() #normal # Normalization function using z std. all are continuous data. def norm_func(i): x = (i-i.mean())/(i.std()) return (x) # Normalized data frame (considering the numerical part of data) df_norm = norm_func(computer.iloc[:,[1,2,3,4,8,9]]) df_norm.describe() """ from sklearn.preprocessing import OneHotEncoder # creating instance of one-hot-encoder enc = OneHotEncoder(handle_unknown='ignore') sta=computer.iloc[:,[3]] enc_df = pd.DataFrame(enc.fit_transform(sta).toarray())""" # Create dummy variables on categorcal columns enc_df = computer.iloc[:,[5,6,7]] model_df = pd.concat([computer.iloc[:,[0]],enc_df, df_norm ], axis =1) """5. Model Building 5.1 Build the model on the scaled data (try multiple options) 5.2 Perform Multi linear regression model and check for VIF, AvPlots, Influence Index Plots. 5.3 Train and Test the data and compare RMSE values tabulate R-Squared values , RMSE for different models in documentation and model_dfvide your explanation on it. 5.4 Briefly explain the model output in the documentation. """ ################################## ###LASSO MODEL### import numpy as np from sklearn.linear_model import Lasso lasso = Lasso(alpha = 0.7, normalize = True) #model building lasso.fit(model_df.iloc[:, 1:], model_df.price) # coefficient values for all independent variables# lasso.coef_ lasso.intercept_ plt.bar(height = pd.Series(lasso.coef_), x = pd.Series(model_df.columns[1:])) #state columns has lowest coefficent lasso.alpha pred_lasso = lasso.predict(model_df.iloc[:, 1:]) # Adjusted r-square# lasso.score(model_df.iloc[:, 1:], model_df.price) #RMSE np.sqrt(np.mean((pred_lasso -model_df.price)**2)) ##################### #lasso Regression from sklearn.model_selection import GridSearchCV from sklearn.linear_model import Lasso lasso = Lasso() parameters = {'alpha' : [1e-30,1e-38,1e-17,1e-16,1e-15,1e-14,1e-13,1e-12,1e-10,0,40,80]} lasso_reg = GridSearchCV(lasso, parameters , scoring = 'r2' ,cv = 5) lasso_reg.fit(model_df.iloc[:,1:],model_df.price) lasso_reg.best_params_ lasso_reg.best_score_ lasso_pred = lasso_reg.predict(model_df.iloc[:,1:]) #Adjusted R- square lasso_reg.score(model_df.iloc[:,1:],model_df.price) #RMES np.sqrt(np.mean((lasso_pred-model_df.price)**2)) ### RIDGE REGRESSION ### from sklearn.linear_model import Ridge rm = Ridge(alpha = 0.4, normalize = True) rm.fit(model_df.iloc[:, 1:], model_df.price) #coefficients values for all the independent vairbales# rm.coef_ rm.intercept_ plt.bar(height = pd.Series(rm.coef_), x = pd.Series(model_df.columns[1:])) rm.alpha pred_rm = rm.predict(model_df.iloc[:, 1:]) # adjusted r-square# rm.score(model_df.iloc[:, 1:],model_df.price) #RMSE np.sqrt(np.mean((pred_rm - model_df.price)**2)) ##################### #Ridge Regression from sklearn.model_selection import GridSearchCV from sklearn.linear_model import Ridge ridge = Ridge() parameters = {'alpha' : [1e-16,1e-15,1e-14,1e-13,1e-12,1e-11,1e-10,0,40,80]} ridge_reg = GridSearchCV(ridge, parameters , scoring = 'r2' ,cv = 5) ridge_reg.fit(model_df.iloc[:,1:], model_df.price) ridge_reg.best_params_ ridge_reg.best_score_ ridge_pred = ridge_reg.predict(model_df.iloc[:,1:]) #Adjusted R- square ridge_reg.score(model_df.iloc[:,1:], model_df.price) #RMES np.sqrt(np.mean((ridge_pred- model_df.price)**2))
22661986936f2a7479a52080943c1e351903608c
supercatex/Connect4
/Agent.py
5,709
3.53125
4
#!usr/bin/env python import random import copy from GameBoard import GameBoard import numpy as np class Agent(object): def __init__(self, name, player, game): self.name = name self.player = player self.game = game def get_choice(self): return self.game.get_user_input() class RandomAgent(Agent): def get_choice(self): return random.choice(self.game.get_choices()) class OneStepAgent(RandomAgent): def best_choice(self, player): g = copy.deepcopy(self.game) choices = g.get_choices() for c in choices: g.move(c, player) if g.is_winner(c, player): g.moveback() return c g.moveback() return None def get_choice(self): c = self.best_choice(self.player) if c is not None: return c return super().get_choice() class TwoStepAgent(OneStepAgent): def best_choice(self, player): c = super().best_choice(player) if c is not None: return c g = copy.deepcopy(self.game) choices = g.get_choices() for c in choices: g.move(c, player % 2 + 1) if g.is_winner(c, player % 2 + 1): g.moveback() return c g.moveback() return None class NStepAgent(OneStepAgent): def __init__(self, name, player, game, max_depth=3): super(NStepAgent, self).__init__(name, player, game) self.max_depth = max_depth def minmax(self, depth, g, alpha=-9999, beta=9999, is_your_turn=True): if depth == 0: return 0, None if len(g.records) > 0: last_move = g.records[-1][1] if g.is_winner(last_move, g.player % 2 + 1): if not is_your_turn: return 100, None else: return -100, None choices = g.get_choices() random.shuffle(choices) best_choice = None best_val = -9999 if not is_your_turn: best_val = -best_val for c in choices: g.move(c, g.player) g.next_player() val, choice = self.minmax(depth - 1, g, alpha, beta, not is_your_turn) g.moveback() g.next_player() if is_your_turn: if val > best_val: best_val = val best_choice = c alpha = val if beta <= alpha: break else: if val < best_val: best_val = val best_choice = c beta = val if beta <= alpha: break return best_val, best_choice def get_choice(self): v, c = self.minmax(self.max_depth, copy.deepcopy(self.game)) if c is not None: if v == 0: print("Min-Max-Tree(12):", "Nothing") elif v > 0: print("Min-Max-Tree(12):", "I WIN!") else: print("Min-Max-Tree(12):", "Surrender...Human try...") return self.game.get_user_input() return c print("random choice...") return random.choice(self.game.get_choices()) class Action(object): def __init__(self, choice, previous_action=None): self.choice = choice self.previous_action = previous_action self.next_actions: Action = [] self.simulations = 0 self.winners = 0 def get_next_action(self, choice): for na in self.next_actions: if na.choice == choice: return na return None def remove_next_action(self, choice): for na in self.next_actions: if na.choice == choice: self.next_actions.remove(na) break def get_UCT(self, choices): dict = {} t = self.simulations for a in self.next_actions: if a.choice not in choices: continue w = a.winners n = a.simulations if n > 0: uct = w / n + np.sqrt(2 * np.log10(t) / n) else: uct = 0 dict[a.choice] = uct return dict def make_action(self, choice): if self.get_next_action(choice) is None: self.next_actions.append(Action(choice, self)) def __str__(self): s = "" for na in self.next_actions: s += str(na.choice) + " " return s class UCTAgent(RandomAgent): def __init__(self, name, player, game, round=1000): super(UCTAgent, self).__init__(name, player, game) self.current_action = Action(0) self.round = round self.agent = NStepAgent(name, (player + 1) % 2 + 1, game) def random_walk(self, g, depth=0): player = (self.player + depth + 1) % 2 + 1 choices = g.get_choices() if len(choices) == 0: return 0 c = random.choice(choices) self.current_action.make_action(c) self.current_action.simulations += 1 self.current_action = self.current_action.get_next_action(c) g.move(c, player) g.next_player() # self.game.print_board() result = 0 if g.is_winner(c, player): g.moveback() g.next_player() if player == self.player: result = 1 else: result = self.random_walk(g, depth + 1) g.moveback() g.next_player() self.current_action = self.current_action.previous_action self.current_action.winners += result return result def get_choice(self): v, c = self.agent.minmax(6, copy.deepcopy(self.game)) if v != 0: print("Min-Max-Tree:", v) self.current_action.make_action(c) self.current_action = self.current_action.get_next_action(c) return c for i in range(self.round): self.random_walk(copy.deepcopy(self.game)) while True: uct = self.current_action.get_UCT(self.game.get_choices()) if len(uct) == 0: return random.choice(self.game.get_choices()) choice = max(uct, key=uct.get) g = copy.deepcopy(self.game) g.move(choice, self.player) g.next_player() v, c = self.agent.minmax(6, g) if v > 0: print("Min-Max-Tree(6):", "...finding others...") self.current_action.remove_next_action(choice) if len(self.current_action.next_actions) == 0: return random.choice(self.game.get_choices()) elif v < 0: print("Min-Max-Tree(6):", "I WIN!") self.current_action.make_action(choice) self.current_action = self.current_action.get_next_action(choice) return c else: break print("MCTS: %.2f" % uct[choice]) self.current_action = self.current_action.get_next_action(choice) return choice
e4dd34a7234efac3c151931ce62e092ed32fba9f
Ameenakeem/Guess-game
/Guess game.py
1,141
4
4
win = 0 lose = 0 while True: import random comp = random.randint(1,5) choose = int(input("Guess any number 1-5: ")) if comp == 1: print("bot = 1") elif comp == 2: print("bot = 2") elif comp == 3: print("bot = 3") elif comp == 4: print("bot = 4") elif comp == 5: print("bot = 5") if comp == 1 and choose == 1: print("You win") win = +1 elif comp == 2 and choose == 2: print("You win") win = +1 elif comp == 3 and choose == 3: print("You win") win = +1 elif comp == 4 and choose == 4: print("You win") win = +1 elif comp == 5 and choose == 5: print("You win") win = +1 else: print("You lose") lose = +1 print('''(a) Score (b) Continue (c) Quit''') ch = input("Decide please: ") if ch == "a": print("win = ",win," and lose = ",lose,) elif ch == "b": continue elif ch == "c": break else: print("invalid input") exit()
e671a6a094f5e1315c2088294bb2c2b85734d3b6
PisciTec/PP
/PythonBasics-OO/python-twitter-searcher.py
283
3.734375
4
import math def areasquare(lado): return lado**2 print('Alo mundo') numero = [] soma = 0 math.pi soma = float(input("Escreva aqui o quanto você ganha por hora:")) horas = float(input("Escreva aqui o quanto você trabalha em horas:")) print('Esse é o seu salário:',soma*horas)
4bd0e226f38b81ed7c10e9cc30102b6238b63e26
abc8737/python-private-demo
/zhibo8/MySQLPy.py
1,915
3.875
4
# coding=utf-8 ''' Python连接MySQl ''' import pymysql class Python_MySQL(): ''' host:主机名 userName:数据库拥有者 password:数据库登录密码 tableName:数据库名 ''' def __init__(self, host, userName, paassword, tableName): self.host = host self.userName = userName self.password = paassword self.tableName = tableName db = pymysql.connect(self.host, self.userName, self.password, self.tableName) cursor = db.cursor() # self.insertData(cursor, db) self.delData(cursor, db, 4) self.getMySQLData(cursor) self.closeMySQL(db) # 创建数据表 def createTable(self, cursor, db, sql): try: cursor.execute(sql) db.commit() except: print('Error For It') db.rollback() # 查询 def getMySQLData(self, cursor): # sql = "select version()" sql = "select * from java" cursor.execute(sql) all_datas = cursor.fetchall() for data in all_datas: print(u'id=', data[0], u' name=', data[1], u' gender=', data[2], u' age=', data[3]) # 插值 def insertData(self, cursor, db): sql = "insert into java VALUES (4,'Alexis Sanches','male',28)" try: cursor.execute(sql) print('成功添加数据') db.commit() except: print('SQL语句有错误') db.rollback() def delData(self, cursor, db, id): sql = "delete from java where id=" + str(id) try: cursor.execute(sql) print('成功删除数据') db.commit() except: print('删除数据出现错误') db.rollback() # 关闭连接 def closeMySQL(self, db): db.close() mysql = Python_MySQL('localhost', 'root', '1210933445', 'test')
45ca0cfc0b54d9d9f142d53f24c2d4d41ac241dc
emisticg/ai2-2017
/lab3-functions.py
8,868
4.34375
4
# # Exploring Arguments and Parameters ##################################### # # Familiar Functions ##################################### print("\n############## Familiar Functions ##############\n ") def print_two(a, b): print("Arguments: {0} and {1}".format(a, b)) # print_two() #invalid print_two(4, 1) # print_two(41) #invalid # print_two(a=4, 1) #invalid # print_two(4, a=1) #invalid # print_two(4, 1, 1) #invalid # print_two(b=4, 1) #invalid print_two(a=4, b=1) print_two(b=1, a=4) # print_two(1, a=1) #invalid # print_two(4, 1, b=1) #invalid print("\n############## Default Arguments ##############\n") # # Default Arguments ##################################### def keyword_args(a, b=1, c='X', d=None): print("a:", a) print("b:", b) print("c:", c) print("d:", d) keyword_args(5) print("\n") keyword_args(a=5) print("\n") keyword_args(5, 8) print("\n") keyword_args(5, 2, c=4) print("\n") keyword_args(5, 0, 1) print("\n") keyword_args(5, 2, d=8, c=4) print("\n") # keyword_args(5, 2, 0, 1, "") #invalid - TypeError: for passing 5 args # keyword_args(c=7, 1) # invalid - non keyword arg after keyword arg keyword_args(c=7, a=1) print("\n") keyword_args(5, 2, [], 5) print("\n") # keyword_args(1, 7, e=6) #invalid - TypeError: keyword_args() got multiple values for argument 'e' keyword_args(1, c=7) # keyword_args(5, 2, b=4) #invalid - TypeError: keyword_args() got multiple values for argument 'b' print("\n############## Exploring Variadic Argument lists ##############\n") # # Exploring Variadic Argument lists ##################################### def variadic(*args, **kwargs): print("Positional:", args) print("Keyword:", kwargs) variadic(2, 3, 5, 7) print("\n") variadic(1, 1, n=1) print("\n") # variadic(n=1, 2, 3) # invalid - non keyword arg variadic() print("\n") variadic(cs="Computer Science", pd="Product Design") print("\n") # variadic(cs="Computer Science", cs="CompSci", cs="CS") #invalid - keyword arg repeted variadic(5, 8, k=1, swap=2) print("\n") variadic(8, *[3, 4, 5], k=1, **{'a':5, 'b':'x'}) print("\n") # variadic(*[8, 3], *[4, 5], k=1, **{'a':5, 'b':'x'}) # invalid - invalid syntax # variadic(*[3, 4, 5], 8, *(4, 1), k=1, **{'a':5, 'b':'x'}) # invalid - invalid syntax variadic({'a':5, 'b':'x'}, *{'a':5, 'b':'x'}, **{'a':5, 'b':'x'}) print("\n############## Optional: Putting it all together ##############\n") # # Optional: Putting it all together ##################################### def all_together(x, y, z=1, *nums, indent=True, spaces=4, **options): print("x:", x) print("y:", y) print("z:", z) print("nums:", nums) print("indent:", indent) print("spaces:", spaces) print("options:", options) # all_together(2) #invalid - TypeError: all_together() missing 1 required positional argument: 'y' all_together(2, 5, 7, 8, indent=False) print("\n") all_together(2, 5, 7, 6, indent=None) print("\n") # all_together() #invalid - TypeError: all_together() missing 2 required positional arguments: 'x' and 'y' # all_together(indent=True, 3, 4, 5) #invalid - non keyword arg # all_together(**{'indent': False}, scope='maximum') #invalid - invalid syntax all_together(dict(x=0, y=1), *range(10)) print("\n") # all_together(**dict(x=0, y=1), *range(10)) #invalid - invalid syntax # all_together(*range(10), **dict(x=0, y=1)) #invalid - TypeError: all_together() got multiple values for argument 'x' all_together([1, 2], {3:4}) print("\n") # all_together(8, 9, 10, *[2, 4, 6], x=7, spaces=0, **{'a':5, 'b':'x'}) #invalid - TypeError: all_together() got multiple values for argument 'x' all_together(8, 9, 10, *[2, 4, 6], spaces=0, **{'a':[4,5], 'b':'x'}) print("\n") # all_together(8, 9, *[2, 4, 6], *dict(z=1), spaces=0, **{'a':[4,5], 'b':'x'}) #invalid - invalid syntax print("\n############## Writing Functions ##############\n############## speak_excitedly ##############\n\n") # # speak_excitedly ##################################### def speak_excitedly(message, numberOfExclamation=1, enthusiasm=False): message += '!' * numberOfExclamation if not enthusiasm: return message return message.upper() print(speak_excitedly("I love Python")) print("\n") print(speak_excitedly("Keyword arguments are great", numberOfExclamation=4)) print("\n") print(speak_excitedly("I guess Java is okay...", numberOfExclamation=0)) print("\n") print(speak_excitedly("Let's go Stanford", numberOfExclamation=2, enthusiasm=True)) # # average ##################################### print("\n############## Average ##############\n") def average(*nums): if not nums: return None return sum(nums) / len(nums) print(average()) # => None print(average(5)) # => 5.0 print(average(6, 8, 9, 11)) # => 8.5 # #Challenge: make_table ##Too Hard ##################################### print("\n############## make_table ##############\n") def make_table(key_justify = 'left', value_justify = 'right', **kwargs): justification = { 'left': '<', 'right': '>', 'center': '^' } if key_justify not in justification or value_justify not in justification: print("Error! Invalid justification specifier.") return None key_alignment_specifier = justification[key_justify] value_alignment_specifier = justification[value_justify] max_key_length = max(map(len, kwargs.keys())) max_value_length = max(map(len, kwargs.values())) total_length = 2 + max_key_length + 3 + max_value_length + 2 print('=' * total_length) for key, value in kwargs.items(): print('| {:{key_align}{key_pad}} | {:{value_align}{value_pad}} |'.format(key, value, key_align=key_alignment_specifier, key_pad=max_key_length, value_align=value_alignment_specifier, value_pad=max_value_length )) print('=' * total_length) make_table( first_name="Sam", last_name="Redmond", shirt_color="pink" ) make_table( key_justify="right", value_justify="center", song="Style", artist_fullname="Taylor $wift", album="1989" ) print("\n############## Function Nuances ##############\n############## Return ##############\n\n") # # Return ##################################### def say_hello(): print("Hello!") print(say_hello()) # => Hello! None def echo(arg=None): print("arg:", arg) return arg print(echo()) # => arg: None None print(echo(5)) # => arg: 5 5 print(echo("Hello")) # => arg: Hello Hello def drive(has_car): if not has_car: return return 100 # miles print(drive(False)) # => None print(drive(True)) # => 100 print("\n############## Parameters and Object Reference ##############\n") # # Parameters and Object Reference ##################################### def reassign(arr): arr = [4, 1] print("Inside reassign: arr = {}".format(arr)) def append_one(arr): arr.append(1) print("Inside append_one: arr = {}".format(arr)) l = [4] print("Before reassign: arr={}".format(l)) # => Before reassign: arr=[4] reassign(l) # => Inside reassign: arr=[4,1] print("After reassign: arr={}".format(l)) # => After reassign: arr=[4] print("\n") l = [4] print("Before append_one: arr={}".format(l)) # => Before reassign: arr=[4] append_one(l) # => Inside reassign: arr=[4,1] print("After append_one: arr={}".format(l)) # => After reassign: arr=[4,1] # # Scope ##################################### print("\n############## Scope ##############\n") print("\nCase 1\n") # Case 1 x = 10 def foo(): print("(inside foo) x:", x) y = 5 print(' value:', x * y) print("(outside foo) x:", x) foo() print("(after foo) x:", x) print("\nCase 2\n") # Case 2 x = 10 def foo(): x = 8 # Only added this line - everything else is the same print("(inside foo) x:", x) y = 5 print('value:', x * y) print("(outside foo) x:", x) foo() print("(after foo) x:", x) # # Default Mutable Arguments - A Dangerous Game ##################################### print("\n############## Default Mutable Arguments - A Dangerous Game ##############\n") x = 5 def f(num=x): return num * num x = 6 print(f()) # => 25, not 36 print(f(x)) # => 36 print("\n") def append_twice(a, lst=[]): lst.append(a) lst.append(a) return lst # Works well when the keyword is provided print(append_twice(1, lst=[4])) # => [4, 1, 1] print(append_twice(11, lst=[2, 3, 5, 7])) # => [2, 3, 5, 7, 11, 11] # But what happens here? print(append_twice(1)) print(append_twice(2)) print(append_twice(3))
e920de82ab3d6bd364e6e2c884011cd69f84dffd
nickkeesG/CSC_project
/expert_vs_crowd/expert_vs_crowd_sim.py
1,326
3.578125
4
import numpy as np import matplotlib.pyplot as plt def expert_chooses(crowd): expert = max(crowd) if np.random.uniform(0,1) < expert: return 1 else: return 0 def crowd_chooses(crowd): ballots = [] for c in crowd: if np.random.uniform(0,1) < c: ballots.append(1) else: ballots.append(0) if sum(ballots) > (len(crowd)/2): return 1 else: return 0 def generate_crowd(n, mean, std): crowd = [] for i in range(n): crowd.append(np.random.normal(mean, std)) return crowd mean = float(input("Please give mean accuracy of the crowd")) std = float(input("Please give the standard deviation of the accuracy")) y1 = [] y2 = [] for i in range(3,30,2): print(i) expert_wins = 0 crowd_wins = 0 for j in range(10000): crowd = generate_crowd(i, mean, std) expert_wins += expert_chooses(crowd) crowd_wins += crowd_chooses(crowd) print("Expert accuracy: ", expert_wins/10000) y1.append(expert_wins/10000) print("Crowd accuracy: ", crowd_wins/10000) y2.append(crowd_wins/10000) fig, ax = plt.subplots(1, 1, figsize=(6, 4)) x = [i for i in range(3,30,2)] ax.plot(x, y1, '-', label="Expert Accuracy") ax.plot(x, y2, '-', label="Crowd Accuracy") ax.legend() plt.show()
a5200321001956e5d2321ee175b7f4c984e83b4a
yunlongmain/python-test
/gen.py
450
4
4
# -*- coding: utf-8 -*- print("\n生成器") # 生成器 def gen(): i = 10 yield i i += 1 yield i for j in gen(): print(j) def gen(): for i in range(4): yield i for j in gen(): print(j) # 生成器 表达式 gen = (x for x in range(4)) for j in gen: print(j) # 表推导 print("\n表推导") L = [] for x in range(10): L.append(x**2) print(L) # 快捷写法 L = [x**2 for x in range(10)] print(L)
3692d89377ea9e7fe97e49d1f0c55ed6f31fe438
yunlongmain/python-test
/lib-test/test-itertools.py
1,091
3.640625
4
# coding=utf-8 from itertools import * # 无穷循环器 ''' count(5, 2) #从5开始的整数循环器,每次增加2,即5, 7, 9, 11, 13, 15 ... cycle('abc') #重复序列的元素,既a, b, c, a, b, c ... repeat(1.2) #重复1.2,构成无穷循环器,即1.2, 1.2, 1.2, ... repeat也可以有一个次数限制: repeat(10, 5) #重复10,共重复5次 ''' # imap函数与map()函数功能相似,只不过返回的不是序列,而是一个循环器 rlt = map(pow, [1, 2, 3], [1, 2, 3]) print rlt rlt = imap(pow, [1, 2, 3], [1, 2, 3]) print rlt for num in rlt: print(num) c = compress('ABCD', [1, 1, 0, 1]) print c for num in c: print(num) print "------ groupby ------" def height_class(h): if h > 180: return "tall" elif h < 160: return "short" else: return "middle" friends = [191, 158, 159, 165, 170, 177, 181, 182, 190] friends = sorted(friends, key = height_class) print(friends) for m, n in groupby(friends, key = height_class): print(m) print(list(n)) print(groupby(friends, key = height_class))
fc8f181a8762672b7d63af6a7d6155119e4d704a
ywtail/leetcode
/12_169.py
885
3.65625
4
# coding:utf-8 # Majority Element 多数元素 nums=map(int,raw_input().split()) def majorityElement_1(nums): """ :type nums: List[int] :rtype: int """ n=len(nums) dic={} for i in range(n): if nums[i] in dic: dic[nums[i]]+=1 else: dic[nums[i]]=1 if dic[nums[i]]>n/2: return nums[i] def majorityElement_2(snums): """ :type nums: List[int] :rtype: int """ from collections import Counter n=len(nums) num=dict(Counter(nums)) for key in num: if num[key]>n/2: return key print majorityElement_1(nums) print majorityElement_2(nums) """ 2 9 2 2 1 2 2 题目: 给定一个大小为n的数组,找到多数元素。 多数元素是出现超过n / 2倍的元素。 您可以假定数组非空,且多数元素始终存在于数组中。 """
008d052de6adf2f904b77235bc96b95612bd13ac
ywtail/leetcode
/71_389_2.py
823
3.546875
4
# coding:utf-8 # 389. Find the Difference 找不同 # 42ms beats 93.97% class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ x = list(s) + list(t) ans = 0 for i in range(len(x)): ans ^= ord(x[i]) return chr(ans) solution = Solution() print solution.findTheDifference('abcd', 'abcde') # e print solution.findTheDifference('abcd', 'abecd') # e ''' 题目: 给定两个字符串s和t,它们只包含小写字母。 字符串t由随机混合字符串s生成,然后在随机位置添加一个字母。 找到在t中添加的字母。 例: 输入: s =“abcd” t =“abcde” 输出: e 说明: 'e'是添加的字母。 分析: 将字符转为数字,使用异或 '''
b24b8cb5a6a7200c99bc112b9d5812eb9726bc60
ywtail/leetcode
/35_58.py
616
4.125
4
# coding:utf-8 # Length of Last WordLength of Last Word 最后一个词的长度 s=raw_input() def lengthOfLastWord(s): """ :type s: str :rtype: int """ t=s.split() if len(t)==0: return 0 else: return len(t[-1]) print lengthOfLastWord(s) """ 题目: 给定一个字符串s由大写/小写字母和空格字符''组成,返回字符串中最后一个字的长度。 如果最后一个字不存在,返回0。 注意:单词定义为仅由非空格字符组成的字符序列。 例如, 给出s =“Hello World”, 返回5。 注意:仅当s仅由空格组成时返回0,‘a ’返回1 """
83763bde554e2262ccaadf7eb716cd092a2ac367
ywtail/leetcode
/23_231.py
411
4
4
# coding:utf-8 # Power of Two 二的幂 n=int(raw_input()) def isPowerOfTwo(n): """ :type n: int :rtype: bool """ if n<=0: return False elif n==1: return True else: while n>1: if n%2==0: n=n/2 else: return False return True print isPowerOfTwo(n) """ 2 True 题目: 给定一个整数,写一个函数来确定它是否为2的幂。 (注意:有可能是0或负数) """
ac1df34f0634dee917a178c5a4c39ff245d4ad2e
ywtail/leetcode
/6_14.py
982
3.59375
4
# coding:utf-8 # Longest Common Prefix 最长公共前缀 strs=raw_input().split() def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ n=len(strs) num=0 if n>0: num=len(strs[0]) for i in range(1,n): if num==0: break temp=0 for j in range(num): if len(strs[i])<j+1: break elif strs[0][j]==strs[i][j]: temp+=1 else: break if temp<num: num=temp s="" for i in range(num): s+=strs[0][i] return s print longestCommonPrefix(strs) """ abcd abc ac a 题目: 编写一个函数来查找字符串数组中最长的公共前缀字符串。 分析: 贪心:用num记录当前最长公共前缀长度,遍历strs列表中字符串, 对每个字符串最多遍历到num个字符进行匹配 更新num """
e4d764310e6f59fefd2de5024ff317f3bcf5e146
ywtail/leetcode
/70_204.py
892
3.5625
4
# coding:utf-8 # 204. Count Primes 素数数 # 869ms beats 62.89% class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n <= 2: return 0 re = [1] * n for i in range(2, int(n ** 0.5) + 1): # 只需要到 sqrt(n) if re[i]: for j in range(i * i, n, i): # 从i*i开始,不是2* re[j] = 0 return sum(re) - 2 solution = Solution() print solution.countPrimes(3) # 1 print solution.countPrimes(12) # 5 print solution.countPrimes(100) # 25 print solution.countPrimes(1500000) # 114155 ''' 题目: 计算小于非负数 n 的素数数。 分析: 从素数2开始,所有素数的倍数都不是素数,标记为0。 最后统计1的个数就是素数的个数。注意的是,re从0开始,0和1都不是素数,所以-2 '''
2523c9163f640eb7570f3a17c6d2d6838baaaed0
ywtail/leetcode
/58_566_2.py
1,973
3.625
4
# coding:utf-8 # 566. Reshape the Matrix 重塑矩阵 # 205ms beats 26.08% class Solution(object): def matrixReshape(self, nums, r, c): """ :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ n = len(nums) m = len(nums[0]) if n * m == r * c: ans = [[0 for i in range(c)] for j in range(r)] for i in range(r * c): ans[i / c][i % c] = nums[i / m][i % m] return ans else: return nums solution = Solution() print solution.matrixReshape([[1, 2], [3, 4]], 1, 4) # [[1, 2, 3, 4]] print solution.matrixReshape([[1, 2], [3, 4]], 2, 4) # [[1, 2], [3, 4]] print solution.matrixReshape([[1, 2], [3, 4]], 4, 1) # [[1], [2], [3], [4]] print solution.matrixReshape([[1, 2], [3, 4],[5,6]], 2, 3) # [[1, 2, 3], [4, 5, 6]] ''' 题目: 在MATLAB中,有一个非常有用的函数叫做“reshape”,它可以将矩阵重新形成一个不同大小的矩阵,但是保持其原始数据。 给出一个由二维数组表示的矩阵,两个正整数r和c分别表示所需重组矩阵的行号和列号。 重新组合的矩阵需要以与它们相同的行遍历顺序填充原始矩阵的所有元素。 如果具有给定参数的“reshape”操作是可行且合法的,则输出新的重构矩阵;否则,输出原始矩阵。 示例1: 输入: nums = [[1,2],  [3,4] r = 1,c = 4 输出: [[1,2,3,4]] 说明: 数字的行遍历是[1,2,3,4]。新的重构矩阵是一个1 * 4矩阵,使用上一个列表逐行填充。 示例2: 输入: nums = [[1,2],  [3,4] r = 2,c = 4 输出: [[1,2],  [3,4] 说明: 无法将2 * 2矩阵重塑为2 * 4矩阵。所以输出原来的矩阵。 注意: 给定矩阵的高度和宽度在[1,100]范围内。 给定的r和c都是正的。 分析: 注意,在初始化 ans 时,如果写成 [[0]*c]*r 结果将发生错误,慎用 '''
9021ca9e375c5114fddfb39e507b95902ce923f8
ywtail/leetcode
/66_121_2.py
1,731
3.796875
4
# coding:utf-8 # 121. Best Time to Buy and Sell Stock 买卖股票 # 59ms beats 34.93% class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ n = len(prices) if n < 2: return 0 max_cur = 0 max_sofar = 0 for i in range(1, n): max_cur = max(0, max_cur + prices[i] - prices[i - 1]) max_sofar = max(max_sofar, max_cur) return max_sofar solution = Solution() print solution.maxProfit([7, 1, 5, 3, 6, 4]) # 5 print solution.maxProfit([7, 6, 4, 3, 1]) # 0 ''' 题目: 说你有一个数组,第i个元素是第i天给定股票的价格。 如果只允许最多完成一个交易(即购买一个交易,并出售股票一个),则设计一个算法来找到最大利润。 示例1: 输入:[7,1,5,3,6,4] 输出:5 最大差= 6-1 = 5(不是7-1 = 6,因为售价需要大于购买价格) 示例2: 输入:[7,6,4,3,1] 输出:0 在这种情况下,没有交易完成,即最大利润= 0。 分析: Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 这一题的逻辑与"最大子数列"(找到一个连续的子数列,使该子数列的和最大)相同。 求 [7, 1, 5, 3, 6, 4] 最大利润,相当于求 [0,-6,4,-2,3,-2] 最大子数列。 max_cur的值分别为:0,0,4,2,5,3 Kadane算法扫描一次整个数列的所有数值,在每一个扫描点计算以该点数值为结束点的子数列的最大和(正数和)。 该子数列有可能为空,或者由两部分组成:以前一个位置为结束点的最大子数列、该位置的数值。 '''
8c5a93b99d7878cea460afd9d488dbbadf9a39df
SRI-VISHVA/Pandas
/day_6/analytics_3.py
1,213
3.875
4
# Objective # To find the average age of male and female candidates using pandas import pandas as pd import numpy as np from day_6.list_tuple import main_list from datetime import date, datetime from datetime import date today = date.today() def calculate_age(born): today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) id = [] age = [] # line_count = 0 for row in main_list: person = list(row) try: date_object = datetime.strptime(person[4], '%Y-%m-%d').date() except ValueError: break if person[3] == 'Male': age.append(calculate_age(date_object)) id.append(person[0]) else: pass s = pd.Series(age, index=id) print("Average age of Male: " + str(np.average(s.values))) id = [] age = [] # line_count = 0 for row in main_list: person = list(row) try: date_object = datetime.strptime(person[4], '%Y-%m-%d').date() except ValueError: break if person[3] == 'Female': age.append(calculate_age(date_object)) id.append(person[0]) else: pass s = pd.Series(age, index=id) print("Average age of Female: " + str(np.average(s.values)))
f2852937a8ccd26a097ba7094852c2c13fe536dd
WassimBenzarti/DataScienceCheckpoints
/Checkpoint1/ex1.py
176
3.90625
4
text = input("Hello, please talk\n") print("Your talk is {} chars long".format(len(text))) print("words={}, spaces={}".format( len(text.split(" ")), text.count(" ") ))
5a8494efaee7fde7782fa3a5910a786e76ca7f96
WassimBenzarti/DataScienceCheckpoints
/Checkpoint1/ex2.py
159
3.890625
4
a = int(input("Type a:\n")) b = int(input("Type b:\n")) print("input: a={}, b={}".format(a,b)) c = a a = b b = c print("input: a={}, b={}".format(a,b))
836473508e62183e7d8b269440a89a106000f11d
AdrianGallo98/TweepySE
/plot1.py
912
3.546875
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 21 14:02:49 2020 @author: Adrian Gallo """ import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style import pandas as pd style.use('fivethirtyeight') fig = plt.figure() ax1 = fig.add_subplot(1,1,1) x = [] pos = [] neg = [] neu = [] def animate(i): data = pd.read_csv('abortion.csv', index_col=False) x = data['ID'].values pos = data['Positives'].values neg = data['Negatives'].values neu = data['Neutrals'].values ax1.clear() ax1.plot(x, pos, label='Positives') ax1.plot(x, neg, label='Negatives') ax1.plot(x, neu, label='Neutrals') ax1.set_title('Difference between sentiment analysis of tweets') ax1.legend(loc='upper left') ax1.set_xlabel('total') ax1.set_ylabel('tweets') ani = animation.FuncAnimation(fig,animate,interval=100) plt.show()
fd12f0e509ecf0c186a156a645d1b078166527de
nielsenjared/algorithms
/11-array-partition/main.py
545
3.921875
4
def swap(arr, left, right): temp = arr[left] arr[left] = arr[right] arr[right] = temp return arr # TODO Hoare def partitionLomuto(arr, left = 0, right = None): if right == None: right = len(arr) - 1 pivot = arr[right] index = left for i in range(left, right): if arr[i] < pivot: swap(arr, index, i) index += 1 swap(arr, index, right) return index unsorted = [10, 1, 9, 2, 8, 3, 7, 4, 6, 5] result = partitionLomuto(unsorted) print(result)
7787ec8e52e7c9fece089e8ba745f0e69add93ad
nielsenjared/algorithms
/01-swap/main.py
122
3.96875
4
x = 123 y = 456 def swap(x, y): temp = x x = y y = temp return (x, y) result = swap(x, y) print(result)
729e39a20eabb246536a39ea6585699262088905
nielsenjared/algorithms
/16-insertion-sort/main.py
388
4.0625
4
def insertion_sort(list): for curr in range(1, len(list)): temp = list[curr] prev = curr - 1 while(prev >= 0): if (list[prev] > temp): list[prev + 1] = list[prev] list[prev] = temp prev = prev - 1 return list list = [10, 1, 9, 2, 8, 3, 7, 4, 6, 5] result = insertion_sort(list) print(result)
5b7c929f5305f9aee2af8c5e1ec7c02358a60a8c
jittania/core-problem-set-recursion
/part-1.py
1,193
3.890625
4
# There are comments with the names of # the required functions to build. # Please paste your solution underneath # the appropriate comment. #============================================================================= # factorial def factorial(n): if n == 0: return 1 try: return factorial(n-1) * n except RecursionError: raise ValueError #============================================================================= # reverse def reverse(text): if len(text) == 0: return text else: # text[1:] slices the string except for the first character return reverse(text[1:]) + text[0] #============================================================================= # bunny def bunny(count): if count == 0: return 0 else: return 2 + bunny (count - 1) #============================================================================= # is_nested_parens def is_nested_parens(parens, i=0, j=0): if i == len(parens): return j == 0 if parens[i] == "(": return is_nested_parens(parens, i+1, j+1) elif parens[i] == ")": return is_nested_parens(parens, i+1, j-1)
1c55fb74f1c254f4520b91e3c96e1df42aa45743
lazistar/Nado_Practice
/data type/data type_변수.py
560
3.546875
4
# 애완동물을 소개해 주세요~ animal = "강아지" name = "연탄이" age = 4 hobby = "산책" is_adult = age >= 3 # print("우리집" + animal + "의 이름은" + name + "이에요") # hobby = "공놀이" # print(name, "는 ", age, "살이며,", hobby, "을 아주 좋아해요.") # print(name + "는 어른일까요? " + str(is_adult)) print("우리집 {0}의 이름은 {1}에요.".format(animal, name)) print("{0}는 {1}살이며, {2}를 아주 좋아해요.".format(name, age, hobby)) print("{0}는 어른일까요? {1}".format(name, is_adult))
5b13b24acbbc286305aa9cda7adc9afd7709104f
sjNT/checkio
/Elementary/Fizz Buzz.py
1,288
4.15625
4
""" "Fizz buzz" это игра со словами, с помощью которой мы будем учить наших роботов делению. Давайте обучим компьютер. Вы должны написать функцию, которая принимает положительное целое число и возвращает: "Fizz Buzz", если число делится на 3 и 5; "Fizz", если число делится на 3; "Buzz", если число делится на 5; """ def checkio(number: int) -> str: msg = '' if number % 3 == 0: msg += 'Fizz ' if number % 5 == 0: msg += 'Buzz' elif msg == '': msg = str(number) return msg.rstrip() # Some hints: # Convert a number in the string with str(n) # These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': print('Example:') print(checkio(15)) assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5" assert checkio(6) == "Fizz", "6 is divisible by 3" assert checkio(5) == "Buzz", "5 is divisible by 5" assert checkio(7) == "7", "7 is not divisible by 3 or 5" print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
e0fc07696c72475b1dcfa376084f2ef16bfb0b22
sjNT/checkio
/Elementary/Second Index.py
1,607
3.890625
4
""" Даны 2 строки. Необходимо найти индекс второго вхождения второй строки в первую. Разберем самый первый пример, когда необходимо найти второе вхождение "s" в слове "sims". Если бы нам надо было найти ее первое вхождение, то тут все просто: с помощью функции index или find мы можем узнать, что "s" – это самый первый символ в слове "sims", а значит индекс первого вхождения равен 0. Но нам необходимо найти вторую "s", а она 4-ая по счету. Значит индекс второго вхождения (и ответ на вопрос) равен 3. """ def second_index(text: str, symbol: str) -> [int, None]: if symbol in text and text.count(symbol) >= 2: li = list(text) li.pop(li.index(symbol)) return li.index(symbol) + 1 return None if __name__ == '__main__': print('Example:') print(second_index("sims", "s")) # These "asserts" are used for self-checking and not for an auto-testing assert second_index("sims", "s") == 3, "First" assert second_index("find the river", "e") == 12, "Second" assert second_index("hi", " ") is None, "Third" assert second_index("hi mayor", " ") is None, "Fourth" assert second_index("hi mr Mayor", " ") == 5, "Fifth" print('You are awesome! All tests are done! Go Check it!')
5e7cb56c67e23bf802c689e64f15619e25fde9a7
sjNT/checkio
/Home/Time Converter (24h to 12h).py
1,426
3.84375
4
""" Вы предпочитаете использовать 12-часовой формат времени, но современный мир живет в 24-часовом формате и вывидите это повсюду. Ваша задача - переконвертировать время из 24-часового формата в 12-часовой, использкя следующие правила: - выходной формат должен быть 'чч:мм a.m.' (для часов до полудня) или 'чч:мм p.m.' (для часов после полудня) - если часы меньше 10 - не пишите '0' перед ними. Например: '9:05 a.m.' """ def time_converter(time): h, m = time.split(':') if int(h) == 0: return '{}:{} a.m.'.format(int(h) + 12, m) if int(h) == 12: return '{}:{} p.m.'.format(int(h), m) if int(h) > 12: return '{}:{} p.m.'.format(int(h) - 12, m) return '{}:{} a.m.'.format(int(h), m) if __name__ == '__main__': print("Example:") print(time_converter('12:30')) #These "asserts" using only for self-checking and not necessary for auto-testing assert time_converter('12:30') == '12:30 p.m.' assert time_converter('09:00') == '9:00 a.m.' assert time_converter('23:15') == '11:15 p.m.' print("Coding complete? Click 'Check' to earn cool rewards!")
f6328df30cd69193ea4182ba56d55c88fd3f5781
dtekluva/first_repo
/variance/variance.py
887
3.96875
4
# numbers = [4,5,3,6,5] # mean_nums = sum(numbers)/len(numbers) # ALSO OUR X_BAR # print("MEAN : ", mean_nums) # for number in numbers: # print(number, round(number - mean_nums, 1), (number - mean_nums)**2) ############################### # A MORE DESCRIPTIVE APPROACH # ############################### numbers = [4,5,3,6,5,] x_bar = sum(numbers)/len(numbers) # ALSO OUR X_BAR print("MEAN : ", x_bar, "\n") variance = 0 print(str("x").ljust(4), "|", str("x_xbar").ljust(6), "|", str("x_xbar_squared").ljust(8), "|") print(str("-"*4).ljust(4), "+", str("-"*6).ljust(6), "+", str("-"*14).ljust(8), "-") for number in numbers: x_xbar = round(number - x_bar, 2) x_xbar_squared = round(x_xbar**2, 2) variance += x_xbar_squared print(str(number).ljust(4), "|", str(x_xbar).ljust(6), "|", str(x_xbar_squared).ljust(14), "|") print("\nVariance : ",variance)
1e30e88c79c0941f93ce4239a74eb38d4dcd02f5
dtekluva/first_repo
/datastructures/ato_text.py
1,616
4.125
4
# sentence = input("Please enter your sentence \nWith dashes denoting blank points :\n ") # replacements = input("Please enter your replacements in order\nseperated by commas :\n ") # ## SPLIT SENTENCE INTO WORDS # sentence_words = sentence.split(" ") # print(sentence_words) # ## GET CORRESPONDING REPLACEMENTS # replacement_words = replacements.split(',') # replacement_index = 0 # # search and replace dashes with replacement words # for i in range(len(sentence_words)): # ## FIND DASHES IN WORDS OF GIVEN SENTENCE # if sentence_words[i].find("_") != -1: # ## REPLACE DASHES WITH CORRESPONDING REPLACEMENT WORDS. # sentence_words[i] = sentence_words[i].replace("_", replacement_words[replacement_index]) # replacement_index+=1 # full_sentence = " ".join(sentence_words) # print(full_sentence) # prices = [200, 300, 400, 213, 32 ] # marked = 1.5 # for i in range(len(prices)): # prices[i] = prices[i]*marked # print(prices) x = 20 # def do_somthing(): # global x # x = 30 # print(x) # return 23 # do_somthing() # print(x) # def numbers(one, two, three): # print("One : ",one, "Two : ", two, "Three : ", three) # numbers(2,3,1) # numbers(two = 2, three = 3, one = 1) def greet(name, gender): if gender == "male": print(f"Hello Mr {name}..!") else: print(f"Hello Mrs {name}..!") greet("Bolu", "female") people = [("bolu", "male", 23), ("ade", "female", 15), ("sholu", "female", 45), ("manny", "male", 33)] # for person in people: # greet(person[0], person[1]) for name, gender in people: greet(name, gender)
798c8c8298cdfe9cc86bed320be8ab80e4aae5ba
dtekluva/first_repo
/class3.py
5,130
3.84375
4
# math_score = input("Please enter math score : ") # english_score = input("Please enter english score : ") # math_score = int(math_score) # english_score = int(english_score) # print() # print("Qualified for Engineering".ljust(26), ":", math_score >= 80 and english_score >= 70) # print("Qualified for Business".ljust(26), ":", math_score >= 60 and english_score >= 70) # print("Qualified for Theology".ljust(26), ":", math_score >= 20 and english_score >= 80) # print(12, 6, 2020, sep = "-") # print(12, 6, 2020, sep = "/") # print(12, 6, 2020, sep = ".") # my_file = open("printing.csv", "w") # print(12, 6, 2020, sep = "-", file = my_file) # print(12, 6, 2020, sep = "/") # print(12, 6, 2020, sep = ".") # def crazy_func(): # """I AM JUST A CRAZY OL' FUNKY FUNCTION OOPSY I DO NOTHING HAHA""" # pass # crazy_func # print(-1) # print(abs(-1)) # name = "cbDd" # print(min(name)) # print(max(name)) my_range = range(23) # CASE OF A SINGLE VALUE INPUT GIVES FROM ZERO TO SPECIFIED VALUE my_range_list = list(range(23)) # CASE OF A SINGLE VALUE INPUT GIVES FROM ZERO TO SPECIFIED VALUE CONVERTED TO LIST my_range_list = list(range(10,23)) # CASE OF A START AND STOP VALUE INPUT GIVES FROM START TO SPECIFIED VALUE CONVERTED TO LIST my_range_list = list(range(2,23,3)) # CASE OF A START AND STOP STEP VALUE INPUT GIVES FROM START TO SPECIFIED VALUE CONVERTED TO LIST # print(my_range) # print(my_range_list) my_ages = [2,8,1,1,0,4,2,7,5,99,5] # print(sorted(my_ages, reverse = True)) # multiplier = lambda age: age * 10 # multipied_ages = map( multiplier, my_ages) # print(list(multipied_ages)) # template_text = "Hello i am a boy and my name is : <name_here>" # print(template_text) # name = input("Please Enter your name : ") # DOB = input("Please Enter your DOB as yy/mm/dd : ") # stripped_name = name.strip() # formatted_text_with_input_name = template_text.replace("<name_here>", stripped_name) # print(name) # print(stripped_name) # print(stripped_name) # print(formatted_text_with_input_name) # splitted_text = name.split() # print(splitted_text) # print(DOB.split("/")) # splitted_dob = DOB.split("/") # year_of_birth = splitted_dob[2] # print(year_of_birth) # reformatted_DOB = [splitted_dob[1], splitted_dob[0]] #FORMAT TO MM-YY # reformatted_DOB = "-".join(reformatted_DOB) # print(reformatted_DOB) # char_list = ['a', 'd', 'a', 'o', 'r', 'a'] # print("".join(char_list)) # reg_user_file = open("registered_users.csv", "a") # current_year = 2020 # name = input("Please enter name : ") # DOB = input("Please enter DOB as dd/mm/yy: ") # year_of_birth = DOB.split("/")[2] # int_year_of_birth = int(year_of_birth) # age = current_year - int_year_of_birth # print("Hello name you are age years old now.".replace("name", name.upper()).replace("age", str(age))) # is_millenial =int_year_of_birth > 1990 and int_year_of_birth < 2000 # is_gen_x = int_year_of_birth >= 2000 # is_baby_boomer = int_year_of_birth < 1990 # print(name.upper(), DOB, age, len(name), is_millenial, is_gen_x, is_baby_boomer, sep = ",", file = reg_user_file) # print('foo' in ['foo', 'bar', 'baz']) # if 'foo' in ['foo', 'bar', 'baz']: # x # print('Outer condition is true') # x # print(10 > 20) # if 10 > 20: # x # print('Inner condition 1') # x # print('Between inner conditions') # x # print(10 < 20) # if 10 < 20: # x # print('Inner condition 2') # x # print('End of outer condition') # x # print('After outer condition') # x # read_or_write = input("What would you like to do\nR for read W for write ") # R for read W for write # if read_or_write.lower() == "w": # name = input("Please enter your Username : ") # password = input("Please enter your password : ") # user_detail_file = open("data/{}_detail.csv".format(name), "w") # user_detail_file.write(f"{name},{password}") # database = open(f"data/{name}_database.txt", "a") # data = input("Please enter your note : ") # database.write(f"{data}\n") # elif read_or_write.lower() == "r": # name = input("Please enter your Username : ") # password_input = input("Please enter your password : ") # user_detail_file = open("data/{}_detail.csv".format(name), "r") # username, password = user_detail_file.readline().split(",") # username_is_correct = username == name # password_is_correct = password == password_input # if username_is_correct and password_is_correct: # database = open(f"data/{name}_database.txt", "r") # data = database.read() # print(data) # user_detail_file.close() # word =15 # try: # print(1/0) # print(word + 10) # except TypeError: # print("Please respect is reciprocal.!!") # print("Cannot add int to string.!!") # except ZeroDivisionError: # print("Please respect is reciprocal.!!") # print("You sef you fit divide by zero.!!") behaviour = "hard" bolu_nickname = "Buttie" if behaviour == "soft" else "omo munshin " print(bolu_nickname)
49498d9b2b5aa8355dc9924b7c42fe307b383f09
edusanketdk/interview-practice
/multiply number strings/solution3.py
924
3.765625
4
# for very large numbers # without directly using multiplication def multiplyStrings(s1, s2): isneg1, isneg2 = 1 if s1[0]=='-' else 0, 1 if s2[0]=='-' else 0 s1, s2 = s1[1:] if isneg1 else s1, s2[1:] if isneg2 else s2 finalsign = "-" if isneg1+isneg2 == 1 else "" ans = [0]*(len(s1)+len(s2)) id1, id2 = 0, 0 for i in s1[::-1]: i = ord(i)-48 id2, carry = 0, 0 for j in s2[::-1]: j = ord(j)-48 sm = i*j + ans[id1+id2] + carry carry = sm//10 ans[id1+id2] = sm%10 id2 += 1 if carry: ans[id1+id2] += carry id1 += 1 return finalsign + "".join(map(str, ans[::-1])).lstrip('0') """ here we multiply two numbers using school mathematics method basically multiple second number with each digit of first number starting in reverse for both numbers and add the results into an array """
1db69ed4f41ead6b2ebca457dfcb7200641dc09b
edusanketdk/interview-practice
/rotate matrix/solution1.py
550
3.9375
4
def rotateby90(a, n): for i in range((n+1)//2): for j in range(n//2): a[i][j], a[n-i-1][n-j-1], a[n-j-1][i], a[j][n-i-1] = \ a[j][n-i-1], a[n-j-1][i], a[i][j], a[n-i-1][n-j-1] """ from the rotation pattern it is observed that the rotation of each element can be visualised as a cycle in which only 4 elements take part at a time so, [i][j] -> [j][n-i-1] [n-i-1][n-j-1] -> [n-j-1][i] a[n-j-1][i] -> [i][j] a[j][n-i-1] -> [n-i-1][n-j-1] time complexity: O(n**2) space complexity: O(1) """
e945ee5667f6a6b11fa47f3f4a60e2838253b019
edusanketdk/interview-practice
/reverse alternate k nodes/solution1.py
521
3.609375
4
# simplest approach def reverse_alt_k(head, k): ar = [] cur = head while cur: ar.append(cur.val) cur = cur.next br = [] for i in range(0, len(ar), k): cur = ar[i:i+k] cur.reverse() for j in cur: br.append(j) newll = linked_list() for i in br: newll.add_node(i) return newll """ copy the linkedlist values sequencially to an array then reverse alternate k elements of the array create a new linkedlist from the new array """
02b914177c985cfa117a75923d0899134c53a8ee
NewbieAI/NewbieAI.github.io
/scripts/segments/neuralnet3.py
4,644
3.671875
4
class DeepNeuralNet: # The class contains at least 0 hidden layer # and exactly 1 output layer # To create a dnn object, specify the structure # and the output units of the network. The class # will automatically initiate the weights and # bias in each layer. The loss function should # also be provided. # 'structure' has the basic type of python 'tuple', # the ith element of the tuple stores the # number of nodes that should be created in the # (i+1)th layer. Note that tuple index starts # with 0 whereas neural net layers starts with # 1. # output_unit_option: # 0--> linear units are used # 1--> logistic sigmoid units are used # 2--> softmax units are used # loss_func_option: # 0--> Mean square Error loss is used # 1--> Cross entropy loss is used def __init__(self, input_D, output_D, structure, output_unit_option): self.depth = len(structure) self.hidden_units = [] iDim = input_D for L in structure: if isinstance(L,int): # layer uses relu activation as default new_layer = Layer(iDim, L, 1) self.hidden_units.append(new_layer) iDim = L elif isinstance(L,tuple) and len(L)==2: # assuming the activation function is specified new_layer = Layer(iDim, L[0], L[1]) self.hidden_units.append(new_layer) iDim = L[0] else: raise ValueError('Invalid structure') self.output_layer = Layer(iDim,output_D,0) self.output_type = output_init_option self.output_unit = output_units[output_unit_option] if output_unit_option==0: self.loss_func = MSE self.gloss_func = gMSE elif output_unit_option==1: self.loss_func = x_entropy self.gloss_func = gx_entropy elif output_unit_option==2: self.loss_func = x_entropy self.gloss_funnc = x_entropy else: raise ValueError('Invalid option for output unit!!') # gloss_func abbreviates 'gradient of the loss function' def save(self, model_id): model = { "layers": [x.export() for x in self.hidden_units], "output_layer": self.output_layer.export(), "output_type": self.output_type } filename = str(model_id) + ".npy" np.save(filename, model) def load(self, model_id): filename = str(model_id) + ".npy" model = np.load(filename).item() output_unit_option = model["output_type"] self.hidden_units = [] self.output_layer = Layer(1, 1, 0) for parameters in model["layers"]: self.hidden_units.append(Layer(1, 1, 0)) self.hidden_units[-1].import_parameters( parameters[0], parameters[1], parameters[2], ) self.output_layer.import_parameters( model["output_layer"][0], model["output_layer"][1], model["output_layer"][2] ) if output_unit_option==0: self.loss_func = MSE self.gloss_func = gMSE elif output_unit_option==1: self.loss_func = x_entropy self.gloss_func = gx_entropy elif output_unit_option==2: self.loss_func = x_entropy self.gloss_funnc = x_entropy else: def train(self,X,Y,learning_rate,iterations): # learns the mapping from input X to output Y, # using (stochastic) gradient descent J = [] for i in range(iterations): # forward propagation: A = X for j in self.hidden_units: A = j.evaluate(A) H = self.output_layer.evaluate(A) J.append(self.loss_func(H,Y)) # gH = gradient_H(J) gH = self.gloss_func(H,Y) #print(gH) # backward propagation: self.output_layer.update(gH,learning_rate) gA = self.output_layer.backprop(gH) for k in self.hidden_units[::-1]: k.update(gA,learning_rate) if k!=self.hidden_units[0]: gA = k.backprop(gA) return J def predict(self,X): A = X for j in self.hidden_units: A = j.evaluate(A) H = self.output_layer.evaluate(A) Y_predicted = self.output_unit(H) return Y_predicted
3782aeec5e97417d57515bd8b9bd54d1c4f5559a
Fernandomn/Ufba
/MATD74 - Algoritmos e Grafos/Atividades/Lista1/1015_DISTANCIAPONTOS.py
347
3.65625
4
import math a = input() b = input() ponto1 = a.split(' ') ponto2 = b.split(' ') ponto1[0], ponto1[1] = float(ponto1[0]), float(ponto1[1]) ponto2[0], ponto2[1] = float(ponto2[0]), float(ponto2[1]) difX = ponto1[0]-ponto2[0] difY = ponto1[1]-ponto2[1] distancia = math.sqrt(math.pow(difX, 2) + math.pow(difY, 2)) print('{0:.4f}'.format(distancia))
1bf46f3ccc9861cfb285358497fa83fcc2c41969
FedeVerstraeten/tda1-fiuba
/tp1/src/all_sorting.py
5,851
3.640625
4
#!/usr/bin/python import random from random import randint import time import sys import csv import pprint SIZE_ARRAY = 10000 MAX_NUM = 10000 NUM_ARRAYS = 10 sys.setrecursionlimit(15000000) ###################### Heap Sort ################################## def swap(i, j, arr): arr[i], arr[j] = arr[j], arr[i] def heapify(end, i, arr): l=2 * i + 1 r=2 * (i + 1) max=i if (l < end and arr[i] < arr[l]): max = l if (r < end and arr[max] < arr[r]): max = r if (max != i): swap(i, max, arr) heapify(end, max, arr) def heapSort(arr): end = len(arr) start = end // 2 - 1 # division entera for i in range(start, -1, -1): heapify(end, i, arr) for i in range(end-1, 0, -1): swap(i, 0, arr) heapify(i, 0, arr) ###################### Merge Sort ################################## def mergeSort(nlist): if (len(nlist)>1): mid = len(nlist)//2 lefthalf = nlist[:mid] righthalf = nlist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=j=k=0 while (i < len(lefthalf) and j < len(righthalf)): if (lefthalf[i] < righthalf[j]): nlist[k]=lefthalf[i] i=i+1 else: nlist[k]=righthalf[j] j=j+1 k=k+1 while (i < len(lefthalf)): nlist[k]=lefthalf[i] i=i+1 k=k+1 while (j < len(righthalf)): nlist[k]=righthalf[j] j=j+1 k=k+1 ###################### Quick Sort ################################## def quickSort(array): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: greater.append(x) return quickSort(less) + equal + quickSort(greater) else: return array ###################### Insertion Sort ################################## def insertionSort(myList, first_position, last_position): for i in range(first_position+1,last_position): aux=myList[i] j=i-1 while j>=first_position and aux<myList[j]: myList[j+1]=myList[j] j=j-1 myList[j+1]=aux ###################### Selection Sort ################################## def selectionSort(myList, first_position, last_position): for i in range(first_position,last_position-1): swap2(myList,i,posMin(myList,i,last_position)) def swap2(myList,i,j): aux=myList[i] myList[i]=myList[j] myList[j]=aux def posMin(myList,i,j): pmin=i for k in range(i+1,j): if myList[k]<myList[pmin]: pmin=k return pmin ######################################################################## def randomIntegerArray(n): nlist = [randint(0, MAX_NUM) for _ in range(n)] return nlist def analyzeSortingAlgorithms(arr, i, j): arr1 = arr[:] #hacemos una copia del array tStart = time.time() heapSort(arr1) tEnd = time.time() print("Numero de Set", i) print("Cantidad elementos", j) print("tLength HeapSort:", tEnd - tStart) print("-------------") arr2 = arr[:] tStart = time.time() mergeSort(arr2) tEnd = time.time() print("Numero de Set", i) print("Cantidad elementos", j) print("tLength MergeSort:", tEnd - tStart) print("-------------") arr3 = arr[:] tStart = time.time() quickSort(arr3) tEnd = time.time() print("Numero de Set", i) print("Cantidad elementos", j) print("tLength QuickSort:", tEnd - tStart) print("-------------") arr4 = arr[:] tStart = time.time() insertionSort(arr4, 0, len(arr4)) tEnd = time.time() print("Numero de Set", i) print("Cantidad elementos", j) print("tLength InsertionSort:", tEnd - tStart) print("-------------") arr5 = arr[:] tStart = time.time() selectionSort(arr5, 0, len(arr5)) tEnd = time.time() print("Numero de Set", i) print("Cantidad elementos", j) print("tLength SelectionSort:", tEnd - tStart) print("-------------") def worstcaseSortingAlgorithms(): # Repeated array array = [1] * SIZE_ARRAY for j in [50, 100, 500, 1000, 2000, 3000, 4000, 5000, 7500, SIZE_ARRAY]: slicedArray = array[:j] analyzeSortingAlgorithms(slicedArray,"repeated_array",j) # Array ordered ascending array = [i for i in xrange(SIZE_ARRAY)] for j in [50, 100, 500, 1000, 2000, 3000, 4000, 5000, 7500, SIZE_ARRAY]: slicedArray = array[:j] analyzeSortingAlgorithms(slicedArray,"ascending_array",SIZE_ARRAY) # Array ordered descending array = [(SIZE_ARRAY-1)-i for i in xrange(SIZE_ARRAY)] for j in [50, 100, 500, 1000, 2000, 3000, 4000, 5000, 7500, SIZE_ARRAY]: slicedArray = array[:j] analyzeSortingAlgorithms(slicedArray,"descending_array",SIZE_ARRAY) def datasetSortingAlgorithms(): # Array initialization arrays = [0,1,2,3,4,5,6,7,8,9] for i in range(0, NUM_ARRAYS): arrays[i] = randomIntegerArray(SIZE_ARRAY) for i in range(0, NUM_ARRAYS): for j in [50, 100, 500, 1000, 2000, 3000, 4000, 5000, 7500, 10000]: slicedArray = arrays[i][:j] analyzeSortingAlgorithms(slicedArray, i, j) ######################################################################## def RunPunto1(mode): if mode == "worstcase": worstcaseSortingAlgorithms() elif mode == "dataset": datasetSortingAlgorithms() ############################## MAIN #################################### def main(): # Exec options if len(sys.argv) > 1: execMode = sys.argv[1] if execMode == "worstcase": print "Analysis of the worst case." RunPunto1("worstcase") elif execMode == "dataset": print "Analysis for the data set." RunPunto1("dataset") else: print "Invalid option." # Default case else: RunPunto1("dataset") if __name__ == '__main__': main()
b9a6f5dfa9f184d24f941addd3aa219dcc16a1bd
harrylb/anagram
/anagram_runner.py
2,436
4.3125
4
#!/usr/bin/env python3 """ anagram_runner.py This program uses a module "anagram.py" with a boolean function areAnagrams(word1, word2) and times how long it takes that function to correctly identify two words as anagrams. A series of tests with increasingly long anagrams are performed, with the word length and time to identify output to a file in the same directory, anagram_results.csv, for easy import into a spreadsheet or graphing program. @author Richard White @version 2017-02-20 """ import random import time import anagram def create_anagrams(word_length): """ Creates a random collection of lowercase English letters, a-z, of a specified word_length, as well as a randomized rearranging of those same letters. The strings word1 and word2 are anagrams of each other, and returned by this function. """ baseword = [] for i in range(word_length): baseword.append(chr(int(random.random()*26) + 97)) # random letter word1 = ''.join(baseword) # Convert list to string # Now go through baseword and pop off random letters to create word2. word2 = "" while len(baseword) > 0: word2 += baseword.pop(int(random.random() * len(baseword))) return word1, word2 def main(): """ This main program includes some timed pauses and timed countdowns to give the user some sense of the time it takes to sort the words. """ MAX_WORD_LENGTH = 10000 print("ANAGRAM RUNNER") results = [] for word_length in range(int(MAX_WORD_LENGTH/10), MAX_WORD_LENGTH, int(MAX_WORD_LENGTH/10)): word1,word2 = create_anagrams(word_length) print("Comparing",word1,"and",word2) print("Starting test") start = time.time() result = anagram.areAnagrams(word1,word2) stop = time.time() print("Stopping test") if result: print("The two words are anagrams") else: print("The two words are not anagrams") print("Time elapsed: {0:.4f} seconds".format(stop - start)) results.append((word_length, stop-start)) outfile = open("anagram_results.csv","w") outfile.write("Anagram length in letters,time to verify(seconds)\n") for result in results: outfile.write(str(result[0]) + "," + str(result[1]) + "\n") outfile.close() print("anagram_results.csv successfully written") if __name__ == "__main__": main()
9e6405c1f69759cf3d8891a3f97a544b2f30eca2
babooloon/CLRS_Algorithm-DataStructure_Python
/CoutingSort.py
889
3.859375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Nov 8 12:10:34 2017 @author: paulyang """ # Time Complexity: O(n + k) # Auxiliary Space: O(k) def countingSort(nums): # Ensure that nums are non negative assert min(nums) >= 0, 'Numbers in nums must be nonnegative.' # Find the maximum number in nums k = max(nums) # Initialize auxiliary list to store count of elements aux = [0] * (k + 1) # Initialize result list to store sorted nums # Index 0 stores nothing res = [0] * (len(nums) + 1) # Count number of elements in nums for num in nums: aux[num] += 1 # Compute running sum of auxiliary list for i in range(1, len(aux)): aux[i] += aux[i - 1] # Place elements to result list for i in xrange(len(nums)-1, -1, -1): res[aux[nums[i]]] = nums[i] aux[nums[i]] -= 1 return res[1:]
1faee04db261806a066f59bf6ddc7785ff98a060
Kang-kyunghun/python_EX
/Example2.py
4,587
3.609375
4
# 파이선 예제 연습 2주차 # 1. 입력을 정수 n 으로 받았을 때, n 이하 까지의 피보나치 수열을 출력하는 함수를 작성하세요. n = int(input('정수 n을 입력하세요: ')) a = [1,1] i=2 if n == 1: print(a[0]) if n == 2: print(a[:2]) if n >2 : while i < n : a.append(a[i-2]+a[i-1]) i = i + 1 print(a) # 2. 사용자로부터 주민등록번호를 입력 받아 출생 연도를 출력하세요. id_num = input('주민등록번호를 입력하세요: ') if id_num[6] == '1' or id_num[6] == '2': print('19' + id_num[:2]+'생 입니다.') if id_num[6] == '3' or id_num[6] == '4': print('출생연도는 20' + id_num[:2]+'생 입니다.') #3. 연도가 주어졌을 때 윤 년이면 1, 아니면 0을 출력하는 프로그램을 작성하세요. # -윤년 = 연도가 4의 배수이면서 100의 배수가 아닐 때 또는 400의 배수일 때) year = int(input('연도를 입력하세요.:')) print(year) if year % 4 == 0 and year % 100 != 0: print('1') elif year % 400 == 0: print('1') else: print('0') # 4. 1부터 100 사이의 숫자를 하나 랜덤하게 생성하고, 이를 맞추는 게임을 작성하세요. # -숫자를 하나 생성하고, 그 다음 사용자가 숫자를 입력하면 이 둘을 비교하여 ‘높음’, ‘낮음’, ‘맞췄다’를 출력해야 한다. # -또한, 몇 번의 guess 끝에 답을 맞췄는지 시도한 횟수를 값으로 출력해야한다 import random n = random.randint(1,100) try_guess = 1 finish = True while finish: guess = int(input('숫자를 맞춰 보세요.:')) print('시도 횟수 : ' +str(try_guess)) if guess == n: print('맞췄습니다.') finish = False elif guess > n: print('더 낮은 숫자를 입력하세요.') try_guess = try_guess + 1 else: print('더 높은 숫자를 입력하세요.') try_guess = try_guess + 1 # 5. 사용자로부터 달러 또는 위안 금액을 입력 받은 후 이를 원으로 환산해라. # -사용자는 100 달러, 100 위안 과 같이 금액과 통화 명 사이에 공백을 넣어 입력 하기로 합니다. # -각 통화 별 환율: 달러 :1112원, 위안: 171원 Money = str(input('금액을 입력하세요.:')) i = 0 while i <len(Money): if Money[i] != ' ': i = i + 1 else: break Money_num = int("".join(Money[0:i])) Money_unit = "". join(Money[i+1:]) if Money_unit == '달러': Exchage = Money_num * 1112 print('달러 -> 원 : '+str(Exchage)+ '원') if Money_unit == '위안': Exchage = Money_num * 171 print('위안 -> 원 : '+str(Exchage)+ '원') # 6. 로또번호 6개를 무작위로 생성하세요(1~45)(중복x) import random i = 0 j = 0 cnt = 0 lotto =[] while i < 6 : n = random.randint(1,45) lotto.append(n) lenght = len(lotto) while j < lenght: if i == j: j = j + 1 elif lotto[i] == lotto[j] : del lotto[i] break else: j = j +1 cnt = cnt + 1 if cnt == lenght-1: i = i +1 j = 0 cnt = 0 else: j = 0 cnt = 0 print(lotto) # 7. 점수를 입력 했을 때 저수가 85점 이상이면 합격, 이하면 불합격이 나오게 작성하세요. d = int(input('점수를 입력하세요. : ')) if d >= 85: print('합격입니다.') else: print('불합격입니다.') # 8. 별찍기. *로 입력한 숫자만큼 높이가 n인 삼각형을 출력하세요. n = int(input('양의 정수 n을 입력하세요..:')) i = 0 cnt = 1 j = n - cnt while i < n : while j < n and j>=0: print('*', end='') j = j+1 print('\n') cnt = cnt + 1 j = j - cnt i = i +1 # 9. 전화번호를 입력받을 때 뒤에 4자리를 제외하고는 *로 가려지게 작성하세요. PN = str(input('전화번호를 입력하세요. : ')) n=len(PN) i = 0 PN = ','.join(PN) PN = PN.split(',') while i < n-4: if PN[i] != '-': del PN[i] PN.insert(i,'*') i = i +1 else: i = i + 1 print(''.join(PN)) # replace 로 바꾼 코드 PN = "010-7764-9954" i = 0 n= int(len(PN)) while i < n-4 : if PN[i] != '-': PN_re = PN.replace(PN[i],'*',1) i = i +1 PN = PN_re else: i = i + 1 print(PN_re) # 10. 리스트 a=[1,1,1,1,2,2,3,3,3,4,4,5,5,5]에서 중복 숫자를 제거한 [1,2,3,4,5] 리스트를 만드세요. list_a=[1,1,1,1,2,2,3,3,3,4,4,5,5,5] my_set = set(list_a) my_list = list(my_set) print(my_list)
c2c9a7d73a7bed548a9ca5628671b9545862be00
myzasani/billy_the_drone
/Billy/Flight2.py
1,564
3.625
4
import tello # Create Billy billy = tello.Tello() # Flight path from Station 1 to all station sequentially station = [[2, "cw", 90, "forward", 100], [3, "ccw", 90, "forward", 80], [4, "ccw", 90, "forward", 40], [5, "ccw", 90, "forward", 40], [6, "cw", 90, "forward", 60], [1, "ccw", 90, "forward", 40]] # Set destination destination = 2 # Put Tello into command mode billy.send("command", 3) # Check battery billy.send("battery?", 3) # Send the takeoff command billy.send("takeoff", 5) # Start at Station 1 and print destination print("Start at Station 1") print("Destination: " + str(destination) + "\n") # Billy's flight path for i in range(len(station)): print("Current location: Station " + str(station[i][0]-1) + "\n") # If arrive at destination station, land for a while, then takeoff again if (station[i][0]-1) == destination: billy.send("land", 3) print("Land at Station " + str(station[i][0]) + "\n") billy.send("takeoff", 5) print("Takeoff again at " + str(station[i][0]) + "\n") # print(station[i][1] + " " + str(station[i][2]) + "\n") # Turn cw or ccw billy.send(station[i][1] + " " + str(station[i][2]), 4) # print(station[i][3] + " " + str(station[i][4]) + "\n") # Move forward billy.send(station[i][3] + " " + str(station[i][4]), 4) # Reach back at Station 1 print("Arrived home") # Turn to original direction before land billy.send("cw 180", 4) # Land billy.send("land", 3) # Check battery billy.send("battery?", 3) # Close the socket billy.sock.close()
7008f73c39d0cffbb93e317e2e4371b16e4a1152
ozgecangumusbas/I2DL-exercises
/exercise_01/exercise_code/networks/dummy.py
2,265
4.21875
4
"""Network base class""" import os import pickle from abc import ABC, abstractmethod """In Pytorch you would usually define the `forward` function which performs all the interesting computations""" class Network(ABC): """ Abstract Dataset Base Class All subclasses must define forward() method """ def __init__(self, model_name='dummy_network'): """ :param model_name: A descriptive name of the model """ self.model_name = model_name @abstractmethod def forward(self, X): """perform the forward pass through a network""" def __repr__(self): return "This is the base class for all networks we will use" @abstractmethod def save_model(self, data=None): """ each model should know what are the relevant things it needs for saving itself.""" class Dummy(Network): """ Dummy machine """ def __init__(self, model_name="dummy_machine"): """ :param model_name: A descriptive name of the model """ super().__init__() self.model_name = model_name def forward(self, x): """ :param x: The input to the network :return: set x to any integer larger than 59 to get passed """ ######################################################################## # TODO # # Implement the dummy machine function. # # # ######################################################################## pass ######################################################################## # END OF YOUR CODE # ######################################################################## return x def __repr__(self): return "A dummy machine" def save_model(self, data=None): directory = 'models' model = {self.model_name: self} if not os.path.exists(directory): os.makedirs(directory) pickle.dump(model, open(directory + '/' + self.model_name + '.p', 'wb'))
f4a5bfa334b7eaf380789f6c2113a4cf84c23cce
mastan-vali-au28/Python
/Day-01/Convert.py
253
3.578125
4
#python data types n1=0O17 n2=0B1110010 n3=0X1c2 n=int(n1) print("octal 17 is:",n) n=int(n2) print("Binery 1110010 is:",n) n=int(n3) print("HexaDecimal 1c2 is:",n) """ int float complex bool str bytes bytearray list tuple dict range set Mapping """
210eec095633773aa996af34caae5daa9b8d3e17
Miragecore/python_study
/opencv/blob/disjoint.py
1,133
3.671875
4
class disJointItem(): def __init__(self,label): self.parent = self self.rank = 0 self.label = label def FindRoot(self): if self.parent != self : self.parent = self.parent.FindRoot() return self.parent ''' if self.parent == self : return self else : return Find(self.parent) ''' def Merge(self,y): xRoot = self.FindRoot() yRoot = y.FindRoot() if xRoot == yRoot : return if xRoot.rank < yRoot.rank : xRoot.parent = yRoot elif xRoot.rank > yRoot.rank : yRoot.parent = xRoot else : yRoot.parent = xRoot xRoot.rank = xRoot.rank + 1 class disjointForest(): def __init__(self): self.items = {0:disJointItem(0)} def isDictItem(self, lbl): return lbl in self.items def AddItem(self, lbl): if self.isDictItem(lbl): return self.items[lbl] = disJointItem(lbl) def GetItem(self, lbl): if self.isDictItem(lbl): return self.items[lbl] return None def MergeByLabel(self, lbl1, lbl2): item1 = self.GetItem(lbl1) item2 = self.GetItem(lbl2) item1.Merge(item2)
99b12df31f0c8ef5b6d195435787d3a26bc0254c
arijitlaik/uw-bits
/mesh_refine/spring_refinement/scripts/myarray.py
677
3.5
4
from numpy import * # a small set of helper functions to # call common array creation functions # these are useful to ensure that # all arrays are created as double-precision # floats, no matter what data are provided # as argument. For example array([1,3,4]) normally returns # an array with data of type int, but arrayf([1,3,4]) # always creates an array of floats kFloatType = float64 def arrayf( arg ): return array( arg, kFloatType ) def asarrayf( arg ): return asarray( arg, kFloatType ) def zerosf( arg ): return zeros( arg, kFloatType ) def identityf( arg ): return identity( arg, kFloatType ) def emptyf( arg ): return empty( arg, kFloatType )
0940f4182a8a5bae239930e6e51cc57879041a1d
CthulhuF/Programming
/pyatnashki_2.py
3,252
3.84375
4
from math import fabs n = int(input("Enter a grid size (3 or 4)")) pole = [[] for i in range(n)] pole_win = [[] for k in range(n)] if n == 3: pole_numb = 9 empty_value = [2, 2] else: pole_numb = 16 empty_value = [3, 3] def init(): active_line = 0 for k in reversed(range(1, pole_numb)): pole[active_line].append(k) active_line += 1 if active_line == n: active_line = 0 pole[n - 1].append('_') active_line = 0 for k in range(1, pole_numb): pole_win[active_line].append(k) active_line += 1 if active_line == n: active_line = 0 pole_win[n - 1].append('_') def draw(): if n == 3: print("=============") for i in range(n): print('||', end="") for k in range(n): print("", pole[k][i], "", end="") print("||") print("=============") else: print("====================") for i in range(n): print('||', end="") for k in range(n): print(" ", pole[k][i], "", end="") print('') print("====================") def win(): for i in range(n): if pole[i] == pole_win[i]: continue else: return 0 print("Congratulations! You win!") return 1 def move(step): print('') for i in range(n): if step in pole[i]: tile_index = [i, pole[i].index(step)] for i in range(2): if fabs(tile_index[i] - empty_value[i]) > 1: return print("Cannot do this turn") a = tile_index[0] b = tile_index[1] c = empty_value[0] d = empty_value[1] if tile_index[0] == empty_value[0] - 1 and tile_index[1] == empty_value[1]: pole[a][b], pole[c][d] = pole[c][d], pole[a][b] empty_value[0] = a empty_value[1] = b return print("You are two steps away from victory") elif tile_index[0] == empty_value[0] + 1 and tile_index[1] == empty_value[1]: pole[a][b], pole[c][d] = pole[c][d], pole[a][b] empty_value[0] = a empty_value[1] = b return print("You are doing great") elif tile_index[0] == empty_value[0] and tile_index[1] == empty_value[1] + 1: pole[a][b], pole[c][d] = pole[c][d], pole[a][b] empty_value[0] = a empty_value[1] = b return print("Can i take a couple of lessons from you") elif tile_index[0] == empty_value[0] and tile_index[1] == empty_value[1] - 1: pole[a][b], pole[c][d] = pole[c][d], pole[a][b] empty_value[0] = a empty_value[1] = b return print("Without comments") else: return print("This step cannot be done") return print("Entered non-existent cell") init() draw() won = win() while won == 0: step = int(input("Enter an tile for turn")) move(step) draw() won = win()
2d215c42bd8db5ac96ec1f2594ce5883def6f864
anilkumarravuru/Group-Spanning-Tree
/random_graph_generator.py
1,116
3.546875
4
# Anil Kumar Ravuru import random def print_graph(G_adj_list): for i in range(len(G_adj_list)): for j in range(len(G_adj_list[0])): print(format(G_adj_list[i][j],'2d'),end=' ') print() def print_graph_to_file(G_adj_list): with open('sample_graph.txt', 'w') as fp: for i in range(len(G_adj_list)): fp.write(' '.join(list(map(str, G_adj_list[i])))) fp.write('\n') node_count = int(input('Number of vertices in the graph: ')) G_adj_list = [[0 for i in range(node_count)] for j in range(node_count)] for i in range(node_count): for j in range(i+1, node_count): G_adj_list[i][j] = random.randint(1, 100) if input('Print on terminal? (y/n): ').lower() == 'y': print_graph(G_adj_list) if input('Output into sample_graph.txt? (y/n): ').lower() == 'y': print_graph_to_file(G_adj_list) group_count = int(input('Number of groups in the graph: ')) groups = [[] for i in range(group_count)] for i in range(node_count): groups[random.randint(0, group_count-1)] += [i] with open('sample_graph_groups.txt', 'w') as fp: for x in groups: if len(x) != 0: fp.write(' '.join(list(map(str, x)))) fp.write('\n')
c7a1d26abadc1ecdcd820ade5c9a03231186a2d0
adcaes/programming-puzzles
/leetcode/min_stack.py
973
3.671875
4
''' https://oj.leetcode.com/problems/min-stack/ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. ''' class MinStack: def __init__(self): self.s = [] self.mins = [] # @param x, an integer # @return nothing def push(self, x): if not self.s or self.getMin() >= x: self.mins.append(x) self.s.append(x) # @return nothing def pop(self): if self.s: if self.top() == self.getMin(): self.mins.pop() self.s.pop() # @return an integer def top(self): return self.s[-1] if self.s else None # @return an integer def getMin(self): return self.mins[-1] if self.s else None
a477f9345fcd496943a6543eba007b5a883bc1d0
Ayaz-75/Prime-checker-program
/pime_checker.py
267
4.125
4
# welcome to the prime number checker def prime_checker(number): for i in range(2, number): if number % i == 0: return "not prime" else: return "prime" num = int(input("Enter number: ")) print(prime_checker(number=num))
8f3ac6c4bd1468f3ef699529f3d4f21b04035586
juliapochynok/LearnKorean_project
/final_console/main.py
1,046
3.984375
4
import fileinput import random from classes import WordController, User def main(): ''' Main function. Responsible for program's work. ''' file_name = make_userfile() fl = open(file_name, "a") user = User(file_name) iterat = True while iterat == True: print(menu()) section = input("Choose: ") if len(section) < 1: iterat = False user.choose_section(section) def make_userfile(): ''' Asks user to enter his name and makes file named the same way. ''' name = input("Please enter your name and surname without white spaces: ") file_name = str(name) + ".txt" time = input("Is it your first time using this program: ") if time == 'yes' or time == 'YES' or time == 'Yes': fl = open(file_name, "w") fl.write("0\n==========\n") fl.close() return file_name def menu(): ''' Prints out menu ''' return """\n1. Learn new word\n 2. Test yourself\n 3.Wordlist\n""" if __name__ == "__main__": main()
c481288f70a5a90afed1aaa7c581cc0ef8af8cf2
czardoz/dsa
/AVLTrees/trees.py~
5,925
3.5625
4
''' Created on Sep 5, 2012 @author: czardoz ''' def printval(node): if node is not None: print node.data class Node: def __init__(self, data, left = None, right = None, parent = None): self.left = left self.right = right self.parent = parent self.data = data def __str__(self): x = z = w = "" if self.parent is not None: x = " Parent: " + str(self.parent.data) y = " Me: " + str(self.data) if self.left is not None: z = " My left: " + str(self.left.data) if self.right is not None: w = " My right: " + str(self.right.data) return x+y+z+w def numofchildren(self): count = 0 if self.left: count+=1 if self.right: count+=1 return count def lookup(self, value): if value == self.data: return self elif value > self.data: if self.right == None: return None else: return self.right.lookup(value) else: if self.left == None: return None else: return self.left.lookup(value) def insert(self, value): if value > self.data: if self.right == None: self.right = Node(value, parent = self) else: self.right.insert(value) elif value < self.data: if self.left == None: self.left = Node(value, parent = self) else: self.left.insert(value) def delete(self, data): node = self.lookup(data) if node is None: return parent = node.parent if node is not None: children_count = node.numofchildren() if children_count == 0: if parent.left is node: parent.left = None else: parent.right = None del node elif children_count == 1: if node.left: n = node.left else: n = node.right if parent.left is node: parent.left = n n.parent = parent else: parent.right = n n.parent = parent del node else: successor = self.getsucessor(node.data) node.data = successor.data if successor.isleftchild(): successor.parent.left = None else: successor.parent.right = None def get_data(self): stack = [] node = self while stack or node: if node: stack.append(node) node = node.left else: node = stack.pop() yield node.data node = node.right def get_array(self): array = [] for i in self.get_data(): array.append(i) return array def get_min(self): x = self while x.left != None: x = x.left return x def get_max(self): x = self while x.right != None: x = x.right return x def get_height(self): if self.numofchildren() == 0: return 0 else: if self.left != None: hleft = self.left.getheight() else: hleft = 0 if self.right != None: hright = self.right.getheight() else: hright = 0 return 1 + max(hleft, hright) def display(self, prefix = ' '): if self.left != None: self.left.display(prefix + ' ') print prefix + str(self.data) if self.right != None: self.right.display(prefix+' ') def printdetails(self): root = self for i in self.get_data(): print root.lookup(i) def get_sucessor(self, value): asorted = self.getarray() i = asorted.index(value) return self.lookup(asorted[i+1]) def get_predecessor(self, value): asorted = self.getarray() i = asorted.index(value) return self.lookup(asorted[i-1]) def isleftchild(self): if self.parent == None: return False if self.parent.left == self: return True else: return False def isrightchild(self): if self.parent == None: return False if self.parent.right == self: return True else: return False def rotateright(self): if self.left is None: return q = self above = q.parent p = q.left b = p.right p.parent = above if q.isleftchild(): if above is not None: above.left = p else: if above is not None: above.right = p p.right = q q.parent = p q.left = b if b is not None: b.parent = q def get_root(self): curr = self while curr.parent is not None: curr = curr.parent return curr def maketree(a): root = Node(a.pop(0)) for i in a: root.insert(i) return root def main(): a = [23,212,21,4,51,13,124,57,74] x = maketree(a) x.display() print "===========================" z = x.lookup(124) z.rotateright() print "===========================" x.get_root().display() print "===========================" if __name__ == '__main__': main()
9ce94185f2abae34925c7942961a27a8e696c7a7
czardoz/dsa
/MergeSort/sort.py
874
3.609375
4
''' Created on Aug 19, 2012 @author: czardoz ''' def merge(a, b): result = [] j = 0 i = 0 # swap if lengths not as assumed # a is shorter than b if len(a) > len(b): temp = a a = b b = temp while 1: if a[i] < b[j]: result.append(a[i]) i+=1 else: result.append(b[j]) j+=1 if j == len(b): result.extend(a[i:]) break if i == len(a): result.extend(b[j:]) break return result def msort(a): if len(a) <= 1: return a middle = len(a)/2 left = msort(a[:middle]) right = msort(a[middle:]) result = merge(left, right) return result def main(): a = [13,526,11,46,1000,22,5,7,32,26,12,55,0,619] c = msort(a) print c if __name__ == '__main__': main()
549e0ff8f318cf667c0094bbb1be8fa31c8eb429
TylerGrantSmith/agricola
/agricola/choice.py
1,233
3.53125
4
class Choice(object): def __init__(self, desc=None): self.desc = desc def validate(self, choice): pass class YesNoChoice(Choice): def __init__(self, desc=None): super(DiscreteChoice, self).__init__(desc) class DiscreteChoice(Choice): def __init__(self, options, desc=None): if not options: raise ValueError( "Cannot create a DiscreteChoice instance with an empty " "options list. Choice description is:\n{0}".format(desc)) super(DiscreteChoice, self).__init__(desc) self.options = list(options) class CountChoice(Choice): def __init__(self, n=None, desc=None): self.n = n super(CountChoice, self).__init__(desc) class ListChoice(Choice): def __init__(self, subchoices, desc=None): super(ListChoice, self).__init__(desc) self.subchoices = subchoices class VariableLengthListChoice(Choice): def __init__(self, subchoice, desc=None, mx=None): super(VariableLengthListChoice, self).__init__(desc) self.subchoice = subchoice self.mx = mx class SpaceChoice(Choice): def __init__(self, desc=None): super(SpaceChoice, self).__init__(desc)
52230fa21f292174d6bca6c86ebcc35cc860cb69
kisyular/StringDecompression
/proj04.py
2,900
4.625
5
############################################# #Algorithm #initiate the variable "decompressed_string" to an empty string #initiate a while True Loop #prompt the user to enter a string tocompress #Quit the program if the user enters an empty string #Initiate a while loop if user enters string #find the first bracket and convert it into an integer #find the other bracket ")" #find the comma index and convert it to an integer #find the first number within the parenthesis and convert it to integer #find the index of the second number within the comma and the last parenthesis #get the string within the first index and the second index numbers #find the decompressed string. Given by the string entered plus string within #update the new string entered to a newer one #replace the backslash with a new line during printing #print the decompressed string Backslash = "\\" #initiate the variable "decompressed_string" to an empty string decompressed_string ="" print() #initiate a while True Loop while True: #prompt the user to enter a string tocompress string_entered=input ("\nEnter a string to decompress (example 'to be or not to(13,3)' \ will be decompressed to 'TO BE OR NOT TO BE' see more examples in the pdf attached \ or press 'enter' to quit: ") #Quit the program if the user enters an empty string if string_entered=="" : print("There is nothing to decompress. The Program has halted") break #Initiate a while loop if user enters string while string_entered.find("(") != -1: #find the first bracket and convert it into an integer bracket_1st=int(string_entered.find("(")) #find the other bracket nd convert to an integer ")" sec_bracket=int(string_entered.find(")")) #find the comma index and convert it to an integer comma=int(string_entered.find(",", bracket_1st, sec_bracket)) # find the first number within the parenthesis and convert it to integer index_1st = int(string_entered[bracket_1st+1: comma]) # find the index of the second number within the comma and the last parenthesis sec_indx=int(string_entered[comma+1 : sec_bracket]) #get the string within the first index and the second index numbers string_within=string_entered[bracket_1st - index_1st \ : bracket_1st - index_1st + sec_indx] #find the decompressed string. Given by the string entered plus string within decompressed_string=(string_entered [ : bracket_1st] + string_within) #update the new string entered to a newer one string_entered=decompressed_string + string_entered[sec_bracket+1: ] #replace the backslash with a new line during printing decompressed_string=string_entered.replace(Backslash, "\n") #print the decompressed string print("\nYour decompressed string is:" "\n") print(decompressed_string)