blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
6ca26889a55b59f612fff3448b8fd200d858b9ef
MAPLE-Robot-Subgoaling/IPT
/data/HW4/hw4_036.py
316
4.1875
4
def main(): x = int(input("Please enter the starting height of the hailstone: ")) while(x != 1): print("Hail is currently at height " + str(x)) if(x % 2 == 0): x = int(x/2) elif(x % 2 !=0): x = int((x*3)+1) print("Hail stopped at height " + str(x)) main()
ebc591c838f31b409164a7d87f76e16ed2727ede
emelynsoria/more_python
/topics/palindrome.py
618
4.0625
4
n = int(input("Enter number:")) temp = n rev = 0 while(n > 0): dig = n % 10 rev = rev*10+dig n = n//10 if(temp == rev): print("The number is a palindrome!") else: print("The number isn't a palindrome!") ######################### # with class class ConvertInt: def __init__(self): self.num = 0 def palindrome(self, num): self.num = num s = str(num) n = s[::-1] # reverse the string if(n == s): return 'Palindrome' else: return 'Not palindrome' print(ConvertInt().palindrome(int(input('Enter a number: '))))
b90973a283d9722802eaa1c4d4a8e579315962fb
miro-lp/SoftUni
/Fundamentals/Dictionaries/Snowwhite.py
867
3.640625
4
from collections import defaultdict dwarfs = {} colors = {} dwarfs_color = defaultdict(int) while True: data = input() if data == "Once upon a time": break dwarf, color, body = data.split(" <:> ") if color not in colors: colors[color] = [] if dwarf not in colors[color]: colors[color].append(dwarf) if (dwarf, color) not in dwarfs: dwarfs[(dwarf, color)] = int(body) else: if int(body) > dwarfs[(dwarf, color)]: dwarfs[(dwarf, color)] = int(body) for clr in colors: for i in colors[clr]: dwarfs_color[(i, clr)] = len(colors[clr]) # dwarfs_color = dict(sorted(dwarfs_color.items(), key=lambda x: -x[1])) dwarfs = dict(sorted(dwarfs.items(), key=lambda y: (-y[1], -dwarfs_color[y[0]]))) for i in dwarfs: dwarf, color = i print(f"({color}) {dwarf} <-> {dwarfs[i]}")
50b8fb8d27008577835e9af8b02300fb9e555770
ed1rac/AulasEstruturasDados
/UNP/ref/Python/TADs e Classes/lista_circular.py
2,583
3.65625
4
class Node: def __init__(self, valor): self.valor = valor self.proximo = None class DequeCircular: def __init__(self): self.head = None self.cauda = None def mostra(self): atual = self.head while atual: print(atual.valor) atual = atual.proximo if atual == self.head: break def mostra_cabeca(self): print(f'Cabeça: {self.head.valor}') def mostra_cauda(self): print(f'Cauda: {self.cauda.valor}') def insere_no_inicio(self, valor): node = Node(valor) if not self.head: self.head = node self.cauda = node self.cauda.proximo = self.head else: node.proximo = self.head self.head = node self.cauda.proximo = self.head def insere_no_fim(self, valor): node = Node(valor) if not self.head: self.head = node self.cauda = node self.cauda.proximo = self.head else: self.cauda.proximo = node self.cauda = node self.cauda.proximo = self.head def __len__(self): atual = self.head cont = 0 while atual: cont += 1 atual = atual.proximo if atual == self.head: break return cont def remove_do_inicio(self): if self.head == self.cauda: self.head = None self.cauda = None else: self.head = self.head.proximo self.cauda.proximo = self.head def remove_do_fim(self): if self.head == self.cauda: self.head = None self.cauda = None else: atual = self.head while atual.proximo != self.cauda: atual = atual.proximo atual.proximo = self.head self.cauda = atual meu_deque_circular = DequeCircular() meu_deque_circular.insere_no_fim(1) meu_deque_circular.insere_no_fim(2) meu_deque_circular.insere_no_fim(3) meu_deque_circular.insere_no_fim(4) meu_deque_circular.mostra() # 1 2 3 4 meu_deque_circular.mostra_cabeca() meu_deque_circular.mostra_cauda() meu_deque_circular.insere_no_inicio(5) meu_deque_circular.mostra() # 1 2 3 4 meu_deque_circular.mostra_cabeca() meu_deque_circular.mostra_cauda() print('Tamanho da lista: ', len(meu_deque_circular)) meu_deque_circular.remove_do_inicio() meu_deque_circular.mostra() # 2 3 4 meu_deque_circular.mostra_cabeca() meu_deque_circular.mostra_cauda()
df6c09cb637bd26cd6330d554743143d02b9345b
lolegoogle1/asyncio_learning
/syncfunc_in_eloop.py
823
3.953125
4
# loop.run_in_executor, start in the separate thread import asyncio from urllib.request import urlopen # a synchronous function def sync_get_url(url): return urlopen(url).read() # func for processing sync_function in the thread pool executor async def load_url(url, loop=None): if loop is None: raise KeyError("there should be a loop obj") future = loop.run_in_executor(None, sync_get_url, url) # run_in_executor means to start the code in the inner thread pool executor of the event loop response = await future # we need to wait for completion of the future_obj print(len(response)) loop = asyncio.get_event_loop() loop.run_until_complete(load_url("https://google.com", loop=loop)) # Run the event loop until a Future is done. # Return the Future's result, or raise its exception.
23aace72286877f35ec3a2b80377a9be3ef62181
rishinkaku/Software-University---Software-Engineering
/Python Fundamentals/MidExam_Preparation/01. Disneyland Journey.py
519
3.515625
4
journey_cost = float(input()) months = int(input()) savings = 0 for i in range(1, months+1): if i % 2 != 0 and i > 1: spend = savings * 0.16 savings -= spend if i % 4 == 0: bonus = savings * 0.25 savings += bonus money = journey_cost * 0.25 savings += money if savings >= journey_cost: print(f"Bravo! You can go to Disneyland and you will have {savings-journey_cost:.2f}lv. for souvenirs.") else: print(f"Sorry. You need {journey_cost-savings:.2f}lv. more.")
1e158d33b47f3a6ee0fdef3a1142334f039bb69f
RSA99/python_1
/validate.py
1,934
4.125
4
def is_valid(creditnumber): creditint = int(creditnumber) creditlist = list(creditnumber) if creditint < 0 or creditint%1 != 0: # I check whether the credit card number is negative or a decimal return False else: listnumber = [] for i in creditlist: listnumber.append(int(i)) # creditlist is converted to a list of integers, so that calculations can be made listnumber.reverse() counter = 0 sumall = 0 for digit in listnumber: if counter%2 == 0: # values in listnumber for which modulo of counter == 0 are not doubled sumall += digit else: doubled = digit*2 if doubled >= 10: # if doubled digit is greater than 10, its digits are added together using modulo of number + 1 sumall += (doubled % 10 + 1) else: sumall += doubled counter += 1 if sumall % 10 == 0: return True else: return False creditnumber = "492X818708805X89" credlist = list(creditnumber) result = [] for x,i in enumerate(credlist): if i == "X": result.append(x) # positions of "X"s are appended into a list 'result' if len(result) == 1: # if length of results ==1, there is one "X" position = result[0] for m in range(9): credlist[position] = m # "X" is replaced with integers in range(9) # need to convert the elements to a string, and join the list of strings to a string for being able to call is_valid function if is_valid(''.join(str(e) for e in credlist)) == True: print(m) if len(result) == 2: position1 = result[0] position2 = result[1] for m in range(9): credlist[position1] = m for n in range(9): # 'for' loop is nested so all possible combinations of integers replacing both 'X's are checked credlist[position2] = n # need to convert the elements to a string, and join the list of strings to a string for being able to call is_valid function if is_valid(''.join(str(e) for e in credlist)) == True: print(m,n)
74316a9c7e7181d5dc31d42220486171462f934c
AJB363/PartIA-Flood-Warning-System-AJB363-MK2078
/floodsystem/plot.py
1,292
3.765625
4
import matplotlib.pyplot as plt import matplotlib.dates as d from numpy import linspace from .analysis import polyfit def plot_water_levels(station, dates, levels): """ Plots the station water level history against time """ # Return early if data is invalid if len(dates) != len(levels): print("floodsystem.plot.py plot_water_levels: len(dates) != len(levels)") return plt.plot(dates, levels) plt.xlabel('date') plt.ylabel('water level (m)') plt.xticks(rotation=45) plt.title('Station: {}'.format(station.name)) plt.tight_layout() plt.show() def plot_water_level_with_fit(station, dates, levels, p): """ Plots the station water level history against time, with a polynomial line of best fit of order p. """ # Return early if data is invalid if len(dates) != len(levels): print("floodsystem.plot.py plot_water_levels: len(dates) != len(levels)") return poly, d0 = polyfit(dates, levels, p) x = linspace(0, d.date2num(dates[-1]) - d.date2num(d0), len(dates)) plt.plot(dates, levels) plt.plot(dates, poly(x)) plt.xlabel('date') plt.ylabel('water level (m)') plt.xticks(rotation=45) plt.title('Station: {}'.format(station.name)) plt.tight_layout() plt.show()
d2c868b5ee8561a532eaf4aa5a440b6ccb193c59
rafxrad/inpcodes
/lista_4.py
311
4.125
4
# Programa que calcula raio, perímetro e área de circunferência a partir do diâmetro. diametro = float(input('Por favor, digite o diâmetro em cm: ')) pi = 3.14 raio = diametro / 2 P = 2 * pi * raio A = pi * (raio ** 2) print('Raio: ', raio, "cm") print('Perímetro: ', P, 'cm') print('Área: ', A, 'cm')
e1c7097ceae257b2a2c6abad1db72717219b4580
DreamOfTheRedChamber/leetcode
/Python/DepthBreathFirstSearch/BackTrackingAllResults/CombinationSum.py
1,076
3.640625
4
import unittest from typing import List class CombinationSum(unittest.TestCase): def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: def dfs(candidates: List[int], target: int, start: int, currSum: int, path: List[int], result: List[List[int]]): # edge case if currSum > target: return if currSum == target: result.append(path.copy()) return # recursion for i in range(start, len(candidates)): path.append(candidates[i]) dfs(candidates, target, i, currSum + candidates[i], path, result) path.pop() return result result = [] dfs(candidates, target, 0, 0, [], result) return result def test_normal(self): print(self.combinationSum([2, 3, 5], 8)) print(self.combinationSum([2, 3, 6, 7], 7)) def test_Edgecase(self): print(self.combinationSum([2, 4], 7)) if __name__ == '__main__': unittest.main()
49f8d20625352fd65d82a0a366560afc8e185613
shuowenwei/LeetCodePython
/Medium/LC49.py
1,484
3.640625
4
# -*- coding: utf-8 -*- """ @author: Wei, Shuowen https://leetcode.com/problems/group-anagrams/ LC49, LC72 """ class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ dict_word_index = collections.defaultdict(list) for i, w in enumerate(strs): sort_w = ''.join(sorted(w)) dict_word_index[sort_w].append(i) res = [] for _, indices in dict_word_index.items(): tmp = [strs[i] for i in indices] res.append(tmp) return res # longer version, Time Limit Exceeded """ from collections import Counter dict_word_len = collections.defaultdict(list) for w in strs: dict_word_len[len(w)].append(w) def isAnagram(a, b): return Counter(a) == Counter(b) res = [] for length, list_words in dict_word_len.items(): visited = set() for i in range(len(list_words)): if i not in visited: tmp = [list_words[i]] visited.add(i) for j in range(len(list_words)): if i != j and j not in visited and isAnagram(list_words[i], list_words[j]): tmp.append(list_words[j]) visited.add(j) res.append(tmp) return res """
e3ce5cee2d429b6ba156a502bfad68fdadf836be
Qinpeng96/leetcode
/面试题 16.11. 跳水板.py
1,020
3.953125
4
""" 你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为shorter, 长度较长的木板长度为longer。你必须正好使用k块木板。编写一个方法,生成跳水板所有可能的长度。 返回的长度需要从小到大排列。 示例: 输入: shorter = 1 longer = 2 k = 3 输出: {3,4,5,6} 提示: 0 < shorter <= longer 0 <= k <= 100000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/diving-board-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def divingBoard(self, shorter: int, longer: int, k: int) -> List[int]: out = [] if k == 0:return out if shorter == longer:return [shorter*k] base = k * shorter for i in range(k+1): out.append(base + (longer-shorter)*i) return out if __name__ == "__main__": s = Solution() print(s.divingBoard(1,3,10000))
82960a0e494ecb49d4aa35ebfd0ab3304e826047
bulatnig/textsolutions
/common_sense/ch10/ex4.py
290
4.0625
4
from typing import Any, List def print_recursively(array: List[Any]) -> None: for item in array: if isinstance(item, List): print_recursively(item) else: print(item) array = [1,2,3,[4,5,6],7,[8,[9,10,11, [12,13,14]]]] print_recursively(array)
0bf2dbf6faf485929b5d508a21ed3d68d7cc86e9
JingyuLeo/md_utils
/md_utils/count_entries.py
2,955
3.625
4
#!/usr/bin/env python """ Adds a string to the beginning and end of a file. """ from __future__ import print_function import sys import argparse from md_utils.md_common import InvalidDataError, create_out_fname, warning __author__ = 'hmayes' # Error Codes # The good status code GOOD_RET = 0 INPUT_ERROR = 1 IO_ERROR = 2 INVALID_DATA = 3 # Constants # # Defaults DEF_NEW_FNAME = None def parse_cmdline(argv): """ Returns the parsed argument list and return code. `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. """ if argv is None: argv = sys.argv[1:] # initialize the parser object: parser = argparse.ArgumentParser(description='Reads in a file and counts the number of columns on the first line.') parser.add_argument("-f", "--file", help="The location of the file to be analyzed.") parser.add_argument("-n", "--new_name", help="Name of amended file.", default=DEF_NEW_FNAME) args = None try: args = parser.parse_args(argv) except IOError as e: warning("Problems reading file:", e) parser.print_help() return args, IO_ERROR except KeyError as e: warning("Input data missing:", e) parser.print_help() return args, INPUT_ERROR return args, GOOD_RET def process_file(f_list, new_f_name): value_dict = {} print("hello world") with open(f_list) as f: for f_name in f.readlines(): f_name = f_name.strip() with open(f_name) as d: for line in d.readlines(): # string2 = string1.strip('\n') line = line.strip() split_line = line.split() entries = len(split_line) # For this purpose, subtract 1 (hydronium) and divide by 3 water_mol_number = (entries - 1) / 3 if water_mol_number in value_dict: value_dict[water_mol_number] += 1 else: value_dict[water_mol_number] = 1 if new_f_name is None: new_f_name = create_out_fname(f_list, suffix='_count') with open(new_f_name, 'w') as w_file: for key in value_dict: w_file.write(str(key) + "," + str(value_dict[key]) + "\n") print(key, value_dict[key]) def main(argv=None): # Read input args, ret = parse_cmdline(argv) # TODO: did not show the expected behavior when I didn't have a required cfg in the ini file if ret != GOOD_RET: return ret try: process_file(args.file, args.new_name) except IOError as e: warning("Problems reading file:", e) return IO_ERROR except InvalidDataError as e: warning("Problems reading data:", e) return INVALID_DATA return GOOD_RET # success if __name__ == '__main__': status = main() sys.exit(status)
7c9bb593ba4c3db31830df324d50e24533291dc2
SmashingBailey/Python-examples
/ex40/demo1.py
1,224
3.75
4
D = 'Devon' A = 'Ashley' J = 'Jacob' M = 'Mikayla' S = 'Shawna' E = 'Eric' definition = "I am defining " line_break = 10 * '-' def Devon(): print definition + D + ':' print "I just want to let you know. We're all counting on you." print line_break raw_input("Hit enter to move to the next line") print line_break def Ashley(): print definition + A print "I am the queen. I do what I please." print line_break raw_input("Hit enter to move to the next line") print line_break def Jacob(): print definition + J print "Hey Bailey, I'm going to hit you." print line_break raw_input("Hit enter to move to the next line") print line_break def Mikayla(): print definition + M print "Don't touch my lightsaber" print line_break raw_input("Hit enter to move to the next line") print line_break def Eric(): print definition + E print "Say another word and my foot will go up your ass" print line_break raw_input("Hit enter to move to the next line") print line_break def Shawna(): print definition + S print "Ich leibe alles" print line_break raw_input("Hit enter to move to the next line") print line_break
cf44586993809628a4b7cbf84a07574926f90a61
brillianthhj/Algorithm_TIL
/python/Week5/Q2.Binary_Search_Tree_Iterator.py
1,103
3.984375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class BSTIterator: def __init__(self, root: TreeNode): self.stack = [] self.stack_leftmost_value(root) def stack_leftmost_value(self, root): while root: self.stack.append(root) root = root.left def next(self) -> int: """ @return the next smallest number """ node = self.stack.pop() if node.right: self.stack_leftmost_value(node.right) return node.val def hasNext(self) -> bool: """ @return whether we have a next smallest number """ return len(self.stack) > 0 root = TreeNode(7) n3 = TreeNode(3) n15 = TreeNode(15) n9 = TreeNode(9) n20 = TreeNode(20) root.left = n3 root.right = n15 n15.left = n9 n15.right = n20 obj = BSTIterator(root) print(obj.next()) print(obj.next()) print(obj.next()) print(obj.next()) print(obj.next()) print(obj.hasNext())
183a3d1aac3207572dd104c9961ffa6a101a7bd3
mkhurramssuet/learn-python
/step07(2)_functions/functions02.py
911
3.90625
4
# Passing an arbitrary number of arguments def make_pizza(*toppings): print(toppings) # print list of arguments make_pizza('mushrooms', 'green peppers', 'extra cheese') # Preventing a function from modifying original List num_list = [0, 1, 2, 3, 4] def change_list(my_list): my_list.append("new element") print("list from function: "+str(my_list)) change_list(num_list[:]) # passing the copy of the list print("original list: "+str(num_list)) def build_profile(first, last, **user_info): # double asterisks create an empty dictionary called user_info profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value # explicitly adding properties to my dictionary return profile user_profile = build_profile('hammad', 'tariq', location='karachi', field='computer science') print(user_profile)
8ca56e2f0faad2af531a5af09357f089c4f4049d
rahuldave/semflow
/newmast/mast_proprdf_iue.py
1,316
3.53125
4
""" This is to be used by mast_proprdf.py and determines how to parse a line from the <mission>_proposal.txt file, since it appears to be mission specific. The IUE proposal list looks like OD89K|Observing the Earth|Ralph C.|Bohlin|STScI|Abstract unavailable|N where the 'Abstract unavailable' can be filled in with the abstract text and this text can contain | characters. Note that the proposal title can contain \n (at least it does for proposal id OD88Z). The PI name can be first=" ", last="misc", which we treat as missing. """ def splitProposalLine(line): """Given a single line of text representing a proposal, split out the interesting fields and return as a dictionary: propid title pi_first pi_last The only required field is propid, although expect to have pi_last if pi_first is present. """ (propid, title, pi_first, pi_last, place, remainder) = \ line.split("|", 5) out = { "propid": propid } def addit(field, value): val = value.strip() if val != "": out[field] = val addit("title", title) # remove the misc PI field; it looks like all occurrences # have misc as a last name if pi_last != "misc": addit("pi_first", pi_first) addit("pi_last", pi_last) return out
17d518bc1caf68e49f6553bd002c415e1c2df4eb
davidlyness/Advent-of-Code-2016
/14/14b.py
1,375
3.921875
4
# coding=utf-8 """Advent of Code 2016, Day 14, Part 2""" import hashlib def get_hash(string): """ Calculate the MD5 hash of a given string, repeated 2017 times. :param string: the given string :return: hexadecimal hash of the string """ for _ in range(2017): string = hashlib.md5(string.encode()).hexdigest() return string def get_repeating_sequence(string): """ Determine the first thrice-repeating character within a string. :param string: the given string :return: the repeating character if it exists; None otherwise """ for position in range(len(string) - 2): sequence = string[position:position+3] if sequence == string[position] * 3: return sequence[0] return None with open("input.txt") as f: salt = f.read().rstrip("\n") hashes = [] key_indexes = [] for i in range(1000): hashes.append(get_hash(salt + str(i))) index = 0 while len(key_indexes) < 64: hashes.append(get_hash(salt + str(index+1000))) candidate_key = hashes[index] candidate_character = get_repeating_sequence(candidate_key) if candidate_character: extended_sequence = candidate_character * 5 if any(extended_sequence in hashed_string for hashed_string in hashes[index+1:index+1001]): key_indexes.append(index) index += 1 print(key_indexes[-1])
84c30c72c56ca91f9813288ad42b088f614bad8e
ericsonyc/ItelliJ_Projects
/PythonProject/partA_3.py
489
4
4
def sign_magnitude(number, bits): maxValue = 2 ** (bits - 1) - 1 minValue = -2 ** (bits - 1) if number > maxValue or number <= minValue: return 'None' output = '{:b}'.format(number) if number < 0: output = output[1:] output = format(output, '0>' + str(bits)) if number < 0: output = '1' + output[1:] return output if __name__ == '__main__': number = -16 bits = 5 output = sign_magnitude(number, bits) print(output)
bbd488952f6a7784c43e421bf3971849f53503b1
cara-the-walker/number-guessing
/guessing.py
1,213
4
4
import pandas as pd import numpy as np import random #def display(input): # print('The answer is ',answer,'!') def guess(ans): dic = {'target' : ans} r = range(1,100) while True: while True: guess = input('Please make you guess by entering an integral number between 0 and 100: ').strip() try: int(guess) break except ValueError: print('\n\nYour input is not recoginizable. \nWe\'ll need to ask you for ONLY integral number.\n\n') guess = int(guess) # print(type(guess),' ',guess,' ',dic['target'], ' ',isinstance(ans,int), ' ',guess in r) if guess in r: dic['user input'] = guess break; else: print('\n\nYour input is not recoginizable. \nWe\'ll need to ask you for that number BETWEEN 0 AND 100.\n\n') return dic def main(): print('Welcome to Number Guessing game!! \n\nThe target number is between 0 and 100.\n\n') answer = int(random.random()*100) while True: num = guess(answer) print(num) # print(guess(answer)) print('break') break if __name__ == "__main__": main()
4983a886150dde733fab68ff7c1c1e87f1d384ff
denisefavila/python-playground
/src/linked_list/models/sum_lists.py
1,170
4.125
4
from src.linked_list.models.linked_list import LinkedList def sum_lists(linked_list1: LinkedList, linked_list2: LinkedList) -> LinkedList: """ You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Implements a function that adds the two numbers and returns the sum as a linked list. Input: (7-> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295. Output: 2 -> 1 -> 9. That is, 912. """ result_linked_list = LinkedList() current_node1, current_node2 = linked_list1.head, linked_list2.head carry = 0 while current_node1 or current_node2: result = 0 if current_node1: result += current_node1.item current_node1 = current_node1.next if current_node2: result += current_node2.item current_node2 = current_node2.next result += carry carry = result // 10 result_linked_list.push_back(result % 10) if carry: result_linked_list.push_back(carry) return result_linked_list
02001090d72fccec7facb05cc36c2ce3ba9607d9
e-lin/LeetCode
/19-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-list.py
1,221
3.921875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ ptr = head length = self.countNodeLength(ptr) idx = length - n #position to remove if 0 == idx: return head.next for i in range(idx-1): #find the previous one ptr = ptr.next # print "ptr to delete: " + str(ptr.next.val) ptr.next = ptr.next.next return head def countNodeLength(self, node): ptr = node length = 0 while ptr is not None: length += 1 ptr = ptr.next return length def printNode(node): ptr = node while ptr is not None: print ptr.val ptr = ptr.next def main(): node = ListNode(1) node.next = ListNode(2) node.next.next = ListNode(3) node.next.next.next = ListNode(4) n = 1 solution = Solution() result = solution.removeNthFromEnd(node, n) printNode(result) if __name__ == '__main__': main()
b36538b2ae34ab461dd8a66601e3364099f2e49f
dada99/python-learn
/builtin/enum1.py
305
4.09375
4
from enum import Enum class Color(Enum): #Even though we use the class syntax to create Enums, Enums are not normal Python classes RED = 1 GREEN = 2 BLUE = 3 #Color.RED.name = 'ORANGE' # This action will raise exeption myenum = Color # Make a copy of Color enum object print(myenum.RED.value)
e2460cec801cff88b6abde53c2270f074631fabe
Sheep-coder/practice2
/Python00/chap02list0211.py
414
3.890625
4
# 二つの整数値を読み込んで加減乗除(その1:文字列を読み込んで整数に変換) s=input('整数a:') a=int(s) s=input('整数b') b=int(s) print('a+bは',a+b,'です。') print('a-bは',a-b,'です。') print('a*bは',a*b,'です。') print('a/bは',a/b,'です。') print('a//bは',a//b,'です。') print('a%bは',a%b,'です。') print('a**bは',a**b,'です。')
d31b8c8cfde4b0d8a68ab6438745471dbcdafabe
shivam-raj-4/1BM17CS095
/lab4.py
768
3.71875
4
class University: def __init__(self): self.id=None self.age=None self.marks=None def validate_marks(self): if self.marks>=0 and self.marks<=100: print("valid marks") return True return False def validate_age(self): if self.age>=20: print("valid age") return True return False def check_qualification(self): if self.marks>=65: return True return False def setter(self): self.id=input("Enter id:") self.age=int(input("Enter Age:")) self.marks=float(input("Enter marks:")) def getter(self): print("ID :",self.id) print("AGE :",self.age) print("MARKS :",self.marks) u=University() u.setter() u.getter() if u.check_qualification(): print("Student Qualify for Admission") else: print("Student not Qualify for Admission")
363c4a94b722bf9c8852550567e74bd59992e229
SreeramSP/Python-Programs-S1
/Division-Of-2-Numbers.py
125
3.734375
4
a = input("Enter the 1st number=") b = input("Enter the 2nd number=") division = int(a) / int(b) print("Division=", division)
c044e9f0a594e084f4adb4e11a3012611af85480
aroques/perceptron
/main.py
2,332
3.703125
4
from random import choice from numpy import dot, random from dataset import get_training_data_from_txt_file, line_to_int_list def main(): num_columns, num_rows, training_data = get_training_data_from_txt_file() iterations = 100 w = random.rand(3) eta = 0.2 no_error_count = 0 print('Training the perceptron...') for i in range(iterations): x, expected = choice(training_data) result = dot(w, x) error = expected - sign(result) if error == 0: no_error_count += 1 else: # Reset the error count no_error_count = 0 w += eta * error * x error_rate = compute_error_rate(training_data, w) print('Iteration {:2}: Error Rate = {:2}%'.format(i, error_rate * 100)) if no_error_count == 30: print('No error was recorded 30 consecutive times, so the perceptron is trained.') print('30 is an arbitrarily chosen number and may need to be adjusted.') break print('\nTesting each sample in the training data...') for x, _ in training_data: result = dot(x, w) print("Sample {}: Result: {} -> Class: {}".format(x[:num_columns], result, sign(result))) print('\nEntering a loop to query the perceptron. Press ctrl-c at anytime to exit.') while True: sample = input('Enter a sample ({} numbers separated by a space): '.format(num_columns)) try: sample = line_to_int_list(sample) sample.append(1) # Append bias except ValueError: print('Input was not {} numbers separated by a space. Please try again. '.format(num_columns)) continue result = dot(sample, w) print("Sample {}: Result: {} -> Class: {}".format(sample[:num_columns], result, sign(result))) def compute_error_rate(training_data, w): num_misclassified = count_num_misclassified(training_data, w) return num_misclassified / float(len(training_data)) def count_num_misclassified(training_data, w): num_incorrect = 0 for x, expected in training_data: result = dot(x, w) error = expected - sign(result) if error != 0: num_incorrect += 1 return num_incorrect def sign(x): return -1 if x < 0 else 1 if __name__ == '__main__': main()
3cde79afe33d051398a9c4e7a117c0c38d3a23dc
SriYUTHA/PSIT
/Week 5/Stepper I.py
143
3.78125
4
"""Stepper I""" def main(): """It will show your print""" num = int(input()) for xxx in range(1, num+1): print(xxx) main()
dddf85629ed405be4074dd87dd8e448a64d78f3b
Nazim2722/java_practice
/pya6.txt
215
4.09375
4
a=int(input("enter a ")) b=int(input("enter b ")) c=int(input("enter c ")) if a>b and a>c and b>c: print("number in descending order are:",a,b,c) elif b>c and c>a: print("number in descending order are:",b,c,a)
91e47d01ead2e7bc648a5366934ede599210bc9a
Aasthaengg/IBMdataset
/Python_codes/p03011/s069668061.py
132
3.640625
4
A,B,C = map (int, input ().split ()) if A>=B>=C or A>=C>=B: print (B+C) elif B>=A>=C or B>=C>=A: print (A+C) else: print (A+B)
2b43148bd7d12a9c39ecf71317c43e6b7a6a7b9a
turlapatykaushiksharma/Programs-and-codes
/Project-Euler/smallest_multiple_problem5.py
205
3.765625
4
from fractions import gcd from functools import reduce def lcm(a,b): "Calculate the lowest common multiple of two integers a and b" return a*b//gcd(a,b) k = reduce(lcm, range(1,20+1)) print k
96528e7d767cd9dd6e9b685389a4c5251589711e
MilesYeah/ASimpleSummary-Python
/ObjectedOriented.面向对象/super()/codes/super.1.py
586
3.671875
4
class Parent(object): def __init__(self): print("Enter Parent") super().__init__() print("Leaving Parent") class Son1(Parent): def __init__(self): print("Enter Son1") super().__init__() print("Leaving Son1") class Son2(Parent): def __init__(self): print("Enter Son2") super().__init__() print("Leaving Son2") class GrandSon(Son1, Son2): def __init__(self): print("Enter GrandSon") super().__init__() print("Leaving GrandSon") print(GrandSon.__mro__) o = GrandSon()
127982c848e9dbb5fd6492070a8dc5366e730a10
philwil/python
/basic_tests/py2.py
449
3.578125
4
#!/usr/bin/python #coding:utf-8 class Demo(object): def __init__(self,x): self.x = x @classmethod def addone(self, x): return x+1 @staticmethod def addtwo(x): return x+2 def addthree(self, x): return x+3 def main(): print Demo.addone(2) print Demo.addtwo(2) #print Demo.addthree(2) #Error demo = Demo(2) print demo.addthree(2) if __name__ == '__main__': main()
3e8ebb3d764e4def6bded8eb8e3f5ecf15a6a94a
tokenflow/Machine-Learning-101
/coding_templates_and_data_files/machine_learning/0. data_preprocessing/data_preprocessing.py
2,131
4
4
# Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('data.csv') # Outputs the columns Country -> Salary + all it's values X = dataset.iloc[:, :-1].values # Outputs the last column + all its values y = dataset.iloc[:, 3].values #------------------------------------------------- # Taking care of missing data from sklearn.preprocessing import Imputer imputer = Imputer(missing_values="NaN", strategy="mean", axis=0) # We grab only the columns with the missing data imputer = imputer.fit(X[:, 1:3]) # Replace the missing fields of data with the mean of the column X[:, 1:3] = imputer.transform(X[:, 1:3]) #------------------------------------------------- # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelEncoder_X = LabelEncoder() # Change Country Values in first column to an array # of 'label numbers' & adds them to the X X[:, 0] = labelEncoder_X.fit_transform(X[:, 0]) # Splits the Country column into 3 separate columns oneHotEncoder = OneHotEncoder(categorical_features=[0]) X = oneHotEncoder.fit_transform(X).toarray() # Change the Purchase column using LabelEncoder labelEncoder_y = LabelEncoder() y = labelEncoder_y.fit_transform(y) #------------------------------------------------- # Spliting the dataset into the Training set & Test set from sklearn.cross_validation import train_test_split # Make it so that the Test set is 20% and Training set is 80% X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) #------------------------------------------------- # Feature Scaling from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() # Scale the X Training set by fitting it X & then transforming it # X Train must be done first before X Test # This is to ensure that they will both be on the same scale X_train = sc_X.fit_transform(X_train) # Scale the X Test set by transforming it # We don't need to fit this because it is already fitted to the X Train X_test = sc_X.transform(X_test)
e1a17922bdd4e3d03d72d72aeb96362b0592a84f
pbs526443/Py1901Advance
/0409/demo03.py
577
3.515625
4
import threading,time def prt(): print('++') time.sleep(1) def timecount(f): def fun(): start = time.time() f() end = time.time() print(f.__name__,'消耗',end - start) return fun @timecount def main(): for i in range(5): prt() @timecount def threamain(): for i in range(5): t1 = threading.Thread(target=prt,name='Mythread %d' % i) t1.start() # print(threading.enumerate()) print(threading.currentThread()) t1.join() if __name__ == '__main__': # main() threamain()
56ba69c023779cc07f76faaeb17905ac513a311a
jungleQi/leetcode-sections
/classification/data structure/1-linked list/two link/23. Merge k Sorted Lists.py
1,196
4.03125
4
#coding=utf-8 ''' Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 ''' from ....utils import * def mergeKLists(lists): all_nodes = [] for list in lists: while list: all_nodes.append(list) list = list.next all_nodes.sort(key=lambda x:x.val) head = cur = ListNode(-1) for i, node in enumerate(all_nodes): cur.next, cur = node, node return head.next import heapq def mergeKLists_heap(lists): dummy = ListNode(0) head = dummy heap = [] for i, l in enumerate(lists): if not l: continue heapq.heappush(heap, [l.val, l]) lists[i] = l.next #通过堆顶元素的next作为下一个入堆对象,是非常合理的 #如果通过遍历list,每次 依次出堆,然后依次将遍历list的节点入堆,是思维处于模糊状态,不优雅且错误的做法 while heap: head.next = heapq.heappop(heap)[1] head = head.next if head.next: heapq.heappush(heap, [head.next.val, head.next]) return dummy.next
861e6e0416a0491238fb4209c9df331453d7525c
azodnemasam/JFS_Python
/Exercise9_IntersectingLists.py
489
3.953125
4
# Take two lists, return intersecting elements and count. print("\nUsing integers from input") L1 = map(int,input('Enter numbers separated by comma for List1:').split(',')) L1 = set([int(x) for x in L1]) L2 = map(int,input('Enter numbers separated by comma for List2:').split(',')) L2 = set([int(x) for x in L2]) def intersectingElements(L1,L2): result = {'intersecting_elements':list(L1&L2),'count':len(elem_list)} return result print(intersectingElements(L1,L2))
16694fba9cc8328012ea5f5b8cd92038e9948fe3
RinatStar420/programming_training
/lesson/guess_num_func.py
556
3.875
4
def finde_number_while(run): num = 23 run = True while run: guess = int(input("Введите целое число: ")) if guess == num: print("Вы угадали число!") run = False elif guess < num: print("Загаданное число больше этого") else: print("Загаданное число меньше этого") else: print("Цикл while закончен") print("Завершено") finde_number_while(int)
fbef35b67c0d1447091cdfac59672c13a1746b56
jmdavi/Writings
/season_poem.py
165
3.96875
4
seasons = ["spring","summer","fall","winter"] cycle = iter(seasons) next(cycle) for season in seasons: print(f"{season} begat {next(cycle, 'spring eternal')}")
d361c33c0c24b5881addbbc34e694d78eb2bf427
hwans21/python
/Day03/list_search.py
1,172
3.625
4
''' *리스트의 탐색과 정렬 1. index(): 리스트에서 특정값이 저장된 인덱스를 반환 2. count(): 리스트 내부에 저장된 특정 요소의 개수를 반환 3. sort(): 리스트를 오름차 정렬 4. reverse(): 리스트 데이터를 역순으로 배치 ''' points=[99,14,87,100,55,100,99,100,22] perfect = points.count(100) print(f'만점자는 {perfect}명 입니다.') print(f'87점을 획득한 학생은 {points.index(87)+1}번째 입니다.') # 내장함수 len(), max(), min() print(f'학생 수는 {len(points)}명 입니다.') print(f'최고 점수는 {max(points)}점 입니다.') print(f'최저 점수는 {min(points)}점 입니다.') # 오름차 정렬 sort() print('-'*40) print(points) points.sort() print(points) points.sort(reverse=True) print(points) points.reverse() # 역순배치 print(points) # 리스트 내의 요소의 유무를 검사하려면 in 키워드를 사용합니다. food_menu = ['김밥', '닭강정', '라면', '김말이'] name = input('음식명을 입력하세요: ') if name in food_menu: print(f'{name}이 주문완료되었습니다.') else: print(f'{name}은 없는 음식입니다.')
d821eca76590aa125ef0b3ace8ba654e8757851c
petmik2018/Python_lessons_basic
/lesson02/home_work/hw02_normal.py
5,604
4.25
4
# Задача-1: # Дан список, заполненный произвольными целыми числами, получите новый список, # элементами которого будут квадратные корни элементов исходного списка, # но только если результаты извлечения корня не имеют десятичной части и # если такой корень вообще можно извлечь # Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2] import math list1 = [2, -5, 8, 9, -25, 25, 4] result = [] for number in list1: if number>= 0.0: # извлекаем конень только из неотрицательных чисел sqrtCurr = math.sqrt(number) if int(sqrtCurr)==sqrtCurr: # имеет ли корень десятичную часть? result.append(int(sqrtCurr)) print(result) # Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013. # Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года. # Склонением пренебречь (2000 года, 2010 года) myDate = "02.11.2013" day = myDate[0:2] month = myDate[3:5] year = myDate[6:10] # формирование вспомогательного списка от 1 до 31 из 2-х символов; '01', '02', и т.д. num = [] for i in range(1,32): if i<10: num.append("0" + str(i)) else: num.append(str(i)) # вспомогательный список для формирования числительных numWord1 = ["один", "два", "три", "четыре", "пять", "шесть", "семь", "восемь", "девять"] # начало формирования списка числительных daysList = ["Первое", "Второе", "Третье", "Четвертое", "Пятое", "Шестое", "Седьмое", "Восьмое", "Девятое", "Десятое", "Одиннадцатое", "Двенадцатое", "Тринадцатое", "Четырнадцатое"] # список месяцев, наверное, есть встроенный, но я не нашел monthesList = ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"] # дополнение списка числительных для 15-19 for i in range(4,9): newStr = str(numWord1[i][:-1])+"надцатое" daysList.append(newStr.title()) # это понятно daysList.append("Двадцатое") # дополнение списка числительных для 21-29 for i in range(0,9): newStr = "Двадцать " + daysList[i].lower() daysList.append(newStr) # это понятно daysList.append("Тридцатое") daysList.append("Тридцать первое") # формирование словарей дат и месяцев daysDict = {num[i]:daysList[i] for i in range(0,31)} monthesDict = {num[i]:monthesList[i] for i in range(0,12)} # вывод искомого print("Дата {} в текстовом виде: {} {} {} года". format(myDate, daysDict[day], monthesDict[month], year)) # Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами # в диапазоне от -100 до 100. В списке должно быть n - элементов. # Подсказка: # для получения случайного числа используйте функцию randint() модуля random import random myList = [] n = input("Введите желаемое количество чисел: ") for i in range(0,int(n)): randomNumber = random.randint(-100,100) myList.append(randomNumber) print(myList) # Задача-4: Дан список, заполненный произвольными целыми числами. # Получите новый список, элементами которого будут: # а) неповторяющиеся элементы исходного списка: # например, lst = [1, 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 2, 4, 5, 6] # б) элементы исходного списка, которые не имеют повторений: # например, lst = [1 , 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 4, 6] listStart = [1, 2, 4, 5, 6, 2, 5, 2] listTarget1 = [] listTarget2 = [] print("Исходник:",listStart) # ------------пункт а---------------- for element in listStart: # Перебор всех элементов из первого списка if element in listTarget1: # Проверяем есть ли текущий элемент в динамическом второго списка pass else: # если его там нет, добавляем listTarget1.append(element) print("Список без повторов:",listTarget1) # ------------пункт б---------------- for element in listStart: # Перебор всех элементов из первого списка if listStart.count(element) == 1: # если элемент присутствует один раз, добавляем во второй список listTarget2.append(element) print("Элементы без повторений:",listTarget2)
acd30e4fc02784d197c19cc9192761f9c765303f
srijan-singh/Hacktoberfest-2021-Data-Structures-and-Algorithms
/HackerRank-30-Days-Of-Code/Python/1.py
161
3.796875
4
intvar = int(input()) doub = float(input()) st = input() # Print the sum of both integer variables on a new line. print(intvar+i) print(d+doub) print(s+st)
ae013ed336e4bab47f6b9b93c2257a2bfcb30a0f
bennosski/ME
/test_date.py
165
3.515625
4
from datetime import date today = date.today() print today print type(today) print today.timetuple()[0] print today.timetuple()[1] print today.timetuple()[2]
2cc1e22fcad503787fb5510c6b15f2267f957e8f
noushkia/data-platform
/notebooks/static/notebooks/snippets/factorial.py
212
4
4
def factorial(num): if not ((num >= 0) and (num % 1 == 0)): raise Exception("Number can't be floating point or negative.") return 1 if num == 0 else num * factorial(num - 1) factorial(6) # 720
8ce814488f9f1860e316d61498628fa78525238a
bhupi6316011/assignment
/assignment7/assignment-7.py
798
3.75
4
# #1. area of circle def area(): r=int(input("enter r")) a=3.14*r*r print(a) area() #fx.perfect and prove it perfect def perfect(x) perfect(n): sum = 0 for i in range (1,n): if n%i==0: sum=sum+i if sum==n: print("perfect number:",n) for x in range(1,1001): perfect(x) #print multiplication table of 12 using reccursion def table(n,i): print (n*i) i=i+1 if i<=10: table(n,i) table(12,1) #write a fx. to cal the power def power(a,b): if b==1: return a else: return a*power(a,b-1) print(power(6,2)) #5. write a fx. to find a fact. n=5 def rec(x): if (x==1 or x==0): return 1 #base case else: f= x*rec(x-1) #reccase return f fact=rec(n) print(fact)
a1a5411d9d2c28b6d05a9d1a6b46fceb5bcdbeaa
Nico0106/CA268
/w3-Sequences-set-and-maps/make_map.py
582
3.875
4
def make_map(): import sys d = {} for pair in sys.stdin: try: name, mark = pair.strip().split() d[name] = mark except: break return d def main(): student = make_map() # Call the student function print(type(student)) # check the type ... should be a map (or in python, dict) names = student.keys() # get all names for name in sorted(names): # sort the names print(name + " has mark " + student[name]) # print the names and marks if __name__ == "__main__": main()
a17938da59abcd1e41803fafdaa94b3fef38f7e7
Ansub/Image-Face-Detection
/main.py
803
3.8125
4
import cv2 from random import randrange #load some pre-trained data on face frontals from opencv trained_face_data = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") #choose an image to detect the face img = cv2.imread("people.jpg") #changing to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #detect Faces face_coordinates = trained_face_data.detectMultiScale(grayscaled_img) print(face_coordinates) #draw rectangle for (x,y,w,h) in face_coordinates: cv2.rectangle(img, (x,y),(x+w, y+h), (randrange(256),randrange(256),randrange(256)),3) #here 255 is green and 2 is the thickness of the rectangle #print(face_codinates) # to show the image cv2.imshow("Ansub Khan Face Detector",img) cv2.waitKey() #pauses the execution of the above line print("This is Ansub Khan")
9414aee8b52bda67a3fe06a2f3bb7a20e899d307
jgdepew/algorithmsAndDataStructures
/thirdMax.py
1,032
4.375
4
# Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). # Example 1: # Input: [3, 2, 1] # Output: 1 # Explanation: The third maximum is 1. # Example 2: # Input: [1, 2] # Output: 2 # Explanation: The third maximum does not exist, so the maximum (2) is returned instead. # Example 3: # Input: [2, 2, 3, 1] # Output: 1 # Explanation: Note that the third maximum here means the third maximum distinct number. # Both numbers with value 2 are both considered as second maximum. def thirdMax(nums): numbers = set(nums) print numbers results = [] for i in xrange(len(nums)): maximum = max(numbers) results.append(maximum) numbers.remove(maximum) if len(results) == 3 or len(numbers) == 0: break print results if len(results) == 3: return min(results) else: return max(results) nums = [1,1,2] print thirdMax(nums)
dee0f9bc20116a74481ebb3167058054a9654206
KonradMarzec1991/books_examples
/Chapter 14 - Iterables, Iterators and Generators/4 - A lazy implementation.py
424
3.578125
4
""" re.findall() - eager evaluation / returns list re.finditer() - lazy evaluation / returns generator """ import re import reprlib RE_WORD = re.compile('\w+') class Sentence: def __init__(self, text): self.text = text def __repr__(self): return 'Sentence(%s)' % reprlib.repr(self.text) def __iter__(self): for match in RE_WORD.finditer(self.text): yield match.group()
4ef189b23e1e8028a3afe67abe59e48a8c30fce7
davidchuck08/InterviewQuestions
/src/intersectionOfTwoLinkedList.py
998
3.96875
4
#!/usr/bin/python class Node(): def __init__(self,value): self.value=value self.next=None def findIntersection(head1, head2): if head1 is None or head2 is None: return None len1=0 len2=0 p1=head1 p2=head2 while p1 is not None: len1+=1 p1=p1.next while p2 is not None: len2+=1 p2=p2.next p1=head1 p2=head2 diff = abs(len1-len2) if len1>len2: for i in range(diff): p1=p1.next else: for i in range(diff): p2=p2.next while p1 is not None and p2 is not None: if p1.value == p2.value: return p1 else: p1=p1.next p2=p2.next return None root1=Node(1) root1.next=Node(3) root1.next.next=Node(5) root1.next.next.next=Node(6) root2=Node(4) root2.next=Node(5) intersection = findIntersection(root1, root2) if intersection is not None: print intersection.value else: print None
a71124450038129bca362b8db3d2af455f6e34cc
lee3164/newcoder
/leetcode/96.不同的二叉搜索树/main.py
1,332
3.65625
4
# coding=utf-8 class Solution(object): """ 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 f[n] = f[0]*f[n-1] + f[1]*f[n-2] + ... + f[n-1]*f[0] """ def numTrees(self, n): if n == 0: return 0 def build_tree(s, e, dic): dis = e - s + 1 if dis == 0: return 1 if dis in dic: return dic[dis] count = 0 for i in xrange(s, e + 1): left = build_tree(s, i - 1, dic) right = build_tree(i + 1, e, dic) count += left * right dic[dis] = count return count return build_tree(1, n, {}) def numTrees2(self, n): dp = [0] * (n + 1) dp[0] = 1 for i in range(1, n + 1): for j in range(i): dp[i] += dp[j] * dp[i - j - 1] return dp[-1] if __name__ == '__main__': """ 1 2 3 4 5 6 """ print Solution().numTrees2(10)
c47bb0ee8ca8df02b4ad94b60c18d3f639d7439b
ETorres95/Hoja-de-Programacion
/Ejer 08.py
233
3.5625
4
c = float(input('Ingrese monto a Invertir: ')) i = float(input('Ingrese el interes Anual (En decimal): ')) a = float(input('Ingrese la cantidad de años a invertir: ')) t = (((c*i)*a)+c) print('El interes obtenido es:', round(t, 2))
6811d964c37c5463aeb4153ac78875868a66e7a1
guiwoda/untref-edd-tp1
/ConversorUnidades.py
678
3.515625
4
import math class ConversorUnidades(): @staticmethod def distancia_legible(distancia): """Convierte una distancia en metros a una distancia legible.""" if 1000 > distancia: return '%s m' % distancia return '%s km' % round(distancia / 1000, 1) @staticmethod def tiempo_legible(tiempo): """Convierte un tiempo en segundos a un tiempo legible.""" if tiempo > 3600 * 24: dias, horas = math.modf(tiempo / (3600 * 24)) return '%s dias, %s hs' % (dias, horas) if tiempo > 3600: return '%s hs' % round(tiempo / 3600, 1) return '%s mins' % round(tiempo / 60, 1)
9a1ebb3bc88339532892887ef415e9042e345abe
steve-yuan-8276/pythonScrapy
/practiceFolder/ComputerProgrammingforKids/num_puzzle.py
1,248
3.734375
4
import easygui, random greeting_words = """Hello There. My name is Pirate Roberts, and I have a number puzzle. Would you want to play a puzzle game? """ title_ynbox = "NUMBER PUZZLE" if easygui.ynbox(greeting_words, title_ynbox): easygui.msgbox("OK, Let's play.\nIt's a secret number from 1 to 99.\nYou have 6 tries.") else: easygui.msgbox("Bye.") sys.exit(0) secret_number = random.randint(1,99) try_times = 0 guess_number = easygui.integerbox(msg="Let's begin. Please guess a integer number: ", lowerbound=0, upperbound=99) #print("Hello! My name is Pirate Roberts, and I have a number puzzle.") #print("Would you want to play a puzzle game? OK, You have 6 tries.") while try_times <= 6: if guess_number < secret_number: easygui.integerbox(msg="Too low. Please try again. Give me another number: ", lowerbound=0, upperbound=99) elif guess_number > secret_number: easygui.integerbox(msg="Too high. Please try again. Give me another number: ", lowerbound=0, upperbound=99) try_times = try_times + 1 if guess_number == secret_number: easygui.msgbox(f"You are correct. The number is {secret_number}. ") else: easygui.msgbox(f"No more guess. Wish you have a better luck!\nThe secret number is {secret_number}")
6f5aac86b6c8d8b42dd13d5ef1e6cdeda73a7d2c
monikalakshmanan/wipro-J2EE
/vowel.py
115
4
4
x=input() y=x.lower() if y=="a" or y=="e" or y=="i" or y=="o" or y=="u": print("Vowel") else: print("Consonant")
4d1f5cc9602e387ea69ffae1891cdf35cbdbbbdb
AmitGupta700/Python
/First N natural number in reverse order.py
79
4.09375
4
num=int(input("Enter The Number")) while num: print(num) num=num-1
2e693f06433760cd4e16d2013ffc2d1c945ba023
AssiaHristova/SoftUni-Software-Engineering
/Programming Basics/nested_loops/combinations.py
201
3.625
4
n = int(input()) x1 = 0 x2 = 0 x3 = 0 count = 0 for x1 in range(n+1): for x2 in range(n+1): for x3 in range(n+1): if x1 + x2 + x3 == n: count += 1 print(count)
4692dd333b1a0c8e500647e6e5bd3506ba86ef5e
Chechin21/kuryach
/test.py
208
4.25
4
a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] #print(list(zip(*a))) for i in range(3): a = list(zip(*reversed(a))) for i in a: print(i) #for i in a: # a[i] = list((*reversed(i)) #print(list(zip(*a)))
7870baa5e7d558cbb4b2cfe48563678dbf374a85
elitasheva/Python-Programming
/Exercises/lecture_02/name.py
232
3.796875
4
text = input("Enter first text: ") params = text.split() initial = "" for name in params: if name[0].isupper(): initial += name[0] + "." print(initial) # txt = "| a ||||||||||||" # print(txt.strip("|"))
554e54c1df9e33bb4d80254b28c32a0246c76b90
MAGI-Yang/LeetCode
/2. Add Two Numbers.py
689
3.6875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Cal(object): def getNumber(self, l): rate = 1 number = 0 while l != None: number = l.val * rate + number rate = rate * 10 l = l.next return number def getList(self, n): ans = [] for i in range(0, len(str(n))): ans.append(n%10) n = n / 10 return ans class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ calculator = Cal() sum = calculator.getNumber(l1) + calculator.getNumber(l2) ans = calculator.getList(sum) return ans
edfb469929776b221130f044397fa2a60f83e778
julie-oh/Algorithm-study-julie
/python/DP/fib_call_0_1.py
431
3.765625
4
""" return count(Int) that count calls for fib(0) or fib(1)""" def fib(n): return fib_helper(n, [None] * (n+1)) def fib_helper(n, arr_0): if n == 0: return 1 if n == 1: return 0 if arr_0[n] is not None: return arr_0[n] arr_0[n] = fib_helper(n-1, arr_0) + fib_helper(n-2, arr_0) return arr_0[n] if __name__ == '__main__': print(fib(4)) print(fib(5)) print(fib(13))
cc406bfe24d0afaa52fe37a48cfb3f59217e3e50
Patrick-Carawan/SurveyStatistics
/__init__.py
1,719
3.5625
4
import re import csv from tkinter import * from tkinter import filedialog file_lines = None def main(): global file_lines survey_stats = '' root = Tk() root.withdraw() path = filedialog.askopenfilename(initialdir="/", title="Select file", filetypes=[("CSV files", "*.csv")]) try: _file = open(path, newline='') except FileNotFoundError: print("ERR: The file does not exist") quit() csv_file = csv.reader(_file) file_lines = [] while 1: try: file_lines.append(next(csv_file)) except StopIteration: break file_lines.pop(1) # Remove second line of csv preview_count = 2 while preview_count < len(file_lines): if file_lines[preview_count][2] == "Survey Preview": # Remove previews file_lines.pop(preview_count) else: preview_count += 1 for column in range(21, len(file_lines[0])): survey_stats += get_letters(column) + " " + file_lines[0][column] + ", Mean: " + get_average(column) + '\n' stats_name = path.split('/')[-1].split('.')[0] final_file = open(stats_name + ".txt", "w") final_file.write(survey_stats) final_file.close() quit() def get_average(column): global file_lines total = 0.0 num_responses = 0.0 for line in file_lines: val = line[column] if re.match(r"^\d+$", val): total += float(val) num_responses += 1 if not num_responses: return str(0) return str(total / num_responses) def get_letters(value): if value < 26: return chr(value + 65) else: return chr(int(value / 26)+64) + chr(int(value % 26)+65) main()
18b45cedc50e3021fb956884fd49f9e685c43bec
Flora-SunnyDay/LearningPythonRepl
/main.py
152
3.796875
4
print("Welcome to my greeting program!") answer = input("What's your name? ") print("Hi " + answer +" , Nice to meet you") input("Press enter to exit!")
c155e81c156fb81fa624bd47151ea36add39d24f
littlemoonstones/AAPUB1
/ME2002WeekX/L24Ex1.py
181
4.25
4
number = int(input("Please enter a number: ")) if number % 2 == 0: print("You entered", number, "which is even") else: print("You entered", number, "which is odd")
9ebb850a7a1cffaf7ac9224e66d516a64d30f1b8
KatarzynaMyrcik/nauka_pythona
/skrypt7.py
635
3.703125
4
skarpetki = {'lewa_paski': 'paski', 'prawa_paski': 'paski', 'lewa_kropki': 'kropki', 'lewa_sloneczka': 'sloneczka'} print(skarpetki) print(skarpetki['lewa_paski']) print(skarpetki.get('lewa_paski')) skarpetki['lewa_choinki']= 'choinki' skarpetki['lewa_kwiatki'] = 'kwiatki' print(skarpetki) # # petla po kluczu # for key in skarpetki: # print("Masz w szafie skarpetke w {0}. Jest to skarpetka {1}".format(skarpetki[key], key)) # petla po kluczy i wartosci: for key, value in skarpetki.items(): print("Przyszla pora wyprac skarpetke w {1}. Dokladnie chodzi o te {0}".format(key, value))
a5f2e75806aa13f272cb73457e004d1b8603eecf
SatoshiJIshida/projects
/Python - Coding Challenges/areequallystrong.py
1,074
4.3125
4
""" Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities find out if you two are equally strong. Example: For yourLeft = 10, yourRight = 15, friendsLeft = 15, and friendsRight = 10, the output should be solution(yourLeft, yourRight, friendsLeft, friendsRight) = true; [execution time limit] 4 seconds (py3) [input] integer yourLeft [input] integer yourRight [input] integer friendsLeft [input] integer friendsRight [output] boolean true if you and your friend are equally strong, false otherwise. Tests passed: 27/27. """ def solution(yourLeft, yourRight, friendsLeft, friendsRight): result = False if ((yourLeft == friendsLeft) or (yourLeft == friendsRight)) and ((yourRight == friendsLeft) or (yourRight == friendsRight)): result = True return result
74d45860e658663d21eeba39414a254c6caeab27
toniferraprofe/login_python
/lib/01-filter.py
942
3.59375
4
""" Filtrar datos de Jugadores de Basket """ # clase para los jugadores(nombre, posicion, puntos) class Jugador: # función constructor def __init__(self,nombre,posicion,puntos): self.nombre = nombre self.posicion = posicion self.puntos = puntos # función string, devolver un string de los datos en la función def __str__(self): return f'{self.nombre} tiene la posición de {self.posicion} en el equipo, y sus puntos por partido son {self.puntos}.' # instanciar 5 jugadores jugadores_del_equipo = [ Jugador('Tomas','Pivot',22), Jugador('Pepe','Alero',9), Jugador('Juan','Base',4), Jugador('Anselmo','Alero-Pivot',14), Jugador('Pedro','Pivot',8) ] # Filtrar los jugadores con une media de puntos superior a 10 filtro_sup_diez = filter(lambda masDiez: masDiez.puntos > 10,jugadores_del_equipo) for jugador_puntos in filtro_sup_diez: print(jugador_puntos)
7c0bf8bca393af433bf0305567f67816507bf5c8
samvelarakelyan/ACA-Intro-to-python
/Practicals/Practical4/pract4.py
2,299
3.96875
4
""" CONDITIONALS: -------------------- """ #1) n1=int(input("Enter first number:")) n2=int(input("Enter second number:")) print("The number ​%d is the greatest" %n1) if n1>n2 else print("The number %d is greatest" %n2) #2) a=int(input("Enter the first side:")) b=int(input("Enter the second side:")) if a<=0 or b<=0: print("Enter a valid sides!") else: print("rectangle") if a!=b else print("square") #3) name=input("Enter a name:") age=int(input("Enter a age:")) password=input("Enter a password:") if name=="Batman": print("Welcome Mr. Batman!") else: if age<16: print("Dear %s, you are too young to register" %name) elif "*" not in password and "&" not in password: print("Please enter a different password") #4) d={"name": "Armen", "age": 15,"grades": [10, 8, 8, 4, 6, 7]} is_there="weight" in d.keys() if is_there: [print(d[i]) for i in d if i=="weight"] else: n=input("Enter any number:") d.update({"weight":n}) """ LOOPS: ------------- """ #5) for i in range(101): if i%2==1: print("i=",i) #6) for i in range(7): if i==2 or i==6: continue print("i=",i) #7) for i in range(1,21): if i%3==0 and i%5==0: break print("i=",i) #8) list1=[5, 7, -7, "abc", 2, 4, True, 3, 4, 6, 7, 7] for i in list1: if i==3: break print(i) #9) correct_num=5 count=0 while True: count+=1 guess=int(input("Enter a number:")) if guess==correct_num: print("That was a good guess!") break if count==10: break """ LIST COMPREHENSION: ---------------------- """ #10) num=[7,8, 120, 25, 44, 20, 27] print("list before removing evens:",num) num=[x for x in num if x%2!=0] print("list after removing evens:",num) #11) list3=[x**2 for x in range(1,51)] print("list3:",list3) #12) list1=[1,2,3,4,5,10,20,30,40,50,100,200,300,400,500] print("list1:",list1) list2=[x for x in list1 if x>20] print("list2:",list2) #13) str1=input("Enter a string:") print("str1:",str1) l1=[letter for letter in str1] print("l1:",l1) #14) list1=['a', 'abc', 'xyz', 's', 'aba','1221'] other_list=[item for item in list1 if len(item)>2 and item[0]==item[-1]] print(len(other_list),"element: ",other_list)
90d6b87c7ff77c3f82477828045cd321057be070
Zhenye-Na/leetcode
/python/219.contains-duplicate-ii.py
1,254
3.625
4
# # @lc app=leetcode id=219 lang=python3 # # [219] Contains Duplicate II # # https://leetcode.com/problems/contains-duplicate-ii/description/ # # algorithms # Easy (38.51%) # Likes: 1232 # Dislikes: 1345 # Total Accepted: 320.4K # Total Submissions: 829.5K # Testcase Example: '[1,2,3,1]\n3' # # Given an array of integers and an integer k, find out whether there are two # distinct indices i and j in the array such that nums[i] = nums[j] and the # absolute difference between i and j is at most k. # # # Example 1: # # # Input: nums = [1,2,3,1], k = 3 # Output: true # # # # Example 2: # # # Input: nums = [1,0,1,1], k = 1 # Output: true # # # # Example 3: # # # Input: nums = [1,2,3,1,2,3], k = 2 # Output: false # # # # # # # @lc code=start from collections import defaultdict class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: history = defaultdict(list) for idx, num in enumerate(nums): if num not in history: history[num].append(idx) else: if idx - history[num][-1] <= k: return True else: history[num].append(idx) return False # @lc code=end
d63b6a6b5d8498ccc6f3507f6bacb8585fe8c1c0
Malyaj/csv_to_sql
/01.py
1,991
3.71875
4
# -*- coding: utf-8 -*- """ Script to functionalize conversion of standard table csv to sql queries """ import os import pandas as pd def query_create(filepath, table_name=None, primary=None, null=None): ''' filepath to the csv file returns the sql query to create table tailored for postgresql may work elsewhere as well ''' if table_name is None: table_name = os.path.splitext(os.path.basename(filepath))[0] df = pd.read_csv(filepath) create_query = """ CREATE TABLE {table_name} ( """.format_map({'table_name':table_name}) field_headers = list(df.columns) ## extracted from the csv file field_types = ['INT', 'VARCHAR(150)', 'VARCHAR(150)', 'VARCHAR(150)', 'VARCHAR(7)', 'INT'] ## can these be infered ? primary_flag = [True, False, False, False, False, False] # could be passed as a list of column names to be inferred as primary key non_null_flag = [True, True, True, False, True, True] # could be based on fields having or not having missing values ? def primary(bool_val): if bool_val: return 'PRIMARY KEY' return '' def non_null(bool_val): if bool_val: return 'NOT NULL' return '' primary_flag = list(map(primary,primary_flag)) non_null_flag = list(map(non_null, non_null_flag)) suffix = ',\n' for each in zip(field_headers, field_types, primary_flag, non_null_flag): create_query = create_query + ' '.join(list(each)) + suffix create_query = create_query.strip()[:-1] create_query = create_query + '\n);' return create_query ## collect parameters path = os.path.dirname(__file__) os.chdir(path) filename = 'janta.csv' filepath = os.path.join(path, filename) ## call the function query = query_create(filepath) ## write the query to a sql file sqlfilepath = os.path.join(path, 'query.sql') with open(sqlfilepath, 'w') as f: f.write(query)
f090dfa16123846ffcd342a661a8b003ebd66880
FinnDempsey/repo1
/assignment1ProSkills.py
621
3.703125
4
res1 = [] res2 = [] allVAT=0 plusVAT=0 total=0 def plusVAT(): for i in res1: global res2 global allVAT res2.append(i*(23/100)+i) allVAT = allVAT + (i*(23/100)) return allVAT for x in range (1, 100): num=int(input('Enter a Sale Figure (Enter -1 to end): ')) if (num==-1): break total = num+total res1.append(num) plusVAT() total = allVAT+total print('The figure you entered were', res1) print('These Sales figures including VAT are', res2) print('The VAT charged in total is', allVAT) print('The total sales are', total)
b646a7ef38ee26fdd18a37b06c80ec05c339f44b
napdragn/leetcode-50-common-inteview-questions
/array_and_string/valid_palindrome.py
513
3.671875
4
def valid_palindrome(s: str) -> bool: start_ind, end_ind = 0, len(s) - 1 while start_ind <= end_ind: if s[start_ind].isalnum() and s[end_ind].isalnum(): if s[start_ind] == s[end_ind]: start_ind += 1 end_ind -= 1 continue else: return False elif not s[start_ind].isalnum(): start_ind += 1 continue elif not s[end_ind].isalnum(): end_ind -= 1 return True
8abf6259b247f900c0f27effa7e49c34d15de7c0
vusaliko/Laboratorniye
/Лабораторная 7.6.py
391
3.953125
4
while True: print("Введите числа a,b,c") a=int(input()) b=int(input()) c=int(input()) if a**2+b**2==c**2: print("Истина") else: if a**2+c**2==b**2: print("Истина") else: if b**2+c**2==a**2: print("Истина") else: print("Ложь")
9457aff794060dbf5b47afcffb511acf44d186c4
jeffreyrampineda/takugen
/main.py
1,509
3.546875
4
import tkinter as tk from pynput import keyboard from takugen import Translator import hangul import hiragana import katakana root = tk.Tk() language_selected_text = tk.StringVar(root) class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def create_widgets(self): self.hangul_button = tk.Button(self, text="Hangul", command= lambda: self.select_language(0)) self.hangul_button.pack(side="top") self.hiragana_button = tk.Button(self, text="Hiragana", command= lambda: self.select_language(1)) self.hiragana_button.pack(side="top") self.katakana_button = tk.Button(self, text="Katakana", command= lambda: self.select_language(2)) self.katakana_button.pack(side="top") def select_language(self, option=0): options = [ hangul.Hangul, hiragana.Hiragana, katakana.Katakana, ] language = options[option] language_selected_text.set(language._language) Translator(language).start() app = Application(master=root) app.master.title("Takugen") app.master.minsize(200, 200) tk.Label(root, textvariable=language_selected_text).pack() language_selected_text.set('None') app.mainloop() ## TODO: Close/Stop current TranslatorThread when switching between languages ## - You have to ESC first before switching to another language or will cause error
e78136e59ed0adc27834c6b0f6fefba702c7b21b
RahulBendre1/edx-mitx-6.00
/lec7-1.py
147
3.9375
4
def factR(x): """ Assumes n is int and n >= 1 """ if x == 1: return x else: return x*factR(x-1) print("Factorial of 4: " + str(factR(4)))
a19d32ae464bc6cfc3700e5a2dabf8a7b1eb09eb
rawalarpit1445/clocks
/main.py
1,278
3.734375
4
""" _author_ = Arpit Rawal """ def clock_angle(request): """ 1. Function calculates angle clock hands of hours and mins 2. Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text will be string in form Angle ->90 """ request_json = request.get_json() request_args = request.args if request.args and 'hrs' in request.args: hrs = int(request.args.get('hrs')) mins = int(request.args.get('mins')) elif request_json and 'hrs' in request_json: hrs = int(request_json['hrs']) mins = int(request_json['mins']) elif request_args and 'hrs' in request_args: hrs = int(request_args['hrs']) mins = int(request_args['mins']) else: ans_str = "Cannot compute due to some error" if (0 <= int(hrs) <= 12 and 0 <= int(mins) <= 59): degree_per_min = 6 degree_per_hour = 30 degree_intern = 0.5 if hrs == 12: hrs = 0 angle_between = abs(hrs*degree_per_hour - mins*degree_per_min + mins*degree_intern) ans_str = "Angle ->{0}".format(str(angle_between)) else: ans_str = "Invalid Input, cannot compute, Try Again" return ans_str
871f046cf81db41d15570bcac7915bfdc578d575
alexeyantonov/NeuralNet
/NeuralNetwork.py
11,659
3.6875
4
import math, random import numpy as np P = 1 def activation(value): #Map the output to a curve between 0 and 1 #output = 1/(1+e^(-a/p)) try: return 1/(1+math.exp(-value/P)) except OverflowError: return 1/(1+math.exp(700/P)) class Neuron(object): def reset(self): return def adjustWeights(self, targetOutput, EW,\ learningRate = None, useMomentum = None ): return class OutputNeuron(Neuron): def __init__(self, outputCount, bias = None, learningRate = 0.3, useMomentum = False ): self.outputCount = outputCount self.inputs = list() self.weights = list() self.learningRate = learningRate self.useMomentum = useMomentum if bias is None: self.bias = random.random() * 1.0 else: self.bias = bias self.processed = False self.rightReceived = 0 self.errorRate = 0 self.outputValue = 0 self.changeMomentums = list() def getOutput(self): #If we've already processed it this time around then just skip the work and return #the answer if self.processed: return self.outputValue #Do some work, get the values from the inputs times by their respective weights #added all up totalSum = 0 for i in range(len(self.inputs)): totalSum += self.inputs[i].getOutput() * self.weights[i] #Subtract the bias totalSum -= self.bias #Save the outputValue after putting it between 0 and 1 self.outputValue = activation(totalSum) self.processed = True return self.outputValue def adjustWeights(self, targetOutput, EW,\ learningRate = None, useMomentum = None ): #If this is an output layer neuron targetOutput will be a value and EW will be 0 # if this is a hidden layer neuron targetOutput will be 0 and EW will be # one of the downstream connected neuron's weight times error rate #Only if we've processed it if learningRate is not None: self.learningRate = learningRate if useMomentum is not None: self.useMomentum = useMomentum if self.processed: runAdjustment = False #If this is an output layer neuron if self.outputCount == 0: runAdjustment = True self.errorRate = (targetOutput - self.outputValue) * \ self.outputValue * ( 1 - self.outputValue ) else: # if this is a hidden layer neuron # add the weighted error rate self.errorRate += EW # count on up self.rightReceived += 1 # if that's all the downstream connected neurons that we're waiting for if self.rightReceived == self.outputCount: runAdjustment = True #calculate our actual error rate self.errorRate *= self.outputValue * ( 1 - self.outputValue ) if runAdjustment: for i in range(len(self.inputs)): # Adjust the weight for each input based on its weight and output if self.useMomentum: self.changeMomentums[i] += self.inputs[i].getOutput() *\ self.learningRate * self.errorRate self.changeMomentums[i] /= 2.0 self.weights[i] += self.changeMomentums[i] else: self.weights[i] += self.inputs[i].getOutput() *\ self.learningRate * self.errorRate # Then adjust the weight on up self.inputs[i].adjustWeights( 0, self.weights[i] * self.errorRate,\ learningRate = learningRate, useMomentum = useMomentum ) return def reset(self): if self.processed: self.processed = False self.rightReceived = 0 self.errorRate = 0 self.outputValue = 0 for i in self.inputs: i.reset() class InputNeuron(Neuron): def __init__(self ): self.inputValue = 0 def getOutput(self): #return activation( self.inputValue ) return self.inputValue class Network(object): def __init__(self, inputs, outputs, hiddenLayerMakeup, structure = None, learningRate = 0.3, useMomentum = False ): self.inputs = inputs self.outputs = outputs self.inputNeurons = list() #self.outputNeurons = list() self.allNeurons = list() self.tempLayer = list() self.lastLayer = list() self.hiddenLayerMakeup = hiddenLayerMakeup #Create input layer for i in range(inputs): newNeuron = InputNeuron( ) self.inputNeurons.append( newNeuron ) self.allNeurons.append( newNeuron ) self.lastLayer.append( newNeuron ) #Create each hidden layer id = 0 for i in range(len(hiddenLayerMakeup)): outputCount = outputs if i < len(hiddenLayerMakeup)-1: outputCount = hiddenLayerMakeup[i+1] for j in range(hiddenLayerMakeup[i]): s = None if structure is not None: s = structure[id] self.createNeuron( outputCount, structure = s,\ learningRate = learningRate, useMomentum = useMomentum ) id += 1 self.lastLayer = self.tempLayer self.tempLayer = list() #Create the output layer for i in range(outputs): s = None if structure is not None: s = structure[id] self.createNeuron( 0, structure = s ) id += 1 self.outputNeurons = self.tempLayer def createNeuron(self, outputCount, structure = None, learningRate = 0.3, useMomentum = False ): b = None if structure is not None: b = structure[0] # float newNeuron = OutputNeuron( outputCount, bias = b,\ learningRate = learningRate, useMomentum = useMomentum ) if structure is not None: newNeuron.weights = structure[1] # list for n in self.lastLayer: newNeuron.inputs.append( n ) if structure is None: newNeuron.weights.append( random.random() * 1.0 + 0.0000000000001 ) newNeuron.changeMomentums.append( 0.0 ) self.tempLayer.append( newNeuron ) self.allNeurons.append( newNeuron ) def getOutput(self, inputs): if len(inputs) != len(self.inputNeurons): raise NameError('Inputs not the same, expected ' + str(len(self.inputNeurons))\ + ' but got ' +str(len(inputs)) ) #Give the input neurons their inputs for i in range(len(inputs)): self.inputNeurons[i].inputValue = inputs[i] # self.inputNeurons[i].inputValue = activation( inputs[i] ) #Reset the neurons for outputNeuron in self.outputNeurons: outputNeuron.reset() #Fill the output list and return it outputList = list() for outputNeuron in self.outputNeurons: outputList.append( outputNeuron.getOutput() ) return outputList def adjustWeights( self, targetOutputs,\ learningRate = None, useMomentum = None ): if len(targetOutputs) != len(self.outputNeurons): raise NameError('Outputs not the same, expected ' + str(len(self.outputNeurons))\ + ' but got ' +str(len(targetOutputs)) ) # make sure our targetOutputs are all between 0 and 1 if np.less(targetOutputs,0.0).any(): raise NameError('Outputs cannot be below 0.0 ') if np.greater(targetOutputs,1.0).any(): raise NameError('Outputs cannot be above 1.0 ') ## for i in range( len( targetOutputs) ): ## if targetOutputs[i] > 1: ## targetOutputs[i] = 1 ## elif targetOutputs[i] < 0: ## targetOutputs[i] = 0 for i in range( len( self.outputNeurons ) ): self.outputNeurons[i].adjustWeights( targetOutputs[i], 0,\ learningRate = learningRate, useMomentum = useMomentum ) def printStructure(self): print( 'Inputs:', self.inputs ) print( 'Hidden Layer Makeup:', self.hiddenLayerMakeup ) print( 'Outputs:', self.outputs ) print( 'Structure:' ) print ('[' ) for neuron in self.allNeurons: if neuron in self.inputNeurons: continue print ('[', neuron.bias, ',', neuron.weights,' ],' ) print (']' ) print() if __name__ is '__main__': import time starttime = time.time() network = Network(2,1,[ 2 ] ) results = list() count = 0 while True: count += 1 a = random.randint(0,1) b = random.randint(0,1) outputs = network.getOutput( [ a, b] ) if len(results)>=500: del results[0] if (a or b) and not (a and b): network.adjustWeights( [1] ) if outputs[0]>0.5: results.append( True ) else: results.append( False ) else: network.adjustWeights( [0] ) if outputs[0]<0.5: results.append( True ) else: results.append( False ) ratio = 0.0 for result in results: if result: ratio += 1.0 ratio /= len(results) print( 'Accuracy: %s' % ratio ) if len(results)>90 and ratio==1.0: break; print( count ) secs = time.time() - starttime print( 'Per iteration time: ', secs/count ) # network.printStructure() # # # network = Network(2,1,[ 3, 2 ], structure = [ # [ 0.6633567588312668 , # [-1.5375843295941822, 5.874506983837322] ], # [ 0.4120877206601512 , # [4.8660870490681996, -1.2138872657105046] ], # [ 1.4782880551917223 , # [5.693297909529692, 4.938349753203479] ], # [ 0.4721888376272143 , # [6.556709105012925, 1.0470135495294646, -5.415906557801467] ], # [ 1.3969295933872528 , # [1.7701308884840654, -4.126382784320171, 3.712795339141683] ], # [ 0.17927038692452002 , # [-6.498125924286288, 7.297829204670113] ], # ] ) # results = list() # count = 0 # while True: # count += 1 # a = random.randint(0,1) # b = random.randint(0,1) # outputs = network.getOutput( [ a, b] ) # if len(results)>=500: # del results[0] # if (a or b) and not (a and b): # network.adjustWeights( [1] ) # if outputs[0]>0.5: # results.append( True ) # else: # results.append( False ) # else: # network.adjustWeights( [0] ) # if outputs[0]<0.5: # results.append( True ) # else: # results.append( False ) # ratio = 0.0 # for result in results: # if result: # ratio += 1.0 # ratio /= len(results) # print( ratio ) # if len(results)>90 and ratio==1.0: # break; # print( count ) # # network.printStructure()
0868a3498adb551a84f6a07f4e8463db2ae57519
MayWorldPeace/QTP
/Python基础课件/代码/第二天的代码/10-while嵌套应用一之打印三角形.py
677
4.5625
5
""" * ** *** **** ***** """ # 考虑第一件事情 分析如何打印出5行 # 定义一个变量 # row = 1 # # 循环 # while row <= 5: # print("*") # row += 1 # 考虑第二件事情 打印出每一行的每一列的* # 在默认的情况下 使用print 默认打印完成后 会有一个换行 # print("哈哈") 完整的格式 print("哈哈", end="\n") # 定义一个变量 # col = 1 # while col <= 5: # print("*", end="") # col += 1 # 定义一个变量 记录行数 row = 1 while row <= 5: # 定义一个变量 记录列数 col = 1 while col <= row: print("*", end="") col += 1 # 换行 print() row += 1
eb4a9a30949d6ceae6ef99bc2e3a4aa35339a2c0
stepochek/work
/w5.py
1,002
3.546875
4
git statusimport random text_data = input('Write your text: ').split() text_data_index = [] for i in range(len(text_data)): text_data_index.append(text_data[i] + '_' + str(i+1)) shuffled_data_index = [] while text_data_index != []: word = random.choice(text_data_index) shuffled_data_index.append(word) text_data_index.remove(word) secret_indexes = [] for i in range(len(shuffled_data_index)): index = shuffled_data_index[i].split('_')[-1] # index in str index = int(index) # index in digit secret_indexes.append(index) shuffled_data_index[i] = '_'.join(shuffled_data_index[i].split('_')[:-1]) print(shuffled_data_index) print(secret_indexes) answer = '' m = 1 z = 1 o = len(secret_indexes) for q in secret_indexes: for b in range(m): for y in shuffled_data_index: if q == z: answer += str(y) answer += ' ' z += 1 else: m += 1 m = 1 print(answer, z)
8948113def088ba9b2b7484d1cbfa2f0975a4b8f
olof/hacks
/utils/selector-scrape
964
3.5
4
#!/usr/bin/python3 # scrape content from web pages using css selectors # # e.g. # # $ selector-scrape https://en.wikipedia.org/wiki/List_of_HTTP_status_codes 'dl > dt' # 100 Continue # 101 Switching Protocols # 102 Processing (WebDAV; RFC 2518) # 103 Early Hints (RFC 8297) # 200 OK # 201 Created # 202 Accepted # 203 Non-Authoritative Information (since HTTP/1.1) # 204 No Content # ... # # Or from stdin: # # $ selector-scrape 'dl > dt' <list_of_http_status_codes.html # # You have to figure out the magic selector string yourself. And yeah, don't # forget to quote it, especially if you're using '>' :-). import sys import requests from bs4 import BeautifulSoup uri = sys.argv.pop(1) if len(sys.argv) > 2 else None selector = sys.argv[1] if uri: resp = requests.get(uri) resp.raise_for_status() blob = resp.content else: blob = sys.stdin bs = BeautifulSoup(blob, features='lxml') for r in bs.select(selector): print(r.text)
8f15bed1376d566fe712b4721115aea6c5c0db83
bogardan/python
/lesson_4/7.py
951
3.5625
4
""" 7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом: for el in fibo_gen(). Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые 15 чисел. Подсказка: факториал числа n — произведение чисел от 1 до n. Например, факториал четырёх 4! = 1 * 2 * 3 * 4 = 24. """ def generator(): my_list = range(1,16) for i in my_list: yield i result = 1 for i in generator(): result = result*i print("Факториал равен: ", result)
9822ff9721e2457a78479c02d72bbd032b32ac38
BlackJin1/FirstProgramm
/Chapter_1/Trust_fund_bad.py
1,311
4.09375
4
# Рантье print(""" Рантье Программа подсчитывает ваши ежемесячные расходы. Эту статистику нужно знать, чтобы у вас не закончились деньги и вам не пришлось искать работу. Введите суммы расходов по всем статьям, перечисленным ниже. Вы богаты - так не мело- читесь, пишите суммы в лолларах, без центов. """) car = int(input("Техническое обслуживание машины 'Ламборджини': ")) rent = int(input("Съем роскошной квартиры на Манхеттене: ")) jet = int(input("Аренда личного самолета: ")) gifts = int(input("Подарки: ")) food = int(input("Обеды и ужины в ресторанах: ")) staff = int(input("Жалование прислуге: ")) guru = int(input("Платы личному психоаналитику: ")) games = int(input("Компьютерные игры: ")) total = car+rent+jet+gifts+food+staff+guru+games print("\nОбщая сумма: ", total) input("Нажмите Enter, чтобы продолжить.")
75109760a907429443f30404a87ac5a7aea28078
wanderso/AvatarWorld
/advantages.py
54,687
3.546875
4
import enum import math class Advantage_Type(enum.Enum): COMBAT_ADVANTAGE = 1 FORTUNE_ADVANTAGE = 2 GENERAL_ADVANTAGE = 3 SKILL_ADVANTAGE = 4 class Cost_Type(enum.Enum): FLAT_RANK = 1 PYRAMID_RANK = 2 NO_RANK = 3 class Advantage: advantage_list = None advantage_cost_type = None advantage_needs_skill = False advantage_needs_rank = False advantage_needs_name = False advantage_has_list = False def __init__(self, name): self.advantage_name = name self.advantage_cost = 0 self.instance_cost_type = Cost_Type.FLAT_RANK self.advantage_rank = 0 self.advantage_func_list = None def dictify(self): return { "advantage_cost": self.advantage_cost, "instance_cost_type": self.instance_cost_type, "advantage_rank": self.advantage_rank, "advantage_func_list": self.advantage_func_list, "calculate_cost": self.calculate_cost, "representation": self.representation } def representation(self): if self.instance_cost_type == Cost_Type.NO_RANK: return self.advantage_name else: if self.advantage_rank == 1: return self.advantage_name else: return "%s %d" % (self.advantage_name, self.advantage_rank) def represent_no(self): return "%s" % self.advantage_name def represent_rank(self): if self.advantage_rank == 1: return "%s" % self.advantage_name return "%s %d" % (self.advantage_name, self.advantage_rank) def represent_list(self): list_string = "" data_list = [] try: data_list = self.list_value except AttributeError: print("Uh-oh. Couldn't find list when running represent_list.") for entry in sorted(data_list): list_string += "%s ," % entry try: list_string = list_string[:-2] except IndexError: print("Empty list sent to represent_list.") return "%s (%s)" % self.advantage_name, list_string def combine_advantage(self): pass def calculate_cost(self): print("Will we ever reach this?") if self.instance_cost_type == Cost_Type.FLAT_RANK: return self.advantage_rank elif self.instance_cost_type == Cost_Type.PYRAMID_RANK: ret_val = 0 for i in range (1, self.advantage_rank+1): ret_val += i return ret_val elif self.instance_cost_type == Cost_Type.NO_RANK: return 1 def pyramid_cost(self): ret_val = 0 for i in range(1, self.advantage_rank + 1): ret_val += i return ret_val def flat_cost(self): return self.advantage_rank def no_rank_cost(self): return 1 def init_flat(self,rank): self.advantage_cost = rank self.instance_cost_type = Cost_Type.FLAT_RANK self.advantage_rank = rank self.advantage_func_list = None self.calculate_cost = self.flat_cost self.representation = self.represent_rank def init_no(self): self.advantage_cost = 1 self.instance_cost_type = Cost_Type.NO_RANK self.advantage_rank = 1 self.advantage_func_list = None self.calculate_cost = self.no_rank_cost self.representation = self.represent_no def init_pyramid(self,rank): self.advantage_cost = 0 self.instance_cost_type = Cost_Type.PYRAMID_RANK self.advantage_rank = rank self.advantage_func_list = None self.calculate_cost = self.pyramid_cost self.representation = self.represent_rank class Accurate_Attack(Advantage): """When you make an accurate attack (see Maneuvers, page 249) you can take a penalty of up to –5 on the effect modifier of the attack and add the same number (up to +5) to your attack bonus.""" advantage_needs_rank = True advantage_cost_type = Cost_Type.PYRAMID_RANK def __init__(self, rank): super().__init__("Accurate Attack") self.init_pyramid(rank) class Agile_Feint(Advantage): """You can use your Acrobatics bonus or movement speed rank in place of Deception to feint and trick in combat as if your skill bonus or speed rank were your Deception bonus (see the Deception skill description). Your opponent opposes the attempt with Acrobatics or Insight (whichever is better).""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Agile Feint") self.init_no() class All_Out_Attack(Advantage): """When you make an all-out attack (see Maneuvers, page 249) you can take a penalty of up to –5 on your active defenses (Dodge and Parry) and add the same number (up to +5) to your attack bonus.""" advantage_needs_rank = True advantage_cost_type = Cost_Type.PYRAMID_RANK def __init__(self, rank): super().__init__("All Out Attack") self.init_pyramid(rank) class Animal_Empathy(Advantage): """You have a special connection with animals. You can use interaction skills on animals normally, and do not have to speak a language the animal understands; you communicate your intent through gestures and body language and learn things by studying animal behavior. Characters normally have a –10 circumstance penalty to use interaction skills on animals, due to their Intellect and lack of language.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Animal Empathy") self.init_no() class Artificer(Advantage): """You can use the Expertise: Magic skill to create temporary magical devices. See Magical Inventions, page 212, for details""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Artificer") self.init_no() class Assessment(Advantage): """You’re able to quickly size up an opponent’s combat capabilities. Choose a target you can accurately perceive and have the GM make a secret Insight check for you as a free action, opposed by the target’s Deception check result. If you win, the GM tells you the target’s attack and defense bonuses relative to yours (lower, higher, or equal). With each additional degree of success, you learn one of the target’s bonuses exactly. If you lose the opposed roll, you don’t find out anything. With more than one degree of failure, the GM may lie or otherwise exaggerate the target’s bonuses.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Assessment") self.init_no() class Attractive(Advantage): """You’re particularly attractive, giving you a +2 circumstance bonus on Deception and Persuasion checks to deceive, seduce, or change the attitude of anyone who finds your looks appealing. With a second rank, you are Very Attractive, giving you a +5 circumstance bonus. This bonus does not count as part of your regular skill bonus in terms of the series power level, but also does not apply to people or situations which (in the GM’s opinion) would not be influenced by your appearance. While superheroes tend to be a fairly good-looking lot, this advantage is generally reserved for characters with particularly impressive looks.""" advantage_needs_rank = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, rank): super().__init__("Attractive") self.init_flat(rank) class Beginners_Luck(Advantage): """By spending a hero point, you gain an effective 5 ranks in one skill of your choice you currently have at 4 or fewer ranks, including skills you have no ranks in, even if they can’t be used untrained. These temporary skill ranks last for the duration of the scene and grant you their normal benefits.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Beginner's Luck") self.init_no() class Benefit(Advantage): """You have some significant perquisite or fringe benefit. The exact nature of the benefit is for you and the Gamemaster to determine. As a rule of thumb it should not exceed the benefits of any other advantage, or a power effect costing 1 point (see Feature in the Powers chapter). It should also be significant enough to cost at least 1 power point. An example is Diplomatic Immunity (see Sample Benefits). A license to practice law or medicine, on the other hand, should not be considered a Benefit; it’s simply a part of having training in the appropriate Expertise skill and has no significant game effect. Benefits may come in ranks for improved levels of the same benefit. The GM is the final arbiter as to what does and does not constitute a Benefit in the setting. Keep in mind some qualities may constitute Benefits in some series, but not in others, depending on whether or not they have any real impact on the game. Sample Benefits The following are some potential Benefits. The GM is free to choose any suitable Benefit for the series. • Alternate Identity: You have an alternate identity, complete with legal paperwork (driver’s license, birth certificate, etc.). This is different from a costumed identity, which doesn’t necessarily have any special legal status (but may in some settings). • Ambidexterity: You are equally adept using either hand, suffering no circumstance penalty for using your off-hand (as you don’t have one). • Cipher: Your true history is well hidden, making it difficult to dig up information about you. Investigation checks concerning you are made at a –5 circumstance penalty per rank in this benefit. • Diplomatic Immunity: By dint of your diplomatic status, you cannot be prosecuted for crimes in nations other than your own. All another nation can do is deport you to your home nation. • Security Clearance: You have access to classified government information, installations, and possibly equipment and personnel. • Status: By virtue of birth or achievement, you have special status. Examples include nobility, knighthood, aristocracy, and so forth. • Wealth: You have greater than average wealth or material resources, such as well-off (rank 1), independently wealthy (rank 2), a millionaire (rank 3), multimillionaire (rank 4), or billionaire (rank 5).""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_needs_name = True advantage_needs_rank = True def __init__(self, benefit_name, rank): super().__init__("Benefit") self.benefit_name = benefit_name self.init_flat(rank) self.representation = self.representation_benefit def representation_benefit(self): return "Benefit %d: (%s)" % (self.advantage_rank, self.benefit_name) class Chokehold(Advantage): """If you successfully grab and restrain an opponent (see Grab, page 248), you can apply a chokehold, causing your opponent to begin suffocating for as long as you continue to restrain your target (see Suffocation, page 238).""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Chokehold") self.init_no() class Close_Attack(Advantage): """You have a +1 bonus to close attacks checks per rank in this advantage. Your total attack bonus is still limited by power level. This advantage best suits characters with a level of overall close combat skill (armed and unarmed). For capability with a particular type of attack, use the Close Combat skill.""" advantage_needs_rank = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, rank): super().__init__("Close Attack") self.init_flat(rank) class Connected(Advantage): """You know people who can help you out from time to time. It might be advice, information, help with a legal matter, or access to resources. You can call in such favors by making a Persuasion check. The GM sets the DC of the check, based on the aid required. A simple favor is DC 10, ranging up to DC 25 or higher for especially difficult, dangerous, or expensive favors. You can spend a hero point to automatically secure the favor, if the GM allows it. The GM has the right to veto any request if it is too involved or likely to spoil the plot of the adventure. Use of this advantage always requires at least a few minutes (and often much longer) and the means to contact your allies to ask for their help.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Connected") self.init_no() class Contacts(Advantage): """You have such extensive and well-informed contacts you can make an Investigation check to gather information in only one minute, assuming you have some means of getting in touch with your contacts. Further Investigation checks to gather information on the same subject require the normal length of time, since you must go beyond your immediate network of contacts.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Contacts") self.init_no() class Daze(Advantage): """You can make a Deception or Intimidation check as a standard action (choose which skill when you acquire the advantage) to cause an opponent to hesitate in combat. Make a skill check as a standard action against your target’s resistance check (the same skill, Insight, or Will defense, whichever has the highest bonus). If you win, your target is dazed (able to take only a standard action) until the end of your next round. The ability to Daze with Deception and with Intimidation are separate advantages. Take this advantage twice in order to be able to do both.""" advantage_has_list = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, skill_list): super().__init__("Daze") self.list_value = skill_list rank = len(skill_list) self.init_flat(rank) self.representation = self.represent_list class Defensive_Attack(Advantage): """When you make a defensive attack (see Maneuvers, page 249), you can take a penalty of up to –5 on your attack bonus and add the same number (up to +5) to both your active defenses (Dodge and Parry).""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Defensive Attack") self.init_pyramid(rank) class Defensive_Roll(Advantage): """You can avoid damage through agility and “rolling” with an attack. You receive a bonus to your Toughness equal to your advantage rank, but it is considered an active defense similar to Dodge and Parry (see Active Defenses in the Abilities chapter), so you lose this bonus whenever you are vulnerable or defenseless. Your total Toughness, including this advantage, is still limited by power level. This advantage is common for heroes who lack either superhuman speed or toughness, relying on their agility and training to avoid harm.""" advantage_needs_rank = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, rank): super().__init__("Defensive Roll") self.init_flat(rank) class Diehard(Advantage): """When your condition becomes dying (see Conditions in the Action & Adventure chapter) you automatically stabilize on the following round without any need for a Fortitude check, although further damage—such as a finishing attack—can still kill you.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Diehard") self.init_no() class Eidetic_Memory(Advantage): """You have perfect recall of everything you’ve experienced. You have a +5 circumstance bonus on checks to remember things, including resistance checks against effects that alter or erase memories. You can also make Expertise skill checks to answer questions and provide information as if you were trained, meaning you can answer questions involving difficult or obscure knowledge even without ranks in the skill, due to the sheer amount of trivia you have picked up.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Eidetic Memory") self.init_no() class Equipment(Advantage): """You have 5 points per rank in this advantage to spend on equipment. This includes vehicles and headquarters. See the Gadgets & Gear chapter for details on equipment and its costs. Many heroes rely almost solely on Equipment in conjunction with their skills and other advantages.""" advantage_needs_rank = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, rank): super().__init__("Defensive Roll") self.init_flat(rank) class Evasion(Advantage): """You have a +2 circumstance bonus to Dodge resistance checks to avoid area effects (see the Area extra in the Powers chapter). If you have 2 ranks in this advantage, your circumstance bonus increases to +5.""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Evasion") self.init_pyramid(rank) class Extraordinary_Effort(Advantage): """When using extra effort (see Extra Effort in The Basics chapter), you can gain two of the listed benefits, even stacking two of the same type of benefit. However, you also double the cost of the effort; you’re exhausted starting the turn after your extraordinary effort. If you are already fatigued, you are incapacitated. If you are already exhausted, you cannot use extraordinary effort. Spending a hero point at the start of your next turn reduces the cost of your extraordinary effort to merely fatigued, the same as a regular extra effort.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Extraordinary Effort") self.init_no() class Fascinate(Advantage): """One of your interaction skills is so effective you can capture and hold other’s attention with it. Choose Deception, Intimidation, or Persuasion when you acquire this advantage. You can also use Fascinate with an appropriate Expertise skill, like musician or singer, at the GM’s discretion. You are subject to the normal guidelines for interaction skills, and combat or other immediate danger makes this advantage ineffective. Take a standard action and make an interaction skill check against your target’s opposing check (Insight or Will defense). If you succeed, the target is entranced. You can maintain the effect with a standard action each round, giving the target a new resistance check. The effect ends when you stop performing, the target successfully resists, or any immediate danger presents itself. Like all interaction skills, you can use Fascinate on a group, but you must affect everyone in the group in the same way. You may take this advantage more than once. Each time, it applies to a different skill.""" advantage_has_list = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, skill_list): super().__init__("Fascinate") self.list_value = skill_list rank = len(skill_list) self.init_flat(rank) self.representation = self.represent_list class Fast_Grab(Advantage): """When you hit with an unarmed attack you can immediately make a grab check against that opponent as a free action (see Grab, page 248). Your unarmed attack inflicts its normal damage and counts as the initial attack check required to grab your opponent.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Fast Grab") self.init_no() class Favored_Environment(Advantage): """You have an environment you’re especially suited for fighting in. Examples include in the air, underwater, in space, in extreme heat or cold, in jungles or woodlands, and so forth. While you are in your favored environment, you gain a +2 circumstance bonus to attack checks or your active defenses. Choose at the start of the round whether the bonus applies to attack or defense. The choice remains until the start of your next round. This circumstance bonus is not affected by power level.""" advantage_has_list = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, environment_list): super().__init__("Favored Environment") self.list_value = environment_list rank = len(environment_list) self.init_flat(rank) self.representation = self.represent_list class Favored_Foe(Advantage): """You have a particular type of opponent you’ve studied or are especially effective against. It may be a type of creature (aliens, animals, constructs, mutants, undead, etc.), a profession (soldiers, police officers, Yakuza, etc.) or any other category the GM approves. Especially broad categories like “humans” or “villains” are not permitted. You gain a +2 circumstance bonus on Deception, Intimidation, Insight, and Perception checks dealing with your Favored Foe. This circumstance bonus is not limited by power level.""" advantage_has_list = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, foe_list): super().__init__("Favored Foe") self.list_value = foe_list rank = len(self.list_value) self.init_flat(rank) self.representation = self.represent_list class Fearless(Advantage): """You are immune to fear effects of all sorts, essentially the same as an Immunity to Fear effect (see Immunity in the Powers chapter).""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Fearless") self.init_no() class Grabbing_Finesse(Advantage): """You can use your Dexterity bonus, rather than your Strength bonus, to make grab attacks. You are not vulnerable while grabbing. See Grab, page 248, for details. This is a good advantage for skilled unarmed combatants focused more on speed than strength.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Grabbing Finesse") self.init_no() class Great_Endurance(Advantage): """You have a +5 bonus on checks to avoid becoming fatigued and checks to hold your breath, avoid damage from starvation or thirst, avoid damage from hot or cold environments, and to resist suffocation and drowning. See Hazards and the Environment in the Action & Adventure chapter for details on these checks.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Great Endurance") self.init_no() class Hide_In_Plain_Sight(Advantage): """You can hide (see Hiding under Stealth in the Skills chapter) without any need for a Deception or Intimidation check or any sort of diversion, and without penalty to your Stealth check. You’re literally there one moment, and gone the next. You must still have some form of cover or concealment within range of your normal movement speed in order to hide.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Hide In Plain Sight") self.init_no() class Improved_Aim(Advantage): """You have an even keener eye when it comes to ranged combat. When you take a standard action to aim, you gain double the normal circumstance bonus: +10 for a close attack or ranged attack adjacent to the target, +5 for a ranged attack at a greater distance. See Aim, page 246, for details.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Improved Aim") self.init_no() class Improved_Critical(Advantage): """Increase your critical threat range with a particular attack (chosen when you acquire this advantage) by 1, allowing you to score a critical hit on a natural 19 or 20. Only a natural 20 is an automatic hit, however, and an attack that misses is not a critical. Each additional rank applies to a different attack or increases your threat range with an existing attack by one more, to a maximum threat range of 16-20 with 4 ranks.""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_skill = True advantage_needs_rank = True def __init__(self, skill, rank): super().__init__("Improved Critical") self.skill = skill self.init_pyramid(rank) self.representation = self.represent_improved_crit def represent_improved_crit(self): return "Improved Critical %d (%s)" % (self.advantage_rank, self.skill) class Improved_Defense(Advantage): """When you take the defend action in combat (see Defend in the Action & Adventure chapter) you gain a +2 circumstance bonus to your active defense checks for the round.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Improved Defense") self.init_no() class Improved_Disarm(Advantage): """You have no penalty to your attack check when attempting to disarm an opponent and they do not get the opportunity to disarm you (see Disarm in the Action & Adventure chapter).""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Improved Disarm") self.init_no() class Improved_Grab(Advantage): """You can make grab attacks with only one arm, leaving the other free. You can also maintain the grab while using your other hand to perform actions. You are not vulnerable while grabbing (see Grabbing in the Action & Adventure chapter).""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Improved Grab") self.init_no() class Improved_Hold(Advantage): """Your grab attacks are particularly difficult to escape. Opponents you grab suffer a –5 circumstance penalty on checks to escape.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Improved Hold") self.init_no() class Improved_Initiative(Advantage): """You have a +4 bonus to your initiative checks per rank in this advantage.""" advantage_needs_rank = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, rank): super().__init__("Improved Initiative") self.init_flat(rank) class Improved_Smash(Advantage): """You have no penalty to attack checks to hit an object held by another character (see Smash in the Action & Adventure chapter).""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Improved Smash") self.init_no() class Improved_Trip(Advantage): """You have no penalty to your attack check to trip an opponent and they do not get the opportunity to trip you. When making a trip attack, make an opposed check of your Acrobatics or Athletics against your opponent’s Acrobatics or Athletics, you choose which your opponent uses to defend, rather than the target choosing (see Trip in the Action & Adventure chapter). This is a good martial arts advantage for unarmed fighters.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Improved Trip") self.init_no() class Improvised_Tools(Advantage): """You ignore the circumstance penalty for using skills without proper tools, since you can improvise sufficient tools with whatever is at hand. If you’re forced to work without tools at all, you suffer only a –2 penalty.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Improvised Tools") self.init_no() class Improvised_Weapon(Advantage): """When wielding an improvised close combat weapon— anything from a chair to a telephone pole or entire car— you use your Close Combat: Unarmed skill bonus for attack checks with the “weapon” rather than relying on your general Close Combat skill bonus. Additional ranks in this advantage give you a +1 bonus to Damage with improvised weapons per rank. Your maximum Damage bonus is still limited by power level, as usual.""" advantage_needs_rank = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, rank): super().__init__("Improvised Weapon") self.init_flat(rank) class Inspire(Advantage): """You can inspire your allies to greatness. Once per scene, by taking a standard action and spending a hero point, allies able to interact with you gain a +1 circumstance bonus per Inspire rank on all checks until the start of your next round, with a maximum bonus of +5. You do not gain the bonus, only your allies do. The inspiration bonus ignores power level limits, like other uses of hero points. Multiple uses of Inspire do not stack, only the highest bonus applies.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Inspire") self.init_flat(rank) class Instant_Up(Advantage): """You can go from prone to standing as a free action without the need for an Acrobatics skill check.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Instant Up") self.init_no() class Interpose(Advantage): """Once per round, when an ally within range of your normal movement is hit by an attack, you can choose to place yourself between the attacker and your ally as a reaction, making you the target of the attack instead. The attack hits you rather than your ally, and you suffer the effects normally. You cannot use this advantage against area effects or perception range attacks, only those requiring an attack check.""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Interpose") self.init_pyramid(rank) class Inventor(Advantage): """You can use the Technology skill to create inventions. See Inventing, page 211, for details.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Inventor") self.init_no() class Jack_Of_All_Trades(Advantage): """You can use any skill untrained, even skills or aspects of skills that normally cannot be used untrained, although you must still have proper tools if the skill requires them""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Jack-of-all-Trades") self.init_no() class Languages(Advantage): """You can speak and understand additional languages. With one rank in this advantage, you know an additional language. For each additional rank, you double your additional known languages: two at rank 2, four at rank 3, eight at rank 4, etc. So a character with Languages 7 is fluent in 64 languages! Characters are assumed to be fluent in any languages they know, including being able to read and write in them. For the ability to understand any language, see the Comprehend effect in the Powers chapter.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_has_list = True def __init__(self, language_list): super().__init__("Languages") self.list_value = language_list rank = (math.ceil(math.log(len(language_list),2))) self.init_flat(rank) self.representation = self.represent_list class Leadership(Advantage): """Your presence reassures and lends courage to your allies. As a standard action, you can spend a hero point to remove one of the following conditions from an ally with whom you can interact: dazed, fatigued, or stunned.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Leadership") self.init_no() class Luck(Advantage): """Once per round, you can choose to re-roll a die roll, like spending a hero point (see Hero Points, page 20), including adding 10 to re-rolls of 10 or less. You can do this a number of times per game session equal to your Luck rank, with a maximum rank of half the series power level (rounded down). Your Luck ranks refresh when your hero points “reset” at the start of an adventure. The GM may choose to set a different limit on ranks in this advantage, depending on the series.""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Luck") self.init_pyramid(rank) class Minion(Advantage): """You have a follower or minion. This minion is an independent character with a power point total of (advantage rank x 15). Minions are subject to the normal power level limits, and cannot have minions themselves. Your minions (if capable of independent thought) automatically have a helpful attitude toward you. They are subject to the normal rules for minions (see page 245). Minions do not earn power points. Instead, you must spend earned power points to increase your rank in this advantage to improve the minion’s power point total and traits. Minions also do not have hero points. Any lost minions are replaced in between adventures with other followers with similar abilities at the Gamemaster’s discretion.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_needs_rank = True advantage_needs_name = True def __init__(self, minion_name, rank): super().__init__("Minion") self.minion_name = minion_name self.init_flat(rank) class Move_By_Action(Advantage): """When taking a standard action and a move action you can move both before and after your standard action, provided the total distance moved isn’t greater than your normal movement speed.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Move-By Action") self.init_no() class Power_Attack(Advantage): """When you make a power attack (see Maneuvers, page 250) you can take a penalty of up to –5 on your attack bonus and add the same number (up to +5) to the effect bonus of your attack.""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Power Attack") self.init_pyramid(rank) class Precise_Attack(Advantage): """When you make close or ranged attacks (choose one) you ignore attack check penalties for cover or concealment (choose one), although total cover still prevents you from making attacks. Each additional rank in this advantage lets you choose an additional option, so with Precise Attack 4, all your attacks (both close and ranged) ignore penalties for both cover and concealment.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_has_list = True def __init__(self, penalty_list): super().__init__("Precise_Attack") self.list_value = penalty_list rank = len(self.list_value) self.init_flat(rank) self.representation = self.represent_list class Prone_Fighting(Advantage): """You suffer no circumstance penalty to attack checks for being prone, and adjacent opponents do not gain the usual circumstance bonus for close attacks against you.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Prone Fighting") self.init_no() class Quick_Draw(Advantage): """You can draw a weapon from a holster or sheath as a free action, rather than a move action.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_needs_rank = True def __init__(self,rank): super().__init__("Quick Draw") self.init_flat(rank) class Ranged_Attack(Advantage): """You have a +1 bonus to ranged attacks checks per rank in this advantage. Your total attack bonus is still limited by power level.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_needs_rank = True def __init__(self,rank): super().__init__("Ranged Attack") self.init_flat(rank) class Redirect(Advantage): """If you successfully trick an opponent (see Trick under Deception in the Skills chapter), you can redirect a missed attack against you from that opponent at another target as a reaction. The new target must be adjacent to you and within range of the attack. The attacker makes a new attack check with the same modifiers as the first against the new target.""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Redirect") self.init_pyramid(rank) class Ritualist(Advantage): """You can use the Expertise: Magic skill to create and cast magical rituals (see page 212). This advantage is often a back-up or secondary magical power for superhuman sorcerers, and may be the only form of magic available to some “dabbler” types.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Ritualist") self.init_no() class Second_Chance(Advantage): """Choose a particular hazard, such as falling, being tripped, triggering traps, mind control (or another fairly specific power effect, such as Damage with the fire descriptor) or a particular skill with consequences for failure. If you fail a check against that hazard, you can make another immediately and use the better of the two results. You only get one second chance for any given check, and the GM decides if a particular hazard or skill is an appropriate focus for this advantage. You can take this advantage multiple times, each for a different hazard.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_has_list = True def __init__(self, chance_list): super().__init__("Second Chance") self.list_value = chance_list rank = len(self.list_value) self.init_flat(rank) self.representation = self.represent_list class Seize_Initiative(Advantage): """You can spend a hero point to automatically go first in the initiative order. You may only do so at the start of combat, when you would normally make your initiative check. If more than one character uses this advantage, they all make initiative checks normally and act in order of their initiative result, followed by all the other characters who do not have this advantage.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Seize Initiative") self.init_no() class Set_Up(Advantage): """You can transfer the benefits of a successful combat use of an interaction skill to your teammate(s). For example, you can feint and have your target vulnerable against one or more allies next attack(s), rather than yours. Each rank in the advantage lets you transfer the benefit to one ally. The interaction skill check requires its normal action, and the affected allies must be capable of interacting with you (or at least seeing the set-up) to benefit from it.""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Set-Up") self.init_pyramid(rank) class Sidekick(Advantage): """You have another character serving as your partner and aide. Create your sidekick as an independent character with (advantage rank x 5) power points, and subject to the series power level. A sidekick’s power point total must be less than yours. Your sidekick is an NPC, but automatically helpful and loyal to you. Gamemasters should generally allow you to control your sidekick, although sidekicks remain NPCs and the GM has final say in their actions. Sidekicks do not earn power points. Instead, you must spend earned power points to increase your rank in Sidekick to improve the sidekick’s power point total and traits; each point you spend to increase your rank in Sidekick grants the sidekick 5 additional power points. Sidekicks also do not have hero points, but you can spend your own hero points on the sidekick’s behalf with the usual benefits. Sidekicks are not minions, but full-fledged characters, so they are not subject to the minion rules.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_needs_rank = True advantage_needs_name = True def __init__(self, sidekick_name, rank): super().__init__("Sidekick") self.sidekick_name = sidekick_name self.init_flat(rank) class Skill_Mastery(Advantage): """Choose a skill. You can make routine checks with that skill even when under pressure (see Routine Checks in The Basics chapter). This advantage does not allow you to make routine checks with skills that do not normally allow you to do so. You can take this advantage multiple times for different skills.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_has_list = True def __init__(self, skill_list): super().__init__("Skill Mastery") self.list_value = skill_list rank = len(skill_list) self.init_flat(rank) self.representation = self.represent_list class Startle(Advantage): """You can use Intimidation rather than Deception to feint in combat (see Feint under the Deception skill description). Targets resist with Insight, Intimidation, or Will defense.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Startle") self.init_no() class Takedown(Advantage): """If you render a minion incapacitated with an attack, you get an immediate extra attack as a free action against another minion within range and adjacent to the previous target’s location. The extra attack is with the same attack and bonus as the first. You can continue using this advantage until you miss or there are no more minions within range of your attack or your last target. A second rank in this advantage allows you to attack nonadjacent minion targets, moving between attacks if necessary to do so. You cannot move more than your total speed in the round, regardless of the number of attacks you make. You stop attacking once you miss, run out of movement, or there are no more minions within range of your attack.""" advantage_cost_type = Cost_Type.PYRAMID_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Takedown") self.init_pyramid(rank) class Taunt(Advantage): """You can demoralize an opponent with Deception rather than Intimidation (see Demoralize under the Intimidation skill description), disparaging and undermining confidence rather than threatening. Targets resist using Deception, Insight, or Will defense.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Taunt") self.init_no() class Teamwork(Advantage): """You’re effective at helping out your friends. When you support a team check (see Team Checks in The Basics chapter) you have a +5 circumstance bonus to your check. This bonus also applies to the Aid action and Team Attacks.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Teamwork") self.init_no() class Throwing_Mastery(Advantage): """You have a +1 damage bonus with thrown weapons per rank in this advantage. You can also throw normally harmless objects—playing cards, pens, paper clips, and so forth—as weapons with a damage bonus equal to your advantage rank and range based on the higher of your advantage rank or Strength (see Ranged in the Powers chapter). Your maximum damage bonus with any given weapon or attack is still limited by power level.""" advantage_cost_type = Cost_Type.FLAT_RANK advantage_needs_rank = True def __init__(self, rank): super().__init__("Throwing Mastery") self.init_flat(rank) class Tracking(Advantage): """You can use the Perception skill to visually follow tracks like the Tracking Senses effect (see the Powers chapter).""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Tracking") self.init_no() class Trance(Advantage): """Through breathing and bodily control, you can slip into a deep trance. This takes a minute of uninterrupted meditation and a DC 15 Awareness check. While in the trance you add your Awareness rank to your Stamina rank to determine how long you can hold your breath and you use the higher of your Fortitude or Will defenses for resistance checks against suffocation (see Suffocation, page 238). Poison and disease effects are suspended for the duration of the trance. It requires a Perception check with a DC equal to your Awareness check result to determine you’re not dead because your bodily functions are so slow. You are aware of your surroundings while in trance and can come out of it at any time at will. You cannot take any actions while in the trance, but your GM may allow mental communication while in a trance.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Trance") self.init_no() class Ultimate_Effort(Advantage): """You can spend a hero point on a particular check and treat the roll as a 20 (meaning you don’t need to roll the die at all, just apply a result of 20 to your modifier). This is not a natural 20, but is treated as a roll of 20 in all other respects. You choose the particular check the advantage applies to when you acquire it and the GM must approve it. You can take Ultimate Effort multiple times, each time, it applies to a different check. This advantage may not be used after you’ve rolled the die to determine if you succeed.""" advantage_has_list = True advantage_cost_type = Cost_Type.FLAT_RANK def __init__(self, skill_list): super().__init__("Ultimate Effort") self.list_value = skill_list rank = len(skill_list) self.init_flat(rank) self.representation = self.represent_list class Uncanny_Dodge(Advantage): """You are especially attuned to danger. You are not vulnerable when surprised or otherwise caught off-guard. You are still made vulnerable by effects that limit your mobility.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Uncanny Dodge") self.init_no() class Weapon_Bind(Advantage): """If you take the defend action (see Defend in the Action & Adventure chapter) and successfully defend against a close weapon attack, you can make a disarm attempt against the attacker immediately as a reaction. The disarm attempt is carried out normally, including the attacker getting the opportunity to disarm you.""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Weapon Bind") self.init_no() class Weapon_Break(Advantage): """If you take the defend action (see Defend in the Action & Adventure chapter) and successfully defend against a close weapon attack, you can make an attack against the attacker’s weapon immediately as a reaction. This requires an attack check and inflicts normal damage to the weapon if it hits (see Smash in the Action & Adventure chapter).""" advantage_cost_type = Cost_Type.NO_RANK def __init__(self): super().__init__("Weapon Break") self.init_no() class Well_Informed(Advantage): """You are exceptionally well-informed. When encountering an individual, group, or organization for the first time, you can make an immediate Investigation or Persuasion skill check to see if your character has heard something about the subject. Use the guidelines for gathering information in the Investigation skill description to determine the level of information you gain. You receive only one check per subject upon first encountering them, although the GM may allow another upon encountering the subject again once significant time has passed.""" advantage_cost_type = Cost_Type.NO_RANK def init(self): super().__init__("Well Informed") self.init_no() combat_adv = """Accurate Attack Trade effect DC for attack bonus. All-out Attack Trade active defense for attack bonus. Chokehold Suffocate an opponent you have successfully grabbed. Close Attack +1 bonus to close attack checks per rank. Defensive Attack Trade attack bonus for active defense bonus. Defensive Roll +1 active defense bonus to Toughness per rank. Evasion Circumstance bonus to avoid area effects. Fast Grab Make a free grab check after an unarmed attack. Favored Environment Circumstance bonus to attack or defense in an environment. Grabbing Finesse Substitute Dex for Str when making grab attacks. Improved Aim Double circumstance bonuses for aiming. Improved Critical +1 to critical threat range with an attack per rank. Improved Defense +2 bonus to active defense when you take the defend action. Improved Disarm No penalty for the disarm action. Improved Grab Make grab attacks with one arm. Not vulnerable while grabbing. Improved Hold –5 circumstance penalty to escape from your holds. Improved Initiative +4 bonus to initiative checks per rank. Improved Smash No penalty for the smash action. Improved Trip No penalty for the trip action. Improvised Weapon Use Unarmed Combat skill with improvised weapons, +1 damage bonus. Move-by Action Move both before and after your standard action. Power Attack Trade attack bonus for effect bonus. Precise Attack Ignore attack check penalties for either cover or concealment. Prone Fighting No penalties for fighting while prone. Quick Draw Draw a weapon as a free action. Ranged Attack +1 bonus to ranged attack checks per rank. Redirect Use Deception to redirect a missed attack at another target. Set-up Transfer the benefit of an interaction skill to an ally. Takedown Free extra attack when you incapacitate a minion. Throwing Mastery +1 damage bonus with thrown weapons per rank. Uncanny Dodge Not vulnerable when surprised or caught off-guard. Weapon Bind Free disarm attempt when you actively defend. Weapon Break Free smash attack when you actively defend.""" fortune_adv = """Beginner’s Luck Spend a hero point to gain 5 temporary ranks in a skill. Inspire Spend a hero point to grant allies a +1 circumstance bonus per rank. Leadership Spend a hero point to remove a condition from an ally. Luck Re-roll a die roll once per rank. Seize Initiative Spend a hero point to go first in the initiative order. Ultimate Effort Spend a hero point to get an effective 20 on a specific check.""" general_adv = """Assessment Use Insight to learn an opponent’s combat capabilities. Benefit Gain a significant perquisite or fringe benefit. Diehard Automatically stabilize when dying. Eidetic Memory Total recall, +5 circumstance bonus to remember things. Equipment 5 points of equipment per rank. Extraordinary Effort Gain two benefits when using extra effort. Fearless Immune to fear effects. Great Endurance +5 on checks involving endurance. Instant Up Stand from prone as a free action. Interpose Take an attack meant for an ally. Minion Gain a follower or minion with (15 x rank) power points. Second Chance Re-roll a failed check against a hazard once. Sidekick Gain a sidekick with (5 x rank) power points. Teamwork +5 bonus to support team checks. Trance Go into a deathlike trance that slows bodily functions.""" skill_adv = """Agile Feint Feint using Acrobatics skill or movement speed. Animal Empathy Use interaction skills normally with animals. Artificer Use Expertise: Magic to create temporary magical devices. Attractive Circumstance bonus to interaction based on your looks. Connected Call in assistance or favors with a Persuasion check. Contacts Make an initial Investigation check in one minute. Daze Use Deception or Intimidation to daze an opponent. Fascinate Use an interaction skill to entrance others. Favored Foe Circumstance bonus to checks against a type of opponent. Hide in Plain Sight Hide while observed without need for a diversion. Improvised Tools No penalty for using skills without tools. Inventor Use Technology to create temporary devices. Jack-of-all-trades Use any skill untrained. Languages Speak and understand additional languages. Ritualist Use Expertise: Magic to create and perform rituals. Skill Mastery Make routine checks with one skill under any conditions. Startle Use Intimidation to feint in combat. Taunt Use Deception to demoralize in combat. Tracking Use Perception to follow tracks. Well-informed Immediate Investigation or Persuasion check to know something""" Advantage.advantage_list = {"Accurate Attack":Accurate_Attack, "Agile Feint":Agile_Feint, "All Out Attack":All_Out_Attack, "Animal Empathy":Animal_Empathy, "Artificer":Artificer, "Assessment":Assessment, "Attractive":Attractive, "Beginner's Luck":Beginners_Luck, "Benefit":Benefit, "Chokehold":Chokehold, "Close Attack":Close_Attack, "Connected":Connected, "Contacts":Contacts, "Daze":Daze, "Defensive Attack":Defensive_Attack, "Defensive Roll":Equipment, "Diehard":Diehard, "Eidetic Memory":Eidetic_Memory, "Evasion":Evasion, "Extraordinary Effort":Extraordinary_Effort, "Fascinate":Fascinate, "Fast Grab":Fast_Grab, "Favored Environment":Favored_Environment, "Favored Foe":Favored_Foe, "Fearless":Fearless, "Grabbing Finesse":Grabbing_Finesse, "Great Endurance":Great_Endurance, "Hide In Plain Sight":Hide_In_Plain_Sight, "Improved Aim":Improved_Aim, "Improved Critical":Improved_Critical, "Improved Defense":Improved_Defense, "Improved Disarm":Improved_Disarm, "Improved Grab":Improved_Grab, "Improved Hold":Improved_Hold, "Improved Initiative":Improved_Initiative, "Improved Smash":Improved_Smash, "Improved Trip":Improved_Trip, "Improvised Tools":Improvised_Tools, "Improvised Weapon":Improvised_Weapon, "Inspire":Inspire, "Instant Up":Instant_Up, "Interpose":Interpose, "Inventor":Inventor, "Jack-of-all-Trades":Jack_Of_All_Trades, "Languages":Languages, "Leadership":Leadership, "Luck":Luck, "Minion":Minion, "Move-By Action":Move_By_Action, "Power Attack":Power_Attack, "Precise_Attack":Precise_Attack, "Prone Fighting":Prone_Fighting, "Quick Draw":Quick_Draw, "Ranged Attack":Ranged_Attack, "Redirect":Redirect, "Ritualist":Ritualist, "Second Chance":Second_Chance, "Seize Initiative":Seize_Initiative, "Set-Up":Set_Up, "Sidekick":Sidekick, "Skill Mastery":Skill_Mastery, "Startle":Startle, "Takedown":Takedown, "Taunt":Taunt, "Teamwork":Teamwork, "Throwing Mastery":Throwing_Mastery, "Tracking":Tracking, "Trance":Trance, "Ultimate Effort":Ultimate_Effort, "Uncanny Dodge":Uncanny_Dodge, "Weapon Bind":Weapon_Bind, "Weapon Break":Weapon_Break, "Well Informed":Well_Informed}
f100bbaaf98a2a01a05e32fd428ad1cfce616ca3
WuraolaS/pyhour
/MIT_test1.py
482
3.71875
4
total_cost = float(1000000) #down payment amount portion_down_payment = 0.25 * total_cost current_savings = 0 r = 0.04 annual_salary=float(120000) portion_saved = 0.1 monthly_salary = float(annual_salary/12) #number_of_months = portion_down_payment/portion_saved #It keeps ending in an infinite loop count = 0 while current_savings <= portion_down_payment: current_savings += float((portion_saved*monthly_salary)) + float((current_savings*r))/12.0 count += 1 print(count)
925a18d8f83ca6b3840fb9af556ce6be6a990ec7
MuddSub/CVImageHandling
/imgDistribution.py
5,392
3.734375
4
# inputs: folder with all the images, list of names that will label the images # has one folder of images that it splits so everyone has a folder of images # nest folders so they're still in the larger folder # importing os module import os, os.path, shutil def get_names(file): """ Input: text file with names Generates a list of names, gathered from a text file Output: list of names """ name_file = open(file, "r") list_of_names = [] for line in name_file: stripped_line = str(line.strip()) line_string = stripped_line.split() list_of_names +=line_string name_file.close() return list_of_names def pair_people(names): """ Input: a list of unpaired names Output: a list, where each element is a pair of names of the form "name1-name2" If the number of names is odd, pair_people will append 'Other' to the final name """ pair_names = [] if (len(names) % 2) == 1: names += ['Other'] if len(names) > 2: pair_names += [names[0] + '-' + names[1]] + pair_people(names[2:]) else: if (len(names) % 2) == 0: pair_names += [names[0] + '-' + names[1]] return pair_names def rename_images(pair_names, parent_dir): """ Inputs: a list of pairsand a directory with images Outputs: the same directory, but with renamed images rename_images cycles through the images stored in the directory and assigns them evenly among the provided pairs, using the naming convention "name1-name2_#.jpg" """ images = os.listdir(parent_dir) if '.DS_Store' in images: images.remove('.DS_Store') numPairs = len(pair_names) for x in range(len(images)): whichPair = x % numPairs os.rename(parent_dir +'/'+ images[x], parent_dir + '/' + pair_names[whichPair] + '_' + str(x) + '.jpg') return images def move_images(parent_dir): """ creates new folders in the parent_dir and moves images into the folders image names need to be name_number folder names are name """ images = [f for f in os.listdir(parent_dir) if os.path.isfile(os.path.join(parent_dir, f))] for image in images: folder_name = image.split('_')[0] new_path = os.path.join(parent_dir, folder_name) if not os.path.exists(new_path): os.makedirs(new_path) old_image_path = os.path.join(parent_dir, image) new_image_path = os.path.join(new_path, image) shutil.move(old_image_path, new_image_path) folders = [folder for folder in os.listdir(parent_dir) if os.path.isdir(os.path.join(parent_dir, folder))] for folder in folders: name1 = folder.split('-')[0] name2 = folder.split('-')[1] folder_path = os.path.join(parent_dir, folder) name1_path = os.path.join(folder_path, name1) os.makedirs(name1_path) name2_path = os.path.join(folder_path, name2) os.makedirs(name2_path) def main(names_file = 'names.txt', parent_dir = '/home/cvteam1/imageLabeling/compData/'): """ Inputs: txt file with peoples' names, directory of images to be sorted (parent_dir should contain only images) Gets names from file Creates pairs (format: name1-name2) Renames images (format: name1-name2_0.jpg) Moves images to folders named name1-name2 Output: none """ names = get_names(names_file) pairs = pair_people(names) rename_images(pairs, parent_dir) move_images(parent_dir) def admin_rename_images(names, parent_dir): """ Inputs: a list of names and a directory with images Outputs: the same directory, but with renamed images rename_images cycles through the images stored in the directory and assigns them evenly among the provided names, using the naming convention "admin_name'name1-name2_#.jpg" """ images = os.listdir(parent_dir) if '.DS_Store' in images: images.remove('.DS_Store') numNames = len(names) for x in range(len(images)): whichName = x % numNames os.rename(parent_dir +'/'+ images[x], parent_dir + '/' + names[whichName] + "'" + images[x]) return images def admin_move_images(parent_dir): """ creates new folders in the parent_dir and moves images into the folders """ images = [f for f in os.listdir(parent_dir) if os.path.isfile(os.path.join(parent_dir, f))] for image in images: folder_name = image.split("'")[0] new_path = os.path.join(parent_dir, folder_name) if not os.path.exists(new_path): os.makedirs(new_path) old_image_path = os.path.join(parent_dir, image) new_image_path = os.path.join(new_path, image) shutil.move(old_image_path, new_image_path) folders = [folder for folder in os.listdir(parent_dir) if os.path.isdir(os.path.join(parent_dir, folder))] for folder in folders: folder_path = os.path.join(parent_dir, folder) text_path = os.path.join(folder_path, folder) os.makedirs(text_path) def admin_distribution(admin_file = 'admin_names.txt', parent_dir = '/home/cvteam1/imageLabeling/compData/admin/'): """ distributes images within the admin folder """ admin_names = get_names(admin_file) admin_rename_images(admin_names, parent_dir) admin_move_images(parent_dir)
529770fd3db4dc60ae1af48c538ab6c5fcc72fff
rk2100994/python_basics
/construntor_destructor.py
787
4.1875
4
# class Car: # def __init__(self): # print('Hello World!!! I am constructor') # # instance # car = Car() # class Vehicle: # def __init__(self): # print("Vehicle created") # def __del__(self): # print('Destructor called, vehicle deleted') # vehicle = Vehicle() # print("Hello World!! after Destructor") ''' multiple constructors ''' class Man: def __init__(self): print("I'm default Constructor of Man") # @classmethod # def eye(cls,color,shape): # cls.color = color # cls.shape = shape # print("In first def",color) @classmethod def eye(cls,shape,color): cls.shape = shape cls.color = color print("In second def",shape,",",color) man = Man() ob2 = Man.eye("round","brown") ob1 = Man.eye("black","triangle")
6fb0a94cc2a937ef3cef9c795dcc6d26ecdb9ec3
DeepanshuSarawagi/python
/DictionariesAndSets/dictionary3.py
3,432
4.65625
5
fruits = {"Orange": "A sweet orange citrus fruit, usually good for skin", "Apple": "Good for health if eaten once a day", "Lime": "A green sour/sweet citrus fruit", "Lemon": "A yellow sour citrus fruit, usually good with Vodka"} print(fruits) print(fruits.keys()) print(fruits["Lemon"]) vegetables = {"cabbage": {1: "Good for health"}, "carrot": {2: "Good for eye"}} print(vegetables["carrot"][2]) # Extracting the value from dictionary within dictionary veg = {"Cabbage": "Good for health. Mostly preferred in salads", "Carrot": "Very good for eyes. Rich in Vitamin A", "Spinach": "High proteins. Good for hair and eyes", "Broccoli": "Very high proteins."} print(veg) print() veg.update(fruits) # We have updated the dictionary veg by adding fruits dictionary in it. print() print(veg) print(fruits["Orange"].split()) print() nice_veg = fruits.copy() # Creating a new dictionary by copying fruits dictionary in it nice_veg.update(veg) # Updating the newly created dictionary by adding another dictionary "veg" in it print(nice_veg) print() for f in sorted(nice_veg.keys()): print(f + " - " + nice_veg[f]) """Continued dictionary challenge as per dictionary2.py We need to modify the program in such a way that users can enter the location name instead of the exits and the program should work.""" locations = {0: "You are sitting in front of the computer learning Python", 1: "You are standing at the end of the road before a small brick building", 2: "You are at the top of a hill", 3: "You are inside a building, a well house for small stream", 4: "You are in a valley beside a stream", 5: "You are in the forest"} # We have created a dictionary containing the locations and its corresponding keys. # Now we will create a list of dictionaries for available exits. exits = {0: {"Q": 0}, 1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0}, 2: {"N": 5, "Q": 0}, 3: {"W": 1, "Q": 0}, 4: {"N": 1, "W": 2, "Q": 0}, 5: {"W": 2, "S": 1, "Q": 0}} namedExits = {1: {"2": 2, "3": 3, "5": 5, "4": 4}, 2: {"5": 5}, 3: {"1": 1}, 4: {"1": 1, "2": 2}, 5: {"2": 2, "1": 1}} vocabulary = {"QUIT": "Q", "NORTH": "N", "SOUTH": "S", "EAST": "E", "WEST": "W", "ROAD": "1", "HILL": "2", "BUILDING": "3", "VALLEY": "4", "FOREST": "5"} loc = 1 while True: availableExits = ", ".join(exits[loc].keys()) # for direction in exits[loc].keys(): # print(direction) # availableExits += direction + ", " print(locations[loc]) if loc == 0: break else: allExits = exits[loc].copy() allExits.update(namedExits[loc]) chosenDirection = input("Available exits are " + availableExits + ": ").upper() # We are going to create a for loop to check if the user input is in vocabulary if len(chosenDirection) > 1: words = chosenDirection.split() for word in words: if word in vocabulary: chosenDirection = vocabulary[word] if chosenDirection in allExits: loc = allExits[chosenDirection] print(loc) else: print("You cannot go in that direction")
d4d1a1d3aaeacbcc72d80b797b41e3739a1d7f2a
thenatzzz/Tutorials
/Tutorial_ML_A-Z/PART_1_DATA_PREPROCESSING/data_preprocessing_template.py
2,966
3.84375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd import os ############## LOADING & ASSIGNING DEPENDENT + INDEPENDENT VARIABLE ##### CURRENT_WORKING_DIR = os.path.dirname(os.path.abspath(__file__)) DATASET_FOLDER = 'DATASET' CSV_FILE_NAME = 'Data.csv' path_dataset = os.path.join(CURRENT_WORKING_DIR,DATASET_FOLDER,CSV_FILE_NAME) # print(path_dataset) dataset = pd.read_csv(path_dataset) # print(dataset) # Independent variable: Country, Age, Salary # Dependent variable: Purchased # Predict whether Purchased or not X = dataset.iloc[:,:-1].values # note: 1st index = row, 2nd index = col # note2: .values = to get all value into line array print(X) y = dataset.iloc[:,-1].values print(y) ############# DEALING WITH MISSING VALUES ################################### # replace missing data with MEAN from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = 'NaN', strategy= 'mean', axis = 0) # axis = 0 -> along col imputer = imputer.fit(X[:,1:3]) # replace just missing value in col 2, 3 (index = 1,2) X[:,1:3] = imputer.transform(X[:,1:3]) # function transfor for assigning correct value back to X print(X) ############# ENCODING CATEGORICAL DATA ################################ # CATEGORICAL var = var that is not number ie Country & Purchased from sklearn.preprocessing import LabelEncoder, OneHotEncoder label_encoder_X = LabelEncoder() label_encoder_X = label_encoder_X.fit_transform(X[:,0]) X[:,0] = label_encoder_X # print(label_encoder_X) print(X) #create dummy variable: varible that does not care rank of elements onehotencoder = OneHotEncoder(categorical_features = [0]) # 0 = index of country X = onehotencoder.fit_transform(X).toarray() print(X) labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) print(y) ########## SPLITING DATASET: training set & test set ############################################# from sklearn.cross_validation import train_test_split # random_state may not need (just for checking result) X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2,random_state=0) print(X_train) print("X length: ", len(X)) print("X_train length: ",len(X_train)) print("X_test length: ",len(X_test)) print("y_train length: ",len(y_train)) print("y_test length: ",len(y_test)) ############## FEATURE SCALING ########################### # problem: range of age and salary are in different scale # ml relies on euclidean distance # fix: scale -1 to 1 value # standardisation & normalization from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() print("X_train before fit_transform: ",X_train) X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) # do not need fit anymore since training set already fit # fit vs fit_transform ref: https://datascience.stackexchange.com/questions/12321/difference-between-fit-and-fit-transform-in-scikit-learn-models print("X_train after fit_transform: ",X_train)
d9d06b8bd24a4330e3af1f1413f90cecdecbd70b
ysantur/Veri-Yapilari
/H5/queue.py
974
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 3 23:17:31 2018 @author: sntr """ class Queue(): def __init__(self): self.entries = [] self.length = 0 self.front=0 #Kuyruğun sonuna eleman ekler def insert(self, item): self.entries.append(item) self.length = self.length + 1 #Kuyruğun başındaki elemanı çeker. def remove(self): if self.length>0: item=self.entries[0] self.length = self.length - 1 del self.entries[0] return item else: print("Kuyruk boş") #Kuyruğun başındanki elemanı çeker, silmeden. def front(self): return self.entries[0] #Kuyruktaki eleman sayısı def size(self): return self.length #Kuyruğu yazdır def show(self): print(self.entries) x=Queue() x.insert(1) x.insert(2) x.show() x.remove() x.remove() x.remove() x.show()
3ffda0df307f97f47d7886f2c92686df0fd5dac9
anmolrajaroraa/HMR_Python_ML
/chat_app.py
601
4
4
print("Welcome".center(100)) #flag = True ''' This is a multi-line comment ''' hello_intent = ['hi', 'hello', 'hi there', 'hola'] while True: userMessage = input("Enter your message : ") userMessage = userMessage.lower() #if userMessage == "hello" or userMessage == "hi" or userMessage == "hola" or userMessage == "hi there": if userMessage in hello_intent: print("Hi") elif userMessage == "bye": print("See you later") #flag = False break #exit(0) #quit() else: print("I don't understand") print('Program terminated')
3ba52806cf794b23881fe16028ebe32c59bffdf5
hacksicredi2019/Time-Lilas
/poaonrails/crawlers/security.py
494
3.578125
4
# -*- coding: utf-8 -*- import csv import sqlite3 from datetime import date con = sqlite3.connect('../poaonrails/db/development.sqlite3') cursor = con.cursor() with open('data/security.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 i = {} statistics = [] for row in csv_reader: bairro = row[0].upper() fr = int(row[1]) statistics.append([bairro, fr]) statistics.sort(key=lambda x: x[1]) print(statistics)
793e4491f3ff3c3668315bac57b4193e1dedb02d
nilamkurhade/Week2
/DataStructurePrograms/balancedParantheses.py
805
3.90625
4
from DataStructurePrograms.stack import Stack class BalancedParantheses: s = Stack() # Object of the class exp = input('Please enter the expression: ') for c in exp: if c == '(': # if we receive the opening parantheses we push into stack s.push(1) elif c == ')': if s.isEmpty(): is_balanced = False break s.pop() # once we receive the closing parantheses we pop from stack else: if s.isEmpty(): is_balanced = True else: is_balanced = False if is_balanced: print('Expression is correctly parenthesized.') else: print('Expression is not correctly parenthesized.') if __name__ == "__main__": obj = BalancedParantheses()
efc571dd921569df3666bc3bcb8a8ae467e9815c
kennethhung863/matrix_reducer
/matrix_reducer.py
1,854
4.1875
4
# function declaration def print_matrix(matrix): for row in range(0,len(matrix)): print(matrix[row]) def swap_row(matrix,row1,row2): for i in range(0,len(matrix)+1): temp=matrix[row1][i] matrix[row1][i]=matrix[row2][i] matrix[row2][i]=temp def scale_row(matrix,row,factor): for i in range(0,len(matrix)+1): matrix[row][i]=float(matrix[row][i])*float(factor) def add_to_row(matrix,rowTarget,rowSource,factor): for i in range(0,len(matrix)+1): matrix[rowTarget][i]=float(matrix[rowTarget][i])+float(matrix[rowSource][i])*float(factor) size=float(input("Enter the size of the matrix: ")) #initializing list with rows and columns: extra column for constant term matrix=[[] *(int(size)+1) for i in range(int(size))] for row in range(0,int(size)): for column in range(0,int(size)+1): matrix[int(row)].append(input("Enter row "+str(row+1)+" column "+str(int(column)+1)+": ")) print("The size of the matrix is :",len(matrix)) print("The original matrix is:\t") print_matrix(matrix) # matrix reducing loop for row in range(0,len(matrix)): # while the first element is 0, swap until it is not if float(matrix[row][row])==0: swap=0 while matrix[swap][swap]==0: swap+=1 swap_row(matrix,row,swap) # now the row we're on is not 0 in the diagonal scale_row(matrix,row,1.0/float(matrix[row][row])) for i in range(0,len(matrix)): if i!=row: add_to_row(matrix,int(i),int(row),-float(matrix[i][row])) # making the numbers nice for row in range(0,int(size)): for column in range(0,int(size)+1): matrix[row][column]=round(float(matrix[row][column]),4) if float(matrix[row][column])==0: matrix[row][column]=float(0) # final print print("\nThe RREF form is:") print_matrix(matrix)
eeb5baa91f244dc9c5f35930831564125f380002
himanshugupta005/hackerrankContests
/pyramid_triangle..py
132
3.703125
4
num=int(input()) N=1 for i in range(1,num+1): for k in range(1,i+1): print(N,end=' ') N+=1 print()
543bef82a24e156fd1506d71d27cbd84d46f2b76
peterdjlee/ds_algorithms
/tree/bst.py
1,111
3.78125
4
import random class Node: def __init__(self, value, left = None, right = None): self.value = value self.left = left self.right = right def __str__(self): return str(self.value) def insert(root, node): if node.value < root.value: if root.left is None: root.left = node else: insert(root.left, node) if node.value > root.value: if root.right is None: root.right = node else: insert(root.right, node) def find(root, key): if root is None or root.value == key: return root if key < root.value: return find(root.left, key) if key > root.value: return find(root.right, key) def printBST(node): if node is None: return else: printBST(node.left) print(node.value) printBST(node.right) root = Node(8) insert(root, Node(9)) insert(root, Node(10)) insert(root, Node(7)) insert(root, Node(6)) for i in range(100000): insert(root, Node(random.randint(1,10000000))) # printBST(root) print(find(root, 9))
c625547694a286f51d3391abf84eb4eccc4f074e
radium006/9-24
/Assignment1.py
1,206
4.0625
4
class Person(object): def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.friends = [] self.greeting_count = 0 def greet(self, other_person): print ('Hello {0}, I am {1}!'.format(other_person.name, self.name)) self.greeting_count += 1 def info(self): print("{0}'s email is {1} and {2}'s number is {3}".format(self.name, self.email, self.name, self.phone)) def add_friend(self,other_person): self.friends.append(other_person) def num_friends(self): print(len(self.friends)) def __repr__(self): return "{0} {1} {2}".format(self.name, self.email, self.phone) class Vehicle: def __init__(self,make,model,year): self.make = make self.model = model self.year = year def print_info(self): print("{0} {1} {2}".format(self.year,self.make,self.model)) person1 = Person("Sonny", "sonny@hotmail.com", '483-485-4948') person2 = Person("Jordan","jordan@aol.com", "495-586-3456") person1.greet(person2) person1.info() person2.greet(person1) person2.info() person1.add_friend(person2) person1.num_friends() print(person1)
14a3ca6a3c79c980b3ac1eaddad347b83ed9fa6f
Hub972/game
/maze.py
3,824
3.984375
4
#! /usr/bin/env python3 # -*- coding: utf8 -*- import random import pygame from pygame.locals import * pygame.init() class Maze: def __init__(self): self.tiles = Maze.make_level() self.count = 0 @staticmethod def make_level(): """Load the level and add 3 objects under random position""" with open("level.txt", "r") as file: build_level = [list(line) for line in file.read().split("\n")] for i in range(3): while True: x = random.randint(0, 14) y = random.randint(0, 14) if not build_level[x][y] in ("1", "2", "3", "4", "5", "6"): build_level[x][y] = str(i + 4) break return build_level def find_tile(self, tile): """Check the position about the tile in parameter""" for i in range(len(self.tiles)): for j in range(len(self.tiles[i])): if self.tiles[i][j] == tile: return i, j return None def find_mac(self): """Check the position of mac""" return self.find_tile("3") def move_right(self): """Make a new position for '3' if it don't '1'""" x, y = self.find_mac() if y < 14: if self.tiles[x][y + 1] != "1": self.tiles[x][y + 1] = "3" self.tiles[x][y] = "0" def move_left(self): """Make a new position for '3' if it don't '1'""" x, y = self.find_mac() if y > 0: if self.tiles[x][y - 1] != "1": self.tiles[x][y - 1] = "3" self.tiles[x][y] = "0" def move_up(self): """Make a new position for '3' if it don't '1'""" x, y = self.find_mac() if x > 0: if self.tiles[x - 1][y] != "1": self.tiles[x - 1][y] = "3" self.tiles[x][y] = "0" def move_down(self): """Make a new position for '3' if it don't '1'""" x, y = self.find_mac() if x < 14: if self.tiles[x + 1][y] != "1": self.tiles[x + 1][y] = "3" self.tiles[x][y] = "0" def component_counter(self): """Check the count of component""" cnt = 0 for i in range(len(self.tiles)): for y in range(len(self.tiles[i])): if self.tiles[i][y] == "4" or self.tiles[i][y] == "5" or self.tiles[i][y] == "6": cnt += 1 self.count = cnt def component_found(self): """Check if the component is under the maze""" return self.find_tile("4") or self.find_tile("5") or self.find_tile("6") def draw(self, pictures): """Blit all the pictures on the maze""" ORANGE = 255, 100, 0 # color for the text text = pygame.font.SysFont('freesans', 13) # Police and size screen = pygame.display.set_mode((450, 450)) # Set the size' screen screen.blit(pictures["00"], (0, 0)) # Picture for the font """Loop for blit all the pictures""" for n_line, line in enumerate(self.tiles): for n_tile, tile in enumerate(line): x = n_tile * 30 y = n_line * 30 if tile != "0": screen.blit(pictures[tile], (x, y)) """Set the rect for the counter in the screen""" self.component_counter() title_text = text.render("Number of object(s) to found: {}".format(self.count), True, ORANGE) textpos = title_text.get_rect() textpos.centerx = 350 textpos.centery = 10 screen.blit(title_text, textpos) pygame.display.flip() def check_final_condition(self): """Check if mac is on the guard""" return self.find_tile("2") is None
2f040de6383c59cf0dc63700e5b8151a655a1640
arsh0611/100_days_of_code
/100DOC_8.py
1,690
4.375
4
""" Given an array arr[] with N elements, the task is to find out the longest sub-array which has the shape of a mountain. The Longest Peak consists of elements that are initially in ascending order until a peak element is reached and beyond the peak element all other elements of the sub-array are in decreasing order. Input: arr = [2, 2, 2] Output: 0 Explanation: No sub-array exists that shows the behaviour of a mountain sub-array. Input: arr = [1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5] Output: 11 Explanation: There are two sub-arrays that can be as mountain sub-arrays. The first one is from index 0 – 2 (3 elements) and next one is from index 2 – 12 (11 elements). As 11 > 2, our answer is 11."""" def LongestPeak(a): # Write your code here result=0 if (a[0]<a[1]): ascending=True else: ascending=False count=[0] counts=0 for i in range(0,len(a)): if i+1 != len(a): if(a[i]==a[i+1]): break if ascending==False: if i+1 != len(a): if a[i]<a[i+1]: counts=counts+1 count.append(counts) counts=0 ascending=True else: counts=counts+1 else: counts= counts+1 count.append(counts) break if(ascending==True): counts=counts+1 if i+1 != len(a): if a[i]>a[i+1]: ascending=False result= max(count) print(count) return result if __name__ == "__main__": d = [ 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 ] print(LongestPeak(d))
ef2dc5e5585a5a7ff763960da165638f226df4a7
ginnikhanna/Development
/CourseraMachineLearning/NeuralNetworks/multiclass_classification_with_forwardpropagation.py
1,453
4.09375
4
from __future__ import division import numpy as np import scipy.io import matplotlib.pyplot as plt from CourseraMachineLearning.Utility import plot from CourseraMachineLearning.Utility import neuralnetworks ''' The neural network is a 3 layer neural network with 1 input layer, 1 hidden layer and 1 output layer Therefore it will have two stages of thetas or weights theta_1 and theta_2 ''' # Load Data data = scipy.io.loadmat('ex3data1.mat') X_training = data['X'] y_training = data['y'] #Plot data plot_training_data = plot.display_data(X_training, 36, fig_number=1) #plt.show() # Load weights of neural network theta = scipy.io.loadmat('ex3weights.mat') theta_1 = theta['Theta1'] theta_2 = theta['Theta2'] print(theta_1.shape) print(theta_2.shape) number_of_hidden_layers = 2 theta = [theta_1.transpose(), theta_2.transpose()] prediction = neuralnetworks.predict_outcome_for_digit_dataset(X_training.transpose(), theta) accuracy = neuralnetworks.get_accuracy(prediction, y_training.flatten()) print(f'Accuracy of the neural network is : {accuracy}') random_row = np.random.randint(0, 5000) print(random_row) input_image = X_training[random_row :random_row + 1,:] prediction_digit = neuralnetworks.predict_outcome_for_digit_dataset(input_image.transpose(), theta) print(f'Predicted digit: {prediction_digit} and training digit : {y_training[random_row]}') plot_random_digit = plot.display_data(input_image, 1, fig_number=2) plt.show()