blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4aeb16c71d1878219dbfd44a3551e7b7685d1843 | w51w/python | /0831/ex1-3.py | 153 | 3.921875 | 4 | '''
d=3
h=2
x=3*2/2
print(x)
'''
print(10+20)
print("재미있는 파이썬")
print("abc " * 3)
x =25
y = 32
z = x+y
print(x,y)
print(x, '+', y, '=', z) |
359dbe864699f98da54d2f1476bfdfeb0644c10b | HuangZengPei/LeetCode | /Middle/Que95不同的二叉搜索树.py | 969 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def generateTrees_(start,end):
if start > end:
return [None,]
results = []
for i in range(start,end+1):
left = generateTrees_(start,i-1)
right = generateTrees_(i+1,end)
for l in left:
for r in right:
currTree = TreeNode(i)
currTree.left = l
currTree.right = r
results.append(currTree)
return results
return generateTrees_(1,n) if n else []
|
42bd05eec1c5c329295a4d25c5f6943b09d846c5 | anythingth2/DataStructure_and_Algorithm_Practice | /lab3_1.py | 559 | 3.65625 | 4 | class Queue:
def __init__(self,size=None,queue=None):
if queue == None:
self.queue = []
else:
self.queue = queue
self.size = size
def __str__(self):
return str(self.queue)
def enQueue(self,i):
if not self.isFull():
self.queue.append(i)
def deQueue(self):
return self.queue.pop(0)
def isEmpty(self):
return len(self.queue)==0
def isFull(self):
return len(self.queue) == self.size
def size(self):
return len(self.queue) |
72da115f09867963a3c4608f3dde4d60a2aa4746 | JUANSEBASTIANCAMACHO/JOBS | /JOBS/EJERCICIOS PARA EL 02-03-2021/PUNTO DE PAGINA 15.py | 809 | 3.625 | 4 | #Se desea conocer una serie de datos de una empresa con 50 empleados: a) ¿Cuántos empleados ganan
#más de 300.000 pesetas al mes (salarios altos); b)entre 100.000 y 300.000 pesetas (salarios medios);
#y c) menos de 100.000 pesetas (salarios bajos y empleados a tiempo parcial)?
empleados_altos=0
empleados_medios=0
empleados_bajos=0
for x in range(1,51):
salario=int(input("digite el salario del empleado: "))
if salario >= 300000:
empleados_altos=empleados_altos + 1
elif salario >= 100000 and salario <= 300000:
empleados_medios=empleados_medios + 1
else:
empleados_bajos=empleados_bajos + 1
print(str(empleados_altos) + "Tienen el salario alto")
print(str(empleados_medios) + "Tienen el salario medio")
print(str(empleados_bajos) + "Tienen el salario bajo")
|
83e35d4d1f8c669566a24d9767b1da9cdf048fd1 | thechutrain/uvm_salary | /count_positions.py | 1,827 | 3.734375 | 4 | #local copy
import pprint # to print things pretty
import operator # used to sort the dictionary
from open_cleanfile import open_cleanfile # imports open_cleanfile function
__author__ = 'alanchu'
################### READ ME #####################
# this function count_positions will accept the master
# list of employees and return a dictionary of the counts of
# unique employee positions, and can have it sorted
# first parameter = list of employees
# second parameter = A or D (assending or descending)
# RETURNS: sorted list of positions
def count_positions(employee_list, order):
e_pos_dict = {} # dictionary of the employee positions
sorted_e_pos_list = None
try:
for e in employee_list:
if (e[1] in e_pos_dict):
e_pos_dict[e[1]] += 1
else:
e_pos_dict[e[1]] = 1
# See if user wants the list sorted by ascending or descending order
user_choice = order[0].upper()
if (user_choice == "A"):
sorted_e_pos_list = sorted(e_pos_dict.items(), key=operator.itemgetter(1), reverse=False)
elif (user_choice == "D"):
sorted_e_pos_list = sorted(e_pos_dict.items(), key=operator.itemgetter(1), reverse=True)
else:
print "Please enter either 'A' or 'D' as the second argument in count_positions to get the positions sorted "
finally:
return sorted_e_pos_list
# pprint.pprint(sorted_e_pos_list)
# return e_pos_dict
##### TESTING ######
clean_employee_list = open_cleanfile("uvmSalary15.csv")
sorted_position_list = count_positions(clean_employee_list, "a")
# see how many unique positions there are
# print type(sorted_position_list)
#print "This is how many unique positions of employment there are at UVM: ", len(sorted_position_list)
|
1346a02194742e80eee1872a5cf4681e56338f15 | zltunes/AlgorithmExercise | /jianzhiOffer/MST4.py | 1,034 | 3.65625 | 4 | # -* - coding: UTF-8 -* -
# 替换空格为20%
# 设置两个指针,从后往前遍历,遇到空格插入
import collections
class Solution():
def replaceSpace(self,s):
if not s:
return s
blankNum=collections.Counter(s)[' ']
if blankNum==0:
return s
new=range(len(s)+blankNum*2)
l,r=len(s)-1,len(s)+blankNum*2-1
while(l>=0):
if s[l]!=' ':
new[r]=s[l]
l,r=l-1,r-1
else:
new[r],new[r-1],new[r-2]='0','2','%'
l,r=l-1,r-3
return "".join(new)
def replace(self,ss):
if not ss:return ss
slist=list(ss)
index=0
while index<len(slist):
if slist[index]==' ':
# slist.replace(index,'%20')
slist[index]='%20'
index+=3
else:
index+=1
return "".join(slist)
tmp="hello world."
s=Solution()
# print s.replaceSpace(tmp)
print(s.replace(tmp))
|
8a6069e937a29f5e657ef4254f4c23940976d90b | jaechoi15/DojoAssignments | /Python/Stars/stars.py | 912 | 4.09375 | 4 | # Part I
# Create a function called draw_stars() that takes a list of numbers and prints out *.
x = [4, 6, 1, 3, 5, 7, 25]
stars = "*"
def draw_stars(arr):
for i in range (0, len(arr)):
print stars * x[i]
draw_stars(x)
# Part II
# Modify the function above. Allow a list containing integers and strings to be passed to the draw_stars() function. When a string is passed, instead of displaying *, display the first letter of the string according to the example below. You may use the .lower() string method for this part.
y = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
stars = "*"
def draw_stars2(arr):
for i in range (0, len(arr)):
selection_type = type(y[i])
if selection_type is int:
print stars * y[i]
else:
lowercase_name = y[i].lower()
name_length = len(y[i])
print lowercase_name[:1] * name_length
draw_stars2(y) |
065bda239deec208da3cd87287452d36b8753cca | Near-River/leet_code | /31_40/35_search_insert_position.py | 1,787 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1, 3, 5, 6], 5 → 2
[1, 3, 5, 6], 2 → 1
[1, 3, 5, 6], 7 → 4
[1, 3, 5, 6], 0 → 0
"""
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# def binary_search(nums, start):
# length = len(nums)
# if length == 0: return start
# if length == 1: return start if target <= nums[0] else start + 1
#
# mid = (length - 1) // 2
# if nums[mid] > target:
# return binary_search(nums[0:mid], start)
# elif nums[mid] < target:
# return binary_search(nums[mid + 1:], start + mid + 1)
# else:
# return start + mid
def binary_search2(nums, start):
mid = (len(nums) - 1) // 2
if nums[mid] > target:
return binary_search2(nums[0:mid], start) if mid > 0 else start
elif nums[mid] < target:
return binary_search2(nums[mid + 1:], start + mid + 1) if mid + 1 < len(nums) else start + 1
else:
return start + mid
return binary_search2(nums, 0)
if __name__ == '__main__':
solution = Solution()
print(solution.searchInsert([1, 3, 5, 6], 5))
print(solution.searchInsert([1, 3, 5, 6], 2))
print(solution.searchInsert([1, 3, 5, 6], 7))
print(solution.searchInsert([1, 3, 5, 6], 0))
print(solution.searchInsert([1, 3, 5, 6, 9], 0))
|
e6b4b2ea84eabd28a578ec7b3431d0174d51ae1d | jeelani18/python_udemy_course | /escapechar.py | 326 | 3.625 | 4 | print('this lines\n are going\n to split to\n next line\n this is split string\n')
print('this\tis\ttabbed\tstring ')
print(' "\ \'" this here is a escape char ')
print(""" we can do this in \ \" \ \" \ \" also""")
print('\ can also \
escape \
split string')
print(" how\\t are\\n you")
print(r" how \t are \n you") |
e4c3727065af377477d22802c4a70272d1831ced | edderick/literate-spoon | /hackernews.py | 1,299 | 3.84375 | 4 | #!/usr/bin/python3
"""
This is a utility tool to fetch the latests posts from HackerNews and
output it in a JSON format.
"""
import argparse
import json
import sys
import hnapi
# Maximum number of posts to fetch
MAX_NUM_POSTS = 100
def main():
"""
Main function:
- parse command line arguments
- fetch Hacker News data
- output in JSON format
"""
# Parse command line arguments {{{
parser = argparse.ArgumentParser()
parser.add_argument(
'--posts',
metavar='N',
dest='num_posts',
type=int,
help='how many posts to print. A positive integer <= 100.')
args = parser.parse_args()
if args.num_posts is None:
print('Please specify the number of posts to display.',
file=sys.stderr)
parser.print_help()
return 1
elif args.num_posts <= 0 or args.num_posts > MAX_NUM_POSTS:
print('Invalid number of posts (0 < N <= {})'.format(MAX_NUM_POSTS),
file=sys.stderr)
parser.print_help()
return 2
# End of command line parsing }}}
# Fetch HackerNews stories
stories = hnapi.get_normalized_top_items(args.num_posts)
# Output it to JSON
print(json.dumps(stories, indent=2))
if __name__ == '__main__':
main()
|
5b32bcbefe55914f035c2c5ffd123bd35057c27c | karibou/python_training | /list1.py | 208 | 3.609375 | 4 | #!/usr/bin/python
alldays=['lundi','mardi','mercredi','jeudi','vendredi','samedi','dimanche']
semaine = alldays[:5]
weekend = alldays[5:]
print "semaine : %s" %semaine
print "weekend : {}".format(weekend)
|
fbdc920f209bba00346febcc818128b45abe4eeb | fahim0120/leetcode | /371 Sum of Two Integers.py | 352 | 3.59375 | 4 | """
fahim0120@gmail.com
"""
# https://leetcode.com/problems/sum-of-two-integers/
# Easy
# Top Interviews
# Bit Manipulation
class Solution:
def getSum(self, a: int, b: int) -> int:
MASK = 0xFFFFFFFF # 32 1s
while b & MASK != 0:
a, b = a^b, (a&b) << 1 # a <- sum; b <- carry
return a & MASK if b else a
|
919c35f69b8c500e0c3d8d20509ced53e19cab1a | ReneNyffenegger/temp-Python | /types/list/sort.py | 102 | 3.578125 | 4 | #!/usr/bin/python
ary = ['foo', 'bar', 'baz']
ary_sorted = sorted(ary)
print(' - '.join(ary_sorted))
|
cf4faf3c708ce84418538edf8d0009ab30741527 | MKen212/pymosh | /03-getting_input.py | 214 | 4.03125 | 4 | name = input("What is your name? ")
print("Hello " + name)
# Exercise
first_name = input("What is your firstname? ")
fav_colour = input("What is your favourite colour? ")
print(first_name + " likes " + fav_colour) |
0ffd015814b5b0776dca654814ac9ceaff266409 | matchdav/ledvis | /old/led_1_test.py | 780 | 3.53125 | 4 | import time
from neopixel import *
from config import *
# Define functions which animate LEDs in various ways.
def colorWipe(strip, color, wait_ms=5.0):
"""Wipe color across display a pixel at a time."""
for i in range(strip.numPixels()):
strip.setPixelColor(i, color)
strip.show()
time.sleep(wait_ms/1000.0)
if __name__ == "__main__":
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_1_COUNT, LED_1_PIN, LED_1_FREQ_HZ, LED_1_DMA, LED_1_INVERT, LED_1_BRIGHTNESS, LED_1_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()
colors = [Color(255, 0, 0), Color(0, 255, 0), Color(0, 0, 255)]
while True:
for color in colors:
colorWipe(strip, color, wait_ms=5.0) |
a51152012414272777c96b8a253df19112ba32bf | yjh8806/python-2019-July | /17일/18.클래스/10.문제.py | 969 | 3.640625 | 4 | class Animal: #모든 동물의 공통 기능
def __init__(self, weight, sound):
self.weight = weight
self.sound = sound
def sleep(self):
print("코 잔다")
def speak(self):
print(self.sound)
def eat(self):
print("먹는다")
def show(self):
print("동물 : %.2fkg"%self.weight)
class Cat(Animal):
def eat(self):
print("츄르를 먹는다")
def show(self):
print("고양이 : %.2fkg"%self.weight)
class Dog(Animal):
def eat(self):
print("개껌을 먹는다")
def show(self):
print("개 : %.2fkg"%self.weight)
jinwoo = Animal(66, "진우진우")
jinwoo.sleep()
jinwoo.eat()
jinwoo.speak()
jinwoo.show()
print()
cheeze = Cat(3.5, "냥냥")
cheeze.sleep()
cheeze.eat()
cheeze.speak()
cheeze.show()
print()
dangdang = Dog(6.5, "멍멍")
dangdang.sleep()
dangdang.eat()
dangdang.speak()
dangdang.show()
print()
|
cd3f10e062e33eccd9e2abddea60876dc816a1c4 | la-ursic/redtape | /forExercises.py | 1,206 | 3.84375 | 4 | print ("Multiplo de dos")
counter = 0
for i in range(1,100):
if i % 2 == 0:
counter = counter + 1
print (counter)
print ("Acumulador")
accumulate = 0
for i in range(1,5):
print (i)
accumulate = accumulate + i
print(accumulate)
print ("1 al 10 000, impresos")
for i in range (1,10001):
print (i)
print ("Pares del 1 al 10 000, impresos")
for i in range (1,10001):
if i % 2 == 0:
print(i)
print("Tell me where the third E is")
elefante = "ELEFANTE"
counter = 0
eCounter = 0
for i in elefante:
counter = counter + 1
if i == "E":
eCounter = eCounter + 1
if eCounter == 3:
print ("encontré la tercera 'E' en la posición", counter)
print ("Cart rules implementation")
itemsInCart = int(input("¿Cuantos productos desea comprar, joven? \n"))
itemPrice = int(input("¿Cuanto cuesta este producto? \n"))
if itemsInCart > 5:
grandTotal = (itemPrice * itemsInCart) * 0.95
else:
grandTotal = (itemsInCart * itemPrice)
print ("El precio total de su compra es de", grandTotal)
print("Contador de pares e impares")
userInputs = int(input("Ingresa el numero de valores que desees introducir"))
if userInputs < 1:
print("Imposible")
else:
evenNumbers = 0
for i in range (1,userInputs):
in = |
99e384101abd2d91c3660b37ff99de76c04c0326 | zigbeemuema/zb.001 | /upper/test_upper.py | 755 | 3.828125 | 4 | import unittest
from upper import Upper
class TestUpper(unittest.TestCase):
def setUp(self):
self.upper = Upper()
def test_Upper_is_uppercase_method_for_false(self):
self.assertFalse(self.upper.is_uppercase('c'))
self.assertFalse(self.upper.is_uppercase('hello I AM DONALD'))
self.assertFalse(self.upper.is_uppercase('ACSKLDFJSgSKLDFJSKLDFJ'))
self.assertFalse(self.upper.is_uppercase('%*&#()%&^#'))
def test_Upper_is_uppercase_method_for_true(self):
self.assertTrue(self.upper.is_uppercase('C'))
self.assertTrue(self.upper.is_uppercase('HELLO I AM DONALD'))
self.assertTrue(self.upper.is_uppercase('ACSKLDFJSGSKLDFJSKLDFJ'))
if __name__ == '__main__':
unittest.main() |
7e0e1333be44eebbe3a8bc2e12ba0016e10430ee | draju1980/Hello-World | /fun_items_price.py | 575 | 4.125 | 4 | # Write a function named items_price that accepts two lists as parameters.
# The first list contains the quantities of n different items, the second list
# contains the prices that correspond to those n items respectively. Now,
# calculate the total amount of money required to
# purchase those items. Assume that both the lists will have equal lengths
def items_price(a,b):
c=[]
total=0
for a1,b1 in zip(a,b):
c.append(a1*b1)
for i in c:
total = total + i
return total
print(items_price([2, 3, 5, 7, 9],[5, 8, 4, 1, 11]))
|
b844abfaa73c7c2e46d1082d80134dbe02f3cf39 | yangyuxiang1996/leetcode | /剑指 Offer II 005. 单词长度的最大乘积.py | 1,349 | 3.828125 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-24 23:01:47
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-24 23:13:07
FilePath: /leetcode/剑指 Offer II 005. 单词长度的最大乘积.py
Description:
给定一个字符串数组 words,请计算当两个字符串 words[i] 和 words[j] 不包含相同字符时,它们长度的乘积的最大值。
假设字符串中只包含英语的小写字母。如果没有不包含相同字符的一对字符串,返回 0。
'''
class Solution(object):
def maxProduct(self, words):
"""
:type words: List[str]
:rtype: int
"""
# 二维数组,判断是否有重复单词
flags = [[0] * 26 for _ in range(len(words))]
ans = 0
for i in range(len(words)):
for c in words[i]:
flags[i][ord(c) - ord('a')] = 1
for i in range(0, len(words)):
for j in range(i+1, len(words)):
k = 0
while k < 26:
if flags[i][k] and flags[j][k]:
break
k += 1
if k == 26:
ans = max(ans, len(words[i]) * len(words[j]))
return ans
if __name__ == '__main__':
words = ["abcw","baz","foo","bar","fxyz","abcdef"]
print(Solution().maxProduct(words))
|
885bbf6f7ff4492bca91e3d6ea0fb3586e453603 | jriall/algoexpert | /medium/monotonic_array.py | 929 | 4.375 | 4 | # Monotonic Array
# Write a function that takes in an array of integers and returns a boolean
# representing whether the array is monotonic.
# An array is said to be monotonic if its elements, from left to right, are
# entirely non-increasing or entirely non-decreasing.
# Non-increasing elements aren't necessarily exclusively decreasing; they simply
# don't increase. Similarly, non-decreasing elements aren't necessarily
# exclusively increasing; they simply don't decrease.
# Note that empty arrays and arrays of one element are monotonic.
# Sample Input
# array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]
# Sample Output
# true
# Solution
def is_monotonic(array):
increase = 0
decrease = 0
for index in range(len(array) - 1):
if array[index] < array[index + 1]:
increase += 1
if array[index] > array[index + 1]:
decrease += 1
return False if increase > 0 and decrease > 0 else True
|
aeda4a1b13c027229b21ec4b8614388b01de6daf | hackrush01/os_lab | /Scripts/day6/test/Amit 15-IT-54/8.py | 173 | 4.21875 | 4 | from math import sqrt
num = int(input("Enter a POSITIVE number: "))
result = sqrt(num)
print("Square root of {0:d} upto 5 decimal places is: {1:.5f}".format(num, result))
|
2c39b943d56d92bb545911d2ac932936458afb09 | ariesduanmu/python3_standard_library | /18_language_tools/03_dis/performance/dis_fastest_loop.py | 448 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# @Author: Li Qin
# @Date: 2020-03-12 11:13:51
# @Last Modified by: Li Qin
# @Last Modified time: 2020-03-12 13:18:20
import collections
class Dictionary:
def __init__(self, words):
self.by_letter = collections.defaultdict(list)
self.load_data(words)
def load_data(self, words):
by_letter = self.by_letter
for word in words:
by_letter[word[0]].append(word)
|
c2f9d03d0ec74eb2663ea73ddcbe2e331a827b2a | amolnayak311/epi-python | /power_x_y.py | 776 | 3.65625 | 4 | def power_iter(x, y):
res = 1.0
x, power = (x, y) if y > 0 else (1 / x, -y)
while power:
if power & 1:
res *= x
x *= x
power >>= 1
return res
#Recursive and more succinct implementation
def power_rec_(x, y):
if y == 0:
return 1
if y == 1:
return x
h = power_rec_(x, y // 2)
return x * h * h if y & 1 else h * h
def power_rec(x, y):
return power_rec_(x, y) if y >= 0 else power_rec_(1 / x, -y)
def power(x, y):
#return power_iter(x, y)
return power_rec(x, y)
from sys import exit
from test_framework import generic_test, test_utils
if __name__ == '__main__':
exit(generic_test.generic_test_main('power_x_y.tsv', power))
|
4a53a68d07bcdf8158fe0194c410095bdf314a51 | 1oser5/LeetCode | /算法/wordBreak.py | 1,674 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : wordBreak.py
@Time : 2019/12/16 09:17:49
@Author : Xia
@Version : 1.0
@Contact : snoopy98@163.com
@License : (C)Copyright 2019-2020, HB.Company
@Desc :
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
注意你可以重复使用字典中的单词。
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# here put the import lib
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
len_s = len(s)
d = set(wordDict)
dp = [False] * (len_s+1)
dp[0] = True
for i in range(len_s):
for j in range(i+1,len_s+1):
if dp[i] and (s[i:j] in d):
dp [j] = True
return dp[-1]
if __name__ == '__main__':
s = Solution()
print(s.wordBreak("leetcode",["leet", "code"])) |
a2dc8683e316187644f9313e59fe021a145efb83 | magda-zielinska/python-level1 | /slices-cont.py | 344 | 4.0625 | 4 | list = [0, 3, 12, 8, 2]
print(5 in list)
print(5 not in list)
print(12 in list)
list2 = [6, 3, 11, 5, 1, 9, 7, 15, 13]
max = list2[0]
for i in range(1,len(list2)):
if list2[i] > max:
max = list2[i]
print(max)
list3 = [6, 9, 2, 18, 4, 3]
max = list3[0]
for i in list3[1:]:
if i > max:
max = i
print(max) |
fb510f31cd3b53e4dd092fba775ff5e3df867821 | SonyChan0807/DeepLearning-project2 | /miniNN/sequential.py | 2,018 | 3.75 | 4 | from .module import Module
from .linear import Linear
class Sequential(Module):
def __init__(self, layer_modules):
"""Sequential model of neural network
:param layer_modules: List of models that construct neural network
"""
super()
self.layer_modules = layer_modules
def forward(self, x_input):
"""Forward pass for neural network
Compute the forward pass for each layers and activation function
:param x_input: input tensor of data
:return: The result of neural network to the loss function
"""
module_input = x_input.clone()
for i in range(len(self.layer_modules)):
module_output = self.layer_modules[i].forward(module_input)
module_input = module_output
return module_output
def backward(self, dz):
"""Backward pass for neural network
Compute the backward pass for each layers and activation function
:param dz: The derivatives of loss wrt neural network output from the Loss class
:return: None
"""
for m in self.layer_modules[::-1]:
dz = m.backward(dz)
def update_params(self, lambda_):
"""Update weight and bias in each Linear class
:param lambda_: learning rate
:return: None
"""
for m in self.layer_modules:
if isinstance(m, Linear):
m.update_params(lambda_)
def zero_gradient(self):
"""Set weight and bias to zero in each Linear class
:return: None
"""
for m in self.layer_modules:
if isinstance(m, Linear):
m.zero_gradient()
def params(self):
"""Get params of each linear layer
:return: List of weight and bias in the same order of the linear modules
"""
param_list = []
for m in self.layer_modules:
if isinstance(m, Linear):
param_list.append(m.param)
return param_list
|
539d36e06d30b2f06a3c26ceee37b79c7b2737a2 | vmilkovic/uvod_u_programiranje | /predavanje4/kontrola_toka3.py | 227 | 3.53125 | 4 | # U slučaju više ugniježdenih prelji, prekinut će se samo ona u kojoj se break nalazi
for i in range(3):
for j in range(3):
for k in range(3):
if k==1:
break
print(i,j,k) |
98373b7a77214bd03b48c6a3c43a1da2009d3fc2 | Ruchithaakula/python | /ASSIGNMENT1_PERIMETER OF SQUARE (1).py | 277 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print("Enter 'x' for exit.");
side = input("Enter side length of square: ");
if side == 'x':
exit();
else:
slength = int(side);
perimeter = 4*slength;
print("\nPerimeter of Square =", perimeter);
# In[ ]:
|
691a1ad0acc1e792457f724c04de3a665972184e | defneikiz/MIS3640 | /session09/word.py | 3,065 | 3.828125 | 4 | fin = open("session09/words.txt")
line = repr(fin.readline())
word = line.strip()
# print(word)
#SPLIT AND
counter = 0
# for line in fin:
# word= line.strip()
# counter += 1
# print(counter)
def read_long_words():
"""
prints only the words with more than 20 characters
"""
counter= 0
for line in fin:
word = line.strip()
if len(word) > 20:
# print(word)
# def has_no_e(word):
# """
# returns True if the given word doesn’t have the letter “e” in it.
# """
# # for letter in word:
# # if letter == 'e':
# # return False
# # return True
# return not 'e' in word.lower() #same thing
print(has_no_e('Babson'))
print(has_no_e('College'))
def has_no_e_2(word):
fin = open('session09/words.txt')
counter = 0
for line in fin:
word = line.strip()
if has_no_e(word): #because this function returns true or false
def avoids(word, forbidden):
"""
takes a word and a string of forbidden letters, and that returns True
if the word doesn’t use any of the forbidden letters.
"""
return not forbidden in word
print(avoids('Babson', 'ab'))
print(avoids('College', 'ab'))
def uses_only(word, available):
"""
takes a word and a string of letters, and that returns True if the word
contains only letters in the list.
"""
# for letter in word:
# if letter not in available: #added in not to avoids
# return False
# return True
return uses_only(required,word)
print(uses_only(word,'aeiou'))
# print(uses_only('Babson', 'aBbsonxyz'))
# print(uses_only('college', 'aBbsonxyz'))
def uses_all(word, required):
"""
takes a word and a string of required letters, and that returns True if
the word uses all the required letters at least once.
"""
for letter in required:
if letter not in word:
return False
return True
print(uses_all('Babson', 'abs'))
print(uses_all('college', 'abs'))
def is_abecedarian(word):
"""
returns True if the letters in a word appear in alphabetical order
(double letters are ok).
"""
last_letter = word [0]
for c in word:
if c < last_letter:
return False
last_letter = c
return True
print(is_abecedarian('abs'))
print(is_abecedarian('college'))
#excercise02
#Rewrite abecedarian using recursion
def is_abecedarian_recursion(word):
if len(word) == 1:
return True
elif ord(word [1]) < ord(word[0]):
return False
else:
return is_abecedarian_recursion(word [1:])
print(is_abecedarian_recursion('abs'))
print(is_abecedarian_recursion('college'))
#Rewrite abecedarian using while loop
def is_abecedarian_while(word):
iteration=0
while iteration< len(word):
previous = word[0]
for c in word:
if c < last_letter:
return False
last_letter = c
return True
print(is_abecedarian_while('abs'))
print(is_abecedarian_while('college'))
|
3d1bc1794905b80c0cd7815b2adda989cf92d77b | hanfeng11/python1 | /rr/day05_2.py | 243 | 3.75 | 4 | list=[]
s=0
for i in range(101,201):
bool=True
for j in range(2,i-1):
if(i%j==0):
bool=False
if(bool==True):
list.append(i)
s+=1
else:
continue
print(list)
print("素数个数为:",s) |
1d9cc8be0fef7d43b446af19f797d64e8c3c5b1f | dyeap-zz/CS_Practice | /DP/Paint.py | 5,496 | 4 | 4 | '''
There are n rows of houses, each house can be painted with one of the three colors: R,G, or B.
The cost of painting each house with a certain color is different. You have to paint all houses
such that no two adj houses have the same color. What is min cost?
cost[][] =
[red, blue, green]
follow all steps
time and space
find tabular solution
1. states -
color,0-2 - 0 = red, 1 = blue, 2 = green
house, i -
cost function
min cost to paint house
2. transition
solve(color,house)
# base case
if no house: return cost 0
if one house?
# recursive case more 1 or more houses
for all colors:
if same color than prev: skip
else:
solve(curr_color,house)
return min_cost
Have a for loop for different colors of the houses
rbg
r b/g (rg)/(b/g)
recurrence relation
solve(color,house) = cost[i] + min(solve(colors[i],i))
3. write the recursive function
'''
def min_cost(cost,prev_color,i):
# base case
if i == -1: return 0
# recursive case
res = float('inf')
for paint in [0,1,2]:
# adj color house check
if paint == prev_color: continue
else:
res = min(res,cost[i][paint] + min_cost(cost,paint,i-1))
return res
cost = [[17,2,17],
[16,16,5],
[14,3,9]
]
print(min_cost(cost,-1,len(cost)-1))
# memoize the solution
#Use a 2D grid and store the prev_color and i(house)
def min_cost(cost,color,i,dp):
# base case
if i == -1: return 0
# recursive case
# check if in cache
if i >=0 and dp[color][i] != float('inf'): return dp[color][i]
res = float('inf')
for paint in [0,1,2]:
# adj color house check
if paint == color: continue
else:
res = min(res,cost[i][paint] + min_cost(cost,paint,i-1,dp))
dp[color][i] = res
return dp[color][i]
num_house = len(cost)
num_colors = 3
dp = [[float('inf') for _ in range(num_house)] for _ in range(num_colors)]
print(min_cost(cost,-1,len(cost)-1,dp))
# bottom up approach
#Try an example
# base case first?
#inc? dec?
'''
Have to do base case first
have this i-1 we need to work with so for i 0
subproblem?
What the min cost at a particular color house
row = color
col = house or index
1. go down the row for base case and init for first house paint it all possible color
dp table
(color,house)
0 1 2
0 17 18 47
1 2 33 21
2 17 102 27
change the recurrence relation to bottom up equation
dp[color][house] = min(dp[color][house], cost[color][house] + dp[~color][house-1])
for house 1-n_houses
for colors
'''
def paint_botup(cost):
# init the dp table
dp = [[float('inf') for _ in range(num_house)] for _ in range(num_colors)]
# init the base case for first house
first_house = 0
#for colors in cost[0]:
#print(colors)
for color,price in enumerate(cost[0]):
#print(color,price)
dp[color][0] = price
#print(dp)
#print(cost)
#res = float('inf')
# start with next column house and do computation
for h in range(1,len(cost)):
for c in range(3):
# need to get the smaller value of the other colors
for prev_c in range(3):
if prev_c == c: continue
else:
dp[c][h] = min(dp[c][h],cost[h][c] + dp[prev_c][h-1])
#res = min(res,dp[c][h])
res = float('inf')
for color in range(3):
res = min(res,dp[color][-1])
return res
#print(cost)
print(paint_botup(cost))
# get the recurrence relation correct
# try to line up grid same as the data structure
# do you need a for loop at the end to go across the results?
#To find the color of the houses you painted use another cache that stores the previous color
#house.
#size of cache will be same as size of dp table
def paint_botup(cost):
# init the dp table
dp = [[float('inf') for _ in range(num_house)] for _ in range(num_colors)]
prev_color = [[-1 for _ in range(num_house)] for _ in range(num_colors)]
# init the base case for first house
for color,price in enumerate(cost[0]):
#print(color,price)
dp[color][0] = price
# start with next column house and do computation
for h in range(1,len(cost)):
for c in range(3):
# need to get the smaller value of the other colors
for prev_c in range(3):
if prev_c == c: continue
else:
if cost[h][c] + dp[prev_c][h-1] < dp[c][h]:
prev_color[c][h] = prev_c
dp[c][h] = min(dp[c][h],cost[h][c] + dp[prev_c][h-1])
# using the new paint then log it in
#res = min(res,dp[c][h])
res = float('inf')
for color in range(3):
res = min(res,dp[color][-1])
# find min house color
min_color = -1
for color in range(3):
if dp[color][-1] == res:
min_color = color
house_color = [-1 for _ in range(len(cost))]
house_color[-1] = min_color
for h in range(len(cost)-1,0,-1):
#print(h,min_color)
house_color[h-1] = prev_color[min_color][h]
min_color = house_color[h-1]
print(house_color)
return res
print(paint_botup(cost))
'''
n is number of houses
m is number of colors
recursion top down
time - O(3*2^n)
space - O(1)
bottom up
time - O(n*m^2)
space - O(n*m)
Solution:
min_cost(i,)
improvements
could have tried store the base case of 0 in the table. So i = 1 means house index of 0
''' |
a28bde88526a4122206426982b8eb4eae31d9410 | jdmarvin7/trabalho1.1 | /exercicio1.py | 293 | 4.125 | 4 | #Faça um Programa que peça um número inteiro e determine se ele é par ou impar. Dica:
# utilize o operador módulo (resto da divisão).
numero = int(input('digite um numero: '))
if numero%2 == 0:
print("O numero digitado é par")
else:
print("O numero digitado é impar")
|
703e08764944aa36c30fd0ceb9ec3410199d53ee | hackerAlice/coding-interviews | /剑指 Offer/53 - I. 在排序数组中查找数字 I/在排序数组中查找数字.py | 366 | 3.515625 | 4 | from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums:
return 0
d = dict()
for n in nums:
if n in d:
d[n] += 1
else:
d[n] = 1
if target in d:
return d[target]
else:
return 0 |
2bdd9a5c1a2aced59ad7b731bbfa2f9f0df91fcd | erikbriganty/PersonalPython | /Income Generator/stadium.py | 1,185 | 3.90625 | 4 | # File name: stadium.py
# Name: Erik Briganty
# Date: 04/07/2020
# Stadium Seating
# Defining the price per ticket
costA = 15
costB = 12
costC = 9
# Welcome Message
print('\nWelcome to the Broward College Stadium!\n')
# Asking user to input number of tickets sold
ticketA = int(input('How many Class A tickets were sold? '))
ticketB = int(input('How many Class B tickets were sold? '))
ticketC = int(input('How many Class C tickets were sold? '))
# Calculating total number of tickets sold
totalSold = ticketA + ticketB + ticketC
# Displaying total number of tickets sold
print('\n**********************')
print('Total number of tickets sold:', totalSold)
# Calculating income generated for each class of tickets
# Calculating total income generated
incomeA = ticketA * costA
incomeB = ticketB * costB
incomeC = ticketC * costC
totalIncome = incomeA + incomeB + incomeC
# Displaying income generated
# Formatted variables for dollar sign, comma, and two decimal places
print('\nIncome Generated:')
print('Class A: ${:,.2f}' .format(incomeA))
print('Class B: ${:,.2f}' .format(incomeB))
print('Class C: ${:,.2f}' .format(incomeC))
print('Total Income: ${:,.2f}' .format(totalIncome))
|
a115468fa623afe8de946ceac9f97c08f7470840 | itenabler-python/PythonDay2 | /fileio/copyandmovefiles.py | 722 | 3.578125 | 4 | import shutil
import os
print(os.getcwd())
path = os.getcwd()
# os.mkdir(path + "/folder2")
#copy helloworld to subfolder "folder2"
# shutil.copy("helloworld.txt", "folder2")
#backup of the folder2
# shutil.copytree("folder2", "folder2_backup")
#move helloworld.txt to a sub-subfolder newfolder
if os.path.isfile(path + "/folder2/newfolder/helloworld.txt" ) is False:
if os.path.isdir(path + "/folder2/newfolder") is False:
os.mkdir(path + "/folder2/newfolder")
shutil.move("folder2/helloworld.txt", "folder2/newfolder/")
else:
print("Folder already exists!")
else:
print("File already exists!")
shutil.move("folder2/newfolder/helloworld.txt", "folder2/newfolder/newhelloworld.txt") |
e92f2e8ccb173792b7be00653675a745e6c62a64 | Mycodeiskuina/Among-Us-game-0.5 | /Segunda_parte.py | 10,402 | 3.890625 | 4 | """En mi codigo el algoritmo astar recorre una matriz de 0s y 1s,
donde los 1 representan obstaculos y retorna un camino,
por eso antes de poner la matriz como parametro de la funcion astar
convierto la matriz en una matriz de 0s y 1s"""
from math import sqrt
import random
#inicializamos la matriz
m = []
for i in range(32):
m.append([" "] * 32)
def draw_canvas_empty():
"""Inicializa los bordes de la cuadricula de 30*30 en la
matriz principal."""
for j in range(32):
m[j][0] = '| '
m[j][31] = '| '
for i in range(32):
m[0][i] = '- '
m[31][i] = '- '
def dibujar(m):
"""Sirve para imprimir una matriz de manera ordenada.
Tiene como parametro una matriz."""
for i in m:
for j in i:
print(j,end="")
print()
def ok1(x,y,a,b):
"""
Verifica si en donde queremos poner las paredes de un espacio las casillas estan vacias y
si los alrededores de las paredes tambien estan vacias, ya que asi cumpliria que los espacios
esten separados en por lo menos 1 casilla.
Tiene como parametros la coordenada de donde empiezo a dibujar el espacio(rectangulo) y
las dimensiones del espacio.
Retorna False o True segun se cumpla lo anterior mencionado.
"""
ok=True
if x-1<2 or y-1<2 or x+a>29 or y+b>29: ok=False
else:
for k in range(0,b,1):
if m[x-1][y+k]!=" " or m[x+a][y+k]!=" ": ok=False
for k in range(-1,a+1,1):
if m[x+k][y-1]!=" " or m[x+k][y+b]!=" ": ok=False
for k in range(-1,b+1,1):
if m[x-2][y+k]!=" " or m[x+a+2][y+k]!=" ": ok=False
for k in range(-2,a+2,1):
if m[x+k][y-2]!=" " or m[x+k][y+b+1]!=" ": ok=False
return ok
espacios=[]
def init_places(espacios):
"""Iniciamos las posiciones de las entradas de los espacios al mismo
tiempo que generamos los espacios como rectangulos de tal manera que
no se intersecten.
Recibe como parametro una lista en donde guardaremos las coordenadas
de las entradas de los espacios que utilizaremos luego."""
j=1
c=[]
for i in range(6):
uwu=True
while uwu:
x = random.randint(2, 28)
y = random.randint(2, 28)
c.append(random.randint(10,15))
for i in range(int(sqrt(c[j-1])),c[j-1]+1):
if c[j-1]%i==0 and ok1(x,y,i,c[j-1]//i):
for k in range(0,c[j-1]//i,1):
m[x-1][y+k] = '- '
m[x+i][y+k]= '- '
for k in range(-1,i+1,1):
m[x+k][y-1] = '| '
m[x+k][y+(c[j-1]//i)] = '| '
uwu=False
break
if uwu: c.pop()
m[x-1][y] = 'E'+str(j)
espacios.append((x-1,y))
j+=1
def init_players(tripulantes):
"""Iniciamos las posiciones de los tripulantes de manera random.
Tiene como parametro una lista en donde guardaremos las coordenadas
de los tripulantes que utilizaremos luego."""
t1 = [random.randint(1, 29), random.randint(1, 29)]
while(m[t1[0]][t1[1]]!=" "):
t1 = [random.randint(1, 29), random.randint(1, 29)]
m[t1[0]][t1[1]] = "t1"
tripulantes.append((t1[0],t1[1]))
t2 = [random.randint(1, 29), random.randint(1, 29)]
while m[t2[0]][t2[1]] != " ":
t2 = [random.randint(1, 29), random.randint(1, 29)]
m[t2[0]][t2[1]] = "t2"
tripulantes.append((t2[0],t2[1]))
t3 = [random.randint(1, 29), random.randint(1, 29)]
while m[t3[0]][t3[1]] != " ":
t3 = [random.randint(1, 29), random.randint(1, 29)]
m[t3[0]][t3[1]] = "t3"
tripulantes.append((t3[0],t3[1]))
t4 = [random.randint(1, 29), random.randint(1, 29)]
while m[t4[0]][t4[1]] != " ":
t4 = [random.randint(1, 29), random.randint(1, 29)]
m[t4[0]][t4[1]] = "t4"
tripulantes.append((t4[0],t4[1]))
class Node():
"""Clase Node para encontrar un camino cuando utilizamos el algoritmo A*."""
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
def astar(maze, start, end):
"""Nos sirve para encontrar un camino desde estar hasta end, teniendo en cuenta
los obstaculos.
Tiene como parametros la matriz, una coodenada inicial y una coordenada final.
Retorna una lista de tuplas(coordenadas) como una ruta desde el inicio
hasta el final en la cuadricula."""
#Crear nodo inicial y final
start_node = Node(None, start)
start_node.g = start_node.h = start_node.f = 0
end_node = Node(None, end)
end_node.g = end_node.h = end_node.f = 0
#Inicializar tanto la lista abierta como la cerrada
open_list = []
closed_list = []
#Agregar el nodo de inicio
open_list.append(start_node)
#Da vueltas hasta que encuentres el final
while len(open_list) > 0:
#Obtener el nodo actual
current_node = open_list[0]
current_index = 0
for index, item in enumerate(open_list):
if item.f < current_node.f:
current_node = item
current_index = index
#Quitar actual de la lista abierta, agregar a la lista cerrada
open_list.pop(current_index)
closed_list.append(current_node)
#Encontre la meta
if current_node == end_node:
path = []
current = current_node
while current is not None:
path.append(current.position)
current = current.parent
return path[::-1] #Retorna el camino inverso
#Generar hijos
children = []
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]: #Casilla adyacente
#Obtener la posición del nodo
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
if Node(current_node, node_position) in closed_list: continue
#Asegúrese de que esté dentro del rango
if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:
continue
#Asegúrese de que el terreno sea transitable
if maze[node_position[0]][node_position[1]] != 0:
continue
#Crear nuevo nodo
new_node = Node(current_node, node_position)
#adjuntar
children.append(new_node)
#Bucle a través de los hijos
for child in children:
#Su hijo está en la lista cerrada
for closed_child in closed_list:
if child == closed_child:
continue
#Cree los valores de f, g y h
child.g = current_node.g + 1
child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2)
child.f = child.g + child.h
#Su hijo ya está en la lista abierta
for open_node in open_list:
if child == open_node and child.g > open_node.g:
continue
#Agregar hijo a la lista abierta
open_list.append(child)
def pinta(m,m1):
"""Convierto m1 en una matriz de 0s y 1s segun m(matriz principal), para
poder ponerlo en la funcion astar.
Tiene como parametros m1 y m."""
for i in range(32):
for j in range(32):
if m[i][j]!=" " and m[i][j]!="X ":
m1[i][j]=1
tiempo={}
def te(tiempo):
"""Inicializamos el tiempo de espera en cada espacio de manera random."""
tiempo["E1"]=random.randint(1, 6)
tiempo["E2"]=random.randint(1, 6)
tiempo["E3"]=random.randint(1, 6)
tiempo["E4"]=random.randint(1, 6)
tiempo["E5"]=random.randint(1, 6)
tiempo["E6"]=random.randint(1, 6)
while True:
option=input()
if option=="init":
m = []
for i in range(32):
m.append([" "] * 32)
draw_canvas_empty()
X = [random.randint(1, 29), random.randint(1, 29)]
m[X[0]][X[1]] = "X "
x=X[0]
y=X[1]
tripulantes=[]
espacios=[]
init_places(espacios)
init_players(tripulantes)
dibujar(m)
"""Hasta aqui solo inicializa la matriz con los espacios
y las posiciones de los tripulantes e impostores."""
option1=input()
tdi=[]
tet=[]
trgi=[]
if option1=="route":
tiempo={}
te(tiempo)
for k in range(4):
start=(X[0],X[1])
end=(tripulantes[k][0],tripulantes[k][1])
m1 = []
for i in range(32):
m1.append([0] * 32)
"""convierto la matriz en 0s y 1s"""
for i in range(32):
for j in range(32):
if m[i][j]=="| " or m[i][j]=="- ":
m1[i][j]=1
if k==0 and m[i][j]=="t1": m1[i][j]=0
elif k==1 and m[i][j]=="t2": m1[i][j]=0
elif k==2 and m[i][j]=="t3": m1[i][j]=0
elif k==3 and m[i][j]=="t4": m1[i][j]=0
path=astar(m1,start,end)
"""Verifico si alguno de los 4 tripulantes esta dentro de algun espacio"""
ok=False
tmp=""
if path!=None:
for i in path:
for j in espacios:
if j==i:
ok=True
tmp1=j
tmp=m[tmp1[0]][tmp1[1]]
break
"""Si esta dentro de un espacio entonces hallo los tdi y tet"""
if ok:
tdi.append((len(path)-1)/10)
tet.append(tiempo[tmp])
"""Si el tripulante 1 esta dentro de un espacio -> pinto con 1s
Si el tripulante 2 esta dentro de un espacio -> pinto con 2s
Si el tripulante 3 esta dentro de un espacio -> pinto con 3s
Si el tripulante 4 esta dentro de un espacio -> pinto con 4s
Si se pasa mas de 1 vez por el mismo camino -> pinto con 0s"""
for i in range(1,len(path)-1):
cur=m[path[i][0]][path[i][1]]
if cur==" " or cur=="E1" or cur=="E2" or cur=="E3" or cur=="E4" or cur=="E5" or cur=="E6":
m[path[i][0]][path[i][1]]=str(k+1)+" "
else:
m[path[i][0]][path[i][1]]="0 "
#Hallando los trgi
n=len(tdi)
for l in range(n):
trgi.append(tdi[l]-tet[l])
dibujar(m)
option2=input()
if option2=="trgi":
ans=float(-1)
for i in trgi:
if i<0: continue
else: ans=max(ans,i)
if ans==-1: print("los tripulantes siempre se escapan")
else : print(ans)
|
1236bf3e3db209548be9f495ff7d7a0f56359f83 | Roky4/SysML_to_VHDL | /sysml/elements/parametrics.py | 1,383 | 3.65625 | 4 | """
Parametric are used to express how one or more constraints — specifically,
equations and inequalities — are bound to the properties of a system.
Parametrics support engineering analyses, including performance, reliability,
availability, power, mass, and cost. Parametrics can also be used to support
trade studies of candidate physical architectures.
"""
from sysml.elements.base import ModelElement
from pint import UnitRegistry as _UnitRegistry
from typing import Optional
from pint import UnitRegistry as _UnitRegistry
_u = _UnitRegistry()
class ValueType(ModelElement):
"""This class defines a value type
Parameters
----------
units : str, default None
Notes
-----
String parameter for units must be defined in the UnitRegistry
Example
-------
>>> kesselrun = 12*sysml.ValueType('parsecs')
>>> kesselrun
<ValueType(12, 'parsecs')>
>>> kesselrun.magnitude
12
>>> kesselrun.units
<Unit('parsec')>
>>> kesselrun.to('lightyear')
<ValueType(39.138799173399406, 'light_year')>
"""
def __init__(self, units: Optional[str] = ""):
super().__init__(self.name)
@property
def name(self):
return self._name
class ConstraintBlock(ModelElement):
"""This class defines a constraint"""
def __init__(self, name: Optional[str] = ""):
super().__init__(name)
|
d1c77534d1b76b6ba67b1b25fe24cdda7b8ea726 | cloudenjr/Calvert-Loudens-GitHub | /Self_Study/Python_MC/Python_CC/Introducing_Lists/names.py | 641 | 3.90625 | 4 | names = ["James", "Jared", "Jeremy", "Kim", "Kenny", "Jason", "Eddie", "Adam", "Vinny", "Davon", "Nate"]
cars = ["audi", "bmw", "acura", "lexus", "volkswagen"]
# print(names[0])
# print(names[1])
# print(names[2])
# print(names[3])
# print(names[4])
# print(names[5])
# print(names[6])
# print(names[7])
# print(names[8])
# print(names[9])
# print(names[10])
for name in names[0:10]:
print("Hello " + name + " it's great to see you!")
print('*' * 40)
for car in cars[0:4]:
if car == "bmw":
print("I'd like to own a " + car.upper() + " one day!")
else:
print("I'd like to own a " + car.title() + " one day!")
|
16d3663aa20eb1af9783213c7a243e5dd8805677 | greenkey/adventofcode | /2015/12/code.py | 375 | 3.640625 | 4 | import json
def objSum(obj):
s = 0
if type(obj) == int:
return obj
if type(obj) == list:
for i in obj:
s += objSum(i)
if type(obj) == dict:
for k,v in obj.items():
if v == "red":
return 0
s += objSum(v)
return s
with open('input', 'r') as content_file:
obj = json.loads(content_file.read())
print("sum of all numbers: {}".format( objSum(obj) ))
|
8425fb2998cf7cc2804e0e478083c1230246ce54 | ShroogAlthubiti/100Days | /27day.py | 334 | 3.984375 | 4 | a=10
b=12
c=10
if a>b and a==c :
print("a greater than b and equle c")
elif a<b or b>c:
print("a less than b and b greater than c")
else :
print("a equle b")
c=81
print("A") if c > 90 else print("B") if c > 80 else print("C")
x=4
if x>0:
print("positive number")
if x%2==0:
print("even number")
else:
print("odd number")
|
4c99475eed91ab23486d1276358a7d972fde05fb | steppedaxis/Python | /udemy python assesment tests/python statement assesment test.py | 1,120 | 4.40625 | 4 | #Use for, .split(), and if to create a Statement that will print out words that start with 's':
st = 'Print only the words that start with s in this sentence'
for x in st.split():
if x[0]=='s':
print(x)
print(' ')
#Use range() to print all the even numbers from 0 to 10.
for x in range(0,11):
if x%2==0:
print(x)
print(' ')
#Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.
my_list=[x if x % 3 == 0 else ' ' for x in range(0,51)]
print(my_list)
print(' ')
#Go through the string below and if the length of a word is even print "even!"
st = 'Print every word in this sentence that has an even number of letters'
for x in st.split():
if len(x)%2==0:
print(x)
print(' ')
#Use List Comprehension to create a list of the first letters of every word in the string below:
st = 'Create a list of the first letters of every word in this string'
new_list=[]
index=0
for x in st.split():
for letter in x:
new_list+=letter[index]
break
print(new_list)
|
ac646304dc0f593d0722eb35c1837e889e599a73 | JiyuanLu/CS456_UWaterloo_F18 | /PA1/client.py | 3,895 | 4.21875 | 4 | from socket import *
import sys
'''
This program implements the client side of CS456 Programming Assignment 1: Introductory Socket Programming.
The communication process between server and client contains 2 stages: Negotiation Stage and Transaction Stage.
In the Negotiation Stage, the server creates a UDP socket with a random port <n_port> and starts listening on <n_port>.
The server prints the <n_port> to the standard output.
The client also creates a UDP socket with the server using serverAddress and <n_port>.
The client sends a <req_code> to the server to get the random port number <r_port> for later use in the transcation stage.
The server receives the UDP request with the user-specified <req_code> from the client.
The server verifies the <req_code>.
If the client fails to send the intended <req_code>, the server does nothing.
If successfully verified, the server creates a TCP socket with a random unused <r_port> and replies back with <r_port> using UDP socket.
The server confirms the <r_port> is successfully sent to the client and sends back an acknowledgement.
The client receives the acknowledgement, and closes its UDP socket.
In the Transaction Stage, the client creates a TCP connection to the server at <r_port>.
The server receives a string from the client, prints it to the standard output along with its TCP port number <r_port>,
reverses this string, and sends the reversed string back to the client.
The client receives the reversed string and prints it to the standard output.
After the TCP session, the server continues to listen on <n_port> for future sessions from new clients.
In this assignment, the server can only handle 1 client at a time.
Example execution:
Run client: python client.py <server_address> <n_port> <req_code> <msg>
<server_address>: string, the IP address of the server
<n_port>: int, the negotiation port number of the server
<req_code>: int, user-specified.
<msg>: string, a string that you want to reverse, should be contained in one quote '' or ""
'''
# check input parameters number and type
if sys.argv[1] == '':
print('Parameters <server_Address>, <n_port>, <req_code>, <msg> missing!')
exit(-1)
elif not len(sys.argv) - 1 == 4:
print('Should have 4 parameters <server_Address>, <n_port>, <req_code>, <msg>!')
exit(-1)
serverAddress= str(sys.argv[1])
try:
n_port = int(sys.argv[2])
except ValueError:
print('<n_port> should be an integer but got %s!' % type(sys.argv[2]))
exit(-2)
try:
req_code = int(sys.argv[3])
except ValueError:
print('<req_code> should be an integer but got %s!' % type(sys.argv[3]))
exit(-2)
msg = sys.argv[4]
if msg == '':
print('msg should not be empty!')
exit(-3)
### Negotiation Stage: ###
# 1. the client creates a UDP socket
clientUDPSocket = socket(AF_INET, SOCK_DGRAM)
# 2. the client sends the req_code to the server to get <r_port>
clientUDPSocket.sendto(str(req_code).encode(), (serverAddress, n_port))
# 3. the client receives <r_port>
r_port = int(clientUDPSocket.recv(2048).decode())
# 4. the client sends back <r_port>
clientUDPSocket.sendto(str(r_port).encode(), (serverAddress, n_port))
# 5. the client receives the ack for <r_port> from server
ack = clientUDPSocket.recv(2048).decode()
if not ack == 'correct':
print('Incorrect r_port sent by client!')
sys.exit(1)
# 6. the client closes the UDP socket
clientUDPSocket.close()
### Transaction Stage ###
# 7. the client creates a TCP connection with the server
clientTCPSocket = socket(AF_INET, SOCK_STREAM)
clientTCPSocket.connect((serverAddress, r_port))
# 8. the client sends the msg to the server
clientTCPSocket.send(msg.encode())
# 9. the client receives the modified msg fro the server
modifiedMsg = clientTCPSocket.recv(2048).decode()
# 10. the client prints out the reversed string and then exits
print('CLIENT_RCV_MSG=%s' % modifiedMsg)
sys.exit(0) |
8c2c0f80d75b1604943425acb8e19a496fa3e1ea | ICC3103-202110/proyecto-01-moore_bedini | /options.py | 2,145 | 3.765625 | 4 | from players import Player
class Options:
def __init__(self,num_players):
self.__num_players=num_players
def menu_character_action():
print ("Choose one of the next options")
print("1: Duke (TAX)")
print("2: Assasin (MURDER)")
print("3: Captain (EXTORTION)")
print("4: Ambassador (EXCHANGE)")
return(int(input()))
def menu_general_action():
print ("Choose one of the next options")
print("1: Take_coin")
print("2:Foreign_Help")
print("3: Strike")
return(int(input()))
def block_action(num_players, players, i):
for a in range(num_players):
if len(players[a].cards)>0:
if players[i].name!=players[a].name:
print (players[a].name," want to counterattack? YES or NO")
b=input()
if b=='YES':
return int(a)
return int(-1)
def strike_action(num_players, players, name):
for a in range(num_players):
if len(players[a].cards)>0:
if players[a].name!=name:
print ("Do you want to hit,", players[a].name," YES or NO")
b=input()
if b=='YES':
return int(a)
def challenge_action(num_players, players, i):
for a in range(num_players):
if len(players[a].cards)>0:
if players[i].name!=players[a].name:
print (players[a].name," want to challenge? YES or NO")
b=input()
if b=='YES':
return int(a)
return int(-1)
def stealing_action(num_players,players, name):
for a in range(num_players):
if len(players[a].cards)>0:
if players[a].name!=name:
print ("Do you want to Extortion from,", players[a].name," YES or NO")
b=input()
if b=='YES':
return int(a) |
55a85584454a67b3ae1b8d1f8cd2a674dbbe3fc7 | EderVs/hacker-rank | /algorithms/implementation/utopian_tree.py | 202 | 3.921875 | 4 | """ Utopian Tree """
cases = int(raw_input())
for i in range(cases):
height = 1
cycles = int(raw_input())
for j in range(cycles):
if j % 2 == 0:
height *= 2
else:
height += 1
print height |
2699abe22ee6ae290a7f2a2c8f52bbcb76603ce3 | zimyk/pycode-repo | /dog.py | 641 | 4.09375 | 4 | class Dog():
""" A simple attempt to model a dog"""
def __init__(self, name, age):
""" Initializes name and age"""
self.name = name
self.age = age
def sit(self):
""" Simulates a dog sitting in response to a command"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
""" Simulate a dog that rolled over"""
print(self.name.title() + " rolled over!")
def main():
my_dog = Dog('mayoe', 5)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
if __name__ == '__main__':
main()
|
2ffc5d59dc504160c5806279dcdec488e4629354 | systemcoding/PythonCrashCourse | /src/inheritence.py | 324 | 3.703125 | 4 | class Person:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
self.x += 1
self.y += 1
print(self.x, self.y)
class Student(Person):
def __init__(self, x, y):
super().__init__(x, y)
studentObj = Student(2, 3)
studentObj.move()
|
21fd08a035bbc0c0edf29103e2025f2ce9a4f05b | AlexanderJDupree/CS160 | /week_9/luckynumber_adupree.py | 1,297 | 4.09375 | 4 | # file: luckynumber_adupree.py
# description: number guessing game
# authors: Alex DuPree
# date: 11/20/2017
# compiler: Python 3.6
from random import randint
def main():
intro()
victory, guess = guess_loop()
message(victory, guess)
def intro():
print("\tGUESS THE LUCKY NUMBER"
"\nYou will heave 15 tries to guess a number between 1 - 100")
def guess_loop():
guesses = 15
lucky_number = randint(1, 100)
while guesses > 0:
try:
guess = int(input("\nEnter a guess: "))
except ValueError:
print("Error: input must be a number between 1 - 100")
continue
if guess > lucky_number and guess < 101:
print("Too high")
guesses -= 1
elif guess < lucky_number and guess > 0:
print("Too low")
guesses -= 1
elif guess == lucky_number:
return True, guesses
else:
print("\nError: input must be a number between 1 - 100")
return False, lucky_number
def message(victory, guess):
if victory == True:
print("Hooray you got it!\nYou took {} guess(es).\nYou're good!"
.format(16 - guess))
else:
print("Sorry, you're out of guesses. The number was {}".format(guess))
main()
|
6ea12dfffc823ff6e3019503db1db44ef31e3d18 | erkanderon/python-challange | /app.py | 573 | 3.828125 | 4 | from game.game import Game
class Main:
def __init__(self):
pass
def enter_game_word(self):
self.ch = input("Enter the Game Word: ")
if type(self.ch) is not str:
print("Please enter a string")
self.enter_game_word()
if self.ch != self.ch.upper():
print("Please enter uppercase")
self.enter_game_word()
if len(self.ch) < 1 or len(self.ch) > 10:
print("The word cannot be 0 or bigger than 10")
self.enter_game_word()
return self.ch
if __name__ == "__main__":
game_word = Main().enter_game_word()
game = Game(game_word)
game.start()
|
bb85086aac7874f032f147840495912a637b7b52 | uasif13/cs115 | /lab3.py | 1,096 | 3.828125 | 4 | # Author: Asif Uddin
# Pledge: I pledge my honor that I have abided by the Stevens Honor System.
# Date: September 19, 2019
def change(amount, coins):
'''Returns the minimum number of coins from a given coin system to make a certain amount
Returns infinity if not possible'''
# base case of recursion
if amount == 0: return 0
# case where it is impossible to form the value with the given change
if (amount < 0 or coins == []): return float("inf")
# case where the coin value is greater than the amount
if coins[0] > amount: return change(amount,coins[1:])
# case where the coin value is less than the amount
else:
#first line is the case when you only need one of the first coin values
#second line is the case where you need more
#third line is the case where it is less but you don't need it
one_time = change(amount-coins[0],coins[1:])
multi_times = change(amount-coins[0],coins)
no_times = change(amount,coins[1:])
return min(1+min(one_time, multi_times),no_times)
|
7b28da54eb250875a74b565cb278ca2eca78e0c8 | HyoHee/Python_month01_all-code | /day13/exercise01.py | 1,400 | 4.25 | 4 | """
创建图形管理器
1. 记录多种图形(圆形、矩形....)
2. 提供计算总面积的方法.
满足:
开闭原则
测试:
创建图形管理器,存储多个图形对象。
通过图形管理器,调用计算总面积方法.
设计:
封装(分):创建图形管理器类/圆形类/矩形类
继承(隔):创建图形类,隔离图形管理器类与具体图形类
继承(做):具体图形类重写图形类的计算方法
"""
class GraphicManager:
def __init__(self):
self.__graphic_list = []
def add(self, graphic):
if isinstance(graphic,Graphic):
self.__graphic_list.append(graphic)
def get_total_area(self):
total_area = 0
for item in self.__graphic_list:
total_area += item.calculate_area()
return total_area
class Graphic:
def calculate_area(self):
pass
class Circular(Graphic):
def __init__(self, r):
self.r = r
def calculate_area(self):
return self.r ** 2 * 3.14
class Rectangle(Graphic):
def __init__(self, legth, wide):
self.legth = legth
self.wide = wide
def calculate_area(self):
return self.legth * self.wide
manager = GraphicManager()
manager.add(Circular(8))
manager.add(Rectangle(2,3))
total_area = manager.get_total_area()
print(total_area)
|
f1557409118bdb68050523435a77f837c4d17738 | IsinghGitHub/advanced_python | /adv_py_3_where_and_if_on_vectors/for_loop_review.py | 209 | 3.625 | 4 | mylist = ['a','b','c','d']
for item in mylist:
print('item = %s' % item)
N = len(mylist)
for i in range(N):
print('i = %i' % i)
item = mylist[i]
print('item = %s' % item)
print('='*20)
|
7054c033d56be7b77cdaf0d7dc24872511bbf1f5 | nbutacm/NBUTACM | /课程资料/机器学习/第二次/陆镇涛小组/谢威/titanic (1).py | 2,262 | 3.5 | 4 | import pandas as pd
from sklearn.feature_extraction import DictVectorizer
from sklearn.tree import DecisionTreeClassifier
# 数据加载
train_data = pd.read_csv('titanic_train.csv')
test_data = pd.read_csv('titanic_test.csv')
# 数据探索
print(train_data.info())# info() 了解数据表的基本情况:行数、列数、每列的的数据类型、数据完整度
print('-'*30)
print(train_data.describe())#describe() 了解数据表的统计情况:总数、平均值、标准差、最小值、最大值等
print('-'*30)
print(train_data.describe(include=['O']))#describe(include=[‘O’]) 查看字符串类型(非数字)的整体情况
print('-'*30)
print(train_data.head())#head 查看前几行数据(默认是前 5 行)
print('-'*30)
print(train_data.tail())#tail 查看后几行数据(默认是最后 5 行)
# 使用平均年龄来填充年龄中的 nan 值
train_data['Age'].fillna(train_data['Age'].mean(), inplace=True)
test_data['Age'].fillna(test_data['Age'].mean(),inplace=True)
# 使用票价的均值填充票价中的 nan 值
train_data['Fare'].fillna(train_data['Fare'].mean(), inplace=True)
test_data['Fare'].fillna(test_data['Fare'].mean(),inplace=True)
print(train_data['Embarked'].value_counts())
# 使用登录最多的港口来填充登录港口的 nan 值
train_data['Embarked'].fillna('S', inplace=True)
test_data['Embarked'].fillna('S',inplace=True)
# 特征选择
features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']
train_features = train_data[features]
train_labels = train_data['Survived']
test_features = test_data[features]
dvec=DictVectorizer(sparse=False)
train_features=dvec.fit_transform(train_features.to_dict(orient='record'))
print(dvec.feature_names_)
['Age', 'Embarked=C', 'Embarked=Q', 'Embarked=S', 'Fare', 'Parch', 'Pclass', 'Sex=female', 'Sex=male', 'SibSp']
# 构造 ID3 决策树
clf = DecisionTreeClassifier(criterion='entropy')
# 决策树训练
clf.fit(train_features, train_labels)
test_features=dvec.transform(test_features.to_dict(orient='record'))
# 决策树预测
pred_labels = clf.predict(test_features)
# 得到决策树准确率
acc_decision_tree = round(clf.score(train_features, train_labels), 6)
print('score 准确率为: {:.2%}'.format(acc_decision_tree)) |
69d96fd98a1d0585766c2714d79a04f79583c24c | tejasgondaliya5/basic-paython | /basicpython/stringvar.py | 551 | 4.03125 | 4 | str1 = "my name is tejas"
str2 = str1
str3 = 'tejas is a good boy'
print(str1)
print(str2)
print(str3)
str3 = "Tejas is bad boy"
print(str3)
print()
print(str1.lower())
print(str1.upper())
print(str1.swapcase())
print(str1.title())
print()
print("split function : ")
str4 = "Gondaliya Tejas Girishbhai "
#used to store database name surname lastname in diffrent columns
print(str4.split(" "))
print()
print("join function : ")
str5 = ("tejas" , "gondaliaya" , "girishbhai")
#used to display datbase to user some columns string join and display
print('_' . join(str5)) |
02bcc5aa60b00942dde3957f8a1bf499feb5f916 | PowerLichen/pyTest | /HW4/1.py | 437 | 4 | 4 | """
Project: Print ASCII list
Author: Minsu Choe
StudentID: 21511796
Date of last update: Mar. 29, 2021
"""
#define list
upper_alp = [chr(i) for i in range(ord('A'),ord('Z')+1)]
lower_alp = [chr(i) for i in range(ord('a'),ord('z')+1)]
digits = [chr(i) for i in range(ord('0'),ord('9')+1)]
#print list
print("Upper case alphabets :")
print(upper_alp)
print("Lower case alphabets :")
print(lower_alp)
print("Digits :")
print(digits) |
953a62dfdbc2eebab22f4e6c1354741204128017 | chenxiaolong2019/Python-for-Economics | /Lesson 4 Homework.py | 1,294 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 23:15:44 2020
@author: 陈小龙 20184035237
"""
def average(x):
sum=0
for num in x:
sum=sum+num
average=sum/len(x)
return average
import pandas as pd
dta_smokers=pd.read_csv("/Users/35865/Desktop/经济软件应用/smokers.csv")
dta_smokers_1 = dta_smokers['tip'].groupby(dta_smokers['time']).apply(average)
print(dta_smokers_1)
'''
Result:
time
Dinner 3.102670
Lunch 2.728088
Name: tip, dtype: float64
According to output data,taking "time" as the grouping basis,
the average tip given by the "Dinner" group is the most.
'''
dta_smokers_2 = dta_smokers['tip'].groupby([dta_smokers['time'],dta_smokers['size']]).apply(average)
print(dta_smokers_2)
'''
Result
time size
Dinner 1 1.000000
2 2.661923
3 3.490000
4 4.122500
5 3.785000
6 5.000000
Lunch 1 1.875000
2 2.423077
3 2.754000
4 4.218000
5 5.000000
6 5.300000
Name: tip, dtype: float64
According to output data, taking "time" and "size" as the grouping basis,
the average tip given by the "Lunch" group, size 6 is the most.
'''
|
07e636b12adba7b048a305a5bdffaf85cf548592 | Sid20-rgb/TkinterProject | /database/database1.py | 2,531 | 4.15625 | 4 | from tkinter import *
import sqlite3
root = Tk()
#creating a database
conn = sqlite3.connect("recording_book.db")
#creating cursor
c = conn.cursor()
'''
#creating table
c.execute(""" CREATE TABLE addresses(first_name text,
last_name, text,
address text
city text,
state text,
zipcode integer
)""")
print("Created a table.")'''
def submit():
conn = sqlite3.connect("recording_book.db")
c = conn.cursor()
c.execute("INSERT INTO addresses VALUES (:first_name, :last_name, :address, :city, :state, :zipcode)",{
"first_name": e1.get(),
"last_name": e2.get(),
"address": e3.get(),
"city": e4.get(),
"state": e5.get(),
"zipcode": e6.get()
})
print("Address in inserted successfully.")
conn.commit()
conn.close()
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
e6.delete(0, END)
def query():
conn = sqlite3.connect("recording_book.db")
c = conn.cursor()
c.execute("SELECT *, oid FROM addresses")
record = c.fetchall()
print(record)
print_record = " "
for records in record:
print_record += str(records)+ "\n"
query_label = Label(root, text = print_record)
query_label.grid(row = 8, column = 0, columnspan = 2)
conn.commit()
conn.close()
#desigining
first_name = Label(root, text = "First Name")
first_name.grid(row = 0, column = 0)
e1 = Entry(root)
e1.grid(row = 0, column= 1)
#
last_name = Label(root, text = "Last Name")
last_name.grid(row= 2, column = 0)
e2 = Entry(root)
e2.grid(row = 2, column = 1)
address = Label(root, text = "Address")
address.grid(row = 3, column = 0)
e3 = Entry(root)
e3.grid(row = 3, column = 1)
city = Label(root, text = "City")
city.grid(row = 4, column = 0)
e4 = Entry(root)
e4.grid(row = 4, column = 1)
state = Label(root, text = "State")
state.grid(row = 5, column = 0)
e5 = Entry(root)
e5.grid(row = 5, column = 1)
zipcode = Label(root, text = "Zip Code")
zipcode.grid(row = 6, column = 0)
e6 = Entry(root)
e6.grid(row =6, column = 1 )
button1= Button(root, text = "Submit", command = submit)
button1.grid(row = 7, column = 1)
button2 = Button(root, text = "Show Record")
button2.grid(row = 8, column = 1)
conn.commit()
conn.close()
root.mainloop()
|
13ba950fc0688df3cfcdc28726e46d3d250a40cf | dmarsola/mizpel | /strings.py | 4,659 | 3.71875 | 4 | # from commons import word_list
def compare_equal(str1, str2, case_sensitive=True):
result = True
counter = 0
try:
# print(f'compare_equal {str1}, {str2} | {len(str1) - len(str2)} | {case_sensitive}')
if not len(str1) - len(str2) == 0:
result = False
else:
if not case_sensitive:
str1 = str1.upper()
str2 = str2.upper()
while True:
try:
if not str1[counter] == str2[counter]:
result = False
break
except IndexError as err:
# Found equal by index error meaning that they are the same until the last letter.
break
else:
counter += 1
except TypeError:
# print(f'type error found, retrying | {str(str1)}, {str(str2)}')
result = compare_equal(str(str1), str(str2), case_sensitive)
return result
def compare_similar(str1, str2, off_by_tolerance=0):
counter = 0
off_count = 0
# print(f'{str1}, {str2}')
str1 = str1.lower()
str2 = str2.lower()
len_str1 = len(str1)
len_str2 = len(str2)
if off_by_tolerance == 0:
return compare_equal(str1, str2, False)
elif abs(len_str1 - len_str2) > off_by_tolerance:
return False
else:
while off_count <= off_by_tolerance:
try:
# case letters at counter are equal - keep going
if str1[counter] == str2[counter]:
# print(f'if equal {str1[counter]} {str2[counter]}')
counter += 1
else: # case next letter at next counter of one of them are equal
for i in range(1, off_by_tolerance+1):
off_count += 1
# print(f'{str1[counter]} {str2[counter]} i:{i} off_count:{off_count}')
if str1[counter + i] == str2[counter + i]:
return compare_similar(str1[counter + i:], str2[counter + i:], off_by_tolerance - i)
else:
try:
if str1[counter] == str2[counter + i]:
return compare_similar(str1[counter:], str2[counter + i:], off_by_tolerance - i)
except IndexError:
return compare_similar(str1[counter+i:], str2[counter:], off_by_tolerance - i)
try:
if str1[counter + i] == str2[counter]:
return compare_similar(str1[counter + i:], str2[counter:], off_by_tolerance - i)
except IndexError:
return compare_similar(str1[counter:], str2[counter+i:], off_by_tolerance - i)
except IndexError:
# print(f'resolved by index error: {len(str1)} {len(str2)} {off_by_tolerance}, {off_count}')
# have to add the off_count index so that it does not go over
# print("index error: ", str1, str2, off_count, counter)
if abs(len(str1)-len(str2)) + off_count <= off_by_tolerance:
return True
elif len(str1)-len(str2) > 0:
if str1[counter + 1] == str2[counter]:
return abs(len(str1) - len(str2)) <= off_by_tolerance
elif len(str2)-len(str1) > 0:
if str1[counter] == str2[counter + 1]:
return abs(len(str1) - len(str2)) <= off_by_tolerance
# catch all
return abs(len(str1) - len(str2)) + off_count + 1 <= off_by_tolerance
if len(str1) > len(str2):
# print(f'len str1 > len str2 - {str1}, {str2}')
return compare_similar(str1[counter+1:], str2[counter:], off_by_tolerance - 1)
else:
# print(f'len str1 < len str2 - {str1}, {str2}')
return compare_similar(str1[counter:], str2[counter + 1:], off_by_tolerance - 1)
#
# def find_similar(str1, strict_equal=False):
# counter = 0
# found_equal = False
# similar_by_1 = []
# for word in word_list:
# counter += 1
# # print(f'comparing {str1} and {word_list[counter]}')
# if compare_similar(str1, word, 1):
# similar_by_1.append(word)
# if compare_equal(str1, word, strict_equal):
# found_equal = True
# print(f'Done! Total number of words searched: {counter}')
# return found_equal, similar_by_1
|
85192877e680cdd62e8a8d21394e005b68ef341f | lazybing/language_learning | /Python_Language_Learning/Beging_Python_3th/ch4/listing4-1.py | 1,013 | 4.5 | 4 | # A simple database
# A dictionary with person names as keys. Each person is represented as
# another dictionary with the key's 'phone' and 'addr' referring to their phone
# number and address, respectively.
people = {
'Alice':{
'phone':'2341',
'addr':'Foo drive 23'
},
'Beth':{
'phone':'9102',
'addr':'Bar street 42'
},
'Cecil':{
'phone':'3158',
'addr':'Baz avenue 90'
}
}
# Descriptive labels for the phone number add address.
# These will be used when printing the output
labels = {
'phone':'phone number',
'addr':'address'
}
name = input('Name: ')
# Are we looking for a phone number of an address?
request = input('Phone number (p) or address (a)?')
# Use the correct key:
if request == 'p':key = 'phone'
if request == 'a':key = 'addr'
# Only try to print information if the name is a valid key in
# our dictionary:
if name in people:print ("{}'s {} is {}.".format(name, labels[key], people[name][key]))
|
c22774e947e499148696a2d021a3eda71cfe9d11 | mbledkowski/HelloRube | /Python/randomrube.py | 315 | 3.609375 | 4 | # Let's hope you're lucky!
# 33-111 is the ASCII values for space to "o", 78 possibilities
# "Hello World!" has length of 12
# Odds: 12^78 ~= 1.5 x 10^84
import random
world = "Hello World!"
word = ""
while (word!=world):
word = ""
for c in range(len(world)):
word+=chr(random.randint(33,111))
print word
|
755f12ae7238160870ab164502a82973962c0534 | lewfer/learning-pi-bot | /qlearning.py | 10,368 | 3.65625 | 4 | # Reinforcement learning using q-learning
#
# A library to faciliate simple q-learning exercises
#
# Think Create Learn 2020
# We will use numpy because it gives us some nice functionality for arrays
import numpy as np
# Pandas gives useful functionality to export to Excel
#import pandas as pd
# For choosing random numbers
import random
# Set numpy print options to wide and print everything
np.set_printoptions(edgeitems=30, linewidth=200, threshold=np.inf)
class Matrix():
"""Representation of a 3D matrix of state, action and next_state.
Can be used to represent both R and Q
"""
def __init__(self, num_states, action_names):
"""Initialise a matrix, specifying the total number of states and the names of the actions"""
self.num_states = num_states
self.num_actions = len(action_names)
self.action_names = action_names
def __str__(self):
"""String representation of the matrix is the string representation of the numpy array"""
return str(self.matrix)
def __repr__(self):
"""Representation of the matrix is the numpy array"""
return repr(self.matrix)
def createMatrix(self, value=-1):
"""Create a matrix of the right shape containing the given value in each cell"""
self.matrix = np.full([self.num_states, self.num_actions, self.num_states], value)
def setMatrix(self, array):
"""Set the matrix to the passed in 3D array"""
self.matrix = np.array(array)
def setValue(self, state, action, next_state, value):
"""Set the value of the cell referenced by the state, action and next_state"""
self.matrix[state, action, next_state] = value
def getValue(self, state, action, next_state):
"""Get the value in the cell referenced by the state, action and next_state"""
value = self.matrix[state, action, next_state]
return value
def maxValue(self, state):
"""Get the max value across all actions possible from the state"""
max_value = np.max(self.matrix[state])
return max_value
def possibleActions(self, state):
"""Finds the possible actions from the given state"""
# Get the row corresponding to the given state, which gives the possible next states
row = self.matrix[state]
# Find the states that have a reward >=0. These are the only valid states.
# np.where returns a tuple
actions, next_states = np.where(row >= 0)
# Zip up tuples containing the action,next_state pairs
return list(zip(actions, next_states))
def allActions(self, state):
"""Finds the all actions from the given state"""
# Get the row corresponding to the given state, which gives the possible next states
row = self.matrix[state]
# Find the states that have a reward >=0. These are the only valid states.
# np.where returns a tuple
actions, next_states = np.where(np.logical_or(row != 0,row==0))
# Zip up tuples containing the action,next_state pairs
return list(zip(actions, next_states))
def bestActions(self, state):
"""Finds the best actions from the given state"""
# Get the row corresponding to the given state, which gives the possible next states
row = self.matrix[state]
# Find the best (i.e. max) value in the row
best_value = np.nanmax(row)
# Find the actions corresponding to the best value
actions, next_states = np.where(row == best_value)
# Zip up tuples containing the action,next_state pairs
return list(zip(actions, next_states))
def copyFill(self, value):
"""Make a copy of the matrix and fill cells with the value"""
new_matrix = Matrix(self.num_states, self.action_names)
new_matrix.createMatrix(value)
return new_matrix
#def print(self):
# ""Print
# print(self.matrix)
def dumpExcel(self, filename):
"""Dump the matrix to an Excel file, one sheet per action"""
with pd.ExcelWriter(filename) as writer:
for a in range(self.num_actions):
data = self.matrix[:,a,:]
pd.DataFrame(data).to_excel(writer, sheet_name=self.action_names[a])
def intersection(lst1, lst2):
"""Utility function to find the intersection between two lists"""
result = [value for value in lst1 if value in lst2]
return result
class QAgent():
"""The QAgent is a reinforcement learning agent using Q-learning"""
def __init__(self, R, goal_state, gamma=0.8, alpha=1):
"""Pass in your reward matrix and the goal state.
Gamma is the discount rate. This is applied to the "future q", so we only take part of the reward from the future.
Alpha is the learning rate. Reduce alpha to make learning slower, but possibly more likely to find a solution in some cases.
If you have no specific goal state (e.g. a walking robot) use -1."""
self.R = R
self.goal_state = goal_state
self.num_states = R.num_states
self.Q = R.copyFill(0)
self.gamma = gamma # discount rate
self.alpha = alpha # learning rate
self.current_state = 0
def chooseRandomAction(self):
"""Choose a random action from the possible actions from the current state"""
# Get the possible actions from the current state
actions = self.R.possibleActions(self.current_state)
# If the above returned no actions, get all actions, not just possible ones
if len(actions)==0:
actions = self.R.allActions(self.current_state)
# Choose one at random and return it
action = random.choice(actions)
return action
def chooseBestAction(self):
"""Choose the best action from the possible actions from the current state"""
# Get the possible actions from the current state
possible_actions = self.R.possibleActions(self.current_state)
# Get the best actions from the current state, i.e. the ones that give the highest q-value
# We may get one or more with the same q-value
best_actions = self.Q.bestActions(self.current_state)
# Intersect the best_actions with the possible actions so we only return valid actions
actions = intersection(possible_actions, best_actions)
# Choose one of the actions at random and return it
action = random.choice(actions)
return action
def chooseBestActionWithRandomness(self):
"""Choose the best action from the possible actions from the current state, but with some randomness to choose less good options sometimes"""
# Get the possible actions from the current state
possible_actions = self.R.possibleActions(self.current_state)
print(possible_actions)
# Choose one of the actions at random and return it
action = random.choice(possible_actions)
return action
def updateQ(self, action, next_state):
"""Update the Q table based on the action. This is the key of the learning part"""
# Find the max value in the Q row (this is the best next Q following the action)
max_future_q = self.Q.maxValue(next_state)
current_r = self.R.getValue(self.current_state, action, next_state)
current_q = self.Q.getValue(self.current_state, action, next_state)
# Sometimes we get nulls. We can't do anything with them
if np.isnan(current_r):
return
# Q learning formula - update the Q table current state with a little of the reward from the future
# Simple version
#new_q = int(current_r + self.gamma * max_future_q)
# Complex version
new_q = ((1-self.alpha) * current_q + self.alpha * (current_r + self.gamma * max_future_q))
# Update q table with the new value
self.Q.setValue(self.current_state, action, next_state, new_q)
def train(self, num_episodes):
"""Train for the given number of episodes"""
# Work out how often to update the user
modcount = max(1,num_episodes/100 )
# Run for the requested number of episodes
for i in range(num_episodes):
# Print out progress message
if i%modcount==0: print("Training episode", i)
# Choose a start state at random
self.current_state = np.random.randint(0, self.num_states)
#print("\nChosen random state", self.current_state)
# Keep randomly choosing actions until we reach the goal state
# Or if we have no goal state (-1), end the episode after one iteration
first_time = True
while (self.goal_state!=-1 and self.current_state != self.goal_state) or (self.goal_state==-1 and first_time):
#print("\nCurrent state:", self.current_state)
# Choose one of the possible actions from the current state at random
action, next_state = self.chooseRandomAction()
# Update the Q table based on that action
self.updateQ(action, next_state)
# Move to the next state
self.current_state = next_state
first_time = False
# See progress in updating Q
#if i%modcount==0:
#print(self.Q)
def run(self, start_state):
"""Run the search for a solution starting at the given state. Assumes you have already trained the agent."""
# Set the current state
self.current_state = start_state
# Keep a track of the path found
path = [("Start", self.current_state)]
# Keep choosing actions until we reach the goal state
while self.current_state != self.goal_state:
# Choose the best action based on the Q table
action, next_state = self.chooseBestActionWithRandomness()
# Keep a track of where we've been
path.append((self.R.action_names[action], next_state))
# Move to the next state
self.current_state = next_state
# Return the chosen path
return path
|
10e34832e0494d57d0ceaf6e4ec11344b1b0233f | chenyaqiao0505/Code111 | /testCode/threading_test_01.py | 1,578 | 3.984375 | 4 | # import threading
# import time
#
# '''直接调用'''
#
# def hello(name):
# print("Hello %s"%name)
# time.sleep(3)
#
# if __name__ == "__main__":
# t1=threading.Thread(target=hello,args=("zhangsan",)) #生成线程实例
# t2=threading.Thread(target=hello,args=("lisi",))
#
# t1.setName("aaa") #设置线程名
# t1.start() #启动线程
# t2.start()
# t2.join() #join 等待t2先执行完
# print("Hello")
# print(t1.getName()) #获取线程名
##设置setDaemon状态(True/False)的区别
# import threading, time
#
#
# def doThreadTest():
# print('start thread time:', time.strftime('%H:%M:%S'))
# time.sleep(10)
# print('stop thread time:', time.strftime('%H:%M:%S'))
#
# threads = []
# for i in range(3):
# thread = threading.Thread(target=doThreadTest)
# # thread.setDaemon(True)
# threads.append(thread)
#
# for t in threads:
# t.start()
#
# for t in threads:
# t.join(1)
# print('stop main thread')
# #多线程请求同一资源情况
# import threading
# import time
#
# num = 100
# def show():
# global num
# time.sleep(1)
# num -= 1
#
# list = []
# for i in range(100):
# t = threading.Thread(target=show)
# t.start()
# list.append(t)
#
# for t in list:
# t.join()
# print(num)
import threading
import time
num = 100
lock = threading.Lock()
def show():
global num
time.sleep(1)
lock.acquire()
num -= 1
lock.release()
list = []
for i in range(100):
t = threading.Thread(target=show)
t.start()
list.append(t)
for t in list:
t.join()
print(num) |
68e49c5d15fad058923a3c194ecd76b7a9dffbbb | nastyakuzenkova/CSC-Python | /anastasiia_kuzenkova_01.py | 3,803 | 4 | 4 | #python homework^1 task^1
def shape(m):
#calculate size of matrix
return len(m), len(m[0])
def print_map(m, pos):
#print map with free and reserved positions and mark current position
n_rows, n_cols = shape(m)
for i in range(n_rows):
for j in range(n_cols):
if (i, j) == pos:
#marked position
print('@', end = "")
elif m[i][j]:
#free position
print('.', end = "")
else:
#reserved position
print('#', end = "")
print()
def neighbours(m, pos):
#find free positions nearby current (top, bottom, left and right)
answer = []
pos_row, pos_column = pos
shifts = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for dr, dc in shifts:
n_pos = (pos_row + dr, pos_column + dc)
n_pos_row, n_pos_column = n_pos
if is_pos_valid(m, n_pos) and m[n_pos_row][n_pos_column]:
answer.append(n_pos)
return answer
def is_pos_valid(m, pos):
#check if current position is inside the map
pos_row, pos_column = pos
n_rows, n_cols = shape(m)
return pos_row >= 0 and pos_row < n_rows and pos_column >= 0 and pos_row < n_rows
def find_route(m, initial):
#find path from current position to one of the side free positions
paths = []
visited = set()
paths.append([initial])
while paths:
path = paths.pop(0)
node = path[-1]
visited.add(node)
if is_exit(m, node):
return path
for neighbour in neighbours(m, node):
if neighbour not in visited:
next_path = path[:]
next_path.append(neighbour)
paths.append(next_path)
return []
def is_exit(m, initial):
#check if current position is side position and free
initial_row, initial_column = initial
n_rows, n_cols = shape(m)
return (initial_row == 0 or initial_column == 0 or \
initial_row == n_rows - 1 or initial_column == n_cols - 1) \
and m[initial_row][initial_column]
def escape(m, initial):
#print one of the paths to escape
route = find_route(m, initial)
if not route:
print("there is no path to escape")
return
for pos in route:
print_map(m, pos)
print()
#python homework^1 task^2
def hamming(seq1, seq2):
assert len(seq1) == len(seq2)
length = len(seq1)
distance = 0
for i in range(length):
if seq1[i] != seq2[i]:
distance += 1
return distance
def hba1(path, distance):
sequences = []
with open(path) as sequences_file:
sequences = sequences_file.read().splitlines()
sequences_size = len(sequences)
hamming_min = len(sequences[0])
hamming_indexes = (0, 0)
for i in range(sequences_size):
for j in range(i + 1, sequences_size):
hamming_current = distance(sequences[i], sequences[j])
if hamming_current < hamming_min:
hamming_min = hamming_current
hamming_indexes = (i + 1, j + 1)
return hamming_indexes
#python homework^1 task^3
def kmers(seq, k = 2):
dictionary = {}
length = len(seq)
for i in range(length - k + 1):
substring = seq[i : i + k]
if substring not in dictionary:
dictionary[substring] = 1
else:
dictionary[substring] += 1
return dictionary
def distance1(seq1, seq2, k = 2):
seq1_dictionary = kmers(seq1, k)
seq2_dictionary = kmers(seq2, k)
substrings = set(list(seq1_dictionary.keys()) + list(seq2_dictionary.keys()))
distance = 0
for substring in substrings:
distance += abs(seq1_dictionary.get(substring, 0) - seq2_dictionary.get(substring, 0))
return distance
|
528219e4649cdcd10365b5e904d397469f9ecb89 | esmeraldastan/world_map | /World map (office).py | 6,293 | 3.78125 | 4 | # -*- coding: utf-8 -*-
import time
import sys
#Name of the Game
time.sleep(0.5)
print "Welcome to CounterCode\n"
print "Your obective in this game will be to get out of\nthe building to safety.\n"
node = None
class Building:#start of the map
def __init__(self, name, description, up, down, north, east, south, west, right, left, outside, inside):
self.name = name
self.description = description
self.up = up
self.down = down
self.north = north
self.east = east
self.south = south
self.west = west
self.right = right
self.left = left
self.outside = outside
self.inside = inside
def move(self, direction):
global node
node = globals()[getattr(self, direction)]
#INTO TO THE GAME
print 'You have woken up from a long sleep. The last thing you remember was escaping\nthe white gas that was spreading throughout the city.'
#BUILDING
#THIRD FLOOR
Office = Building("Office", 'Papers have been shattered everywhere. The lights a\nflashing on and off. There next to you is a light blue paper. Type "pick up" to read what it says.', None, None, 'Conference', 'Secutary', None, None, None, None, None, None)
Conference = Building("Conference Room", 'You are now standing in the Conference Room. A couple of bodies are laying around. Rottening with a nasty smell. There\'s a flashlight on the table. Pick it up...you might need it later on.\n\nHead "east"', None, None, None, 'Elevator', 'Office',None, None, None, None, None)
Elevator = Building("Elevator", 'In the Elevator head down to continue getting to your destination. Type "down".But wait before that you you need to restore to full health.There is a green cyrum laying on the grown. Type "restore" this will get you to full health. ', None, 'Elevator2', None, None, 'Secutary Desk',None, None, None, None, None)
Stairs = Building("Stairs", 'The walls are coverd with blood. You are not alone. Zombies and infecteds run the area now. You don\'t want to encounter with one ...it can be your end.To go down the stairs type down to go on to the next floor.There is blood covering the walls….Bodies laying down with body parts missing. Be careful. ', None, 'Stairs1', None, None, None,None, None, None, None, None)
Secutary = Building("Secutary Desk",' You are standing next to your securary\'s desk. A flash light stands on top. Pick it up you might need it later on. Head "north" to the elevator or "east" to the stairs.', None, None, 'Elevator', 'Stairs', None , None, None, None, None, None)
#PATH TO SECOND FLOOR
Stairs1 = Building("Stairs", 'Pieces from the ceiling fell blocking your path. Find another path to reach out into saftey', None, None, None, None, None,None, None, None, None, None)
Elevator2 = Building("Elevator", 'You are now on the second floor', None, 'Elevator2', None, None, None,None, 'Office1', None, None, None)
#SECOND FLOOR
Office1 = Building('Office 1', 'There seems nothing to be in here help you defeat the infected.\nHead "west" into the other office. There might be something in there', None, None, 'Elevator', 'Office2', 'Janitor',None, None, None, None, None)
Weapon = Building('Weapon Room', 'A variaty of weapons are displayed. The the ones that you think will be useful. Remember thought there is a limit to what you can take', None, None, None, None, 'Secret',None, None, None, None, None)
Secret = Building('Secret Door', 'Inorder to open the door you need to figure out the code', None, None, 'Weapon', 'Janitor', None,None, None, None, None, None)
Janitor= Building('Janitor Room', 'Cleaning applicances are scattered everywhere. Within the room ther is another door.\nWEAPONS\n it reads. Figure out the passcode to get in.', None, None, None, 'Office1', 'Secret',None, None, None, None, None)
Bathroom = Building('Restroom', 'The smell of rottening meat is rising in here. Place the first bomb in here. ', None, None, None, None, 'Stairs','Elevator', None, None, None, None)
Office2 = Building('Office 2 ', '', None, None, None, 'Elevator', 'Stairs','Office1', None, None, None, None)
Stairs2 = Building("Stairs", 'You are now in the first floor. Zombies are following you down. Place the bomb in between the stairs and the front desk. Type "place". Once you do head out.', None, None, None, None, None,None, None, None, None, None)
#FIRST FLOOR
Front = Building('', '', None, None, None, None, None,None, None, None, None, None)
#Door = Building('', '', None, None, None, None, None,None, None, None, None, None)
#Building('', '', None, None, None, None, None,None, None, None, None, None)
#OUTSIDE
Enterence=('Enterence', 'BOOM!!!Peices of glass shattering everywhere. Bodies flying in the sky. Luckly you have made it out saftly. It won\'t be easy now to make it you your destination with infecteds and zombies around.', None, None, None, None, None,None, None, None, None, None)
coffee = ('Coffee Shop', 'You are now standing inforn of a coffee shop. If you are low on health head inside to restore it. If not confinue..\nHead "west"', None, None, None, None, None,None, None, None, None, None)
bank =('', '', None, None, None, None, None,None, None, None, None, None)
node = Office
#Run program
while True:
print node
print "Room: " + node.name
print
print "Description: " + node.description
#WORD DEFINE
infected = "A person who had been contaminated by the gas"
zombie = 'A dead person risen from the dead.The chemicals within the gass had an effect on the dead makeing them come back to life'
response = ['up', 'down', 'north', 'east', 'south', 'west', 'right', 'left', 'outside', 'inside']
pick = ['pick up']
command = raw_input('>').strip().lower()
#QUITE THE PROGRAM
if command in ['q', 'exit', 'quit']:
sys.exit(0)
#paper read out
if command in pick:
print 'Escape to th labatory hidden under the old facotry building.It should be located a couple of blocks\nwest of where you are located.'
print 'Head north or east'
#MOVE INTO DIFFERNT ROOMS
if command in response:
try:
node.move(command)
except:
print 'You can\'t do that way! '
|
30369da1f9159b45dd4c1ddc513233d82aeba2d4 | GorobetsYury/Python_beginning | /lesson_8_task_1.py | 2,084 | 3.671875 | 4 | # Реализовать класс «Дата», функция-конструктор которого должна принимать дату в
# виде строки формата «день-месяц-год». В рамках класса реализовать два метода. Первый,
# с декоратором @classmethod, должен извлекать число, месяц, год и преобразовывать их тип к
# типу «Число». Второй, с декоратором @staticmethod, должен проводить валидацию числа, месяца
# и года (например, месяц — от 1 до 12). Проверить работу полученной структуры на реальных данных.
class Date:
def __init__(self, date):
self.date = date
@staticmethod
def check_date(obj):
data = obj.date.split('-')
new_data = []
for item in data:
new_data.append(int(item))
if new_data[1] == 2 and new_data[0] > 28: # не стал учитывать високосный год
print('Дата некорректна')
elif 1 <= new_data[0] <= 31:
if 1 <= new_data[1] <= 12:
if 1 <= new_data[2] <= 9999:
print('Дата верна')
@classmethod
def str_to_int(cls, data):
data = data.split('-')
new_data = []
for item in data:
new_data.append(int(item))
print(f'Число {new_data[0]} (тип {type(new_data[0])}), '
f'Месяц {new_data[1]} (тип {type(new_data[1])}), '
f'Год {new_data[2]} (тип {type(new_data[2])})')
my_date = Date('18-11-1990')
my_date_2 = Date('30-02-2020')
Date.str_to_int(my_date.date)
# Результат:
# Число 18 (тип <class 'int'>), Месяц 11 (тип <class 'int'>), Год 1990 (тип <class 'int'>)
Date.check_date(my_date) # Дата верна
Date.check_date(my_date_2) # Дата некорректна
|
4fa43cc113371d041d27a1149bd7b2a52b935db2 | ivanFlor3s/first-python-scripts | /Dumb-scripts/string-methods.py | 1,400 | 4.25 | 4 | #!/usr/bin/env python3
spam = 'Hello World'
print('Todo en MAYUSCULA \n' + spam.upper()) #Pasa todo a mayusculas
print('Todo en minuscula \n' +spam.lower())
otroString = 'SOY UN STRING'
otroString.islower() # FALSE
otroString.isupper() # TRUE
# isalpha >> dice si solo tiene letras
# isalnum >> True si tiene numeros y letras
# isspace() >> si tiene ful espacios caracter
# istitle() >> todas las palabras empiezaen en Mayuscula
#
spam.startswith('Hello') # retorna True si e string comienza con el string parametro
spam.endswith('World')
#JOIN cuando tenemos muchos strings y necesitamos unirlos con algo
','.join(['cats','rats','bats'])
#SPLIT lo contrario: usa el parametro para separar el String
#'HOla mundo y su buena madre ma mo me mi'.split('m')
#['HOla ', 'undo y su buena ', 'adre ', 'a ', 'o ', 'e ', 'i']
# ljust(int) y rjust(int): Ajusta el string agreando espacios (o el segundo parametro
# que le pase)para que llegue al length qe paso por parametro
print('hello'.rjust(10))
print('hello'.rjust(10,'@'))
print('hello'.center(20,'-')) #El mejor para mi
#strip() remueve los espacios en blanco (o lo que pasemos por parametro), no modifica el string
#tambien tenemos lstrip() y rstrip()
#replace(lo que se va a reemplazar, por lo que vamos a remplazar)
#Podemos usar los %d %s %f para poner las variables dentro del string como lo haciamos en C
#stirng %(parametros) |
9c34660cf673bc11a0dbcfcde58210cf8bd9d347 | Boberkraft/Data-Structures-and-Algorithms-in-Python | /chapter4/P-4.23.py | 709 | 4 | 4 | """
Implement a recursive function with signature find(path, filename) that
reports all entries of the file system rooted at the given path having the
given file name.
"""
import os
def find(path, filaname):
if os.path.isdir(path):
for file in os.listdir(path):
# for file in directory
if file == filaname:
# if file with serching name have been found
yield os.path.join(path, filaname) # yield it
new_path = os.path.join(path, file)
yield from find(new_path, filaname)
if __name__ == '__main__':
path = os.path.dirname(__file__)
filaname = 'bird'
for file in find(path, filaname):
print(file)
|
a06f898f064d3fe89409109d7356b6154f950614 | Starxyz/leetCodeRecord | /pySln/test/test309.py | 494 | 3.5625 | 4 | from leetcode309 import Solution
sln = Solution()
def test_case0():
stocks = [1, 2, 3, 0, 2]
# 1元买入, 2元卖出,赚1元
# 0元买入, 2元卖出,赚2元
# 总共赚 1+2=3元
assert sln.maxProfit(stocks) == 3
def test_case1():
stocks = [1, 2]
assert sln.maxProfit(stocks) == 1
def test_case2():
stocks = [1, 2, 4]
assert sln.maxProfit(stocks) == 3
def test_case3():
stocks = [6, 1, 3, 2, 4, 7]
assert sln.maxProfit(stocks) == 6
|
373ef96ccb789124d4c34ef4b12310fc6c9e5816 | Kevinliao0857/Road-of-Python | /checkio electronic station/words order.py | 1,129 | 4.03125 | 4 | def words_order(text: str, words: list) -> bool:
text_words = {w for w in text.split() if w in words}
return list(sorted(text_words, key=text.index)) == words
if __name__ == '__main__':
print("Example:")
print(words_order('hi world im here', ['world', 'here']))
# These "asserts" are used for self-checking and not for an auto-testing
assert words_order('hi world im here', ['world', 'here']) == True
assert words_order('hi world im here', ['here', 'world']) == False
assert words_order('hi world im here', ['world']) == True
assert words_order('hi world im here',
['world', 'here', 'hi']) == False
assert words_order('hi world im here',
['world', 'im', 'here']) == True
assert words_order('hi world im here',
['world', 'hi', 'here']) == False
assert words_order('hi world im here', ['world', 'world']) == False
assert words_order('hi world im here',
['country', 'world']) == False
assert words_order('hi world im here', ['wo', 'rld']) == False
assert words_order('', ['world', 'here']) == False
print("Coding complete? Click 'Check' to earn cool rewards!")
|
7eef26a3d1a6eb88caa003a4538a4f99382f6b36 | AaronYang2333/CSCI_570 | /records/12-31/flip.py | 696 | 3.609375 | 4 | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '12/31/2020 10:29 AM'
while 1:
a = int(input())
nums = list(map(int, input().split(' ')))
if a == 1:
print('yes')
break
i, j = 0, 1
flag = True
while i < len(nums) - 1:
if nums[i] < nums[i + 1]:
i += 1
else:
if flag:
j = i + 1
while j < len(nums) - 1:
if nums[j - 1] > nums[j]:
j += 1
else:
break
nums[i:j] = reversed(nums[i:j])
flag = False
else:
print('no')
print('yes')
|
1411c9b02647c219e375cb8c550f624d3c605ecb | y471n/algorithms-n-ds | /ds/stack-postfix-evaulation.py | 724 | 3.875 | 4 | from stack import Stack
import operator
OPS = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.itruediv
}
def do_math(token, op1, op2):
return OPS[token](int(op1), int(op2))
def calculate_postfix(input_expression):
token_list, operand_stack = input_expression.split(), Stack()
for token in token_list:
if token.isalnum():
operand_stack.push(token)
else:
operand_2 = operand_stack.pop()
operand_1 = operand_stack.pop()
result = do_math(token, operand_1, operand_2)
operand_stack.push(result)
return operand_stack.pop()
if __name__ == "__main__":
print(calculate_postfix(input()))
|
b32c285a68a6210f378de9c694bddbe5d9b7b7a1 | supertommc/Neutreeko-Python | /button.py | 6,352 | 3.796875 | 4 | """
Here are all the buttons classes used in the menus
"""
class Button:
"""
This is the base and simple button that only execute its response when it is pressed
"""
def __init__(self, position, width, height, new_color, background_color, pressed_color_offset, new_text,
new_text_size, response):
self._x, self._y = position
self._color = new_color
self._background_color = background_color
self._pressed_color_offset = pressed_color_offset
self._width = width
self._height = height
self._text = new_text
self._text_size = new_text_size
self._response = response
def get_x(self):
return self._x
def get_y(self):
return self._y
def get_position(self):
return self._x, self._y
def get_color(self):
return self._color
def get_background_color(self):
return self._background_color
def get_pressed_color_offset(self):
return self._pressed_color_offset
def get_width(self):
return self._width
def get_height(self):
return self._height
def get_text(self):
return self._text
def get_text_size(self):
return self._text_size
def get_text_x(self, text_width):
return self._x + self._width / 2 - text_width / 2
def get_text_y(self, text_height):
return self._y + self._height / 2 - text_height / 2
def get_text_position(self, text_width, text_height):
return self.get_text_x(text_width), self.get_text_y(text_height)
def set_text(self, new_text, new_text_size):
self._text = new_text
self._text_size = new_text_size
def is_hover(self, mx, my):
return self._x < mx < self._x + self._width and self._y < my < self._y + self._height
def press(self, mx, my):
if self.is_hover(mx, my):
self._response.on_press()
class SlideButton(Button):
"""
This is a more sophisticated button that has a slide bar to choose a number in the values list
"""
def __init__(self, position, width, height, new_color, background_color, new_bar_color, pressed_color_offset,
prefix, new_text_size, values, initial_value_index, response):
Button.__init__(self, position, width, height, new_color, background_color, pressed_color_offset, "",
new_text_size, response)
self.__bar_color = new_bar_color
self.__prefix = prefix
self.__values = values
self.__number_values = len(values)
self.__current_value_index = initial_value_index
self._text = self.__prefix + str(self.__values[self.__current_value_index])
self.set_text(self.__prefix + str(self.__values[self.__current_value_index]), new_text_size)
self.__bar_width = 0.1 * width
self.__bar_height = height
self.__bar_x, self.__bar_y = position
self.__dragging = False
self.update_bar_x_by_index()
def get_bar_color(self):
return self.__bar_color
def get_bar_width(self):
return self.__bar_width
def get_bar_height(self):
return self.__bar_height
def get_bar_x(self):
return self.__bar_x
def get_bar_y(self):
return self.__bar_y
def get_current_value(self):
return self.__values[self.__current_value_index]
def set_dragging(self, new_dragging):
self.__dragging = new_dragging
def update_text(self):
self._text = self.__prefix + str(self.__values[self.__current_value_index])
self.set_text(self.__prefix + str(self.__values[self.__current_value_index]), self._text_size)
def update_bar_x_by_index(self):
ratio = self.__current_value_index / self.__number_values
self.__bar_x = self._x + self._width * ratio
def update_bar_position(self, mx):
self.__bar_x = mx
def update(self, mx):
if mx < self._x + self.__bar_width / 2:
# update bar position
self.__bar_x = self._x
# update index
self.__current_value_index = 0
elif mx > self._x + self._width - self.__bar_width:
# update bar position
self.__bar_x = self._x + self._width - self.__bar_width
# update index
self.__current_value_index = self.__number_values - 1
else:
# update bar position
self.__bar_x = mx
# update index
bar_ratio = (mx - self._x) / self._width
self.__current_value_index = round(bar_ratio * self.__number_values)
self.update_text()
def press(self, mx, my):
if self.is_hover(mx, my):
self.__dragging = True
def release(self):
self.__dragging = False
def drag(self, mx):
if self.__dragging:
self.update(mx)
self._response.on_drag(self)
class ToggleButton(Button):
"""
This is a more sophisticated button that when you press it, it change the current value to the next in the
values list
"""
def __init__(self, position, width, height, new_color, background_color, pressed_color_offset, prefix, new_text_size, values, initial_value_index, response):
Button.__init__(self, position, width, height, new_color, background_color, pressed_color_offset, "", new_text_size, response)
self.__prefix = prefix
self.__values = values
self.__number_values = len(values)
self.__current_value_index = initial_value_index
self._text = self.__prefix + str(self.__values[self.__current_value_index])
self.set_text(self.__prefix + str(self.__values[self.__current_value_index]), new_text_size)
def get_current_value(self):
return self.__values[self.__current_value_index]
def update_text(self):
self._text = self.__prefix + str(self.__values[self.__current_value_index])
self.set_text(self.__prefix + str(self.__values[self.__current_value_index]), self._text_size)
def update(self):
self.__current_value_index = (self.__current_value_index + 1) % self.__number_values
self.update_text()
def press(self, mx, my):
if self.is_hover(mx, my):
self.update()
self._response.on_press(self)
|
ef7aa7fb7bb6b38dce91edc226097a2bb0899f5c | manurajp83/PYTHON | /exercise 1/triangle.py | 348 | 4.34375 | 4 | #Area of right triangle
l=int(input("Enter the length:")) #to enter the length
b=int(input("Enter the breadth:")) #to enter the breadth
print("The area of right angled triangle is:",(l*b)/2)#displays the area
'''output
Enter the length:5
Enter the breadth:6
The area of right angled triangle is: 15.0
'''
|
7f188c9f704296e168b45788fb017a0f0317f01d | deepgully/codes | /leetcode/python/support/tree.py | 7,437 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode OJ support lib of tree
:copyright: (c) 2014 by Gully Chen.
:license: BSD, see LICENSE for more details.
"""
import collections
# Definition for a binary tree node
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
def __repr__(self):
return "<Node %s>" % self.val
__str__ = __repr__
def __iter__(self):
return in_order_iter(self)
def print_node(node, depth=None):
print(depth, node)
def get_depth(node):
if not node:
return 0
left = get_depth(node.left)
right = get_depth(node.right)
return max(left, right) + 1
def in_order_traversal(root, callback=None, cur_depth=0):
if root is None:
return
in_order_traversal(root.left, callback, cur_depth+1)
callback and callback(root, cur_depth)
in_order_traversal(root.right, callback, cur_depth+1)
def in_order_iter(root, cur_depth=0):
if root is None:
raise StopIteration
stack = []
node = root
level = 0
while node is not None:
stack.append((node, (cur_depth + level)))
node = node.left
level += 1
while stack:
node, cur_depth = stack.pop()
yield node, cur_depth
node = node.right
cur_depth += 1
level = 0
while node is not None:
stack.append((node, (cur_depth + level)))
node = node.left
level += 1
def pre_order_traversal(root, callback=None, cur_depth=0):
if root is None:
return
callback and callback(root, cur_depth)
pre_order_traversal(root.left, callback, cur_depth+1)
pre_order_traversal(root.right, callback, cur_depth+1)
def pre_order_iter(root, cur_depth=0):
if root is None:
raise StopIteration
stack = [(root, cur_depth)]
while stack:
node, cur_depth = stack.pop()
yield node, cur_depth
if node.right is not None:
stack.append((node.right, (cur_depth + 1)))
if node.left is not None:
stack.append((node.left, (cur_depth + 1)))
def post_order_traversal(root, callback=None, cur_depth=0):
if root is None:
return
post_order_traversal(root.left, callback, cur_depth+1)
post_order_traversal(root.right, callback, cur_depth+1)
callback and callback(root, cur_depth)
def post_order_iter(root, cur_depth=0):
if root is None:
raise StopIteration
parents = []
last_visted = None
node = root
while parents or node is not None:
if node is not None:
parents.append((node, cur_depth))
node = node.left
cur_depth += 1
else:
top_node, cur_depth = parents[-1]
if top_node.right is not None and last_visted != top_node.right:
node = top_node.right
cur_depth += 1
else:
yield top_node, cur_depth
last_visted, cur_depth = parents.pop()
def level_order_traversal(root, callback=None, completed_tree=False):
if root is None:
return
current_level = [root]
cur_depth = 0
while current_level:
next_level = []
all_done = True
for node in current_level:
callback and callback(node, cur_depth)
if node is not None:
if completed_tree:
next_level.append(node.left)
next_level.append(node.right)
if node.left is not None or node.right is not None:
all_done = False
else:
if node.left is not None:
all_done = False
next_level.append(node.left)
if node.right is not None:
all_done = False
next_level.append(node.right)
if all_done:
break
current_level = next_level
cur_depth += 1
def level_order_iter(root, completed_tree=False):
if root is None:
raise StopIteration
current_level = [root]
cur_depth = 0
while current_level:
next_level = []
all_done = True
for node in current_level:
yield (node, cur_depth)
if node is not None:
if completed_tree:
next_level.append(node.left)
next_level.append(node.right)
if node.left is not None or node.right is not None:
all_done = False
else:
if node.left is not None:
all_done = False
next_level.append(node.left)
if node.right is not None:
all_done = False
next_level.append(node.right)
if all_done:
raise StopIteration
current_level = next_level
cur_depth += 1
def create_node(str_node):
if str_node == "#":
return None
return TreeNode(int(str_node))
def loads_level_order(str_tree):
str_nodes = [s.strip() for s in str_tree.strip(" {}[]()").split(",") if s and s.strip()]
length = len(str_nodes)
if length == 0:
return None
root = create_node(str_nodes[0])
index = 1
parents = collections.deque([root])
while index < length:
if len(parents) == 0:
break
cur_parent = parents.popleft()
if cur_parent is None:
continue
left_node = create_node(str_nodes[index])
cur_parent.left = left_node
index += 1
if index >= length:
break
right_node = create_node(str_nodes[index])
cur_parent.right = right_node
index += 1
parents.append(left_node)
parents.append(right_node)
return root
def dumps_level_order(root, order="level"):
output = []
def dump_node(node, cur_depth):
if node is None:
output.append("#")
else:
output.append(str(node.val))
level_order_traversal(root, dump_node, completed_tree=True)
output = ",".join(output).rstrip("#,")
return "{%s}" % output
def bst_insert(node, value, allow_dup=False):
if node is None:
return TreeNode(value)
if not allow_dup and value == node.val:
return node
if value <= node.val:
node.left = bst_insert(node.left, value, allow_dup)
else:
node.right = bst_insert(node.right, value, allow_dup)
return node
def bst_create(values):
tree = None
for v in values:
tree = bst_insert(tree, v)
return tree
|
579b860f8aabf24cf811e9924fafabf5c4786f7f | hannaht0808/ia241 | /lec5.py | 747 | 3.65625 | 4 | """
lec5 if statment
"""
#import this
#print( 1
# + 2)
#print(2,3,4,5,6,7)
# = 1\
# +1
#print(m)
#a = [1,2,3]
#b = [1,2,3]
#print(id([1,2,3]))
#print(id(a))
#print(id(b))
#X = None
#print(id(X))
#print(id(None))
#print(X == None)
#print(X is None)
#y = []
#print(y == None)
#print(y is None)
#print(True and False)
#if 2>1:
# print('2<1')
#if 2<=1:
# print('2<=1')
#print('not in the id block')
#if 2<=1:
# print('2>1')
#else:
# print('2>1')
#if 2<=2:
# print('2<=2')
#else:
# print('2>2')
#if 2<=1:
# print('2<=1')
#elif 2<=2:
# print('2<=2')
#else:
#print('2>1')
if None:
print(1)
elif {}:
print(2)
elif '0':
print(3)
else:
print(4) |
925cbfc44d39e88571bacf1c394ed0bd0655cba8 | geekyarthurs/iws_assignments | /assignment1/q21.py | 179 | 3.5625 | 4 | from typing import List, Tuple
def sorter( items: List[Tuple[int,int]]) -> List[Tuple[int,int]]:
sorted_items = sorted(items,key=lambda x: x[-1])
return sorted_items |
6f93e8b0751f39f9ce4815a95bdc47a0eaac2c0b | mkoundo/Automate_the_Boring_Stuff | /chapter_14_Google_Sheets/convert_sheets.py | 1,301 | 3.890625 | 4 | #! python3
# convert_sheets.py
# Author: Michael Koundouros
"""
You can use Google Sheets to convert a spreadsheet file into other formats. Write a script that passes a submitted
file to upload(). Once the spreadsheet has uploaded to Google Sheets, download it using downloadAsExcel(),
downloadAsODS(), and other such functions to create a copy of the spreadsheet in these other formats.
usage: convert_sheets.py file
"""
import sys
import ezsheets
from pathlib import Path
def convert_xlsx(file):
# Function converts excel spreadsheets to ods, csv, tsv & pdf formats
# formats csv, tsv & pdf are applicable to the first sheet only.
sheet = ezsheets.upload(str(file))
sheet.downloadAsExcel(f'{file.stem}.xlsx')
sheet.downloadAsODS(f'{file.stem}.ods')
sheet.downloadAsCSV(f'{file.stem}.csv')
sheet.downloadAsTSV(f'{file.stem}.tsv')
sheet.downloadAsPDF(f'{file.stem}.pdf')
return
def main():
# Make a list of command line arguments, omitting the [0] element
# which is the script itself.
args = sys.argv[1:]
if len(args) != 1:
print('usage: convert_sheets.py file')
sys.exit(1)
else:
file = Path(args[0])
print(f'Converting file {file}')
convert_xlsx(file)
print('Done!')
if __name__ == '__main__':
main()
|
29b0dd631630e09a068df48b5a3343eee85d0199 | KRHS-GameProgramming-2019/Madlibs---Ryan-Kayde-and-Carter | /Getword.py | 3,667 | 4.03125 | 4 | def getMenuOption(debug = False):
if debug: print("getMenuOption Function")
goodInput = False
while not goodInput:
option = input("Please select an option: ")
option = option.lower()
if (option == "q" or
option == "quit" or
option == "x" or
option == "exit"):
option = "q"
goodInput = True
elif (option == "1" or
option == "one" or
option == "Story1" or
option == "StoryOne" or
option == "Storyone"):
option = "1"
goodInput = True
else:
print("Please make a valid choice")
return option
def getWord(prompt, debug = False):
if debug: print("getWord Function")
goodInput = False
while not goodInput:
word = input(prompt)
goodInput = True
if isSwear(word, debug):
goodInput = False
print ("Don't use language like that")
return word
def getSport(prompt, debug = False):
if debug: print("getSport Function")
goodInput = False
sports = ["soccer",
"football",
"basketball",
"tennis",
"wiffle ball",
"hockey",
"field hockey",
"lacrosse",
"bad minton",
"swimming",
"swim",
"cheerleading",
"boxing",
"chinese wiffle boxing",
"lumberjack",
"hobbyhorsing",
"volleyball",
"tag",
"parkour",
"world chase tag",
"jousting",
"cardboard fighting",
"cardboard tube fighting league",
"horse riding",
"horseback riding",
"bowling",
"track",
"field",
"track and field",
"snowboarding",
"skiing",
"wrestling",
"esports",
]
while not goodInput:
word = input(prompt)
goodInput = True
if isSwear(word, debug):
goodInput = False
print ("Don't use language like that")
elif word.lower() not in sports:
goodInput = False
print ("That's not a sport stupid, try again")
return word
def isSwear(word, debug = False):
if debug: print("isSwear Function")
if word.lower() in swearList:
return True
else:
return False
swearList = ["poop",
"pee",
"sex",
"damn",
"bernie sanders",
"hillary clinton",
"kyle",
"mackenna",
"42",
"shit",
"booty",
"booty hole",
"butt",
"butthole",
]
def getAdjective(prompt, debug = False):
if debug: print("getAdjective Function")
goodInput = False
adjective = ["juicy",
"wet",
"tall",
"short",
"fast",
"slow",
"dry",
"weak",
"strong",
]
while not goodInput:
word = input(prompt)
goodInput = True
if isSwear(word, debug):
goodInput = False
print ("Don't use language like that")
elif word.lower() not in adjective:
goodInput = False
print ("That's not an adjective brother, again")
return word
|
881b0a4eb60f70f5074e6ce623a43547f5ee74b7 | nikervm/Project-Euler | /7.py | 334 | 3.515625 | 4 | def prime(n):
if not n % 2:
return False
if not n % 3:
return False
if not n % 5:
return False
if not n % 7:
return False
i = 7
while i * i <= n:
if not (n % i):
return False
i += 2
return True
n, i, j = 10001, 4, 7
while i != n:
j += 1
if prime(j):
i += 1
print(prime(j))
print(j)
|
bffb55fb50e0e6a7facf4923bd89a003ac97089d | eichitakaya/self_study | /competitive_probramming/AOJ/eratosthenes_sieve.py | 368 | 4.03125 | 4 | import math
def isprime(x):
if x == 2:
return True
if x < 2 or x % 2 == 0:
return False
i = 3
while i <= math.sqrt(x):
if x % i == 0:
return False
i += 2
return True
cnt = 0
n = int(input())
for i in range(n):
x = int(input())
if isprime(x) == True:
cnt += 1
print(cnt) |
53efa14330471445491781a7c9e4ab96869d15ff | WanJunCode/fluent-python | /第五章一等函数/5-1把函数视作对象.py | 218 | 3.765625 | 4 | def factorial(n):
"""return n!"""
return 1 if n<2 else n* factorial(n-1)
print(factorial(42))
print(factorial.__doc__)
print(type(factorial))
fact=factorial
print(type(fact))
print(list(map(fact,range(11)))) |
9eaf03031362818137a631a2e18cd654457407d5 | kprahman/py_book_exercises | /ch20/letter frequency.py | 442 | 3.96875 | 4 | string_mine = "ThiS is String with Upper and lower case Letters"
letter_count = {}
for letter in string_mine.lower():
if letter is not " ":
letter_count[letter] = letter_count.get(letter,0) + 1
letter_table = list(letter_count.items())
letter_table.sort() ##if list did not need to be alphabetized, could just use a for loop on letter_count.items
for i in letter_table:
print("{0} | {1}".format(i[0],i[1]), end = "\n")
|
65f88f0bef291edb3336fffcb6becca8e800b7dc | Halimeda/Python_Pratice | /Exercices/Exo/Bonus/Exo_20.py | 167 | 4.15625 | 4 | word = input("Enter a word : ")
word_list = []
while word != "end":
word_list.insert (0, word)
word = input("Enter a word : ")
for i in word_list:
print(i) |
a5929b0d83b3c6c15471a34b4b2c34861adc7567 | dima2019python/PYTHON_MASTER | /21.py | 181 | 3.828125 | 4 | words = ['мадам', 'самолет', 'madam', 'oko']
palidromes = []
for word in words:
if word == word[::-1]:
palidromes.append(word)
print(palidromes)
|
fc0e3ff46f43aa82dc1885a21b082b3e9fc70edb | wake-up-emily/learn-alg | /counting_sort.py | 697 | 3.6875 | 4 | def counting_sort(a):
# stable sort
# T(n) = θ(k + n)
# need extra memory
# original array a
# counting array c
# sorted array sorted_a
# c.item.key = range(min(a),max(a)+1)
# use c to count how many times each elem shows in a
# c.item.value = count
# put c.item.key in sorted_a c.item.value times
# then do the next one until done
sorted_a = []
c = {}
for k in range(min(a),max(a)+1):
c[k] = 0
for k in a:
c[k] += 1
for k in c:
while c[k] > 0:
sorted_a.append(k)
c[k] -= 1
return sorted_a
if __name__ == '__main__':
a = [3,5,1,4,7]
res = counting_sort(a)
print(res)
|
a1cc6b423a88375ec7426a0fe278d3597c34f4ec | PPL-IIITA/ppl-assignment-dewana-dewan | /part3/question11/FileNotFoundError/helper/weiter.py | 1,762 | 3.515625 | 4 | import datetime
import csv
"""
contains all logger classes
"""
class write_couple:
"""
initializes class that logs couple formation
"""
def __init__(self):
"""
initializes class that logs couples
"""
pass
def log(self, gname, bname, h=None, c=None):
"""
log funciton
opens couples.csv and logs boy name, girlfriend name, couple's happiness and their compatibility
along with a time stamp
"""
with open('./data/couples.csv', 'a') as csvfile:
logger = csv.writer(csvfile)
logger.writerow([datetime.datetime.now().isoformat(), gname, bname, h, c])
class write_gift:
"""
initializes class that logs gifting transactions
"""
def __init__(self):
"""
initializes class that logs all gifting transactions
"""
pass
def log(self, bname, gname, typ, price):
"""
log function
opens gifts_log.csv and logs a gift transactioin between a couple
along with a time stamp
"""
with open('./data/gifts_log.csv', 'a') as csvfile:
logger = csv.writer(csvfile)
strr = (bname + ' gifted ' + gname + ' a gift of type ' + typ + ' worth ' + str(price))
logger.writerow([datetime.datetime.now().isoformat(), strr])
def log_end(self):
"""
extra function that puts and end string after change of couple
along with time stamp
"""
with open('./data/gifts_log.csv', 'a') as csvfile:
logger = csv.writer(csvfile)
strr= '*****************'
logger.writerow([datetime.datetime.now().isoformat(), strr]) |
a550c050546a80b5fa2d014cb3a17dc71268b22f | aporia3517/ml-gtx980 | /mycode/mlp_test_model.py | 10,955 | 3.9375 | 4 | """
This tutorial introduces the multilayer perceptron using Theano.
A multilayer perceptron is a logistic regressor where
instead of feeding the input to the logistic regression you insert a
intermediate layer, called the hidden layer, that has a nonlinear
activation function (usually tanh or sigmoid) . One can use many such
hidden layers making the architecture deep. The tutorial will also tackle
the problem of MNIST digit classification.
.. math::
f(x) = G( b^{(2)} + W^{(2)}( s( b^{(1)} + W^{(1)} x))),
References:
- textbooks: "Pattern Recognition and Machine Learning" -
Christopher M. Bishop, section 5
"""
__docformat__ = 'restructedtext en'
import os
import sys
import time
import numpy,scipy
import cPickle
import theano
import theano.tensor as T
from logistic_sgd import LogisticRegression, load_data
def ReLU(X):
return T.maximum(X, 0.)
def VReLU(X):
return T.floor(T.maximum(X, 0.)*1000)/1000
def Vtanh(X):
return T.floor(T.tanh(X)*100)/100
# start-snippet-1
class HiddenLayer(object):
def __init__(self, rng, input, n_in, n_out, W=None, b=None,
activation=T.tanh):
"""
Typical hidden layer of a MLP: units are fully-connected and have
sigmoidal activation function. Weight matrix W is of shape (n_in,n_out)
and the bias vector b is of shape (n_out,).
NOTE : The nonlinearity used here is tanh
Hidden unit activation is given by: tanh(dot(input,W) + b)
:type rng: numpy.random.RandomState
:param rng: a random number generator used to initialize weights
:type input: theano.tensor.dmatrix
:param input: a symbolic tensor of shape (n_examples, n_in)
:type n_in: int
:param n_in: dimensionality of input
:type n_out: int
:param n_out: number of hidden units
:type activation: theano.Op or function
:param activation: Non linearity to be applied in the hidden
layer
"""
self.input = input
# end-snippet-1
# `W` is initialized with `W_values` which is uniformely sampled
# from sqrt(-6./(n_in+n_hidden)) and sqrt(6./(n_in+n_hidden))
# for tanh activation function
# the output of uniform if converted using asarray to dtype
# theano.config.floatX so that the code is runable on GPU
# Note : optimal initialization of weights is dependent on the
# activation function used (among other things).
# For example, results presented in [Xavier10] suggest that you
# should use 4 times larger initial weights for sigmoid
# compared to tanh
# We have no info for other function, so we use the same as
# tanh.
if W is None:
W_values = numpy.asarray(
rng.uniform(
low=-numpy.sqrt(6. / (n_in + n_out)),
high=numpy.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)
),
dtype=theano.config.floatX
)
if activation == theano.tensor.nnet.sigmoid:
W_values *= 4
W = theano.shared(value=W_values, name='W', borrow=True)
if b is None:
b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
b = theano.shared(value=b_values, name='b', borrow=True)
self.W = W
self.b = b
lin_output = T.dot(input, self.W) + self.b
self.output = (
lin_output if activation is None
else activation(lin_output)
)
# parameters of the model
self.params = [self.W, self.b]
# start-snippet-2
class MLP(object):
"""Multi-Layer Perceptron Class
A multilayer perceptron is a feedforward artificial neural network model
that has one layer or more of hidden units and nonlinear activations.
Intermediate layers usually have as activation function tanh or the
sigmoid function (defined here by a ``HiddenLayer`` class) while the
top layer is a softamx layer (defined here by a ``LogisticRegression``
class).
"""
def __init__(self, rng, input, n_in, n_hidden1, n_out):
"""Initialize the parameters for the multilayer perceptron
:type rng: numpy.random.RandomState
:param rng: a random number generator used to initialize weights
:type input: theano.tensor.TensorType
:param input: symbolic variable that describes the input of the
architecture (one minibatch)
:type n_in: int
:param n_in: number of input units, the dimension of the space in
which the datapoints lie
:type n_hidden1: int
:param n_hidden1: number of hidden units
:type n_out: int
:param n_out: number of output units, the dimension of the space in
which the labels lie
"""
# Since we are dealing with a one hidden layer MLP, this will translate
# into a HiddenLayer with a tanh activation function connected to the
# LogisticRegression layer; the activation function can be replaced by
# sigmoid or any other nonlinear function
self.hiddenLayer = HiddenLayer(
rng=rng,
input=input,
n_in=n_in,
n_out=n_hidden1,
#activation=VReLU
activation=Vtanh
)
# The logistic regression layer gets as input the hidden units
# of the hidden layer
self.logRegressionLayer = LogisticRegression(
input=self.hiddenLayer.output,
n_in=n_hidden1,
n_out=n_out
)
# end-snippet-2 start-snippet-3
# L1 norm ; one regularization option is to enforce L1 norm to
# be small
self.L1 = (
abs(self.hiddenLayer.W).sum()
+ abs(self.logRegressionLayer.W).sum()
)
# square of L2 norm ; one regularization option is to enforce
# square of L2 norm to be small
self.L2_sqr = (
(self.hiddenLayer.W ** 2).sum()
+ (self.logRegressionLayer.W ** 2).sum()
)
# negative log likelihood of the MLP is given by the negative
# log likelihood of the output of the model, computed in the
# logistic regression layer
self.negative_log_likelihood = (
self.logRegressionLayer.negative_log_likelihood
)
# same holds for the function computing the number of errors
self.errors = self.logRegressionLayer.errors
# the parameters of the model are the parameters of the two layer it is
# made out of
self.params = self.hiddenLayer.params + self.logRegressionLayer.params
# end-snippet-3
def test_mlp(learning_rate=0.01, L1_reg=0.00, L2_reg=0.0001, n_epochs=1000,
dataset='mnist.pkl.gz', batch_size=20, n_hidden1=200, seed=1234, model='mlp_mint_AD_tanh_hidden_200.dat'):
"""
Demonstrate stochastic gradient descent optimization for a multilayer
perceptron
This is demonstrated on MNIST.
:type learning_rate: float
:param learning_rate: learning rate used (factor for the stochastic
gradient
:type L1_reg: float
:param L1_reg: L1-norm's weight when added to the cost (see
regularization)
:type L2_reg: float
:param L2_reg: L2-norm's weight when added to the cost (see
regularization)
:type n_epochs: int
:param n_epochs: maximal number of epochs to run the optimizer
:type dataset: string
:param dataset: the path of the MNIST dataset file from
http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz
"""
datasets = load_data(dataset)
test_set_x, test_set_y = datasets[2]
# compute number of minibatches for testing
n_test_batches = test_set_x.get_value(borrow=True).shape[0] / batch_size
######################
# BUILD ACTUAL MODEL #
######################
print '... building the model'
# allocate symbolic variables for the data
index = T.lscalar() # index to a [mini]batch
x = T.matrix('x') # the data is presented as rasterized images
y = T.ivector('y') # the labels are presented as 1D vector of
# [int] labels
rng = numpy.random.RandomState(seed)
# construct the MLP class
classifier = MLP(
rng=rng,
input=x,
n_in=28 * 28,
n_hidden1=n_hidden1,
n_out=10
)
# ww: 4*784*100
ww = []
with open(model, 'r') as f:
for i, param in enumerate(classifier.params):
classifier.params[i].set_value(cPickle.load(f), borrow=True)
with open(model, 'r') as f:
for i, param in enumerate(classifier.params):
ww.append(cPickle.load(f))
print(('weight model is loaded from %s') % model)
# compiling a Theano function that computes the mistakes that are made
# by the model on a minibatch
test_model = theano.function(
inputs=[index],
outputs=classifier.errors(y),
givens={
x: test_set_x[index * batch_size:(index + 1) * batch_size],
y: test_set_y[index * batch_size:(index + 1) * batch_size]
}
)
a0 = test_set_x
a1 = Vtanh(T.dot(test_set_x, ww[0]) + ww[1])
a2 = T.nnet.softmax(T.dot(a1, ww[2]) + ww[3])
ae = a2.eval()
#btl = (T.floor(a0*255)).eval() # 10000*784
btl = a0.eval() # 10000*784
cnt = [] # 256 * 784
for i in numpy.array(range(256))/256.:
cnt.append( (sum( abs(btl - i) < 1./(2*256.) )) )
entropy = [0]*784
total = 10000.0
for j in range(784):
for i in range(256):
p = cnt[i][j]/total
if p>0:
entropy[j] += p * numpy.log2(1/p)
# print(entropy)
print('image: ' + str(sum(entropy)))
#
a1eval = a1.eval() # 10000 * 500
cnt = [] # 201*500
for i in numpy.array(range(-100,101,1))/100.:
cnt.append( sum( abs(a1eval - i) < 0.005 ) )
entropy = [0]*n_hidden1
total = 10000.0
for j in range(n_hidden1):
for i in range(201):
p = cnt[i][j]/total
if p>0:
entropy[j] += p * numpy.log2(1/p)
# print(entropy)
print('hidden layer: ' + str(sum(entropy)))
print( (1./10 * numpy.log2(10) + 9./10 * numpy.log2(10./9)) * 10 )
# hidden: 500
#1310.49424538
#3158.53113109
#4.68995593589
# 1.66% (1.65%)
# hidden: 100
#1310.49424538
#673.790681677
#4.68995593589
# 2.01% (2.00%)
'''
print(ae[0])
print(test_set_y[0].eval())
print(a1[0].eval())
'''
# test it on the test set
test_losses = [test_model(i) for i in xrange(n_test_batches)]
test_score = numpy.mean(test_losses)
print(('test error of best model %f %%') % (test_score * 100.))
if __name__ == '__main__':
test_mlp()
|
59489ea8d13204aa7e52d99587ccccb79537aae3 | Rlogarisation/NihaoPython | /lab03/lab03_timetable/timetable.py | 1,027 | 4.28125 | 4 | from datetime import date, time, datetime
def timetable(dates, times):
'''
Generates a list of datetimes given a list of dates and a list of times.
All possible combinations of date and time are contained within the result.
The result is sorted in chronological order.
For example,
>>> timetable([date(2019,9,27), date(2019,9,30)], [time(14,10), time(10,30)])
[datetime(2019,9,27,10,30), datetime(2019,9,27,14,10), datetime(2019,9,30,10,30), datetime(2019,9,30,14,10)]
'''
"""
result = []
dates = sorted(dates)
times = sorted(times)
i = 0
while (i < len(dates)):
j = 0
while (j < len(times)):
result.append(datetime(dates[i].year, dates[i].month, dates[i].day,times[j].hour,times[j].minute))
j += 1
i += 1
return result
"""
result = []
for d in dates:
for t in times:
result.append(datetime(d.year, d.month, d.day, t.hour, t.minute, t.second))
result.sort()
return result
|
105993b9b2d12c1f916c478bc0277dd04e5858ed | entirelymagic/Link_Academy | /fundamentals/ppf-ex06/solution/triangle.py | 107 | 3.609375 | 4 | H = 10
a = 1
for i in range(H):
for j in range(a):
print("*", end="")
a += 1
print("")
|
94d218e9ebc6ba114bfc086702d07e7ccbeefe69 | semmani/Lecture2A | /6FEB2020.py | 5,373 | 3.65625 | 4 |
import mysql.connector as lib
class Customer:
def __init__(self,mode):
if mode == 1:
self.pid = 0
self.name = input("ENTER CUSTOMER NAME: ")
self.phone = input("ENTER CUSTOMER PHONE NUMBER:")
self.email = input("ENTER CUSTOMER EMAIL:")
elif mode == 2:
self.pid = int(input("ENTER CUSTOMER ID: ")) #id is changed into the integer value and then saved in pid
self.name = input("ENTER CUSTOMER NAME: ")
self.phone = input("ENTER CUSTOMER PHONE NUMBER:")
self.email = input("ENTER CUSTOMER EMAIL:")
else:
pass
def showCustomerDetails(self):
print("ID:{}, NAME:{}, PHONE:{}, EMAIL:{}".format(self.pid,self.name,self.phone,self.email))
def executeSqlQuery(sql):
con = lib.connect(user= "root",password="",database = "manmeetdb", host="127.0.0.1", port="3306")
print("CONNECTION CREATED")
cursor = con.cursor()
cursor.execute(sql)
con.commit()
repeat = "yes"
while repeat == "yes":
print("=====~Welcome to Customer Management System~=====")
print("1. Register new customer")
print("2. Update Existing customer")
print("3. Delete Existing customer")
print("4. View all Customer")
print("5. View all Customer by ID")
print("6. View Customer BY Phone")
choice = int(input("Enter your Choice: "))
if choice == 1: #if choice is 1 then it directs to the mode == 1 i.e asks to insert the customer data
customer = Customer(1)
customer.showCustomerDetails()
save = input("Would you like to Save the Customer?(yes/no): ")
if save == "yes":
sql = "insert into Customer values(null,'{}','{}','{}')".format(customer.name, customer.phone, customer.email)
executeSqlQuery(sql)
print("CUSTOMER SAVED->")
elif choice == 2:
customer = Customer(2)
customer.showCustomerDetails()
save = input("Would you like to Update the Customer Details?(yes/no): ")
if save == "yes":
sql = "update Customer set name = '{}',phone = '{}',email='{}'".format(customer.name, customer.phone, customer.email)
executeSqlQuery(sql)
print("---------CUSTOMER UPDATED->")
elif choice == 3: # to delete the customer of provided id
idd = int(input("Enter the id to delete: "))
delete = input("Would you like to delete the Customer?(yes/no): ")
if delete == "yes":
sql = "delete from Customer where id = {}".format(idd) #alterntve way of writing-(id)
con = lib.connect(user="root", password="", database="manmeetdb", host="127.0.0.1", port="3306")
cursor = con.cursor()
rows = cursor.fetchall()
for row in rows:
customer = Customer(3)
customer.id = row[0]
if customer.id == idd:
cursor.execute(sql)
else:
print("Reccord for {} Dont Exist".format(idd))
elif choice == 4:
sql = "select * from Customer"
con = lib.connect(user="root", password="", database="manmeetdb", host="127.0.0.1", port="3306")
cursor = con.cursor()
cursor.execute(sql)
# todisplay all the data we save the data from the file into the variable and then display column wise
rows = cursor.fetchall() # this fetches all data in the format of rows
for row in rows:
customer = Customer(3)
customer.id = row[0] # as data is stored in the form of rows separated with commas
customer.name = row[1]
customer.phone = row[2]
customer.email = row[3]
print(row) #prints all the rows
#customer.showCustomerDetails()
elif choice == 5: #to search with given id
id = int(input("Enter the id to be searched: "))
sql = "select * from Customer where id = {}".format(id)
con = lib.connect(user="root", password="", database="manmeetdb", host="127.0.0.1", port="3306")
cursor = con.cursor()
cursor.execute(sql)
# todisplay all the data we save the data from the file into the variable and then display column wise
row = cursor.fetchone() # this fetches a row in the format of row
if row is not None:
print(row) # prints the row if data exists
else:
print("Record for id {} dont Exist".format(id))
elif choice == 6: #record to be searched using phone number
phone = input("Enter phone no of Customer to be searched: ")
sql = " select * from Customer where phone= '{}'".format(phone)
con = lib.connect(user="root", password="", database="manmeetdb", host="127.0.0.1", port="3306")
cursor = con.cursor()
cursor.execute(sql)
row = cursor.fetchone()
if row is not None:
print(row)
else:
print("Cusomter with phone number {} Not found".format(phone))
else:
print("Enter a Valid Choice>>")
repeat = print("Would You like to Re-use this App(yes/no)?: ")
|
5dbe40305a3e94daaf004b2143e67c3b795f55c6 | MichelleMiGG/CVMundo2 | /exercício40.py | 355 | 3.96875 | 4 | # aluno aprovado ou reprovado
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1 + n2) / 2
print(f'Sua primeira nota foi {n1} sua segunda nota foi {n2} média foi {media}')
if media < 5.0:
print('Reprovado')
elif media >= 5.0 and media <= 6.9:
print('Recuperação')
else:
print('Aprovado')
|
28d351c49073f54d06764b4a8163b93f91420cf2 | ToddDiFronzo/Data-Structures | /singly_linked_list/singly_linked_list.py | 6,296 | 4.28125 | 4 | class Node:
def __init__(self, value=None, next_node=None):
# the value at his linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
# add get method
def get_value(self):
return self.value
# get next node
def get_next(self):
return self.next_node
# set next node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:
def __init__(self):
# reference to head of list
self.head = None
# reference to tail of list
self.tail = None
def __str__(self):
output = ''
current_node = self.head
while current_node is not None:
output += f'{current_node.value} --> '
current_node = current_node.next_node
return output
def add_to_head(self, value):
# create new node
new_node = Node(value, None)
# check if list is empty
if not self.head:
self.head = new_node
self.tail = new_node
else:
new_node.set_next = self.head
self.head = new_node
def add_to_tail(self, value):
# 1. create the Node from the value
new_node = Node(value, None)
# These three steps assume that the tail is already referring to a node (so wont work in all cases if it is not)
# So what do we do if tail is equal to None?
# What is rule we want to set to indicate the linked list is empty?
# Would it be better to check head? well lets just check them both to see if no head or tail
if not self.head:
# in a one element linked list, what should head and tail be pointing to?
# have both head and tail referring to the single node
self.head = new_node
# if no tail, set the new node to be the tail
self.tail = new_node
else:
# 2. set the old tail's 'next' to refer to the new Node
self.tail.set_next(new_node)
# 3. reassign self.tail to refer to the new Node
self.tail = new_node
# let's remove from the head
def remove_head(self):
# if we have an empty linked list
if not self.head:
return None
# what if only 1 element in the linked list?
# so both head and tail are pointing at the same node
if not self.head.get_next():
head = self.head
# delete the linked list's head reference
self.head = None
# also delete the linked list tail reference
self.tail = None
return head.get_value()
value = self.head.get_value()
# set self.head to the node after the head
self.head = self.head.get_next()
return value
# lets remove from the tail
def remove_tail(self):
# if we have an empty linked list
if not self.head:
return None
if self.head is self.tail:
value = self.head.get_value()
self.head = None
self.tail = None
return value
# if we have a non-empty linked list(ll) then:
# a. set the tail to be None
# b. move self.tail to the Node before it
# we cant just - 1 since it does not know what points to it
# we have to start at the head and move down the linked list
# until we get to the node right before the tail
# We need to iterate over our linked list
# We generally will use a While loop
current = self.head
while current.get_next() is not self.tail:
current = current.get_next()
# at this point, current is the node right before the tail
# so set tail to None
value = self.tail.get_value()
# self.tail = None # technically dont need this step since we are going to make self.tail = current; so can remove
# move self.tail to the Node right before
self.tail = current
return value
def contains(self, value):
if not self.head:
return False
# recursive solution
# def search(node):
# if node.get_value() == value:
# return True
# if not node.get_next():
# return False
# return search(node.get_next())
# return search(self.head)
# # reference to node we are at; update as we go
current = self.head
# check if we are at a valid node
while current:
# return True if current value we are looking for
if current.get_value() == value:
return True
# update current node to current node's next node
current = current.get_next()
# if here, target not in list
return False
def get_max(self):
if not self.head:
return None
# reference to the largest value we've seen so far
max_value = self.head.value
# reference to our current node as we traverse the list
current = self.head.get_next()
# check to see if still at a valid node
while current:
# check to see if the current value is > than max
if current.get_value() > max_value:
# if so, update our max_value variable
max_value = current.get_value()
# update the current node to the next node
current = current.get_next()
return max_value
# def get_max(self):
# if not self.head:
# return None
# current = self.head
# max_val = self.head.value
# while current:
# if current.value > max_val:
# max_val = current.value
# current = current.next_node
# return max_val
def printList(self):
temp = self.head
while(temp):
print(temp.value)
temp = temp.next_node
def llprint(self):
printval = self.head
while printval is not None:
print(printval.value)
printval = printval.next
|
b0de2d5813ecb4861c8044fd8955aad8338db331 | FaheemSajjad-dev/Python_small_projs | /python projects/Password generator/pass gen.py | 549 | 3.9375 | 4 | import random
rand_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!@#$%^&*()_+,./<>?;:-=:\|[]"
while 1: # 1 means true
pass_length = int(input("What should be the length of password: "))
pass_count = int(input("How many passwords should be generated: ")) # in one shot
for x in range(0,pass_count):
password = ""
for x in range(0,pass_length):
pass_char = random.choice(rand_chars)
password = password + pass_char
print(password)
|
f86994206505d450fc04f30cc78ebd714090cf90 | venkatesh897/miscellaneous_python_programs | /converting_image_to_grayscale.py | 463 | 3.625 | 4 | import PIL
from PIL import Image
def grayscale(picture):
res=PIL.Image.new(picture.mode, picture.size)
width, height = picture.size
for i in range(0, width):
for j in range(0, height):
pixel=picture.getpixel((i,j))
avg=int((pixel[0]+pixel[1]+pixel[2])/3)
res.putpixel((i,j),(avg,avg,avg))
res.show()
image_fp = r'Screenshot-from-2018-10-16-09-31-31.png'
image = Image.open(image_fp)
grayscale(image)
|
884f50b3e36febba49de86b87b4cdf25384b489a | seymakara/CTCI | /04TreesAndGraphs/LCinvertTree.py | 417 | 4.03125 | 4 | # Invert a binary tree.
# Example:
# Input:
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
# Output:
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
class Solution(object):
def invertTree(self, root):
if root == None:
return None
temp = root.left
root.left = self.invertTree(root.right)
root.right = self.invertTree(temp)
return root |
c5c863c7ff84f18c690b4b174cbf8bef05aaa33e | Tsumida/dsalgo | /src/leetcode/sword offer/15.py | 590 | 3.5625 | 4 | class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
assert n > 0 # 负数会导致死循环,要注意逻辑右移和算术右移
while n > 0:
if n % 2 == 1:
res += 1
n = n >> 1
#print(res)
return res
s = Solution()
assert 0 == s.hammingWeight(n=0)
assert 1 == s.hammingWeight(n=1)
assert 2 == s.hammingWeight(n=3)
assert 3 == s.hammingWeight(n=7)
assert 1 == s.hammingWeight(n=16)
assert 1 == s.hammingWeight(n=1 << 10)
assert 10 == s.hammingWeight(n=1023)
assert 3 == s.hammingWeight(n=56)
|
0b0bfb5ec453ef9620824f80d9212e43e48c8a2b | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/nth-prime/ab011fc8b46a40fb865fa41ffe05364a.py | 391 | 3.9375 | 4 | from random import randint
primes = [2, 3]
def isprime(n):
prime = False
for i in range(3):
b = randint(1, n-1)**(n-1)
if b%n == 1:
prime = True
return prime
def nth_prime(n):
test = primes[-1]
while n>len(primes):
test+=2
if isprime(test):
primes.append(test)
return primes[n-1]
|
54757f9a69bad08d92c5de636c7c18f779fbac93 | tommyshere/ctci | /1-2_permutation.py | 828 | 3.75 | 4 | # Given two strings,
# write a method to decide if one is a permutation of the other.
from collections import Counter
class Solution(object):
def check_permutation():
s1 = "ab"
s2 = "eidbaooo"
# the sliding window
# check a splice of the longer text
# can assume s2 will always be longer than s1
shorter = len(s1)
longer = len(s2)
short_counter = Counter(s1)
for i in range(longer - shorter + 1):
window = s2[i:i+shorter]
# check if the count of letters in window
# match up to count of letters in s1
longer_counter = Counter(window)
if short_counter == longer_counter:
return True
return False
if __name__ == "__main__":
print(Solution.check_permutation())
|
9b83b7703c8ed50e18a6b672e1fb00cae557fa77 | valdinei-mello/python | /herança.py | 4,178 | 4.125 | 4 | """
POO - Herança ( Inheritance)
A ideia de herança é a de reaproveitar codigo. Tambme extender nossas classes.
OBS: Com a herança, apartir de uma classe existente, nós extendemos outra classe que passa
a herdar atributos e metodos da classe herdada.
Cliente:
-nome;
-sobrenome;
-cpf;
renda;
Funcionario:
-nome;
-sobrenome;
-cpf;
matricula;
================================================================
PERGUNTAR: Existe alguma entidade generica o suficiente para
encapsular os atributos e metodos comuns a outras entidades ?
class Cliente:
def __init__(self, nome, sobrenome, cpf, renda):
self.__nome = nome
self.__sobrenome = sobrenome
self.__cpf = cpf
self.__renda = renda
def nome_completo(self):
return f'{self.__nome} {self.__sobrenome}'
class Fucionario:
def __init__(self, nome, sobrenome, cpf, matricula):
self.__nome = nome
self.__sobrenome = sobrenome
self.__cpf = cpf
self.__matriucla = matricula
def nome_completo(self):
return f'{self.__nome} {self.__sobrenome}'
cliente1 = Cliente('valdinei', 'mello', '321.321.654-90', 5000.00)
print(cliente1.nome_completo())
funcionario1 = Fucionario('jorge', 'garcia', '321.147.582-58', 002864j)
print(funcionario1.nome_completo())
OBS: Quando uma classe herda de outra classe ela herda todos os atributos e métodos da classe herdada.
Quando uma classe herda de outra classe a classe herdada é conhecida por:
[Pessoa]
-SuperClasse;
-Classe mãe;
-Classe pai;
-Classe base;
-Classe generica;
Quando uma classe herda de outra classe ela é chamada :
[Cliente, Funcionario]
-Sub classe;
-Classe filha;
-Classe especifica;
=================================================
class Pessoa:
def __init__(self, nome, sobrenome, cpf):
self.__nome = nome
self.__sobrenome = sobrenome
self.__cpf = cpf
def nome_completo(self):
return f'{self.__nome} {self.__sobrenome}'
class Cliente(Pessoa):
# Cliente herda Pessoa
def __init__(self, nome, sobrenome, cpf, renda):
Pessoa.__init__(self, nome, sobrenome, cpf) # Não é uma forma comun de se fazer a declaração de herança
self.__renda = renda
class Fucionario(Pessoa):
# Funcionario herda Pessoa
def __init__(self, nome, sobrenome, cpf, matricula):
super().__init__(nome, sobrenome, cpf) # Forma correta de se fazer a declaração de herança
self.__matriucla = matricula
cliente1 = Cliente('valdinei', 'mello', '321.321.654-90', 5000.00)
print(cliente1.nome_completo())
funcionario1 = Fucionario('jorge', 'garcia', '321.147.582-58', 002864j)
print(funcionario1.nome_completo())
print(funcionario1.__dict__)
print(cliente1.__dict__)
====================================================================================
# Sobrescrita de métodos (Overriding)
Ocorre quando sobrescrevemos/reiplementamos um método presente na super classe em classes filhas.
"""
class Pessoa:
def __init__(self, nome, sobrenome, cpf):
self.__nome = nome
self.__sobrenome = sobrenome
self.__cpf = cpf
def nome_completo(self):
return f'{self.__nome} {self.__sobrenome}'
class Cliente(Pessoa):
"""Cliente herda Pessoa"""
def __init__(self, nome, sobrenome, cpf, renda):
Pessoa.__init__(self, nome, sobrenome, cpf) # Não é uma forma comun de se fazer a declaração de herança
self.__renda = renda
class Fucionario(Pessoa):
"""Funcionario herda Pessoa"""
def __init__(self, nome, sobrenome, cpf, matricula):
super().__init__(nome, sobrenome, cpf) # Forma correta de se fazer a declaração de herança
self.__matriucla = matricula
def nome_completo(self):
print(super().nome_completo())
print(self._Pessoa__cpf)
return f'{self.__matriucla} {self._Pessoa__nome}'
cliente1 = Cliente('valdinei', 'mello', '321.321.654-90', 5000.00)
funcionario1 = Fucionario('jorge', 'garcia', '321.147.582-58', 002864j)
print(cliente1.nome_completo())
print(funcionario1.nome_completo())
|
18caf9446a4eddc22887e696806f9fa6bca13623 | sangam92/https---github.com-sangam92-data_structure | /regular_expression.py | 435 | 3.765625 | 4 | """
10. Regular Expression Matching
"""
def all_check(s):
for i in s:
if i == '*':
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if len(s) < 0 or len(s) > 20:
return 'false'
if len(p) < 0 or len(p) > 30:
return 'false'
if s.isupper:
return 'false'
if p.isupper:
return 'false'
for i in p:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.