blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
e4ad940ac568588877d05f12ff2013d0ea5f2aa4
|
DineshBE/fjod7ofofk
|
/d2.2.py
| 79 | 3.859375 | 4 |
x=list(input())
y=list(reversed(x))
if(x==y):
print('yes')
else:
print('no')
|
d9d29e3ad76408f866807dab2b6615638fa37ba7
|
MrHamdulay/csc3-capstone
|
/examples/data/Assignment_6/kndsit001/question4.py
| 573 | 3.90625 | 4 |
"""Program to categorize marks
Sithasibanzi Kondleka
24 April 2014"""
marks = input("Enter a space-separated list of marks:\n")
mark = marks.split(" ")
#print(mark)
#assigning variables to print the axes
a = "1 |"
b = "2+|"
c = "2-|"
d = "3 |"
e = "F |"
for i in mark: #categorizing the marks
if eval(i)>=75:
a = a + "X"
elif eval(i)>=70:
b = b + "X"
elif eval(i)>=60:
c = c + "X"
elif eval(i)>=50:
d = d + "X"
elif eval(i)<50:
e = e + "X"
print(a)
print(b)
print(c)
print(d)
print(e)
|
dc2985cf1f2aa7f175e02fb4a1da1c2ef33dd3a9
|
omarbagna/firstPyhtonRepo
|
/paulTask.py
| 1,796 | 4.21875 | 4 |
#Defining a function to calculate the range of values.
def calcValues(low_num,upper_num,choice):
evenlist = []#Defining an even list array to hold even numbers
oddlist = []#Defining an odd list array to hold odd numbers
#statement outputs a list of even numbers or odd numbers within the range depending on what the user chooses.
for value in range(low_num,upper_num):
if(value%2==0):
evenlist.append(value)
else:
oddlist.append(value)
if choice == 'E':
print(evenlist)
elif choice == 'O':
print(oddlist)
else:
print('Invalid')
def UserInput(): # Defining a user input function.
while True: #Exception handling
try:
Lower_limit=int(input("Enter the first number for range: ")) #Allows user to input a value for lower limit
except ValueError:
print('Sorry I did not understand that')
continue
else:
break
while True:
try:
Upper_limit=int(input("Enter the second number for range: ")) #Allows user to input a value for an upper limit
except ValueError:
print('Sorry I did not understand that')
continue
else:
break
userchoice = str(input('Do you want to display even(E) or odd(O)? ')) #Allows a user to make a choice: (E) or (O)
return calcValues(Lower_limit,Upper_limit,userchoice.upper())
UserInput() #Calls the userInput function
tryAgain = str(input('Do you want to run this again? Y/N: '))
while tryAgain.upper() == 'Y':
UserInput()
tryAgain = str(input('Do you want to run this again? Y/N: '))
else:
if tryAgain.upper() == 'N':
print('Thank You for using the program')
else:
print('Invalid Input')
|
4048c025d607ffac7fd2675d8b02733d8a8bdbf1
|
yipjoe/quiz
|
/quiz.py
| 215 | 3.53125 | 4 |
import json
print("Hello World")
with open('part2.json') as json_file:
data = json.load(json_file)
for p in data['quiz']:
print('Question Number' + " : " + p['question_no'])
print(p['question'])
print('')
|
4b139af0f980350718e06b2cabe8ded3da7d3a0c
|
WaleedRanaC/Prog-Fund-1
|
/Lab 7/RandomNumbers.py
| 362 | 3.59375 | 4 |
import random
#constants
ROWS=3
COLS=4
def main():
#create a 2-d list
values=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
#fill w/ random numbers
for r in range(ROWS):
for c in range(COLS):
values[r][c]=random.randint(1,100)
#display list
print(values,'\n')
#call main
main()
|
1a06669af32d0eb75659ab44117a984efbc758da
|
satya-sudo/Cses
|
/pemutation.py
| 269 | 3.921875 | 4 |
if __name__ == '__main__':
n = int(input())
if (n != 3 and n != 2):
for i in range(n-1,0,-2):
print(i,end=" ")
for j in range(n,0,-2):
print(j,end=" ")
print()
else:
print("NO SOLUTION")
|
f5a51d39a9d206bfed6bb8714202c04b8b14edd7
|
Axect/PL2020
|
/07_root/main.py
| 607 | 3.828125 | 4 |
from bisect_method import bisect, log
import numpy as np
import matplotlib.pyplot as plt
# Root
root1 = bisect(lambda x: 2**x - 2 - x, 0, 10)
root2 = bisect(lambda x: x - log(x+2, 2), 0, 10)
root3 = bisect(lambda x: 2**x - 2 - log(x+2, 2), 0, 10)
print(root1)
print(root2)
print(root3)
# Plot
x = np.arange(-1, 4, 0.01)
y1 = np.power(2, x) - 2
y2 = np.log2(x+2)
y3 = x
plt.figure(figsize=(10,6), dpi=300)
plt.title("Graph for exp, log")
plt.plot(x, y1, label="Exp")
plt.plot(x, y2, label="Log")
plt.plot(x, y3, label="x")
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
plt.grid()
plt.savefig("graph.png")
|
959e7972d5908e8d2e089b5146771074fe34563f
|
rack-leen/python-tutorial-notes
|
/chapter5_data_structures/set_example.py
| 622 | 3.859375 | 4 |
#!/usr/bin/env python
# coding=utf-8
'''
sets集合
'''
basket = {'apple','orange','apple','pear','orange','banana'} #用{}创建sets
print(basket)#不重复输出元素
#判断sets中的value是否在字典中
a = 'orange' in basket
print(a)
b = 'cranfg' in basket
print(b)
#对两个单词的操作
a = set('abracadabra')
b = set('alacazam')
print(a) #不重复输出a中的字母
c = a - b #相减
print(c)
d = a | b #或
print(d)
e= a ^ b #取反
print(e)
f = a & b #取并集
print(f)
#用列表生成式
g = {x for x in 'abracadabra' if x not in 'abc'} #输出不在abc范围中的字符串中的字母
print(g)
|
b6c055acf874acf5f40bb64c58740e9594c8413b
|
EricMontague/Leetcode-Solutions
|
/medium/problem_131_palindrome_partitioning.py
| 2,692 | 3.625 | 4 |
"""This file contains my solutions to Leetcode problem 131."""
class Solution:
def partition(self, string: str) -> List[List[str]]:
if not string:
return [""]
palindrome_partitions = []
current_partition = []
self.generate_partitions(
string,
0,
current_partition,
palindrome_partitions
)
return palindrome_partitions
def generate_partitions(self, string, start, current, partitions):
if start == len(string):
partitions.append(current.copy())
else:
for end in range(start, len(string)):
if self.is_palindrome(string, start, end):
current.append(string[start: end + 1])
self.generate_partitions(
string,
end + 1,
current,
partitions
)
current.pop()
def is_palindrome(self, string, start, end):
while start < end:
if string[start] != string[end]:
return False
start += 1
end -= 1
return True
class Solution:
def partition(self, string: str) -> List[List[str]]:
if not string:
return [""]
is_palindrome = [
[False for j in range(len(string))]
for i in range(len(string))
]
palindrome_partitions = []
current_partition = []
self.generate_partitions(
string, 0, current_partition, palindrome_partitions, is_palindrome
)
return palindrome_partitions
def generate_partitions(
self, string, start, current, partitions, is_palindrome
):
if start == len(string):
partitions.append(current.copy())
else:
for end in range(start, len(string)):
self.update_is_palindrome(is_palindrome, string, start, end)
if is_palindrome[start][end]:
current.append(string[start: end + 1])
self.generate_partitions(
string,
end + 1,
current,
partitions,
is_palindrome
)
current.pop()
def update_is_palindrome(self, is_palindrome, string, start, end):
if (
string[start] == string[end]
and (end - start <= 2 or is_palindrome[start + 1][end - 1])
):
is_palindrome[start][end] = True
|
a99a3a05c9a8b643ae8e71dafcc71c5a94840efa
|
nkukarl/myCoffeeProj
|
/test.py
| 314 | 3.984375 | 4 |
def fibo(n):
"""
Args:
n: positive integer
Returns:
nth fibo number
"""
if n == 1 or n == 2:
return 1
a, b = 1, 1
while n - 2:
a, b = b, a + b
n -= 1
return b
if __name__ == "__main__":
for i in range(1, 10):
print i, fibo(i)
|
3741cc0fb62a921e2ceecc1d2dfafafc01552235
|
ShenTonyM/LeetCode-Learn
|
/Q189RotateArray.py
| 1,130 | 4.03125 | 4 |
# class Solution1:
# def rotate(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: void Do not return anything, modify nums in-place instead.
# """
#
# length = len(nums)
#
# new_nums = [0 for x in range(length)]
# for old_index in range(length):
# new_index = (old_index + k) % length
# new_nums[new_index] = nums[old_index]
#
# for i in range(length):
# nums[i] = new_nums[i]
# 三次翻转
class Solution2:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k = k % length
self.reverse(nums, 0, length)
self.reverse(nums, 0, k)
self.reverse(nums, k, length)
def reverse(self,nums, start, end):
while start < end:
nums[start],nums[end-1] = nums[end-1], nums[start]
start += 1
end -= 1
if __name__ == '__main__':
Solution2().rotate([1,2,3,4,5,6,7],3)
|
fa5541a2f4993b1dc264deab7cdc4e150eed21bf
|
lwesterl/Level-Jump-Game
|
/game_files/config.py
| 13,962 | 3.578125 | 4 |
import os
class Config():
# class variables, these are read from config file
# other classes use these (below are the standard values)
# this means that in the main Config object needs to be created first and read_config method called
# when Config object is created
level_number = 0 # this is used to name new levels (see leveleditor)
distance_x = 50
distance_right_limit = 50
empty_line_height = 10
static_object_height = 20
static_object_width = 20
enemy_height = 10
enemy_width = 10
player_height = 19
player_width = 15
player_speed = 5
player_jump_x = 2
player_jump_y = 5
player_jump_max_height = 60
player_fall_y = 2
player_fall_x = player_jump_x
enemy_speed = 1
enemy_fall_y = 10
invisible_object_height = 5
def __init__(self):
self.config_return_value = self.read_config() #when config object is created, it reads config file
def read_config(self):
#NOTICE: The dir containing the config file needs to be named as game_config
# config file needs to be named as config.txt
# config file must have a specific format, otherwise it content is ignored
# Returns: 0,1 or 2, this return value affects how the main continues, it's stored in self.config_return_value
# 0 means a fatal error in reading the config file
# 1 config file ok
# 2 smt incorrect in the config, partially using standard set values
#However notice that this method does not check are values really functioning (ie. if speed values are too big objects can't move)
path = os.getcwd() #get the current working dir
try:
os.chdir('game_config') #change to the folder where config.txt should be located
file = open('config.txt', 'r') #This should work with every os
current_line = file.readline()#read the first line
static_object_height = 0
static_object_width = 0
width_counter = 0 #these are used to detect duplicates in static_object width and height
height_counter = 0
level_number = False # bool for determining if the file contains level_number
smt_wrong = False
while current_line:
#loop until an EOF char is found
if current_line[0] != '%':
#a line is not starting with comment symbol, so it is not skipped
line = current_line.split() #skip whitespace
if len(line) != 0:
#skip lines that contain only whitespace
actual_line = ''
for i in range (len(line)):
actual_line += line[i] #construct a whitespace free line
line_content = actual_line.split(':') # : is the content separator in the config
if len(line_content) == 2:
#the line should now contain only one parameter and a set value for it
# else we just read a new line
#now line_content[0] should contain a parameter
if line_content[0] == 'level_number':
if self.check_values(line_content[1],1000,0,'int'):
Config.level_number = int(line_content[1]) #number was ok, but this can't check if it's correct
# it is strongly advised not to change level_number from config file, wrong number will probably resort to a non-working game
level_number = True
elif line_content[0] == 'distance_x':
if self.check_values(line_content[1],500,0,'int'):
Config.distance_x = int(line_content[1])
elif line_content[0] == 'distance_right_limit':
if self.check_values(line_content[1],200,0,'int'):
Config.distance_right_limit = int(line_content[1])
elif line_content[0] == 'empty_line_height':
if self.check_values(line_content[1],70,0,'int'):
Config.empty_line_height = int(line_content[1])
elif line_content[0] == 'static_object_height':
height_counter += 1 #update counter
if self.check_values(line_content[1],500,1,'int'):
Config.static_object_height = int(line_content[1])
static_object_height = Config.static_object_height #this is just for detecting that player and enemy's heights are correct
elif line_content[0] == 'static_object_width':
width_counter += 1 #update counter
if self.check_values(line_content[1],500,1,'int'):
Config.static_object_width = int(line_content[1])
static_object_width = Config.static_object_width # same use purpose as static_object_height
elif line_content[0] == 'enemy_height':
if self.check_values(line_content[1],static_object_height -1,0,'int'):
Config.enemy_height = int(line_content[1])
else:
#enemy height is not correct in relation to static_object
smt_wrong = True
elif line_content[0] == 'enemy_width':
if self.check_values(line_content[1],static_object_width,0,'int'):
Config.enemy_width = int(line_content[1])
else:
#enemy width is not correct in relation to static_object
smt_wrong = True
elif line_content[0] == 'player_height':
if self.check_values(line_content[1],static_object_height -1 ,0,'int'):
Config.player_height = int(line_content[1])
else:
#player height is not correct in relation to static_object
smt_wrong = True
elif line_content[0] == 'player_width':
if self.check_values(line_content[1],static_object_width,0,'int'):
Config.player_width = int(line_content[1])
else:
#player width is not correct in relation to static_object
smt_wrong = True
elif line_content[0] == 'player_speed':
if self.check_values(line_content[1],100,0,'float'):
Config.player_speed = float(line_content[1])
elif line_content[0] == 'player_jump_x':
if self.check_values(line_content[1],50,0,'float'):
Config.player_jump_x = float(line_content[1])
elif line_content[0] == 'player_jump_y':
if self.check_values(line_content[1],static_object_height,1,'int'):
Config.player_jump_y = int(line_content[1])
else:
#the jump value is incorrect
smt_wrong = True
elif line_content[0] == 'player_jump_max_height':
if self.check_values(line_content[1],1000,0,'int'):
Config.player_jump_max_height = int(line_content[1])
elif line_content[0] == 'player_fall_y':
if self.check_values(line_content[1],static_object_height,1,'int'):
Config.player_fall_y = int(line_content[1])
else:
#the fall value is incorrect
smt_wrong = True
elif line_content[0] == 'player_fall_x':
if self.check_values(line_content[1],50,0,'float'):
Config.player_fall_x = float(line_content[1])
elif line_content[0] == 'enemy_speed':
if self.check_values(line_content[1],100,0,'float'):
Config.enemy_speed = float(line_content[1])
elif line_content[0] == 'enemy_fall_y':
if self.check_values(line_content[1],static_object_height,1,'int'):
Config.enemy_fall_y = int(line_content[1])
else:
#the fall value is incorrect
smt_wrong = True
elif line_content[0] == 'invisible_object_height':
if self.check_values(line_content[1],static_object_height,0,'int'):
Config.invisible_object_height = int(line_content[1])
else:
#the invisible_object_height is incorrect'
smt_wrong = True
current_line = file.readline() #this is inside the loop, when the line content is checked, read a new line
os.chdir(path) #after the loop, change dir to the current working dir
file.close() #reading the file has reached end, close the file
if Config.static_object_height <= Config.player_height or Config.static_object_height <= Config.enemy_height \
or Config.static_object_width < Config.player_width or Config.static_object_height < Config.enemy_width:
#user has set only static object width or height value and those values are incorrect
#this is added later (after minor errors emerged in the final test of this game) and this makes those earlier smt_wrong check partially unnecessary
smt_wrong = True
if not level_number:
return 0 #the file is fatally malformed
elif smt_wrong or width_counter > 1 or height_counter > 1:
#if static_object width or height is > 1, there is duplicates (which are not allowed)
# Object height and width values or jump/fall values may be incorrect, use standard values
Config.static_object_height = 20
Config.static_object_width = 20
Config.enemy_height = 10
Config.enemy_width = 10
Config.player_height = 19
Config.player_width = 15
Config.player_jump_x = 2
Config.player_jump_y = 5
Config.player_jump_max_height = 60
Config.player_fall_y = 2
Config.player_fall_x = Config.player_jump_x
Config.enemy_fall_y = 10
Config.invisible_object_height = 5
return 2
return 1 #everything went fine
except FileNotFoundError:
#a major error occurred
os.chdir(path) #change dir to the current working dir
return 0
def check_values (self,value,max_value, min_value, value_type):
# A help method used by read_config
# Checks if values are correct, returns True or False
# value is the value to be checked in a string format
# max value is the biggest value for the parameter
# min value is the smallest value for the parameter
# value_type is int or float
if value_type == 'int':
try:
value_int = int(value)
if value_int <= max_value and value_int >= min_value:
#the value is ok
return True
except ValueError:
# ValueError is raised if user has set value that is not a number
return False
elif value_type == 'float':
try:
value_float = float(value)
if value_float <= max_value and value_float >= min_value:
#the value is ok
return True
except ValueError:
# ValueError is raised if user has set value that is not a number
return False
return False #if function reaches this line value hasn't been ok
|
37f719b7f9740d940d96abf6bb07a3733347f4e2
|
xpenalosa/YouTubeDataApiReader
|
/youtube_data_reader/api/request_handler.py
| 1,316 | 3.796875 | 4 |
import json
from urllib.parse import urljoin
import requests
_DOMAIN = "https://www.googleapis.com/youtube/v3/"
def _extract_error(response_body: dict) -> str:
"""Parse the JSON response from a failed request to the Youtube Data API and extracts the error(s).
Expects the body to contain an error API response.
:param response_body: The JSON object to parse.
:return: The error or list of errors found within the response body.
"""
# Remove method and inline call?
# Catch KeyError and raise custom error indicating unexpected response?
return json.dumps(response_body["error"]["errors"])
def query_endpoint(endpoint, parameters: dict) -> dict:
"""Build and execute an HTTPS request against the Youtube Data API.
:param endpoint: The endpoint to query.
:param parameters: A dictionary containing all the parameters to pass with the request.
:return: The JSON response from the API.
:raises requests.exceptions.HTTPError: If the API answers with a 4xx or 5xx code.
"""
response = requests.get(
urljoin(_DOMAIN, endpoint),
params=parameters,
)
body = response.json() # type: dict
if not response.ok:
error_message = _extract_error(body)
raise requests.exceptions.HTTPError(error_message)
return body
|
4e1cc504cac8ac3c91a0ef06f2ff0a1f577fe18d
|
huiup/python_notes
|
/数据结构/二分查找/二分查找.py
| 635 | 3.5625 | 4 |
'''
二分查找只能作用在有序序列中
'''
def find(alist, item):
find = False
low = 0
high = len(alist)-1
while low <= high:#小于等于
mid = (low + high) // 2
if item < alist[mid]:# 查找的元素小于中间元素,则查找的元素在中间元素的左侧
high = mid - 1#low和high就可以表示新序列的范围
elif item > alist[mid]:# 查找的元素在中间元素的右侧
low = mid + 1
else:# 查找的元素就是中间元素
find = True
break
return find
alist = [1,2,3,4,5]
print(find(alist,5))
|
17a4dbc0ab87f58f589ae7820642b36a47fea8e8
|
zzy1120716/my-nine-chapter
|
/ch03/optional/0148-sort-colors.py
| 1,476 | 4.0625 | 4 |
"""
148. 颜色分类
给定一个包含红,白,蓝且长度为 n 的数组,将数组
元素进行分类使相同颜色的元素相邻,并按照红、白、蓝
的顺序进行排序。
我们可以使用整数 0,1 和 2 分别代表红,白,蓝。
样例
给你数组 [1, 0, 1, 2], 需要将该数组原地排序为
[0, 1, 1, 2]。
挑战
一个相当直接的解决方案是使用计数排序扫描2遍的算法。
首先,迭代数组计算 0,1,2 出现的次数,然后依次用
0,1,2 出现的次数去覆盖数组。
你否能想出一个仅使用常数级额外空间复杂度且只扫描遍历
一遍数组的算法?
注意事项
不能使用代码库中的排序函数来解决这个问题。
排序需要在原数组中进行。
"""
"""
三指针
Dijkstra 3-way partitioning
"""
class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
# write your code here
if nums is None or len(nums) == 0:
return
left, right, i = 0, len(nums) - 1, 0
while i <= right:
# 0
if nums[i] == 0:
nums[i], nums[left] = nums[left], nums[i]
left += 1
i += 1
# 1
elif nums[i] == 1:
i += 1
# 2
else:
nums[i], nums[right] = nums[right], nums[i]
right -= 1
|
09e31f9df693a71aa5891eda212f573d130509ea
|
deepy/chrono
|
/today.py
| 2,251 | 3.5625 | 4 |
#!/usr/bin/env python3
from __future__ import print_function
import os
def reversed_lines(file):
"""Generate the lines of file in reverse order."""
part = ''
for block in reversed_blocks(file):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ''
part += c
if part: yield part[::-1]
def reversed_blocks(file, blocksize=4096):
"""Generate blocks of file's contents in reverse order."""
file.seek(0, os.SEEK_END)
here = file.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
file.seek(here, os.SEEK_SET)
yield file.read(delta)
def main():
from itertools import islice
import datetime
import dateutil.parser
import humanize
with open(os.path.expanduser('~/.chronodb'), 'r') as file:
t = datetime.timedelta(0)
now = datetime.datetime.now(datetime.timezone.utc)
today = datetime.timedelta(hours=7)
arr = None
dep = now
for line in islice(reversed_lines(file), 10):
res = line.strip().split(',', 1)
date = dateutil.parser.parse(res[0])
if date.day == now.day:
if res[1] == 'arrive':
if arr is not None:
raise Exception('Missing depart, at {} and found {}'.format(arr, res[1]))
elif dep is None:
if arr is None:
arr = date
continue
raise Exception('Missing depart for arrive, at {} and found {}'.format(arr, res[0]))
arr = date
today -= dep - arr
dep = None
elif res[1] == 'depart':
if dep is not None and dep is not now:
raise Exception('Missing arrive, at {} and found {}'.format(dep, res[0]))
dep = date
arr = None
if today > t:
print("{} left".format(humanize.naturaldelta(today)), end='')
else:
print("{}".format(humanize.naturaltime(-today)), end='')
if __name__ == '__main__':
main()
|
677bb1e247f4d290f08702ec420258b2ec023c15
|
aliarqish/LearnPythonTheHardWay
|
/difference.py
| 397 | 4.0625 | 4 |
#difference between %r and %s
#first example
s='spam'
print(repr(s)) #with quotes
print(str(s)) #without quotes
#second example
x="example"
print "My %r" % x #with quotes
print "My %s" % x #without quotes
# Third Example.
x = 'xxx'
withR = ("Prints with quotes: %r" %x)
withS = ("Prints without quotes: %s" %x)
print(withR)
# Prints with quotes: 'xxx'
print(withS)
# Prints without quotes: xxx
|
2d9f3d9e5a657b89ef3eb31201a643d257e1c87d
|
tbarchyn/FEAST
|
/InputData/input_data_classes.py
| 5,552 | 3.65625 | 4 |
"""
This module defines all classes used to store input data
"""
from abc import ABCMeta
from GeneralClassesFunctions.simulation_functions import set_kwargs_attrs
class DataFile(metaclass=ABCMeta):
"""
DataFile is an abstract super class used to store all data files that may be called in FEAST.
"""
def __init__(self, notes='No notes provided', raw_file_name=None, **kwargs):
"""
notes A string containing notes on the object created
raw_file_name path to a raw input file
kwargs optional input dictionary that will override default parameters or add new parameters
"""
self.notes = notes
self.raw_file_name = raw_file_name
set_kwargs_attrs(self, kwargs, only_existing=False)
class LeakData(DataFile):
"""
LeakData is designed to store all leak size data from a reference. It accommodates multiple detection methods
within a single instance
"""
def __init__(self, notes='No notes provided', raw_file_name=None, data_prep_file=None, leak_sizes=None):
"""
notes A string containing notes on the object created
raw_file_name path to a raw input file
leak_sizes list of leak sizes. If leaks were detected using multiple methods, leak_sizes must be a dict
with one key for each detection method
"""
DataFile.__init__(self, notes, raw_file_name, leak_sizes=leak_sizes, data_prep_file=data_prep_file)
self.leak_sizes = dict()
self.well_counts = dict()
def define_data(self, leak_data=None, well_counts=None, keys=None):
"""
Check data formatting and set keys
leak_data leak_data must be a dict if there are multiple detection methods. If there is exactly one
detection method, leak_data may be a list.
well_counts well_counts lists the number of wells monitored by each detection method in keys
keys each detection method should have a unique key associated with it
"""
if keys is None:
# leak_data should be a dict if there are multiple detection methods. Each key will define a detection
# method and the associated dictionary entry will be the list of fluxes from leaks found using that
# detection method
if type(leak_data) is dict:
keys = leak_data.keys()
else:
keys = ['all_leaks']
if keys != leak_data.keys() or leak_data.keys() != well_counts.keys():
error_str = "The 'keys' argument passed to LeakData.defineData(), leak_data.keys() and " \
"well_counts.keys() must all be equivalent"
raise ValueError(error_str)
for key in keys:
self.leak_sizes[key] = leak_data[key]
self.well_counts[key] = well_counts[key]
class WindData(DataFile):
"""
WindData is designed to store all wind data from a reference. It accommodates wind speed, direction and time.
"""
def __init__(self, notes='No notes provided', raw_file_name=None):
"""
notes A string containing notes on the object created
raw_file_name path to a raw input file
"""
DataFile.__init__(self, notes, raw_file_name)
self.wind_speed, self.time, self.wind_direction = [], [], [] # m/s, hour, degrees
def define_data(self, wind_speed=None, time=None, wind_direction=None):
"""
Inputs:
wind_speed list of wind speeds
time list of times at which the wind speeds were recorded
wind_direction list of wind directions
"""
self.wind_speed = wind_speed
self.time = time
self.wind_direction = wind_direction
class RepairData(DataFile):
"""
RepairData is designed to store the costs of repairing leaks from a particular reference an associated notes.
"""
def __init__(self, notes='No notes provided', raw_file_name=None):
"""
Inputs:
notes A string containing notes on the object created
raw_file_name path to a raw input file
"""
DataFile.__init__(self, notes, raw_file_name)
self.repair_costs = []
def define_data(self, repair_costs=None):
"""
Inputs:
repair_costs list of costs to repair leaks
"""
if repair_costs is None:
repair_costs = []
self.repair_costs = repair_costs
class PNNLData(DataFile):
"""
Class for storing PNNL spectra data
"""
def __init__(self, notes, raw_file_name):
DataFile.__init__(self, notes, raw_file_name)
self.km = None
self.nu = None
def define_data(self, km, nu):
self.km = km
self.nu = nu
class HITRAN(DataFile):
"""
Class for storing PNNL spectra data
"""
def __init__(self, notes, raw_file_name):
DataFile.__init__(self, notes, raw_file_name)
self.nu = None
self.s = None
self.gamma = None
self.temp = None
self.lower_e = None
def define_data(self, nu, s, gamma, temp, lower_e):
self.nu = nu
self.s = s
self.gamma = gamma
self.temp = temp
self.lower_e = lower_e
|
8db42195cb5c4a72b13228b39e33abf364787d62
|
cauthu/shadow-browser-plugin
|
/newweb/tools/get-servers-from-country.py
| 930 | 3.546875 | 4 |
# read the countrycode_to_webserver_names json file, and output to
# stdout the list of webserver names from the country specified in
# command line
#
# for use to get list of servers to give to
# "chrome/38.0.2125.122/model_extractor/main.py change-hostnames"
# command, e.g.:
#
# python get-servers-from-country.py US | xargs python3 ~/chrome/38.0.2125.122/model_extractor/main.py change-hostnames ~/nytimes_page_model.json new.json
#
import sys
import json
assert len(sys.argv) == 2
countrycode = sys.argv[1].upper()
# print 'country code: {}'.format(countrycode)
with open('countrycode_to_webserver_names.json') as fp:
countrycode_to_webserver_names = json.load(fp)
pass
if countrycode not in countrycode_to_webserver_names:
raise Exception( 'country code is not found in the json file')
sys.exit(1)
pass
server_names = countrycode_to_webserver_names[countrycode]
print ' '.join(server_names)
|
d91be5ab28ab91c5da3c8761051da3cec55cae29
|
google-code/abj-proyecto-educacion
|
/logico/problemas/acciones/IApagable.py
| 1,194 | 3.609375 | 4 |
# -*- coding: utf-8 -*-
class IApagable(object):
"""
Interfaz que es implementada por todos los objetos que pueden apagarse y encenderse.
@since: 4/14/2011
@version: 1.0
"""
__apagado = False
""" Bandera de referencia para saber si el objeto esta apagado """
def __init__(self):
"""
Constructor
@type self: IApagable
@param self: referencia al objeto IApagable actual
"""
pass
def apagar(self):
"""
Metodo para apagar el IApagable.
@type self: IApagable
@param self: referencia al objeto Apagable actual
"""
self.__apagado=True
def encender(self):
"""
Metodo para encender el IApagable
@type self: IApagable
@param self: referencia al objeto Apagable actual
"""
self.__apagado=False
def get(self):
"""
Metodo para obtener el estado del IApagable. True = Apagado, False = Encendido
@type self: IApagable
@param self: referencia al objeto Apagable actual
"""
return self.__apagado
def getAcciones(self):
"""
Devuelve las acciones que realiza la interfaz
@type self: IApagable
@param self: referencia al objeto Apagable actual
"""
return ['apagar', 'encender']
|
e64ce06d03681212beffa842e7d3c337af3c86fb
|
mollinaca/ac
|
/code/practice/arc/arc020/a.py
| 181 | 3.84375 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a,b = map(int,input().split())
if abs(a) < abs(b):
print ("Ant")
elif abs(a) > abs(b):
print ("Bug")
else:
print ("Draw")
|
ccf878b21e17dee7407ffbb311171fae693ddf8f
|
kearnz/autoimpute
|
/autoimpute/imputations/series/norm.py
| 3,008 | 3.578125 | 4 |
"""This module implements norm imputation via the NormImputer.
The NormImputer imputes missing data with random draws from a construted
normal distribution. Dataframe imputers utilize this class when its strategy
is requested. Use SingleImputer or MultipleImputer with strategy = `norm` to
broadcast the strategy across all the columns in a dataframe, or specify this
strategy for a given column.
"""
from scipy.stats import norm
from sklearn.utils.validation import check_is_fitted
from autoimpute.imputations import method_names
from autoimpute.imputations.errors import _not_num_series
from .base import ISeriesImputer
methods = method_names
# pylint:disable=attribute-defined-outside-init
# pylint:disable=unnecessary-pass
class NormImputer(ISeriesImputer):
"""Impute missing data with draws from normal distribution.
The NormImputer constructs a normal distribution using the sample mean and
variance of the observed data. The imputer then randomly samples from this
distribution to impute missing data. The imputer can be used directly, but
such behavior is discouraged. NormImputer does not have the flexibility /
robustness of dataframe imputers, nor is its behavior identical.
Preferred use is MultipleImputer(strategy="norm").
"""
# class variables
strategy = methods.NORM
def __init__(self):
"""Create an instance of the NormImputer class."""
pass
def fit(self, X, y=None):
"""Fit Imputer to dataset and calculate mean and sample variance.
Args:
X (pd.Series): Dataset to fit the imputer.
y (None): ignored, None to meet requirements of base class
Returns:
self. Instance of the class.
"""
# get the moments for the normal distribution of feature X
_not_num_series(self.strategy, X)
moments = (X.mean(), X.std())
self.statistics_ = {"param": moments, "strategy": self.strategy}
return self
def impute(self, X):
"""Perform imputations using the statistics generated from fit.
The transform method handles the actual imputation. It constructs a
normal distribution using the sample mean and variance from fit.
It then imputes missing values with a random draw from the respective
distribution.
Args:
X (pd.Series): Dataset to impute missing data from fit.
Returns:
np.array -- imputed dataset.
"""
# check if fitted and identify location of missingness
check_is_fitted(self, "statistics_")
_not_num_series(self.strategy, X)
ind = X[X.isnull()].index
# create normal distribution and sample from it
imp_mean, imp_std = self.statistics_["param"]
imp = norm(imp_mean, imp_std).rvs(size=len(ind))
return imp
def fit_impute(self, X, y):
"""Convenience method to perform fit and imputation in one go."""
return self.fit(X, y=None).impute(X)
|
b8a9c3f1b2eb687dbf0ad1792442dd8006ee03a4
|
samuelclark907/data-structures-and-algorithms
|
/python/queue_with_stacks/queue_with_stacks.py
| 738 | 4 | 4 |
from stacks_and_queues.stacks_and_queues import Stack
class PseudoQueue():
def __init__(self):
self.main = Stack()
self.temp = Stack()
def __len__(self):
return len(self.main) + len(self.temp)
def enqueue(self, value):
while not self.main.is_empty():
self.temp.push(self.main.pop())
self.main.push(value)
while not self.temp.is_empty():
self.main.push(self.temp.pop())
return self.main.top.value
def dequeue(self):
# self.main.pop()
return self.main.pop()
# while not self.main.is_empty():
# self.main.pop()
# return self.main.pop()
|
9e1b346a6fd321a14e584e94ca621f3a15ca3a6c
|
DanMeloso/python
|
/Exercicios/ex070.py
| 1,092 | 4 | 4 |
#Exercício Python 070: Crie um programa que leia o nome e o preço de vários produtos.
#O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre:
#A) qual é o total gasto na compra.
#B) quantos produtos custam mais de R$1000.
#C) qual é o nome do produto mais barato.
total = maiorMil = 0
maisBarato = ''
menor = 0
produtoMenor = ''
while True:
produto = str(input('Produto: '))
preco = float(input('R$ '))
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Deseja continuar? [S/N]')).strip().upper()[0]
total += preco
if preco >= 1000:
maiorMil += 1
if menor == 0:
menor = preco
produtoMenor = produto
else:
if preco < menor:
menor = preco
produtoMenor = produto
if continuar == 'N':
break
print('{:-^50}'.format('FIM DO PROGRAMA'))
print(f'O valor total de sua compra é de R${total:.2f}')
print(f'{maiorMil} produtos tem o valor maior que R$1.000')
print(f'O produto mais barato de sua compra é: {produtoMenor}')
print('-'*50)
|
1d8575b5f2ca085d899410e3b52fd50ffbcef978
|
Zorro30/Udemy-Complete_Python_Masterclass
|
/Using Tkinter/tkinter_button_command_1.py
| 532 | 3.625 | 4 |
from tkinter import *
class MyButtons():
def __init__(self, rootone):
frame = Frame(rootone)
frame.pack()
self.button1 = Button(frame, text = "Click Me!", command = self.printMessage)
self.button1.pack()
self.button2 = Button(frame, text = "Click me to Exit!", command = frame.quit) # inbuilt function to quit
self.button2.pack (side = LEFT)
def printMessage(self):
print ("Button Clicked")
root = Tk()
b = MyButtons(root)
root.mainloop()
|
8f0d52e1810315603721b44f1769091b0258de89
|
bmyers624/pyapi
|
/sewing/topcoat.py
| 693 | 3.53125 | 4 |
#!/usr/bin/python3
import threading
import time
def groundcontrol(x):
for i in range(x, -1, -1):
print(i)
time.sleep(1)
def orion():
print("I forgot my socks.")
time.sleep(1)
print("Can we stop this ride?")
time.sleep(2)
print("No? Alright. Ugh. I forgot to close the garage too.")
time.sleep(1)
print("To infinity, and beyond!")
print("Orion, you are primed for launch. Count down begins...")
countdown = 10
mythread = threading.Thread(target=groundcontrol, args=(countdown, ))
astrothread = threading.Thread(target=orion)
mythread.start()
astrothread.start()
mythread.join()
astrothread.join()
input("Press Enter to exit.")
exit()
|
2b4911e2fc9eeeceb70b3e16c49702c02c40f090
|
KostaPapa/Python_Works
|
/Practice/a19LetterGrade.py
| 554 | 4.03125 | 4 |
def getStudentScore():
'''This funtion will get the studetn scores.'''
score = float(raw_input("Enter studetn score: "))
return score
def calcLetterGrade(score):
'''This function will calc the letter grade.'''
if (81 <= score <= 90):
print "A"
elif (71 <= score <= 80):
print "B"
elif (61 <= score <= 70):
print "C"
elif (51 <= score <= 60) :
print "D"
else:
print "F"
def main():
studentScore = getStudentScore()
calcLetterGrade(studentScore)
main()
|
c9de13109437fcee44bf8c590a80ebf347edd963
|
Funkie42/SAP
|
/SAT1/satConverter.py
| 15,584 | 3.640625 | 4 |
import readFile
import writeFile
import interface
import math
import random
import copy
#main logic
counter = 0
colNumber = 0
lineNumber = 0
# convert the array syntax to an ascending number sequence
def writeNumbersInFormat(line, colmun, colNumber):
numberToBeAdded = str(line * colNumber + colmun +1)
return numberToBeAdded
# add clauses to the "sat" file
def addSantaClauses(line, column, colNumber, lineNumber): #bissi spaß muss auch sein
hohoho = []
# Check Horizontal 3 in a row
# "left left middle" and "middle right right" are not neccessary because they are redundant
# we only check "left middle right"
if (column > 0) & (column < colNumber - 1):
for i in range(2):
hohoho.append([writeNumbersInFormat(line, column - 1, colNumber),
writeNumbersInFormat(line, column, colNumber),
writeNumbersInFormat(line, column + 1, colNumber)])
# make content negative
if i == 1:
for j in range(3):
hohoho[len(hohoho) - 1][j] = "-" + hohoho[len(hohoho) - 1][j]
'''for i in range(6):
hoehoehoe.append([writeNumbersInFormat(line, column - 1, colNumber),
writeNumbersInFormat(line, column, colNumber),
writeNumbersInFormat(line, column + 1, colNumber)])
if i > 2:
for j in range(2):
hoehoehoe[len(hoehoehoe) - 1][((i-3)+j)%3] = "-" + hoehoehoe[len(hoehoehoe) - 1][((i-3)+j)%3]
else:
hoehoehoe[len(hoehoehoe) - 1][i] = "-" + hoehoehoe[len(hoehoehoe) - 1][i]'''
# Check vertical 3 in a row
if (line > 0) & (line < lineNumber - 1):
for i in range(2):
hohoho.append([writeNumbersInFormat(line - 1, column, colNumber),
writeNumbersInFormat(line, column, colNumber),
writeNumbersInFormat(line + 1, column, colNumber)])
if i == 1:
for j in range(3):
hohoho[len(hohoho) - 1][j] = "-" + hohoho[len(hohoho) - 1][j]
return hohoho
# Check Lines for 50/50 distribution
# Check Columns for 50/50 distribution
def addAmountDistriction(lineNumber, colNumber, vertical, data):
sack = []
solutions = []
for i in range(lineNumber):
arrayOfCurrentRowIndexes = []
for j in range(colNumber):
if vertical:
#print (data,"data")
#print (lineNumber,"lineNum")
arrayOfCurrentRowIndexes.append(data[i * lineNumber + j])
else:
arrayOfCurrentRowIndexes.append(data[j * lineNumber + i])
whiteBlocks = []
blackBlocks = []
for elem in arrayOfCurrentRowIndexes:
if elem > 0:
whiteBlocks.append(elem)
elif elem < 0:
blackBlocks.append(elem)
surplusOfWhiteBlocks = len(whiteBlocks) - len(arrayOfCurrentRowIndexes)//2
if surplusOfWhiteBlocks < 0:
sack = [[]]
for i in blackBlocks:
sack[0].append(i*-1)
return sack
solutions = buildAllPossibleNegationsIterative(surplusOfWhiteBlocks*-1, len(blackBlocks), blackBlocks, 1)
elif surplusOfWhiteBlocks > 0:
sack = [[]]
for i in whiteBlocks:
sack[0].append(i*-1)
return sack
#The main algorithm is called
#solutions = buildAllPossibleNegationsIterative(colNumber//2-1, colNumber, arrayOfCurrentRowIndexes)
for s in solutions:
sack.append(s)
return (sack)
# this is no longer neede..
# attempt to exclude n amout of blocks per line (is working but solws down the algorithem for huge grids)
def buildAllPossibleNegationsIterative(negationAmount, varAmount, arrayOfLineData, reverse):
cnfOfLineCheckArray = []
for negLevel in range(0, negationAmount+1):
positionToWrite = negLevel
startPosWrite = negLevel
numbersToNeg = []
for i in range(negLevel):
numbersToNeg.append(i+1)
#Main loop to write each possibility
calculating = 1
while calculating:
newCNF = arrayOfLineData.copy()
#LENGTH of array to flip numbers
for number in numbersToNeg:
newCNF[number-1] *= -1
if len(numbersToNeg) > 0:
for number in range(0, len(numbersToNeg)):
if (numbersToNeg[number] == varAmount-(len(numbersToNeg)-number-1)):
if number==0:
calculating = 0 # End Program because it's finished for NegAmount
else:
numbersToNeg[number-1] += 1
numbersToNeg[number] = numbersToNeg[number-1]
if numbersToNeg[len(numbersToNeg) - 1] < varAmount:
numbersToNeg[len(numbersToNeg) - 1] += 1
else:
calculating = 0
cnfOfLineCheckArray.append(newCNF)
for j in range(len(cnfOfLineCheckArray[0])):
cnfOfLineCheckArray[0][j] = cnfOfLineCheckArray[0][j] * -1
return cnfOfLineCheckArray
#Not used
#RECURSIVE! VERY INEFFICENT! R.I.P Stack!
#returns all pos and negativ possibility for a given amout of negations and variables
def buildAllPossibleNegationsRecursive(negationAmout, varAmount, arrayOfLineData, changedNumbers = []):
solutions = []
if negationAmout == 0:
arrayOfLineData = arrayOfLineData + changedNumbers
arrayOfLineDataNeg = []
for i in arrayOfLineData:
dataNegative = i*-1
arrayOfLineDataNeg.append(dataNegative)
solutions.append(arrayOfLineDataNeg)
solutions.append(arrayOfLineData)
return solutions
for i in range(varAmount):
modArray = arrayOfLineData.copy()
changedNumbers.append(-modArray.pop(i))
solution = buildAllPossibleNegationsRecursive(negationAmout-1, varAmount-1, modArray, changedNumbers)
del changedNumbers[-1]
solutions.extend(solution)
return solutions
# convert gamefield and apply sat rules on them and write them in the "sat" file
def convertToSat(data, repeatNumber = 0):
# Read input data to Array "data"
global colNumber, lineNumber
writemode = ""
cnf = []
#3 Blocks Rule applied
if repeatNumber == 0:
colNumber = len(data[0])
lineNumber = len(data)
for i in range(lineNumber):
for j in range(colNumber):
'''Insert given blockcolors as Unit-Clauses
White blocks are represented by a positive value
Black blocks are represented by a negative value
'''
if data[i][j] == 1: # Insert white blocks
cnf.append([writeNumbersInFormat(i, j, colNumber)])
elif data[i][j] == 2: # Insert black blocks
cnf.append(["-" + writeNumbersInFormat(i, j, colNumber)])
# Check only unknown blocks (Grey blocks)
# check all stones and append logic on them add clauses to determine unknown blocks
santasHoeCollection = addSantaClauses(i, j, colNumber, lineNumber)
for clause in santasHoeCollection:
cnf.append(clause)
writemode = "w+"
#Row Col Restiction appended
else:
lineRestictions = addAmountDistriction(lineNumber, colNumber, 1, data)
for lineRestiction in lineRestictions:
cnf.append(lineRestiction)
colRestictions = addAmountDistriction(colNumber, lineNumber, 0, data)
for colRestiction in colRestictions:
cnf.append(colRestiction)
writemode = "a"
# number of literals and terms
lits = colNumber * lineNumber
terms = len(cnf)
# write converted CNF to File
writeFile.writeCNF(lits, terms, cnf, writemode)
# checks if equal amout of white and black in every line
def checkIfDataIsDevineLines(data, cols, lines):
for i in range(lines):
counter = 0
for j in range(cols):
if(data[i * lineNumber + j] > 0):
counter = counter + 1
if(counter != colNumber//2):
return 0
return 1
# same as above but for columns
def checkIfDataIsDevineCols(data, cols, lines):
for i in range(lines):
counter = 0
for j in range(cols):
#print("line: ", i, "col: ", j, "data: ", data[i + lines * j])
if(data[i+lines*j] > 0):
counter = counter + 1
#print("counter: ", counter, "lineNumber: ", lineNumber)
if(counter != lineNumber//2):
return 0
return 1
# convert array formats (unfortunally we have two different formats how our array look like: [[1..len(col)]..len(line)] and [1..n]
def convertData(data, lines, cols):
sol = []
counter = 0
for i in range(lines):
subSol = []
for j in range(cols):
if (data[counter] < 0):
subSol.append(2)
else:
subSol.append(1)
counter += 1
sol.append(subSol)
return sol
# apply the rules of the game
def applyRules(data, lines, cols, greyFields, buildingBoard = 0):
# apply the rule for the 3 solver
convertToSat(data)
data = readFile.readPicosatSolution(cols, lines, 0)
# call the code to add clauses for amount restriction
convertToSat(data, 1)
data = readFile.readPicosatSolution(cols, lines, 0)
puzzleSolved = 0
i = 0
while (puzzleSolved == 0):
convertToSat(data, 1)
data = readFile.readPicosatSolution(cols, lines, 0)
# check if equal amount in al rows
puzzleSolved = checkIfDataIsDevineLines(data, cols, lines)
if (puzzleSolved == 1):
# check if all rows are equal
puzzleSolved = checkIfDataIsDevineCols(data, cols, lines)
# satConverter.convertToSat(data, 1)
data = readFile.readPicosatSolution(cols, lines, 0)
i = i + 1
# we have found the perfect solution but now exclude all other possibilities
# herefor we got throug everystone and check if it could be switched
# if so we have to write this stone in our satfile
if not buildingBoard:
checkEveryStoneForOtherSolutions(data, greyFields)
# data = readFile.readPicosatSolution(cols, lines, 1)
data = convertData(data, lines, cols)
return data
''''# gets data in fomat: [1,2,3,4,5,6,7,8,9,...,n]
def checkEveryStoneForOtherSolutions(data):
gameData = readFile.readFileData('./ueb1/u01puzzle-small1.txt')
lits = colNumber * lineNumber
for elem in data:
#check it for the negative value if it would be possible in other solution
elem = elem*-1
isPossible = readFile.readPicosatWithArgs(str(elem))
if(isPossible==1):
elem = elem*-1
#it can be switched and therefor this possibility has to be excluded
writeFile.writeCNF(lits, 1, [[elem]], "a")'''
# gets data in fomat: [1,2,3,4,5,6,7,8,9,...,n]
def checkEveryStoneForOtherSolutions(data, greyFields, isBuildingNewBoard = 0):
lits = colNumber * lineNumber
counter = 0
for elem in greyFields:
counter += 1
#check it for the negative value if it would be possible in other solution
elem = data[elem]*-1
isPossible = readFile.readPicosatWithArgs(str(elem))
if isPossible == 1:
if isBuildingNewBoard:
return 0 #Not unique anymore! Boardbuilding
else:
elem = elem*-1
#it can be switched and therefor this possibility has to be excluded
writeFile.writeCNF(lits, 1, [[elem]], "a")
return 1 #Still unique board
#Aufgabe 4
def buildNewGrid(lines, cols):
gameField = []
greyFields = []
gridSize = lines*cols
for i in range(gridSize):
gameField.append(0)
for i in range(gridSize//10):
index = random.randint(0,gridSize-1)
gameField[index] = random.randint(1,2)
counter = 0
for i in range(len(gameField)):
if(gameField[i] == 0):
greyFields.append(counter)
counter += 1
arrayInFormat = []
newArrayToAdd = []
for i in range(len(gameField)):
newArrayToAdd.append(gameField[i])
if i % lines == lines - 1:
arrayInFormat.append(newArrayToAdd)
newArrayToAdd = []
return setFieldsForSingularity(arrayInFormat,greyFields, lines, cols)
def setFieldsForSingularity(arrayInFormat, greyFields, lines, cols):
lits = lines * cols
data = applyRules(arrayInFormat, lines, cols, greyFields)
applyRules(data, lines, cols, greyFields)
#just do it through deleting elements
#until at least half the field is empty
oldSolution = copy.deepcopy(data)
greyFields = greyFields
oldGreyFields = copy.deepcopy(greyFields)
counter = 0
successfulReduction = 0
while (counter < len(data)) | (successfulReduction*lines < len(data)//2):
counter += 1
for line in range(len(data)):
newLinegreyFields = []
indizeToDelete = random.randint(0, len(data[line])-1)
if indizeToDelete+line*lines in greyFields:
del greyFields[greyFields.index(indizeToDelete+line*lines)]
data[line][indizeToDelete] = 0
newLinegreyFields.append(indizeToDelete+line*lines)
dataInOtherFormat = []
for j in oldSolution:
for k in j:
dataInOtherFormat.append(k)
applyRules(data, lines, cols, greyFields)
unique = checkEveryStoneForOtherSolutions(dataInOtherFormat, newLinegreyFields, 1)
if unique == 0:
data = copy.deepcopy(oldSolution)
greyFields = copy.deepcopy(oldGreyFields)
unique == 1
else:
oldSolution = copy.deepcopy(data)
oldGreyFields = copy.deepcopy(greyFields)
successfulReduction += 1
#old, wrong solution
'''counter = 0
for elem in greyFields:
# check it for the negative value if it would be possible in other solution
#print ("data",data)
#elemNegated = (data[elem//lineNumber][elem%colNumber]) % 2 + 1
#if elemNegated == 2:
# elem
#else:
elemNegated = elem*-1
#print (elemNegated,"elem Negated")
#applyRules(arrayInFormat, lines, cols, greyFields)
isPossible = readFile.readPicosatWithArgs(str(elemNegated))
if (isPossible == 1):
randomChoice = random.choice((-1, 1))
writeFile.writeCNF(lits, 1, [[elem* randomChoice]], "a")
counter += 1
if(elem* randomChoice > 0):
#print (elem)
arrayInFormat[elem//lineNumber][elem%colNumber] = 1
else:
arrayInFormat[elem//lineNumber][elem%colNumber] = 2'''
return data
if __name__ == "__main__":
#array = []
#arrayLength = 18
#for i in range(1,arrayLength+1):
# array.append(i)
#testNeg = buildAllPossibleNegationsIterative(len(array)//2-1, len(array), array)
impossible = 1
while impossible:
try:
buildNewGrid(8,8)
impossible = 0
except:
impossible = 1
|
2bbf96092934f178e81d209958bfd2fb31caea27
|
sulabhbartaula/python-data-structure
|
/firstRepeatingCharacter.py
| 624 | 3.921875 | 4 |
"""
Description
Given a string str,
create a function that returns the first repeating character.
If such character doesn't exist, return the null character '\0'.
• Input: str = "programming"
• Output: 'r'
"""
def main():
input_string = 'programming'
firstRepeatingChar = findFirstRepeatingCharacter(input_string)
print(firstRepeatingChar)
#time complexity of function is 0(N)
def findFirstRepeatingCharacter(input_string):
visited = {}
for ch in input_string:
if visited.get(ch):
return ch
else:
visited[ch] = True
return '/0';
main()
|
db32b9131cebdce3d5f8651651b1edcd484f34a4
|
mabioo/Python-codewar
|
/未完成/1.找出给定金额的所有找零方式/test.py
| 1,086 | 3.578125 | 4 |
def temp(money,coins):
coins.sort()
coins.reverse()
count_num = 0
i = 0
while i <len(coins):
j = i
count1 =1
if tempMoney > coins[i]:
tempMoney = money - coins[i]*count1
count1 = count1 +1
print ("$$$$$$$$$$$$$$$$$$$$$")
while ( j<len(coins) ):
print ("j:",j)
print ("tempmonsy:",tempMoney)
print ("con:",coins[j])
if tempMoney >= coins[j]:
tempMoney = tempMoney -coins[j]
while (tempMoney >= coins[j]):
if j != len(coins)-1 and (tempMoney-coins[j]<coins[j+1]) and (tempMoney-coins[j] !=0):
break
else:
tempMoney = tempMoney - coins[j]
if tempMoney <= 2*coins[j]:
j = j+1
if tempMoney == 0:
count_num = count_num +1
tempMoney = money- coins[i]
print ("count_num",count_num)
i = i+1
return count_num
if __name__ =="__main__":
print(temp(30,[5,10,20]))
|
7f5bf065bd41cf1d9ac6f76ff74c44b174e7fd13
|
MaxytZhang/F2018-507-Project3
|
/proj3_choc.py
| 11,847 | 3.5 | 4 |
import sqlite3
import csv
import json
import pprint
import textwrap
# proj3_choc.py
# You can change anything in this file you want as long as you pass the tests
# and meet the project requirements! You will need to implement several new
# functions.
# Part 1: Read data from CSV and JSON into a new database called choc.db
DBNAME = 'choc.db'
BARSCSV = 'flavors_of_cacao_cleaned.csv'
COUNTRIESJSON = 'countries.json'
def init_db():
try:
conn = sqlite3.connect(DBNAME)
except:
print("fail to connect to database")
cur = conn.cursor()
# Drop tables
statement = '''
DROP TABLE IF EXISTS 'Bars';
'''
cur.execute(statement)
statement = '''
DROP TABLE IF EXISTS 'Countries';
'''
cur.execute(statement)
conn.commit()
statement = '''
CREATE TABLE 'Bars' (
'Id' INTEGER PRIMARY KEY AUTOINCREMENT,
'Company' TEXT NOT NULL,
'SpecificBeanBarName' TEXT NOT NULL,
'REF' TEXT NOT NULL,
'ReviewDate' TEXT NOT NULL,
'CocoaPercent' REAL NOT NULL,
'CompanyLocationId' INTEGER,
'Rating' REAL NOT NULL,
'BeanType' TEXT NOT NULL,
'BroadBeanOriginId' INTEGER
);
'''
cur.execute(statement)
statement = '''
CREATE TABLE 'Countries' (
'Id' INTEGER PRIMARY KEY AUTOINCREMENT,
'Alpha2' TEXT NOT NULL,
'Alpha3' TEXT NOT NULL,
'EnglishName' TEXT NOT NULL,
'Region' TEXT NOT NULL,
'Subregion' TEXT NOT NULL,
'Population' INTEGER NOT NULL,
'Area' REAL
);
'''
cur.execute(statement)
conn.commit()
conn.close()
def insert_c():
try:
conn = sqlite3.connect(DBNAME)
except:
print("fail to connect to database")
cur = conn.cursor()
with open("countries.json", 'r') as f:
c = json.loads(f.read())
for i in c:
insertion = (None, i['alpha2Code'], i['alpha3Code'], i['name'], i['region'], i['subregion'], i['population'], i['area'])
statement = '''
INSERT INTO Countries
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
'''
cur.execute(statement, insertion)
conn.commit()
conn.close()
def insert_b():
try:
conn = sqlite3.connect(DBNAME)
except:
print("fail to connect to database")
cur = conn.cursor()
with open("flavors_of_cacao_cleaned.csv", 'r') as f:
frows = csv.reader(f)
first_row = 0
for row in frows:
first_row += 1
if first_row == 1:
continue
try:
cid = cur.execute("SELECT Id FROM Countries WHERE EnglishName = ?", (row[5],)).fetchone()[0]
except:
cid = None
try:
bid = cur.execute("SELECT Id FROM Countries WHERE EnglishName = ?", (row[8],)).fetchone()[0]
except:
bid = None
insertion = (None, row[0], row[1], row[2], row[3], float(row[4][:-1])/100, cid, row[6], row[7], bid)
statement = '''
INSERT INTO Bars
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
'''
cur.execute(statement, insertion)
conn.commit()
conn.close()
# Part 2: Implement logic to process user commands
def process_bar(bar11, bar12, rc, od, num):
try:
conn = sqlite3.connect(DBNAME)
except:
print("fail to connect to database")
cur = conn.cursor()
if bar11 is None and bar12 is None:
statement = '''
SELECT b.SpecificBeanBarName, b.Company, c1.EnglishName, b.Rating, b.CocoaPercent, c2.EnglishName
FROM Bars AS b
LEFT JOIN Countries as c1
on b.CompanyLocationId = c1.Id
LEFT JOIN Countries as c2
on b.BroadBeanOriginId = c2.Id
ORDER BY {} {}
LIMIT {}
'''
result = cur.execute(statement.format(rc, od, num)).fetchall()
else:
statement = '''
SELECT b.SpecificBeanBarName, b.Company, c1.EnglishName, b.Rating, b.CocoaPercent, c2.EnglishName
FROM Bars AS b
LEFT JOIN Countries as c1
on b.CompanyLocationId = c1.Id
LEFT JOIN Countries as c2
on b.BroadBeanOriginId = c2.Id
WHERE {} = \'{}\'
ORDER BY {} {}
LIMIT {}
'''
result = cur.execute(statement.format(bar11, bar12, rc, od, num)).fetchall()
conn.close()
return result
def process_com(com11, com12, od, num, agg):
try:
conn = sqlite3.connect(DBNAME)
except:
print("fail to connect to database")
cur = conn.cursor()
if com11 is None and com12 is None:
statement = '''
SELECT b.Company, c1.EnglishName, {}
FROM Bars AS b
LEFT JOIN Countries as c1
on b.CompanyLocationId = c1.Id
GROUP BY b.Company
HAVING COUNT (*) > 4
ORDER BY {} {}
LIMIT {}
'''
result = cur.execute(statement.format(agg, agg, od, num)).fetchall()
else:
statement = '''
SELECT b.Company, c1.EnglishName, {}
FROM Bars AS b
LEFT JOIN Countries as c1
on b.CompanyLocationId = c1.Id
WHERE {} = \'{}\'
GROUP BY b.Company
HAVING COUNT (*) > 4
ORDER BY {} {}
LIMIT {}
'''
result = cur.execute(statement.format(agg, com11, com12, agg, od, num)).fetchall()
conn.close()
return result
def process_cou(cou11, cou12, od, num, agg, ss):
try:
conn = sqlite3.connect(DBNAME)
except:
print("fail to connect to database")
cur = conn.cursor()
if cou11 is None and cou12 is None:
statement = '''
SELECT {}.EnglishName, {}.Region, {}
FROM Bars AS b
LEFT JOIN Countries as c1
on b.CompanyLocationId = c1.Id
LEFT JOIN Countries as c2
on b.BroadBeanOriginId = c2.Id
GROUP BY {}.EnglishName
HAVING COUNT (*) > 4
ORDER BY {} {}
LIMIT {}
'''
result = cur.execute(statement.format(ss, ss, agg, ss, agg, od, num)).fetchall()
else:
statement = '''
SELECT {}.EnglishName, {}.Region, {}
FROM Bars AS b
LEFT JOIN Countries as c1
on b.CompanyLocationId = c1.Id
LEFT JOIN Countries as c2
on b.BroadBeanOriginId = c2.Id
WHERE {}{} = \'{}\'
GROUP BY {}.EnglishName
HAVING COUNT (*) > 4
ORDER BY {} {}
LIMIT {}
'''
result = cur.execute(statement.format(ss, ss, agg, ss, cou11, cou12, ss, agg, od, num)).fetchall()
conn.close()
return result
def process_reg(od, num, agg, ss):
try:
conn = sqlite3.connect(DBNAME)
except:
print("fail to connect to database")
cur = conn.cursor()
statement = '''
SELECT {}.Region, {}
FROM Bars AS b
LEFT JOIN Countries as c1
on b.CompanyLocationId = c1.Id
LEFT JOIN Countries as c2
on b.BroadBeanOriginId = c2.Id
WHERE {}.Region IS NOT NULL
GROUP BY {}.Region
HAVING COUNT (*) > 4
ORDER BY {} {}
LIMIT {}
'''
result = cur.execute(statement.format(ss, agg, ss, ss, agg, od, num)).fetchall()
conn.close()
return result
def process_command(command):
bar11 = None
bar12 = None
com11 = None
com12 = None
cou11 = None
cou12 = None
rc = "Rating"
num = '10'
od = "DESC"
agg = "AVG(b.Rating)"
ss = "c1"
result = None
com_type = ""
command_list = command.split()
for i in range(0, len(command_list)):
if command_list[i] == 'bars' or command_list[i] == 'companies' or command_list[i] == 'countries' or command_list[i] == 'regions':
com_type = command_list[i]
elif command_list[i] == 'ratings':
rc = "Rating"
agg = "AVG(b.Rating)"
elif command_list[i] == 'cocoa':
rc = "CocoaPercent"
agg = "AVG(b.CocoaPercent)"
elif command_list[i][0:3] == 'top':
num = command_list[i][4:]
od = "DESC"
elif command_list[i][0:6] == 'bottom':
num = command_list[i][7:]
od = 'ASC'
elif command_list[i][0:9] == "bars_sold":
agg = "COUNT (*)"
elif command_list[i][0:7] == "sellers":
ss = "c1"
elif command_list[i][0:7] == "sources":
ss = "c2"
elif command_list[i][0:11] == "sellcountry":
bar11 = "c1.Alpha2"
bar12 = command_list[i][12:]
elif command_list[i][0:13] == "sourcecountry":
bar11 = "c2.Alpha2"
bar12 = command_list[i][14:]
elif command_list[i][0:10] == "sellregion":
bar11 = "c1.Region"
bar12 = command_list[i][11:]
elif command_list[i][0:12] == "sourceregion":
bar11 = "c2.region"
bar12 = command_list[i][13:]
elif command_list[i][0:7] == "country":
com11 = "c1.Alpha2"
com12 = command_list[i][8:]
elif command_list[i][0:6] == "region":
com11 = "c1.Region"
com12 = command_list[i][7:]
cou11 = ".Region"
cou12 = command_list[i][7:]
else:
print("Command not recognized: {}".format(command))
return
if com_type == 'bars':
result = process_bar(bar11, bar12, rc, od, num)
if com_type == 'companies':
result = process_com(com11, com12, od, num, agg)
if com_type == 'countries':
result = process_cou(cou11, cou12, od, num, agg, ss)
if com_type == 'regions':
result = process_reg(od, num, agg, ss)
return result
def load_help_text():
with open('help.txt') as f:
return f.read()
# Part 3: Implement interactive prompt. We've started for you!
def interactive_prompt():
help_text = load_help_text()
response = ''
while response != 'exit':
response = input('Enter a command: ')
if response == 'help':
print(help_text)
continue
elif response == 'exit':
print("bye")
return
else:
result = process_command(response)
if result is not None:
for i in result:
for j in i:
if type(j) == str:
mat = "{:12}\t"
if type(j) == float:
mat = "{:5}\t"
if j > 1.0:
j = round(j, 1)
if j <= 1.0:
j = int(j*100)
j = str(j)+"%"
if j is None:
j = "Unkown"
mat = "{:12}\t"
j = str(j)
if len(j) > 12:
j = j[:12]
j += "..."
print(mat.format(j), end="")
print()
print()
# Make sure nothing runs or prints out when this file is run as a module
if __name__=="__main__":
init_db()
insert_c()
insert_b()
# process_command("companies ratings top=8")
interactive_prompt()
# bars ratings
# bars sellcountry=US cocoa bottom=5
# companies region=Europe bars_sold
# companies ratings top=8
|
846db0ccf6f7a6d4b85f0ac0ddc835540d25cd62
|
Cenibee/PYALG
|
/python/fromBook/chapter6/string/5_group_anagrams/5-1.py
| 465 | 3.6875 | 4 |
from collections import defaultdict
from typing import DefaultDict, List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagram_dict = DefaultDict(list)
for word in strs:
anagram_dict["".join(sorted(word))].append(word)
return anagram_dict.values()
sol = Solution()
print(sol.groupAnagrams(["eat","tea","tan","ate","nat","bat"]))
print(sol.groupAnagrams([""]))
print(sol.groupAnagrams(["a"]))
|
cc72d3652a6b03f819a644aceef157df4228cba0
|
dnisbet/pico
|
/lcd/demo.py
| 1,577 | 3.703125 | 4 |
"""Example using a character LCD connected to an ESP8266."""
from time import sleep
from LCD import CharLCD
while True:
"""Run demo."""
# Initialize the LCD
lcd = CharLCD(rs=0, en=1, d4=2, d5=3, d6=4, d7=5,
cols=16, rows=2)
# Print a 2 line centered message
lcd.message('Hello', 2)
lcd.set_line(1)
lcd.message('World!', 2)
sleep(3.0)
# Show the underline cursor.
lcd.clear()
lcd.show_underline()
lcd.message('Underline')
lcd.set_line(1)
lcd.message('Cursor: ')
sleep(3.0)
# Also show the blinking cursor.
lcd.clear()
lcd.show_blink()
lcd.message('Blinking')
lcd.set_line(1)
lcd.message('Cursor: ')
sleep(3.0)
# Disable blink and underline cursor.
lcd.show_underline(False)
lcd.show_blink(False)
# Scroll message right & left.
lcd.clear()
lcd.message('Scrolling Demo')
sleep(1.0)
for i in range(16):
sleep(0.25)
lcd.move_right()
for i in range(16):
sleep(0.25)
lcd.move_left()
sleep(2.0)
# The End
lcd.create_char(0, bytearray([7, 12, 24, 16, 22, 22, 22, 16]))
lcd.create_char(1, bytearray([28, 6, 3, 1, 13, 13, 13, 1]))
lcd.create_char(2, bytearray([16, 20, 20, 23, 19, 24, 12, 7]))
lcd.create_char(3, bytearray([1, 1, 5, 29, 25, 3, 6, 28]))
lcd.clear()
lcd.message('The', 3)
lcd.home()
lcd.message('\x00')
lcd.message('\x01')
lcd.set_line(1)
lcd.message('End', 3)
lcd.set_cursor(0, 1)
lcd.message('\x02')
lcd.message('\x03')
|
4fe869207f750d162f30e583bb32851af5be000b
|
Grande-zhu/CSCI1100
|
/LEC/lec03/printxyz.py
| 115 | 3.5 | 4 |
x = 4
y = 2
print(x,y,sep=' ', end='\n')
print("\n"+str(x),str(y),sep=',', end='\n')
print(str(x)+str(y))
|
288a7a7f6f05638700d209d0dd9f5f592b6a0828
|
tianyaqpzm/book
|
/source/posts/Algorithm/算法专题/树/morrisTraversal.py
| 696 | 3.828125 | 4 |
class Solution:
# 既不使用递归,也不借助栈, 在O(1) 空间完成这个过程
def morrisTrav(self, root):
curr = root
while curr:
if curr.left is None:
print(curr.data, end="")
curr = curr.right
else:
prev = curr.left
while prev.right is not None and prev.right is not curr:
prev = prev.right
if prev.right is curr:
prev.right = None
curr = curr.right
else:
print(curr.data, end="")
prev.right = curr
curr = curr.left
|
81f2ac8f566f604e94a2698d1f4575aedfa45296
|
embersyc/udacityproj
|
/movie trailer project/movie.py
| 1,342 | 3.796875 | 4 |
import webbrowser
# this class contains the data for a movie
class Movie():
"""
Use this class to store data related to a movie.
"""
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
"""
Movie class constructor.
@param self: This is a special parameter used by Python to refer to instance variables.
Similar to 'this' keyword in other languages.
Do not pass this parameter to constructor.
@param movie_title: The title of the movie.
@param movie_storyline: A brief description of the movie
@param poster_image: The URL of the Movie's poster image.
@param trailer_youtube: The URL of the Movie's trailer on youtube.
"""
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
"""
Use this method to open a browser and play the youtube trailer.
@param self: This is a special parameter used by Python to refer to instance variables.
Similar to 'this' keyword in other languages.
Do not pass this parameter to method.
"""
webbrowser.open(self.trailer_youtube_url);
|
eae6f6a5f09737f094e91b76e7a8abf218e2e4d6
|
zkazi97/Tic-Tac-Toe
|
/Tic_Tac_Toe_ZKazi.py
| 1,792 | 3.671875 | 4 |
# Python Project: Tic-Tac-Toe by Zain Kazi
#%% Import packages
import pandas as pd
import numpy as np
#%% Create empty board
emptycol = ["","",""]
initialFrame = {"A" : emptycol,
"B" : emptycol,
"C" : emptycol}
boardFrame = pd.DataFrame(initialFrame); boardFrame.index = boardFrame.index + 1
print(boardFrame)
#%% Define invalid inputs
choices = ["A1","A2","A3","B1","B2","B3","C1","C2","C3"]
taken = []
result = False
def validity(pos1):
while (pos1 in choices) == False or (pos1 in taken):
pos1 = input("Invalid Option, Enter Different Position: ").upper()
pos2 = pos1
return pos2
#%% Determine if match is over
def outcome(df):
result = False
d1 = board.iloc[0,0] + board.iloc[1,1] + board.iloc[2,2]
d2 = board.iloc[0,2] + board.iloc[1,1] + board.iloc[2,0]
bvalues = board.sum(axis=0).append(board.sum(axis=1)).values
bvalues = np.append(bvalues,d1)
bvalues = np.append(bvalues,d2)
if "XXX" in bvalues:
result = True
print("Player 1 wins. Player 2 loses.")
elif "OOO" in bvalues:
result = True
print("Player 2 wins. Player 1 loses.")
elif i == 9:
result = True
print("Tied game.")
return result
#%% Loop through game
result = True
board = boardFrame
for i in range(1,10):
if i % 2 == 1:
pos = input("For Player 1, Enter Position for X: ").upper()
pos2 = validity(pos)
board.loc[int(pos2[1]),pos2[0]] = "X"
print(board)
if i % 2 == 0:
pos = input("For Player 2, Enter Position for O: ").upper()
pos2 = validity(pos)
board.loc[int(pos2[1]),pos2[0]] = "O"
print(board)
taken.append(pos2)
if outcome(board) == True:
break
|
87eb3600648bc571b7295f8de25f30e35bac2939
|
lihujun101/LeetCode
|
/LinkList/L707_design-linked-listt.py
| 2,841 | 3.75 | 4 |
class Node(object):
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class MyLinkedList(object):
# root->Node(1)->Node(2)
def __init__(self):
self.root = Node()
self.tailnode = None
self.length = 0
def get(self, index):
if index >= 0 and index <= self.length - 1:
node = self.root.next
idx = 0
while idx < index:
node = node.next
idx += 1
return node.val
else:
return -1
def addAtHead(self, val):
self.length += 1
head = self.root.next
# 把tailnode节点位置找到
node = Node(val)
if head is None:
self.tailnode = node
self.root.next = node
node.next = head
def addAtTail(self, val):
tailnode = self.tailnode
if tailnode is None:
return self.addAtHead(val)
self.length += 1
node = Node(val)
tailnode.next = node
self.tailnode = node
def addAtIndex(self, index, val):
if index == self.length:
return self.addAtTail(val)
if index == 0:
return self.addAtHead(val)
if index > 0 and index < self.length:
self.length += 1
node = self.root.next
node_insert = Node(val)
cur = node
idx = 0
while idx < index:
cur = node
node = node.next
idx += 1
cur.next = node_insert
node_insert.next = node
def deleteAtIndex(self, index):
if index > 0 and index < self.length - 1:
self.length -= 1
node = self.root.next
idx = 0
cur = node
while idx < index:
cur = node
node = node.next
idx += 1
value = node.val
cur.next = node.next
del node
return value
elif index == self.length - 1:
self.length -= 1
node = self.root.next
idx = 0
cur = node
while idx < index:
cur = node
node = node.next
idx += 1
value = node.val
cur.next = None
self.tailnode = cur
del node
return value
elif index == 0:
self.length -= 1
node = self.root.next
self.root.next = node.next
value = node.val
del node
return value
if __name__ == '__main__':
linkedList = MyLinkedList()
linkedList.addAtHead(1)
linkedList.addAtTail(3)
linkedList.addAtIndex(1, 2)
linkedList.deleteAtIndex(2)
print(linkedList.get(0))
|
ef955b223785b6f866652a9a4d5d38453301891c
|
HavinLeung/CSES-problem-set
|
/permutations/permutations.py
| 297 | 3.828125 | 4 |
n = int(input())
if n == 1:
print(1)
elif n in (2,3):
print("NO SOLUTION")
else:
def first():
for i in range(n, 0, -2):
print(i, end=' ')
def second():
for i in range(n-1, 0, -2):
print(i, end=' ')
if n%2==0:
second()
first()
else:
first()
second()
|
abaff474d4c460857103323418c7e4b30b896fdc
|
avin82/PythonFoundation
|
/my_turtle_moves.py
| 195 | 3.703125 | 4 |
import turtle
turtle = turtle.Turtle()
turtle.speed(20)
def make_moves(distance):
turtle.forward(distance)
turtle.left(distance)
x = 1
while x < 190:
make_moves(x)
x = x + 1
|
68ff7f633eb13ed8e1cadfb6a145f762378e9d60
|
santosclaudinei/Python_Geek_University
|
/sec08_ex24.py
| 233 | 3.65625 | 4 |
def arvore(largura):
tamanho = largura + 1
for i in range(1, tamanho):
anterior = i - 1
simbolo = '*'
print(f'{(anterior + i) * simbolo} ')
largura = int(input('Informe a largura: '))
arvore(largura)
|
1032656b5f2f148b8d0ec2caac7b779568b36a1a
|
david-mclnnis/iot-computing-arduino-script
|
/cheaper02/example/chapter02-grammer-statementfor.py
| 134 | 3.78125 | 4 |
# 반복문
sum01 = 0
for x in range(0,9):
sum01 = sum01 + x
print(sum01)
sum02 = 0
while sum02 < 9:
sum02 += 1
print(sum02)
|
3f744de85b595cbdf474f6614a67eb68a89d7a6b
|
rmitio/CursoEmVideo
|
/Desafio029.py
| 431 | 3.78125 | 4 |
#DESAFIO029 Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 ppor cada km acima do limite.
v = int(input('Digite a velocidade do carro: '))
if v > 80 :
u = 7 * (v - 80)
print('VOCÊ EXCEDEU O LIMITE DE VELOCIDADE!! Tem que pagar uma multa de R${:.2f}'.format(u))
else:
print("Parabéns você está no limite!")
|
e1251011dffaca9d5edb06b8f5835b4af8194925
|
skynetshrugged/paip-python
|
/run_examples.py
| 1,431 | 3.828125 | 4 |
s = "jajkfhdjbaoioiebcjhb"
count = 0
for x in s:
if x in "aeiou":
count+=1
print(count)
d = "aeiou"
c = 0
for x in s:
if x in d:
c+=1
print(c)
print(list(s))
y = dict()
t = list(s)
z = []
for x in t:
if x in "aeiou":
y[x] = y.get(x, 0) + 1
for x,y in y.items():
z.append( (y,x) )
#z.sort()
for x in z:
print(x)
s = 'azcbobobbegbobghakl'
counter = 0
index = 0
while index < len(s):
index = s.find("bob", index)
if index == -1:
break
print("bob found at", index)
counter +=1
index += 2
print("Number of times bob occurs is:", counter)
# import regex as re
#
# x = re.findall("bob", s, overlapped=True)
# print("Number of times bob occurs is:",len(x))
# Assume s is a string of lower case characters.
#
# Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
#
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
#
# Longest substring in alphabetical order is: abc
for i in range(5):
print(i)
a = 2*2
print(f"Hello World {a}\nI Love you!")
x = 2
y = 5
# x = int(input("Please enter x value: "))
# y = int(input("Please enter y value: "))
print(f"{x} * {y} = {x * y}!\n Well done!")
print(2/10 == 0.3)
|
eac579c99580333e49b124ab265647118cc3ff66
|
JevgeniPillau/Algorythms
|
/lesson _02/lesson_02_task08.py
| 699 | 4.03125 | 4 |
'''8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.'''
seq = int(input('how many sequences of numbers will be?: '))
num = int(input('what number i will count?: '))
counter = 0
for i in range(1, seq + 1):
var = int(input(f'Sequence {str(i)}: '))
while var > 0:
if var % 10 == num:
counter += 1
var = var // 10
print(f'You have inserted {counter} number {num}')
|
7a1b99a61715d0d6fbc36e2851a80fcb3a6615dd
|
agnaka/CEV-Python-Exercicios
|
/Pacote-download/Exercicios/ex076.py
| 464 | 3.796875 | 4 |
print('-' * 42)
print(f'LISTAGEM DE PREÇOS'.center(42))
print('-' * 42)
lista = ('Lápis', 1.75, 'Borracha', 2.00, 'Caderno', 15.00, 'Estojo', 25.00, 'Transferidor', 4.20, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.30, 'Livro', 34.9)
# print(lista)
# print(len(lista))
for item in range(0,len(lista), 2):
print(f'{lista[item]:.<30}R$ {lista[item + 1]:>7.2f}')
# for preco in range(0,len(lista), 1):
# print(f'{lista[preco]}')
print('-' * 42)
|
4cef68dd503e276590f32fbd302dd7dc2130fcd7
|
zhanghui0228/study
|
/python_Basics/RegularExpression/regular_re_module.py
| 1,427 | 3.5625 | 4 |
#re模块
'''
re模块
findall()的使用
search()的使用
group()和groups()的使用
split()正则分割
Sub()正则替换
'''
"""
re模块:
re.I re.IGNORECASE 不区分大小写的匹配
re.L re.LOCALE 根据所使用的本地语言通过\w、\W、\b、\B、\s、\S实现匹配
re.M re.MULTILINE ^和$分别匹配目标字符串中的起始和结尾,而不是严格匹配整个字符串本身的起始和结尾
re.S rer.DOTALL "."(点号)通常匹配除了\n(换行符)之外的所有单个字符;该标记表示"."(点号)能够匹配全部字符
re.X re.VERBOSE 通过反斜线转义,否则所有空格加上#(以及在该行中所有后续文字)都被忽略,除非在一个字符类中或者允许注释并且提高可读性
#re模块 ----compile #推荐编译,但不是必须的
书写形式:
compile(pattern, flags = 0) pattern :正则表达式
使用任何可选的标记来编译正则表达式的模式,然后返回一个正则表达式对象
re模块 ----match
书写形式:
match(pattern, string, flags = 0)
尝试使用带有可选的标记的正则表达式的模式来匹配字符串。如果匹配成功,就返回匹配对象;如果失败,就返回None
"""
|
da9b5fffd03a0bb30ddfea80e0a5d444eba963e2
|
tjwjdgks/algorithm
|
/프로그래머스/두 개 뽑아서 더하기/test.py
| 325 | 3.71875 | 4 |
def solution(numbers):
answers = set();
for i in range(len(numbers)):
for j in range(len(numbers)):
if i==j : continue
answers.add(numbers[i]+numbers[j])
answer = list(answers)
answer.sort()
return answer
if __name__ == "__main__" :
b = [2,1,3,4,1]
a = solution(b)
|
af395d85a1322048dc4597b2a31931eeaaff755c
|
DSCBUK/project-euler
|
/problem2-thegezy.py
| 956 | 4.15625 | 4 |
'''Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms. '''
def Fibonacci(x): #function to generate the Fibonnaci sequence
a, b = 1, 2 #initial terms: 1 and 2
while (a < x):
yield a
a, b = b, a+b #swap values, add to get the next term
print ("The even terms of the Fibonacci sequence less than 4,000,000 are:")
s = 0 #initial sum declared
for y in Fibonacci(4000000): #function call
if (y % 2 == 0): #get the even-valued terms
s += y #increment the sum
print (y) #print the terms
print ("And their sum is ", s) #print the sum
|
2fe4d12f458f5a8868fffe83d0367410a9929f0b
|
OdeclasV/movie_website
|
/media.py
| 1,363 | 3.90625 | 4 |
import webbrowser
class Movie():
''' This class provides a way to store movie related information '''
'''This is a constant variable (class variable), and Google StyleGuide says that these type of variables should be spelled out in all caps'''
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
def __init__(self, movie_title,movie_storyline, poster_image, trailer_youtube, date, numb_of_times_watched):
# NOTE:__ underscores tell that this is a reserved word in python
'''Function that constructs instances of Movie class for each movie in the website. Arguments are assigned to corresponding instance variables below.
Arguments:
movie_title(str): Name of the movie
movie_storyline(str): Brief description of the movie and its plot
poster_image(str): ULR of movie posting from Wikipedia (if available)
trailer_youtube(str): URL of movie trailer from YouTube (if available)
date(number): Year in which the movie was relased
numb_of_times_watched (number): Total number of times I've seen that movie'''
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
self.launch_date = date
self.times_watched = numb_of_times_watched
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url) # opens browser to show movie trailer
|
103a556747bbad7e5d221ca3315d032548f3b160
|
semanticmx/grupak_sys
|
/calculadora.py
| 1,248 | 4.3125 | 4 |
"""
Implementa una calculadora que suma, resta, multiplica,
divide y obtiene el residuo entero de una división
"""
def suma(x, y):
"""
suma x + y
"""
return x + y
def resta(x, y):
"""
resta x - y
"""
return x - y
def multiplicacion(x, y):
"""
multiplica x * y
"""
return x * y
def division(x, y):
"""
divide x / y, y valida división entre 0
"""
try:
return x / y
except ZeroDivisionError:
return 'ERR'
def modulo(x, y):
"""
regresa el residuo entero de la división de x / y
"""
return x % y
operadores = ['+', '-', '*', '/', 'res', ]
metodos = [suma, resta, multiplicacion, division, modulo, ]
operaciones = {operador[0]: operador[1] for operador in zip(operadores, metodos)}
def calculadora(operacion, operando_1, operando_2):
"""
ejecuta operacion entre operando_1 y operando_2 y regresa el resultado
>>> calculadora('+', 4, 8)
12
>>> calculadora('*', 3, 2)
6
>>> calculadora('-', 5, 10)
-5
>>> calculadora('/', 20, 5)
4.0
>>> calculadora('res', 10, 3)
1
>>> calculadora('/', 10, 0)
ERR
"""
return print(operaciones[operacion](x=operando_1, y=operando_2))
|
0c207648f09a038a952c549e9b9eab883d48bc66
|
a100kpm/daily_training
|
/problem 0192.py
| 865 | 4.09375 | 4 |
'''
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
You are given an array of nonnegative integers.
Let's say you start at the beginning of the array and are trying to advance to the end.
You can advance at most, the number of steps that you're currently on.
Determine whether you can get to the end of the array.
For example, given the array [1, 3, 1, 2, 0, 1], we can go from indices 0 -> 1 -> 3 -> 5, so return true.
Given the array [1, 2, 1, 0, 0], we can't reach the end, so return false.
'''
array = [1,3,1,2,0,1]
array2= [1,2,1,0,0]
def can_jump(array):
if len(array)<=1:
return True
lenn=len(array)-1
for i in range(lenn):
if i+array[i]>=lenn:
a=can_jump(array[:i+1])
if a==True:
return True
return False
|
bb6dd2ad6ac004fa3045005809ccfc46089f67da
|
bousmahafaycal/tricks_python
|
/couleur.py
| 1,964 | 3.5 | 4 |
"""
Module permettant d'écrire en couleur dans le terminal, de modifier l'intensité des couleurs etc ...
Créé le 02/04/2017
Par Fayçal Bousmaha
Codes SGR complets : https://en.wikipedia.org/wiki/ANSI_escape_code#graphics
"""
class Couleur:
# Voici les codes couleurs :
BLACK = 0
RED = 1
GREEN = 2
YELLOW = 3
BLUE = 4
PURPULE = 5
CYAN = 6
WHITE = 7
DEFAULT = 9
# Code clignotage:
SLOW = 0
FAST = 1
NO = 2
# Voici une fonction permettant soit de changer la couleur du texte, soit celle du background
def color(couleur, background=False):
if background:
print('\033[4{}m'.format(couleur),end='')
else:
print('\033[3{}m'.format(couleur),end='')
# Voici une fonction permettant soit d'augmenter soit de diminuer l'intensité
def intensite (augmenter =True):
if augmenter:
print('\033[1m',end='')
else:
print('\033[2m',end='')
# Voici une fonction qui permet de souligner le texte
def souligner (souligneur=True):
if souligneur:
print('\033[4m',end='')
else :
print('\033[24m',end='')
# Fonction permettant d'incliner le texte
def incliner(incline = True):
if (incline):
print('\033[3m',end='')
else :
print('\033[23m',end='')
# Voici une fonction qui remet le style comme il est par défaut
def defaut():
print('\033[0m',end='')
if __name__ == "__main__":
Couleur.color(Couleur.BLUE)
print("Bleu")
Couleur.color(Couleur.WHITE)
print("Blanc")
Couleur.color(Couleur.RED)
print("Rouge")
print("\n")
Couleur.color(Couleur.GREEN)
print("Hacking")
Couleur.intensite()
Couleur.intensite()
print("Hacking")
Couleur.intensite(False)
Couleur.intensite(False)
print("Hacking")
Couleur.souligner()
print("Hacking")
Couleur.souligner(False)
print("Hacking")
Couleur.incliner()
print("Hacking")
Couleur.incliner(False)
print("Hacking")
Couleur.defaut()
print("Hacking")
Couleur.color(Couleur.PURPULE,True)
print("Sur fond violet")
Couleur.defaut()
print("Merci, au revoir")
|
4ea51ac49b84f2f09627ad41a0240309bee023f5
|
cs-learning-2019/python1fri
|
/Lessons/Week5/Getting_Started_With_Processing/Getting_Started_With_Processing.pyde
| 1,900 | 4.1875 | 4 |
# Focus Learning: Python Level 1
# Getting started with Processing
# Kavan Lam
# March 5, 2021
def setup():
print("Setting up my project")
size(700, 700)
def draw():
fill(255, 255, 0)
rect(0, 200, 50, 50) # rect = rectangle eg/ rect(x, y, length, width) and x, y is the top left corner of the rect
rect(350, 350, 150, 50)
### IGNORE THIS ####
"""
# def = defining
# Note all of the code inside a section must be tabbed (4 spaces)
def setup():
# Note x is always first so size(x, y) x is left to right and y is top to bottom
size(900, 600)
def draw():
background(255, 255, 0) # We use RGB colors. Each number is from 0-255
# White ---> (255, 255, 255)
# Black ---> (0, 0, 0)
pushStyle()
fill(255, 0, 0) # Use this to change the color of the inside of the shape
stroke(0, 0, 255) # Use this to change the color of the perimeter of the shape
strokeWeight(4) # Use this to change the thickness of the perimeter of the shape
rect(0, 200, 50, 50) # rect = rectangle eg/ rect(x, y, length, width) and x, y is the top left corner of the rect
popStyle()
pushStyle()
fill(0, 255, 255) # Use this to change the color of the inside of the shape
stroke(255, 0, 255) # Use this to change the color of the perimeter of the shape
rect(200, 300, 100, 50)
ellipse(450, 300, 100, 100) # ellipse(x, y, length, width)
popStyle()
pushStyle()
stroke(255, 0, 0)
strokeWeight(4)
line(100, 100, 400, 400) # line(x, y, x, y) The first two is for the starting point. The last 2 is for the ending point.
popStyle()
pushStyle()
fill(20, 178, 102)
textSize(50)
text("Hello World", 300, 50) # text("What you want to say", x, y)
popStyle()
"""
|
a6a740dff7968c59177be09dde5b7407e58ed162
|
reddeers77/pythonTkinter
|
/bouncingBallAcceleration.py
| 743 | 3.5625 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 16 16:10:21 2021
@author: Egemen G
"""
from tkinter import *
from random import randint
tk = Tk()
W,H = 400,400
r = 50
ball_coords = ((W/2)-(r/2)), r+10, ((W/2)+(r/2)), ( 2*r )+10
canvas = Canvas(tk, width=W, height=H)
canvas.pack()
ball = canvas.create_oval( ball_coords, fill='red')
Vx = 10
Vy = 10
g=50
def fall():
global Vx, Vy, g
print(g)
canvas.move(ball, Vx,Vy)
if (g<=20):
g=10
canvas.after(g,fall)
left,top,right,bot = canvas.coords(ball)
if (top<=0 or bot >=H):
Vy = -Vy
g-=5
if(left <=0 or right >=W):
Vx = -Vx
g-=5
fall()
tk.mainloop()
|
ea14236143f485458bd7fbffa84591ea52eb8875
|
yred/euler
|
/python/problem_048.py
| 327 | 3.625 | 4 |
# -*- coding: utf-8 -*-
"""
Problem 48 - Self powers
The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
"""
def solution():
return sum(pow(n, n, 10**10) for n in range(1, 1001)) % 10**10
if __name__ == '__main__':
print(solution())
|
65fe03b93606ebaec296277ac347f37b3d6ddc78
|
JaiminiNayee/hhaccessibility.github.io
|
/importers/utils/csv_filter.py
| 3,323 | 3.625 | 4 |
"""
This script is useful for filtering locations from a CSV to a specific latitude and longitude range.
"""
import csv
import sys
from import_helpers.task_loader import get_import_config
from import_helpers.import_config_interpreter import get_location_field
def filter_csv(min_longitude, max_longitude, min_latitude, max_latitude, import_config, csv_input, csv_output):
with open(csv_input, 'r') as csv_input_file:
with open(csv_output, 'w') as csv_output_file:
# if there are titles in the first line, copy it.
if import_config['is_first_row_titles']:
line = csv_input_file.readline()
csv_output_file.write(line)
csv_reader = csv.reader(csv_input_file, delimiter=',', quotechar='"')
writer = csv.writer(csv_output_file, delimiter=',',
quotechar='"', quoting=csv.QUOTE_ALL)
num_values = len(import_config['columns'])
# loop through lines of the file.
for values in csv_reader:
if len(values) != num_values:
print(task['csv_filename'] + ': Line should have ' + str(num_values)
+ ' but ' + str(len(values)) + ' found in line: ' + str(values))
sys.exit(errno.EINVAL)
lon = float(get_location_field(import_config, 'longitude', values).strip())
lat = float(get_location_field(import_config, 'latitude', values).strip())
if lon <= max_longitude and lon >= min_longitude and lat <= max_latitude and lat >= min_latitude:
writer.writerow(values)
is_valid = True
if len(sys.argv) < 8:
print('Usage: min_longitude max_longitude min_latitude max_latitude csv_import_config_json_file csv_input csv_output')
is_valid = False
else:
import_config_filename = sys.argv[5].strip()
if '.json' not in import_config_filename:
print('The import config filename must end with .json. Instead you specified %s.' % import_config_filename)
is_valid = False
csv_input = sys.argv[6].strip()
csv_output = sys.argv[7].strip()
if csv_input == csv_output:
print('The CSV input and output file names must be different to avoid data loss. You specified %s and %s.' % (csv_input, csv_output))
is_valid = False
if '.csv' not in csv_input or '.csv' not in csv_output:
print('The CSV input and output files must end with .csv. You specified %s and %s' % (csv_input, csv_output))
is_valid = False
import_config = get_import_config(import_config_filename)
if is_valid:
min_longitude = float(sys.argv[1].strip())
max_longitude = float(sys.argv[2].strip())
min_latitude = float(sys.argv[3].strip())
max_latitude = float(sys.argv[4].strip())
# Swap longitudes if they're out of order.
if min_longitude > max_longitude:
temp = max_longitude
max_longitude = min_longitude
min_longitude = temp
# Swap latitudes if they're out of order.
if min_latitude > max_latitude:
temp = max_latitude
max_latitude = min_latitude
min_latitude = temp
if min_latitude < -90 or max_latitude > 90:
print('The latitude range must be between -90 and 90 but %f to %f specified.' % (min_latitude, max_latitude))
is_valid = False
if min_longitude < -180 or max_longitude > 180:
print('The longitude range must be between -180 and 180 but %f to %f specified.' % (min_longitude, max_longitude))
is_valid = False
if is_valid:
filter_csv(min_longitude, max_longitude, min_latitude, max_latitude, import_config, csv_input, csv_output)
|
08f4e9e846c4cb9dab391bb465eba8ba992dc697
|
stromatolith/peabox
|
/algorithms/PSO/PSO_defs.py
| 14,731 | 3.984375 | 4 |
#!python
"""
my trial at implementing the particle swarm optimisation algorithm
What is PSO? Imagine you're sitting in a rolling supermarket trolley with a
bungee rope and an anchor in your hand, that allows you to hook up t a truck to
get pulled along or to a lantern pole. Attached to a lantern pole you will be
on an elliptic orbit around it and due to the friction of the trolley wheels
you will be slowly spiralling ever closer to the pole. The lantern pole is
the attractor of your orbit. In PSO the attractors are points in the search
space marked by others as their best point found so far. Secondly, every agent
can have several attractors. Thirdly, the attractor influence is scaled by
random numbers, the scaling value is renewed in each time step, and it is a
different value in each dimension. But the last and perhaps most important
characteristic of PSO is the choice of attractors, and here the word swarm
comes in. A swarm is a communicating group of agents exhibiting collective
behaviour. One can imagine that two herrings swimming closely together in a
swarm are sharing information about their swimming speed and direction, and
that each herring most of the time follows the external influences and sometimes
gives an own little impulse. The unintuitive thing about PSO is that the
closeness in the information sharing network has nothing to do with the
closeness in the search space. It's like your facebook network that might
consist of friends far away. If you are an agent in a traditional PSO setup
then you have two attractors: one is the best spot in your own past trajectory
and the other one is the best memory from the dudes you usually talk to; and
the guys you usually talk to are "the local neighbourhood of degree N in the
communication topology" which is an extra thing being created at the beginning
and remaining constant throughout the search, i.e. the guys you usually talk to
remain the same subgroup of the swarm no matter where everybody moves in the
search space.
Now thinking of attractors as in a planetary system. If you have two attractors
then you are effectively orbiting around the center of mass of the two drawing
nice and smooth orbits around it. In PSO this is not so due to the random force
scalings on the one hand and the intentionally coarse time stepping (widely
scanning the search space is what counts, and not the fine resolution of the
trajectory and the realism of some quasi-physical behaviour) on the
other hand.
One more thing. Making a tangential step forward from a position in an orbit
always increases the radius of the orbit. The radius increase is stronger the
coarser the time stepping is. This is the reason for the strong inertia damping
in PSO, which is necessary to prevent the particle speeds from diverging and
the swarm from exploding.
(There are some more explaining notes at the end of the code, justifying some
choices made for the code implementation below.)
"""
from numpy import zeros, ones, array, asfarray, mod, where, argsort, argmin, argmax, fabs
from numpy.random import rand, randint
from peabox_individual import Individual
from peabox_population import Population
#from peabox_helpers import parentselect_exp
def rand_topo_2D(m,n):
r=rand(m*n)
s=argsort(r)
return s.reshape(m,n)
class PSO_Topo(object):
def __init__(self,nh_degree):
self.tsize=0 # topology size, i.e. how many members
self.nhd=nh_degree # the neighbourhood degree, i.e. only comunicating with first degree neighbours or up to 4th degree or so
class PSO_Topo_standard2D(PSO_Topo):
def __init__(self,shape,nh_degree):
PSO_Topo.__init__(self,nh_degree)
dim1,dim2=shape
self.tsize=dim1*dim2
self.dim1=dim1 # how many lines in the topology array
self.dim2=dim2 # how many columns in the topology array
self.map=rand_topo_2D(dim1,dim2) # the map, i.e. the 2D grid containing the individual numbers
self.imap=zeros((self.tsize,2),dtype=int) # the inverse map
self.update_imap()
def is_of_size(self,n):
return self.dim1*self.dim2 == n
def update_imap(self):
for i in range(self.dim1):
for j in range(self.dim2):
self.imap[self.map[i,j],:]=i,j
def get_indices_of(self,num):
"""wasteful method that should in principle always be obsolete, because the
information is to be made available by the inverse map"""
idx=argmin(fabs(self.map-num))
k=idx/self.dim2; l=idx%self.dim2
return k,l
def get_neighbourhood(self,n,deg):
k,l=self.imap[n,:] # the indices of that individual in the grid
nbs=[] # the list of neighbours
for i,j in enumerate(range(k-deg,k+1)):
jj=j%self.dim1
if i==0:
nbs.append(self.map[jj,l])
else:
nbs.append(self.map[jj,(l-i)%self.dim2])
nbs.append(self.map[jj,(l+i)%self.dim2])
for i,j in enumerate(range(k+deg,k,-1)):
jj=j%self.dim1
if i==0:
nbs.append(self.map[jj,l])
else:
nbs.append(self.map[jj,(l-i)%self.dim2])
nbs.append(self.map[jj,(l+i)%self.dim2])
return nbs
def get_neighbourhood_upto(self,n,deg):
k,l=self.imap[n,:] # the indices of that individual in the grid
nbs=[] # the list of neighbours
for i,j in enumerate(range(k-deg,k+1)):
jj=j%self.dim1
if i==0:
nbs.append(self.map[jj,l])
else:
llo=(l-i)%self.dim2; lhi=(l+i)%self.dim2
for ll in range(llo,lhi+1):
nbs.append(self.map[jj,ll])
for i,j in enumerate(range(k+deg,k,-1)):
jj=j%self.dim1
if i==0:
nbs.append(self.map[jj,l])
else:
llo=(l-i)%self.dim2; lhi=(l+i)%self.dim2
for ll in range(llo,lhi+1):
nbs.append(self.map[jj,ll])
return nbs
class PSO_Individ(Individual):
def __init__(self,objfunc,paramspace):
Individual.__init__(self,objfunc,paramspace)
self.attractors=[]
self.attweights=[]
self.speed=zeros(self.ng,dtype=float)
self.memory={} # will contain 'bestx', 'bestval', 'nhbestx', and 'nhbestval
self.nh=[] # own neighbourhood
self.egofade=0.5 # if 1 then don't listen to neighbourhood, if 0 then don't listen to yourself
self.swarm=None # slot for link to own population
self.random_influence='ND' # '1D' or 'ND'
def delete_attractors(self):
self.attractors=[]
self.attweights=[]
def add_attractor(self,coords,weight):
self.attractors.append(asfarray(coords))
self.attweights.append(weight)
def do_step(self):
#iniDNA=self.get_copy_of_DNA()
self.speed*=self.swarm.alpha
#print 'this guy {}'.format(self.no)
#print 'DNA ',self.DNA
#print 'attractors ',self.attractors
for a,w in zip(self.attractors,self.attweights):
if self.random_influence=='1D': r=rand()
elif self.random_influence=='ND': r=rand(self.ng)
else: raise ValueError("random_influence must be either '1D' or 'ND'")
self.speed += w*r * (a-self.DNA); #print 'adding {}'.format(w*r * (a-self.DNA))
self.DNA += self.speed
#endDNA=self.get_copy_of_DNA()
#print 'last step: {} and speed {}'.format(endDNA-iniDNA,self.speed)
def update_bestx(self):
#print 'hello from dude {} beginning update'.format(self.no)
if self.isbetter(self.memory['bestval']):
self.memory['bestx']=array(self.DNA,copy=1)
self.memory['bestval']=self.score
#print 'dude {} has updated'.format(self.no)
def update_nh(self):
self.nh=self.swarm.get_neighbourhood_upto(self.no,self.swarm.nhd)
def update_nh_bestx(self):
for i,num in enumerate(self.nh):
if i==0:
nhbestx=array(self.swarm[num].memory['bestx'],copy=1)
nhbestval=self.swarm[num].memory['bestval']
else:
if self.whatisfit=='minimize':
if self.swarm[num].memory['bestval'] < nhbestval:
nhbestx[:]=self.swarm[num].memory['bestx']
nhbestval=self.swarm[num].memory['bestval']
elif self.whatisfit=='maximize':
if self.swarm[num].memory['bestval'] > nhbestval:
nhbestx[:]=self.swarm[num].memory['bestx']
nhbestval=self.swarm[num].memory['bestval']
else:
raise ValueError("self.whatisfit should be either 'minimize' or 'maximize', but it is '{}'".format(self.whatisfit))
self.memory['nhbestx']=nhbestx
self.memory['nhbestval']=nhbestval
#print 'dude {} updates nhbestx {} and nhbestval {}'.format(self.no,nhbestx,nhbestval)
class PSOSwarm_standard2D(Population,PSO_Topo_standard2D):
def __init__(self,species,popsize,objfunc,paramspace,toposhape,nh_degree):
Population.__init__(self,species,popsize,objfunc,paramspace)
PSO_Topo_standard2D.__init__(self,toposhape,nh_degree)
if not self.is_of_size(self.psize):
raise ValueError("The topology shape does not fit the population size.")
self.alpha=0.7298
self.psi=2.9922
self.attractor_boost=1.0
for dude in self:
dude.swarm=self # making individuals conscious of the general population
def initialize_memories(self):
for dude in self:
dude.memory['bestx']=array(dude.DNA,copy=1)
dude.memory['bestval']=dude.score
dude.memory['nhbestx']=array(dude.DNA,copy=1)
dude.memory['nhbestval']=dude.score
for dude in self:
dude.update_nh()
dude.update_nh_bestx()
def random_ini(self):
self.new_random_genes()
self.eval_all()
self.initialize_memories()
self.advance_generation()
def do_step(self):
for dude in self:
# empty and refill attractor list, then move
#print '************* next dude {} ***************'.format(dude.no)
#print 'difference between DNA and nhbestx: ',dude.memory['nhbestx']-dude.DNA
#dude.update_bestx()
#dude.attractors=[dude.memory['bestx']]
#dude.attweights=[dude.egofade*(self.psi/2.)*self.attractor_boost]
#dude.update_nh_bestx()
#dude.attractors.append(dude.memory['nhbestx'])
#dude.attweights.append((1.-dude.egofade)*(self.psi/2.)*self.attractor_boost)
#print 'difference between DNA and nhbestx: ',dude.memory['nhbestx']-dude.DNA
#print '-------------- update finished -------------'
dude.delete_attractors()
dude.update_bestx()
dude.add_attractor(dude.memory['bestx'], dude.egofade*(self.psi/2.)*self.attractor_boost)
dude.update_nh_bestx()
dude.add_attractor(dude.memory['nhbestx'], (1.-dude.egofade)*(self.psi/2.)*self.attractor_boost)
dude.do_step()
self.eval_all()
self.advance_generation()
def advance_generation(self):
self.mark_oldno()
self.sort()
self.update_no()
for dude in self:
k,l=self.imap[dude.oldno]
self.map[k,l]=dude.no
self.update_imap()
Population.advance_generation(self)
"""
What is particle swarm optimisation PSO?
Imagine you roll through town sitting in a supermarket trolley, and the special
equipment in your hand is one or several bungee ropes with anchors at their ends.
This allows you to hook yourself up to cars and trucks rolling by, or to statues
lanterns, park benches and fountains. If you let go from a truck and hook
yourself up to a lantern, then you will stay in a circular but more often rather
elipptical orbit and depending on the friction of the trolley wheels you will be
spiralling ever closer towards it more and more relaxing the rubber rope. PSO
means there is a swarm of trolley riders and the poles you hook up with are
markers indicating your best found spot so far and somebody else's best spot,
or more precisely, the best spot found within a subgroup of the swarm, those
few ones you communicate with all the time, which are your neighbours in the
communication network, but which may be placed far away in the swarm in the
actual search space.
Before I started to write the code, these were the options I've been thinking of:
a) create a population and a communication topology separately, then hand it over
to the main algorithm
b) subclassing the Population class and equip it with the communication topology
and the corresponding functionalities
c) create a separate class for the communication topology and let the particle
swarm inherit from both population and topology on an equal level, i.e.
code the particle swarm as a subclass of both
I don't like (a) because you always will have to write algo.topology.update()
and algo.population.do_stuff() and I think this separation into two targets for
your commands is a deviation from the ideal case of letting one single thing,
the swarm, behave its way. If it is good to understand a swarm as a population
of agents with interaction patterns leading to a overall behaviour that can be
described as collective properties of the swarm, then I think it is good to
keep the whole thing together also in your thinking and coding.
Possibility (b) seems like not too much fun for the coding work, because from
the beginning you have to deal with this rather big population class.
I like the idea of coding up and testing the topology class separately, i.e.
taking option (c), that allows testing the thing while it is slim and little.
The only thing to pay attention to will be not to use attribute names which
already exist in the population. If there is only one little topology class one
might as well just add it to the population class while subclassing it immediately,
but it seems there are tons of options for coding up all kinds of 1D, 2D, nD
topologies or networks of whatever shapes like rings of thinly connected cloud
insulas. This means one might end up wanting to write a hierarchy of topology
classes, and during coding there needs to be testing of course. And maybe I
wanna reuse the topology stuff later outside the current context. These were my
arguments for going with option (c).
"""
|
3273697cd996d9192ce36604368535e2d470dbbb
|
zhenyat/Rob
|
/ground/rpigpio/rpi_gpio_demo_1.py
| 1,060 | 3.53125 | 4 |
#!/usr/bin/env python3
################################################################################
# rpi_gpio_demo.py
#
# Demo samples for RPi.GPIO
#
# 03.07.2019 Created by: zhenya
################################################################################
import RPi.GPIO as GPIO
import time
from pprint import pprint
class RPiGPIODemo():
def __init__(self):
GPIO.setmode(GPIO.BCM)
self.button_pin = 17
self.led_pin = 27
GPIO.setup(self.button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(self.led_pin, GPIO.OUT)
def button_callback(self):
led_blink()
def button_event(self):
GPIO.add_event_detect(self.button_pin,GPIO.RISING,callback=button_callback)
message = input("Press enter to quit\n\n")
GPIO.cleanup()
def led_blink(self):
for i in range(4):
GPIO.output(self.led_pin, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(self.led_pin, GPIO.LOW)
time.sleep(0.5)
|
372e73e9e433bbb49bc7041ce6792b7b4c2fbcdf
|
green-fox-academy/Niloofar3275
|
/week4-day1/Greeterfunction.py
| 334 | 4.125 | 4 |
al = "Green fox"
def greet(a):
x = " Greetings , dear " + a
return x
Greeting = greet(al)
print(Greeting)
# - Create variable named `al` and assign the value `Green Fox` to it
# - Create a function called `greet` that greets it's input parameter
# - Greeting is printing e.g. `Greetings, dear Green Fox`
# - Greet `al`
|
522d4b820c91fdfaecec569d7ccf440b236675d6
|
bbert9/Data-Analyst-Nanodegree-Program
|
/No-show datset/Investigate_the_no_show_dataset (2).py
| 9,773 | 3.59375 | 4 |
#!/usr/bin/env python
# coding: utf-8
#
# # Project: Investigate the No-show dataset
#
# ## Table of Contents
# <ul>
# <li><a href="#intro">Introduction</a></li>
# <li><a href="#wrangling">Data Wrangling</a></li>
# <li><a href="#eda">Exploratory Data Analysis</a></li>
# <li><a href="#conclusions">Conclusions</a></li>
# </ul>
# <a id='intro'></a>
# ## Introduction
#
# The No-show dataset: This dataset collects information from 100k medical appointments in Brazil and is focused on the question of whether or not patients show up for their appointment. A number of characteristics about the patient are included in each row.
#
# I choosed for this project to analyse the No-show dataset. For me I found it important to investigate this dataset and to know closer why people don't attend this appointment which is an important one. I decided to find the factors that push people to get rid of this appointment.
# ## Questions I will try to answer
# 1)Is there a gender correlation the No-Show ?
#
# 2)Is there an age correlation to the No-Show factor ?
#
# 3)Is there a schorlarship correlation to the No-Show factor ?
#
# 4)Is there a time correlation ?
#
# 5)Is there an health correlation ?
#
# In[107]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
get_ipython().run_line_magic('matplotlib', 'inline')
df=pd.read_csv('/Users/bert/Downloads/noshowappointments-kagglev2-may-2016.csv')
# <a id='wrangling'></a>
# ## Data Wrangling
#
# > **Tip**: In this section of the report, you will load in the data, check for cleanliness, and then trim and clean your dataset for analysis. Make sure that you document your steps carefully and justify your cleaning decisions.
#
# ### General Properties
# In[4]:
df.head(3)
# In[179]:
df.shape
# In[6]:
df['Scholarship'].value_counts()
# In[5]:
df.dtypes
# In[10]:
df.shape
# In[14]:
df.hist(figsize=(8,8))
#
# ### Data Cleaning
# In[108]:
df['ScheduledDay'] = pd.to_datetime(df['ScheduledDay'])
df['AppointmentDay'] = pd.to_datetime(df['AppointmentDay'])
# In[8]:
df.head(3)
# In[9]:
df.dtypes
# In[18]:
df.drop(df[(df.Age < 0) | (df.Age > 100)].index, inplace = True)
# In[23]:
df['No-show'].value_counts()
# For my fourth question I need the time of the appointment so i'm going to create new columns which are goind to help me.
# In[111]:
df['day']=df['ScheduledDay'].dt.day
df['hour']=df['ScheduledDay'].dt.hour
df['month']=df['ScheduledDay'].dt.month
df['hour'].head(2)
# <a id='eda'></a>
# ## Exploratory Data Analysis
#
# In[180]:
def plot(string):
a = pd.crosstab(df[string], df['No-show'])
a.div(a.sum(1).astype(float), axis=0).plot(kind='bar', stacked=True)
plt.ylabel('Count %')
def Diff_stats(string1, int1, int2):
df_s0 = df[df[string1]==int1]
df_s1 = df[df[string1]==int2]
x=df_s0['No-show'].value_counts(normalize=True).Yes
y=df_s1['No-show'].value_counts(normalize=True).Yes
print('The pourcentage difference is: ',abs(x-y)*100,' %')
#will be useful for a lot of variables
# In[11]:
columns = ['Gender','Scholarship','Diabetes','Hipertension']
color = ['r','g','y','b']
y=0
for i in columns:
plt.subplot(int(str(22)+str((columns.index(i)+1))))
df[i].value_counts(normalize=True).plot.bar(figsize= (9,9), color=color[y])
plt.xlabel(columns[y])
plt.ylabel('% count')
plt.title(columns[y])
y+=1
# -65% are female
# -85% up to 90% doesn't have a scholarship experience
# -<10% suffer from diabtes
# -<20% from hipertension
# In[14]:
df['Neighbourhood'].value_counts(normalize=True).sort_values(ascending = False)[:10].plot.bar(figsize=(24,6), fontsize = 15.0, color = 'g')
plt.title('Neighbourhood', fontsize=20)
plt.ylabel('% Count',fontsize=20)
# In[26]:
sns.distplot(df['Age'])
# In[23]:
df['Age'].plot.box(figsize=(8,8))
# ### Is there a gender correlation ?
# In[150]:
plot('Gender')
# There seems to be no correlation at all between the gender and the no Show. Around 80% of both genders didn't came to the appointment.
# ### Is there an Age correlation ?
# In[44]:
a = pd.crosstab(df['Age'], df['No-show'])
a.plot()
# We could make some histogrammes.
# In[61]:
df_N = df[df['No-show']=='Yes']
df_N.plot(kind='hist', y='Age')
plt.xlabel('Age')
# In[62]:
df_N = df[df['No-show']=='No']
df_N.plot(kind='hist', y='Age')
plt.xlabel('Age')
# Middle age people (around 50-60) and very young babies are more likely to not go to the appointment.
#
# In the 'Yes' population they are more babies and young peoples. In the 'Yes' pop there is freq of 3000 and in the 'no' pop there is a freq of 14000. Babies are not brought to the appointment in the majoratity even its the more important part of the 'yes' pop.
# ### Is there a Scholarship correlation ?
# In[102]:
a = pd.crosstab(df['Scholarship'], df['No-show'])
a.plot.bar()
# In[181]:
plot('Scholarship')
# In[84]:
df_s1 = df[df['Scholarship']==1]
df_s0 = df[df['Scholarship']==0]
a = pd.crosstab(df_s1['Scholarship'], df['No-show'], normalize=True)
a.plot.bar(color=('r','g'))
plt.ylabel('Count %')
b = pd.crosstab(df_s0['Scholarship'], df['No-show'], normalize=True)
b.plot.bar(color=('r','g'))
plt.ylabel('Count %')
# In[89]:
df_s1['No-show'].value_counts(normalize=True)
#the precise values
# In[160]:
df_s0['No-show'].value_counts(normalize=True)
# In[146]:
print(0.237363-0.198057,'%')
# There a lot more people that didn't have a scholarship experience.
#
# for those who didn't have a scholarship experience:
# more than 80% didn't came and less than 20% came.
#
# for those who have a scholarship experience:
# around 75% didn't came and 25% came.
#
# Scholarship as an influence on the relsult (on the No-show). A scholarship experience result in a higher chance of coming to the appointment.
# ### Time correlation
# Time is a good thing to study. I am not going to study month or days because I don't find those relevant in this dataset.
# In[139]:
#Here is the time histogramme for people who came
df_Y = df[df['No-show']=='Yes']
plt.hist(df_Y['hour'], color='g')
# In[147]:
#Here is the time histogramme for people who didn't came
df_N = df[df['No-show']=='No']
plt.hist(df_N['hour'],color='y')
# The two histogrammes are exactly the same exept for one hour slot: 6am. People didn't show up at 6am.
# So the time is a factor just for one hour slot. 6am is pretty early.
# ### Handicap, Diabetes and Hipertension correlation ?
# I decided to treat those variables together because I suppose It have the same impact on the No-show.
# In[182]:
plot('Handcap')
# In[176]:
Diff_stats('Handcap',0,4)
# In[183]:
plot('Diabetes')
# In[177]:
Diff_stats('Diabetes',0,1)
# In[184]:
plot('Hipertension')
# In[178]:
Diff_stats('Hipertension',0,1)
# So as expected Hipertension and Handicap evoluted together and react the same. If a person is impacted by hipertension or diabetes he has around 3% less chances of going to the appointment.
#
# Otherwise If you are impacted by a Handcap you have more chances to go to the appointment. It can get up to 13% if your handcap is class 4 handcap.
#
# So the 3 variables didn't react in the same way.
# <a id='conclusions'></a>
# ## What can we get out of it
#
# We did four little studies on the age, gender, scholarship and time (in hour).
#
# - Gender :
# There are no correlation at all on the No-show. We can't expect from a gender to go more often to the appointment.
#
# - Age:
# There is ! In fact middle age peoples (around 50) and babies are more likely to not show up !
#
# - Scholarship:
# Again there is. People with a scholarship experience are 4% more likely to show up. Maybe people with a scholarship background can better understand the importance of this appointment.
#
# - Hour:
# A little correlation: at 6am a lot more appointment are cancelled. When It is too early peoples don't want to go to the appointment.
#
# - Health:
# Some desease can push you to not go to your appointment by around 3% like the diabete and the hipertension. But f you suffer from handcap you are way more likely to go to the appointment, this go up with the level of your handcap (max 13% for a level 4).
# So we may conclude on the one hand that heavier illness (when your life is in danger) push people to go to the appointment and on the over hand that people with little desease (no life-threatening danger) are maybe more tired and don't want to go to the appointment: maybe they don't need it as much as others.
# We can conclude that many factors are related to the fact that people don't show up but I expected it to be more relevant. There are a lot of factors wich have a little impact. As far as those factors didn't have so much importance we should have had more criterias.
# # Limitations
# What are the limits of this dataset ?
#
# - The dimension of the sample. We may lack some important informations, I don't think that peoples decisions can be reduced to 10 variables. We lack some variables but the purpose of this exploration was just to have a vision of the major variables.
# For exemple the wealth columns would have been appreciated. This one could have been correlate with the scholarship experience and the presence to appointment.
#
# - Not deep enough. To completly understand the dataset we should have looked into the correlations between each variables not just the 'No-show' and one variable at a time. This is caused by a lack of statistical background from me.
#
# - The shape of the dataset. Even if the shape is around 100000 rows it can't represent the all population. I don't know if this sample is from anyone or if It was produced by a minority of the population.
|
aa6e89d58bae51ffab5f87a51b4d7fbe3c702277
|
linchengzeng/day7
|
/test_file/test_class.py
| 769 | 3.96875 | 4 |
# -*- coding:utf-8 -*-
# Author:aling
class Person(object):
def __init__(self,name,age): #self = b, self.name = b.name
self.name = name
self.age = age
def talk(self):
print('person is talking.....')
class BlackPerson(Person):
def __init__(self,name,age,power):#先继承,再重构
Person.__init__(self,name,age)
self.power = power
# print(self.name) #继承后就可以直接使用了
# print(self.age) #继承后就可以直接使用了
def talk(self):
print("I'm %s ,my age %s,my power is %s"%(self.name,self.age,self.power))
def walk(self):
print("is walking .....")
class WritePerson(Person):
pass
b = BlackPerson('aling',22,'Noraml')
b.talk()
b.walk()
|
51d32c4138544ed3f7751336e1cd1dc5553bdc9e
|
ClaudioBotelhOSB/CompetitiveProgramming
|
/Codeforces/Round #682 (Div. 2)/682_D2_A.py
| 107 | 3.609375 | 4 |
for t in range(int(input())):
x = int(input())
res= ""
for i in range(x):
res+="1 "
print(res)
|
3d36464ebdad066f7aaa74d34a509715f466b4cf
|
tinbolw/Python-Stuff
|
/madlibs game.py
| 219 | 3.703125 | 4 |
color = input("Enter a color: ")
plural_noun = input("Enter a plural noun: ")
thing = input("Enter a thing: ")
print("Roses are" + " " + color + ",")
print(plural_noun + " " + "are blue,")
print("I need " + thing)
|
bf54a9354ad1bef2d84a7db12d1a10c0fe6fddc7
|
miguel-dev/holberton-system_engineering-devops
|
/0x16-api_advanced/1-top_ten.py
| 675 | 3.5625 | 4 |
#!/usr/bin/python3
"""
Queries Reddit API and prints the titles of the first 10 hot posts
a given subreddit
"""
import requests
def top_ten(subreddit):
"""Prints titles of first 10 hot posts of a given subreddit"""
url = 'https://api.reddit.com/r/{}/hot?limit=10'.format(subreddit)
headers = {'user-agent': 'linux:api_advanced:v1.2 (by /u/miguel-dev)'}
r = requests.get(url, headers=headers, allow_redirects=False)
if (r.status_code != requests.codes.ok):
print('None')
else:
dict_hot = r.json()
hot_posts = dict_hot.get("data").get('children')
for post in hot_posts:
print(post.get('data').get('title'))
|
2a575c466df0625026e206b918427cfacef9712d
|
stellayk/Python
|
/ch06/6_1_Class.py
| 835 | 3.796875 | 4 |
def calc_func(a,b):
x=a
y=b
def plus():
p=x+y
return p
def minus():
m=x-y
return m
return plus, minus
p, m = calc_func(10, 20)
print('plus=',p())
print('minus=',m())
class calc_class:
x = y = 0
def __init__(self,a,b):
self.x=a
self.y=b
def plus(self):
p=self.x+self.y
return p
def minus(self):
m=self.x-self.y
return m
obj = calc_class(10,20)
print('plus=', obj.plus())
print('minus=', obj.minus())
class Car:
cc=0
door=0
carType=None
def __init__(self, cc, door, carType):
self.cc=cc
self.door=door
self.carType=carType
def display(self):
print(self.cc, self.door, self.carType)
car1=Car(2000,4,"car")
car2=Car(3000,5,"SUV")
car1.display()
car2.display()
|
cb7e561ea7ecd16832691a6e0e3a3962231f148a
|
elim168/study
|
/python/basic/opencv/06.face_multi_check.py
| 754 | 3.515625 | 4 |
# 定位人脸区域,包含多人脸的
import cv2
image = cv2.imread('face03.jpg')
# 把原图转换为灰色图片
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 默认的人脸检测
detector = cv2.CascadeClassifier('/home/elim/dev/projects/study/python/venv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml')
# 检测图片,返回每张人脸的信息。每张人脸包含x,y,width,height四项信息,其中width和height会相等。
faces = detector.detectMultiScale(gray_image)
print(faces)
for x, y, w, h in faces:
# 通过画矩形把每张人脸圈起来
cv2.rectangle(image, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
cv2.imshow('test', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
1226e7ac786317695fcaa47a97c0b124308b04f4
|
harrifeng/leet-in-python
|
/065_valid_number.py
| 1,543 | 4.21875 | 4 |
"""
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should
gather all requirements up front before implementing one.
"""
import unittest
class MyTest(unittest.TestCase):
def test(self):
solution = Solution()
self.assertTrue(solution.isNumber("0"))
self.assertTrue(solution.isNumber(" 0.1 "))
self.assertFalse(solution.isNumber("abc"))
self.assertFalse(solution.isNumber("1 a"))
self.assertTrue(solution.isNumber("2e10"))
self.assertTrue(solution.isNumber("-1."))
self.assertTrue(solution.isNumber(" 005047e+6"))
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.strip()
s += '#'
i = 0
n1, n2, n3 = 0, 0, 0
if s[i] in ['+', '-']:
i += 1
while s[i].isdigit():
i += 1
n1 += 1
if s[i] == '.':
i += 1
while s[i].isdigit():
i += 1
n2 += 1
if n1 == n2 == 0:
return False # e has something on left
if s[i] in ['e', 'E']:
i += 1
if s[i] in ('+', '-'):
i += 1
while s[i].isdigit():
i += 1
n3 += 1
if n3 == 0:
return False # e has something on right
return s[i:] == '#'
|
8cd1f7c6f07dc071ae635c0cb3ecf8d7210fc75b
|
dpres/genalg
|
/Atom_w_Gene.py
| 8,874 | 3.5625 | 4 |
import numpy as np
import random as random
class Gene:
"""Gene class contains x and y coords (float-types) and identities (int-types)"""
index = 0
def __init__(self, value):
self._value = value
Gene.index += 1
def report_value(self):
"""reports the value of the gene"""
return self._value
class Atom:
"""Atom class contains atom-type objects that form clusters."""
index = 0
def __init__(self, genelist, genedict):
"""Creates an atom with position coordinates and a type"""
print genelist
self._list_of_genes = genelist
self._dict_of_genes = genedict
Atom.index += 1
def genes_list_in_atom(self):
"""Returns list of genes in the atom"""
return self._list_of_genes
def genes_dict_in_atom(self):
"""Returns dict of genes in the atom"""
return self._dict_of_genes
def report_xcoord(self):
"""Returns the xcoord of atom."""
return Gene.report_value(self._dict_of_genes[self._list_of_genes[0]])
def report_ycoord(self):
"""Returns the ycoord of atom."""
return Gene.report_value(self._dict_of_genes[self._list_of_genes[1]])
def report_label(self):
"""Returns the label of atom."""
return Gene.report_value(self._dict_of_genes[self._list_of_genes[2]])
def report_pos(self):
"""Returns the coordinates of the atom"""
pos_vect = np.array([Atom.report_xcoord(self), Atom.report_ycoord(self)])
return pos_vect
def report_pos_and_label(self):
"""Returns all three genes of the atom as the_atom=[xcoord, ycoord, label]"""
the_atom = [Atom.report_xcoord(self), Atom.report_ycoord(self), Atom.report_label(self)]
return the_atom
class Cluster:
"""Cluster class contains cluster-type objects comprising atom-type objects."""
index = 0
def __init__(self, list_of_atoms, dict_of_atoms):
"""Creates cluster from a list of atoms"""
self._list_of_atoms = list_of_atoms
self._dict_of_atoms = dict_of_atoms
Cluster.index += 1
def atoms_list_in_cluster(self):
"""Returns list of atoms in the cluster"""
return self._list_of_atoms
def atoms_dict_in_cluster(self):
"""Returns dictionary of atoms in the cluster"""
return self._dict_of_atoms
def cluster_energy(self):
"""Calculates the energy of a cluster by looping through all pairs of atoms in the cluster"""
l = Cluster.atoms_list_in_cluster(self)
d = Cluster.atoms_dict_in_cluster(self)
energy = energy_calculator(l, d)
return energy
def output_cluster(self):
"""Returns cluster as list of lists"""
list_of_lists = []
l = Cluster.atoms_list_in_cluster(self)
d = Cluster.atoms_dict_in_cluster(self)
for atom in l:
list_of_lists.append(Atom.report_pos_and_label(d[atom]))
return list_of_lists
def energy_calculator(atomlist, atomdict):
"""Calculates energy of a set of atoms"""
l = atomlist
d = atomdict
sigma_dict = {(1, 1): sigmaAA, (1, 2): sigmaAB, (2, 1): sigmaAB, (2, 2): sigmaBB}
energy = 0 # initialises energy
for i in xrange(N - 1):
for j in xrange(i + 1, N):
type_i = Atom.report_label(d[l[i]])
type_j = Atom.report_label(d[l[j]])
# print type_i
# print type_j
atom_pair = (type_i, type_j)
sigma = sigma_dict[atom_pair] # picks appropriate sigma for the calculation
pos_i = Atom.report_pos(d[l[i]])
pos_j = Atom.report_pos(d[l[j]])
d_pos = pos_j - pos_i
r_ij = np.sqrt(np.dot(d_pos, d_pos)) # distance between centres of atoms
frac6 = (sigma / r_ij) ** 6 # makes calculation faster
energy += 4 * ((frac6 ** 2) - frac6)
return energy
def mating(p1_alist, p1_adict, p2_alist, p2_adict):
"""mating step with position mutations"""
list_of_atoms = []
dict_of_atoms = {}
for x in xrange(N):
c = random.random()
if c < 0.5:
pos_arr = Atom.report_pos(p1_adict[p1_alist[x]]) + 0.1 * (random.random() - 0.5)
else:
pos_arr = Atom.report_pos(p2_adict[p2_alist[x]]) + 0.1 * (random.random() - 0.5)
d = random.random()
if d < 0.5:
atom_type = Atom.report_label(p1_adict[p1_alist[x]])
else:
atom_type = Atom.report_label(p2_adict[p2_alist[x]])
'''
dict_of_atoms['Atom' + str(Atom.index)] = Atom(pos_arr, atom_type)
list_of_atoms.append('Atom' + str(Atom.index))
'''
return list_of_atoms, dict_of_atoms
'''
global N # N is the total number of atoms in the cluster
global sigmaAA, sigmaAB, sigmaBB # CoM-CoM distance of atoms XX
'''
N = 2 # total number of atoms in the cluster
C = 2 # starting number of clusters
# lists sigmas; sigmaBB needs fixing to allow list of sigmaBBs
sigmaAA = 1
sigmaBB = 1
sigmaAB = (sigmaAA + sigmaBB) / 2
# the size of the 2D space:
x_size = 20
y_size = 20
dict_of_clusters = {}
list_of_clusters = [] # initialises list of clusters that will get updated through the GA
while len(list_of_clusters) < C: # creating C clusters
atom_dict = {}
atom_list = []
while len(atom_list) < N: # each cluster has N atoms
gene_dict = {}
gene_list = []
# randomly assigns position coordinates to create x/ycoord genes
x_coord = x_size * (random.random())
y_coord = y_size * (random.random())
# equal probability of A/B type assignment
# A==1, B==2
t = random.random()
if t < 0.5:
atom_label = 1
else:
atom_label = 2
val_arr = [x_coord, y_coord, atom_label]
for val in val_arr:
gene_dict['Gene' + str(Gene.index)] = Gene(val)
gene_list.append('Gene' + str(Gene.index))
print len(gene_list)
# Atom-type object creation:
atom_dict['Atom' + str(Atom.index)] = Atom(gene_list, gene_dict)
atom_list.append('Atom' + str(Atom.index))
# checks if the cluster is garbage; if not, creates cluster
energy = energy_calculator(atom_list, atom_dict)
if energy > 0.05:
for atom in atom_list:
del atom_dict[atom] # cleans up unneeded memory
# Atom.index -= N # rewinds the Atom index - initialisation of large clusters could cause integer overrun
else:
# print atom_list
dict_of_clusters['Cluster' + str(Cluster.index)] = Cluster(atom_list, atom_dict)
list_of_clusters.append('Cluster' + str(Cluster.index))
# make a dictionary of energies of all clusters
dict_of_cluster_energies = {}
for cluster in list_of_clusters:
dict_of_cluster_energies[cluster] = Cluster.cluster_energy(dict_of_clusters[cluster])
fail_count = 0
steps = 0
while fail_count < 10000:
# choice of two random integers for list of clusters
a = int(C * random.random())
b = int(C * random.random())
if a == b: # try again if the same cluster is picked twice - parthenogenesis is useless
continue
# calls parent clusters and retrieves their atom lists/dicts ... better than retrieving them always
parent1 = list_of_clusters[a]
p1_alist = Cluster.atoms_list_in_cluster(dict_of_clusters[parent1])
p1_adict = Cluster.atoms_dict_in_cluster(dict_of_clusters[parent1])
parent2 = list_of_clusters[b]
p2_alist = Cluster.atoms_list_in_cluster(dict_of_clusters[parent2])
p2_adict = Cluster.atoms_dict_in_cluster(dict_of_clusters[parent2])
print p1_adict, p1_alist, p2_adict, p2_alist
# two parents produce two kids:
for y in range(2):
steps += 1
(thelist, thedict) = mating(p1_alist, p1_adict, p2_alist, p2_adict)
energy = energy_calculator(thelist, thedict)
if energy < max(dict_of_cluster_energies.values()):
thekey = max(dict_of_cluster_energies, key=dict_of_cluster_energies.get)
del dict_of_clusters[thekey]
del dict_of_cluster_energies[thekey]
list_of_clusters.remove(thekey)
dict_of_clusters['Cluster' + str(Cluster.index)] = Cluster(thelist, thedict)
list_of_clusters.append('Cluster' + str(Cluster.index))
dict_of_cluster_energies['Cluster' + str(Cluster.index)] = Cluster.cluster_energy(dict_of_clusters['Cluster' + str(Cluster.index)])
fail_count = 0
else:
for atom in thelist:
del thedict[atom] # cleans up unneeded memory
Atom.index -= N
fail_count += 1
print 'f', steps, fail_count, max(dict_of_cluster_energies.values())
print list_of_clusters
print dict_of_clusters
print dict_of_cluster_energies
|
1fbd573d2647dd5c29a3520c91411ca7df852f52
|
incognito050924/giparang_mirror_server
|
/api/common/common_utils.py
| 374 | 4.125 | 4 |
from enum import Enum
def enum(**enums):
"""
Make a Enum type.
:param enums: Declare types and values what it will be represented.
:return: The instance of Enum class.
Example:
Numbers = enum(ONE=1, TWO=2, THREE='three')
>> Numbers.ONE
1
>> Numbers.TWO
2
>> Numbers.THREE
'three'
"""
return type('Enum', (), enums)
|
6996e9672e30ed401d180daeba296f22a080a8a7
|
cnicogd/holbertonschool-higher_level_programming
|
/0x06-python-classes/1-square.py
| 167 | 3.640625 | 4 |
#!/usr/bin/python3
"""1-square filled by the last excersise"""
class Square:
"""Square class assigns"""
def __init__(self, size):
self.__size = size
|
837f5dfbba9ea1bb25534735069e6fdf7020e4bc
|
sumanshil/TopCoder
|
/TopCoder/python/ntree/MaxDepthOfTree.py
| 1,084 | 3.546875 | 4 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root):
"""
if root is None:
return 0
lDepth = self.maxDepth(root.left)
rDepth = self.maxDepth(root.right)
return max(lDepth, rDepth) + 1
"""
if root is None:
return 0
stack = [(root, 1)]
maxdepth = 0
while len(stack) > 0:
item = stack.pop()
currnode = item[0]
currdepth = item[1]
maxdepth = max(currdepth, maxdepth)
if currnode.left:
stack.append((currnode.left, currdepth+1))
if currnode.right:
stack.append((currnode.right, currdepth+1))
return maxdepth
if __name__ == "__main__":
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.left.right = TreeNode(15)
root.right.right = TreeNode(7)
sol = Solution()
res = sol.maxDepth(root)
print(res)
|
8ea1b92633142538d1de7798c3ead22501957897
|
Indu-Palanisamy/Numbers
|
/digits_add.py
| 252 | 3.765625 | 4 |
try:
a=int(input("Enter the value:"))
sum=0
t=0
c=len(str(a))
if(a>0):
for i in range(0,c):
t=a%10
sum=sum+t
a=a//10
print(sum)
else:
print("Enter only positive numbers")
except ValueError:
print("Enter only digits")
|
6bc95cd64bc12c6aa32cace1c642f4e82a999a11
|
pod1019/python_learning
|
/Interface_Test_Training/test_case/mysql_train/sql_train.py
| 1,209 | 3.515625 | 4 |
import pymysql
from public import Config
'''1创建连接'''
conn = pymysql.connect(**Config.sql_conn_dict)
'''2创建游标,用作操作数据库'''
cur = conn.cursor()
'''数据库操作'''
# sql = 'select * from student'
# cur.execute(sql)
# print(cur.fetchone())
# print(cur.fetchone())
# # cur.scroll(0,mode='absolute') # 绝对移动:把游标移动到初始位置
# cur.scroll(-1,mode='relative')# 相对移动:把游标从当前位置移动到上1行的位置(当前位置线上移动n行,用-n)
# print(cur.fetchone())
# print(cur.fetchone())
# print(cur.fetchmany(2)) # 取下面两行
# print(cur.fetchall()) # 取剩余的所有行
'''
code=1
写法1
# sql = "select * from student where code = %s" %code
# cur.execute(sql)
# 写法2 比写法1更好,能防止SQL注入
sql = "select * from student where code = %s"
cur.execute(sql,code) #把code作为参数传入
'''
# 多个参数
code = (('女','18'),('man','19')) #sex字段和age字段.这样写也能防止SQL注入
sql = "select * from student where sex = %s and age = %s"
cur.executemany(sql,code) #多个参数 必须要用executemany
print(cur.fetchone())
'''关闭游标、关闭连接'''
cur.close()
conn.close()
|
4af4002c377583ea9921b0659d09a7439ad8f235
|
souvik119/157152-Introduction-to-Programming
|
/week 4/souvikghosh_a4.py
| 630 | 4.03125 | 4 |
############################################
# The pattern is as below:
# Display number starts from 10000
# Deducted number starts from 100
# In each iteration of the loop:
# - deducted number is subtracted from display number
# - deducted number is in turn subtracted by 1
# - if deducted number is less than 10 reset it to 100
# - continue the loop till display number is greater than or equal to 0
############################################
display_num = 10000
deduct_num = 100
while display_num >= 0:
print(display_num)
display_num -= deduct_num
deduct_num -= 1
if deduct_num < 10:
deduct_num = 100
|
8e6cdfa57a4d624ff950d48ee64f16fa633f566a
|
mrFred489/AoC2017
|
/code12.py
| 594 | 3.546875 | 4 |
import functools
f = open("data12.txt")
data = dict()
visited = set()
for line in f:
temp = line.strip("\n").split(" <-> ")
data[temp[0]] = temp[1].split(", ")
def visit(name, visited):
children = set()
for child in data[name]:
if child not in visited:
visited.add(child)
visited = visited.union(visit(child, visited))
return visited
print(len(visit("0", set())))
groups = []
for key in data.keys():
if groups == [] or key not in functools.reduce(set.union, groups):
groups.append(visit(key, set()))
print(len(groups))
|
b15204302c0be9694da5164de5d2469abb1b484a
|
wrobdomi/AGH-UST
|
/01_ComputerScience/01_Python/PythonSemantics/09_control_flow_statements.py
| 975 | 4.0625 | 4 |
# There are four primary control flow statements if python:
# if elif else
# while loop
# for loop
# break, continue
x = 10
y = 25
z = 20
if(x < y and x < 20):
print("Yes")
else:
print("No")
if(y // x == 1):
print("x // y is 1")
elif(y // x == 0):
print("x // y is 0")
else:
print("x // y is neither 0 nor 1")
print("Simple while loop")
i = 0
while(i < 6):
i += 1
print(i)
print("While with break")
i = 0
while(i < 10):
if(i%5==0 and i!=0):
break
else:
print(i)
i+=1
print("Simple range for loop, starts at 0, up to 5")
for i in range(6):
print(i)
print("For range loop with specified range, from 2 up to 9")
for j in range(2, 10):
print(j)
print("For range loop with specified range and custom iteration change, from 0, up to 8")
for k in range(0,10,2):
print(k)
numbers = [1,2,3,4,5,6,7]
print("Looping through a list")
for x in numbers:
print(x)
|
c3df230e168f3f396c9e71f4dde84e6ab333a70f
|
GregApple/Number_Game
|
/App.py
| 3,206 | 4.3125 | 4 |
#!/usr/bin/env python3
import random
#App bootup screen in the command prompt.
def Welcome():
print("Welcome to Guess My Number!")
print("""
Enter 'Play' to play the game.
Enter 'Menu' to come back to the menu.
Enter 'Exit' to quit the game.
""")
#Activated by the Play selection from the startup menu.
def Start_Game():
attempt = 0
High_Score = ""
High_Score_Player = ""
number = random.randint(1, 100)
player = input("What is your name?")
print("Welcome {}, to Guess My Number!".format(player))
Guess_My_Number(attempt, High_Score, High_Score_Player, number, player)
#Activated once the user guesses the correct number.
def Play_Again(attempt, High_Score, High_Score_Player, player):
player = player
play_again = input("Would you like to play again? (Y/N) ")
if play_again.title().startswith("Y"):
New_Game(attempt, High_Score, High_Score_Player, player)
else:
print("Thanks for playing!")
print("""
Please type 'Exit' to leave the game
or type 'Menu' to return to the menu.
""")
#Activated if the user enters "Y" when prompted to play again.
def New_Game(attempt, High_Score, High_Score_Player, player):
number = random.randint(1, 100)
player = input("What is your name?")
attempt = 0
Guess_My_Number(attempt, High_Score, High_Score_Player, number, player)
#Guess input loop to handle errors caused by the user input for the guess variable.
def getGuess():
while True:
try:
guess = int(input("What do you think my number is? "))
return guess
except ValueError as err:
print("The value you entered is not an integer. Please try again.")
def Guess_My_Number(attempt, High_Score, High_Score_Player, number, player):
if High_Score != "":
print("""
High Score
{} {}
""".format(High_Score_Player, High_Score))
else:
print("The number will be between 1 and 100.")
#Guess loop that provides responses based on the user's input.
guess = -1
while guess != number:
guess = getGuess()
if guess > 100:
print("The number is below 100.")
continue
elif guess < 1:
print("The number is higher than 0.")
continue
elif guess < number:
print("The number is higher than {}.".format(guess))
attempt += 1
continue
else:
print("The number is lower than {}.".format(guess))
attempt +=1
continue
#The player guessed the correct number and has their score evaluated against the current high score.
if High_Score == "":
High_Score = attempt
High_Score_Player = player
elif attempt < High_Score:
High_Score = attempt
High_Score_Player = player
else:
High_Score = High_Score
plural = "s" if attempt != 1 else ""
print("Congratulations {}! You guessed the number in {} attempt{}.".format(player, attempt, plural))
Play_Again(attempt, High_Score, High_Score_Player, player)
#Initiates the player menu.
Welcome()
while True:
new_selection = input("> ")
new_selection = new_selection.title()
if new_selection == 'Exit':
break
elif new_selection =='Menu':
Welcome()
continue
elif new_selection =='Play':
Start_Game()
continue
|
0909584c605ed30d7fe72a71939a8b2d3ff65d16
|
RaymondDashWu/SPD-2.4-Job-Search-and-Interview-Practice
|
/ll_problem2_reverse_linked_list.py
| 1,742 | 4.21875 | 4 |
# Given a singly-linked list, reverse the order of the list by modifying the nodes’ links.
# Example: If the given linked list is A → B → C → D → E, nodes should be modified/rearranged so the list becomes E → D → C → B → A.
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def print_ll(self):
node = self.head
while node is not None:
print(node.data)
node = node.next
# PSEUDO BRAINSTORM
# keep track of a prev, cur, next pointer
# when prev is not none set cur.next to prev, cur to nxt, and nxt to nxt.next
# break when cur is none
def reverse(self):
prev = None
curr = self.head
nxt = curr.next
while curr is not None:
curr.next = prev
prev = curr
curr = nxt
try:
nxt = nxt.next
except:
break
self.head = prev
def reverse_recursive(self):
def _reverse_recursive(curr, prev):
if curr is None:
return prev
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return _reverse_recursive(curr, prev)
self.head = _reverse_recursive(self.head, None)
if __name__ == "__main__":
ll = LinkedList()
ll.head = Node("A")
second = Node("B")
ll.head.next = second
third = Node("C")
second.next = third
fourth = Node("D")
third.next = fourth
# ll.reverse()
ll.reverse_recursive()
print(ll.print_ll())
print("Head of LL", ll.head.data)
|
343a5661d3d98eafb430210cbf1f5d9aca7659fe
|
xlanor/bored
|
/reverse_in_place.py
| 857 | 4.28125 | 4 |
#!/usr/bin/env python
"""
Reverse words in place in a given string
In a sentence, while preserving spaces, reverse each individual word in place.
"""
def reverse_in_place(current_word: list, start, end):
if start >= end:
return current_word
current_word[start], current_word[end] = current_word[end], current_word[start]
return reverse_in_place(current_word,start+1,end-1)
def reverse_words_in_sentence(sentence: str):
# Split into individual words
sentence_of_words = sentence.split(" ")
# Convert to lists
sentence_of_words = [list(word) for word in sentence_of_words]
sentence_of_words = ["".join(reverse_in_place(cur, 0, len(cur)-1)) for cur in sentence_of_words]
return " ".join(sentence_of_words)
if __name__ == "__main__":
rs = reverse_words_in_sentence(" this is. a test. ")
assert rs == " siht .si a .tset "
|
3351597e0d34ed8fe001d2496bed54a30f9d6326
|
nucleic/atom
|
/examples/tutorial/employee.py
| 2,246 | 3.78125 | 4 |
# --------------------------------------------------------------------------------------
# Copyright (c) 2013-2023, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# --------------------------------------------------------------------------------------
"""Simple example of a class hierarchy built on atom.
"""
import datetime
from atom.api import (
Atom,
Bool,
ChangeDict,
Int,
Range,
Str,
Tuple,
Typed,
Value,
observe,
)
class Person(Atom):
"""A simple class representing a person object."""
last_name = Str()
first_name = Str()
age = Range(low=0)
dob = Value(datetime.date(1970, 1, 1))
debug = Bool(False)
@observe("age")
def debug_print(self, change: ChangeDict) -> None:
"""Prints out a debug message whenever the person's age changes."""
if self.debug:
templ = "{first} {last} is {age} years old."
s = templ.format(first=self.first_name, last=self.last_name, age=self.age)
print(s)
class Employer(Person):
"""An employer is a person who runs a company."""
# The name of the company
company_name = Str()
class Employee(Person):
"""An employee is person with a boss and a phone number."""
# The employee's boss
boss = Typed(Employer)
# The employee's phone number as a tuple of 3 ints
phone = Tuple(Int())
# This method will be called automatically by atom when the
# employee's phone number changes
def _observe_phone(self, val: ChangeDict) -> None:
if val["type"] == "update":
msg = "received new phone number for %s: %s"
print(msg % (self.first_name, val["value"]))
if __name__ == "__main__":
# Create an employee with a boss
boss_john = Employer(
first_name="John", last_name="Paw", company_name="Packrat's Cats"
)
employee_mary = Employee(
first_name="Mary", last_name="Sue", boss=boss_john, phone=(555, 555, 5555)
)
employee_mary.phone = (100, 100, 100)
employee_mary.age = 40 # no debug message
employee_mary.debug = True
employee_mary.age = 50
|
37358a151a1e720985feafd3c391545718afedde
|
terasakisatoshi/pythonCodes
|
/scikitLearn/mlpWithTensorFlow/mlp.py
| 1,752 | 3.734375 | 4 |
"""
Train MNIST dataset with Multi Layer Perceptron with tf.estimator"""
import numpy as np
import tensorflow as tf
# load dataset
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
# format them its type np.float32 or np.int32
X_train = X_train.astype(np.float32).reshape(-1, 28 * 28) / 255.0
X_test = X_test.astype(np.float32).reshape(-1, 28 * 28) / 255.0
y_train = y_train.astype(np.int32)
y_test = y_test.astype(np.int32)
# get validation target from training set
split_threshold = 5000
X_valid, X_train = X_train[:split_threshold], X_train[split_threshold:]
y_valid, y_train = y_train[:split_threshold], y_train[split_threshold:]
feature_cols = [tf.feature_column.numeric_column("X", shape=[28 * 28])]
# define model
dnn_classifier = tf.estimator.DNNClassifier(hidden_units=[300, 100],
n_classes=10,
feature_columns=feature_cols)
# begin training
input_fn = tf.estimator.inputs.numpy_input_fn(x={"X": X_train},
y=y_train,
num_epochs=40,
batch_size=50,
shuffle=True)
dnn_classifier.train(input_fn=input_fn)
# let's evaluate training results
test_input_fn = tf.estimator.inputs.numpy_input_fn(x={"X": X_test},
y=y_test,
shuffle=False)
eval_results = dnn_classifier.evaluate(input_fn=test_input_fn)
print(eval_results)
# predict for each data
y_pred_iter = dnn_classifier.predict(input_fn=test_input_fn)
y_pred = list(y_pred_iter)
print(y_pred[0])
|
566645d7920723a0cac2b4c59da36f972eb67665
|
josephchandlerjr/SmallPythonProjects
|
/ProjectEuler/p50.py
| 1,529 | 3.734375 | 4 |
"""
Consecutive prime sum
Problem 50
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
"""
def prime_gen(stop=10**6):
P = [None,None]+[True]*(stop-1)
for i in range(len(P)):
if P[i]:
yield i
if i < int(stop**0.5+1):
P[i+i::i] = [False]*((stop-i)//i)
def solve():
# create list of sums where prime_sum[i] = sum from first prime up to prime number i
# example prime_sum[2] = 2 prime_sum[3] = 5 prime_sum[5] = 10 ...
prime_sum = [0]
primes = []
total = 0
for p in prime_gen():
total += p
prime_sum.append(total)
primes.append(p)
prime_set = set(primes) # for searching
# now sum from i to j is prime_sum[j] - prime_sum[i]
best_length = 0
for i in range(len(primes)):
for j in range(i+best_length,len(primes)):
sum = prime_sum[j] - prime_sum[i]
if sum > 1000000:
break
if j-i > best_length and sum in prime_set:
best_length, best_sum = j-i, sum
return best_sum
if __name__=='__main__':
from lib.timer import best_time
print(best_time(solve,_reps=3))
|
e7d9bf1216194e6a97fcf1a45a6c7fdc90cb8b9b
|
KayTate/BOMB_Bank_Simulation
|
/complaint.py
| 22,208 | 3.71875 | 4 |
def complaint_to_man():
print('''
Finding the service at the Bank of Mashed Beats less than desireable, you decide to speak with the manager of B.O.M.B.
You glare at the employee who has given you such rudimentary service and demand that you speak to the manager.
The employee stares back at you blankly. They then slowly open their mouth and explain, "Unfortunately, we do not have a head manager at this time. Our last one just recently decided to take all of his savings a plan a family vacation to the plantet Mercury. Yes, I know it's quite strange, but my attempt to persuade him failed miserably"
''')
q1 = input('''
You stare back at the teller confused as all fuck.
You have three options:
1) You could tell the teller that they are the new acting manager and flip them off confidently.
2) You could storm into the \'Manager\' office on your left and see the truth for yourself
3) You could turn and walk away. This bank is filled with lunatic shitheads and you\'re too much of a boss (a poor boss, but a boss still to take this bull.
''')
while q1 not in '123':
q1 = input('''
That was not an option for your adventure. Try again:
1) You could tell the teller that they are the new acting manager and flip them off confidently.
2) You could storm into the \'Manager\' office on your left and see the truth for yourself
3) You could turn and walk away. This bank is filled with lunatic shitheads and you\'re too much of a boss (a poor boss, but a boss still to take this bull.
''')
if q1 == '1':
print('''
The teller raises their eyebrow at you as if your shorter-than-average middle phalange is going to actually make your declaration and their \'new\' position any more real.
"Yeah, listen...", the teller starts "I don\'t know what\'s up wiht you and trying to make me angry but I highkey don\'t have a soul. I work at a fucking bank for christ\'s sake.
BUT! I could use the promotion and our old manager was an asshole anyway, sooooooooo you\'re looking a the new acting manager of B.O.M.B.
They wink, feeling alot more proud of themselves. You can\'t help but feel betryaed because you GAVE them that position, who are they too feel proud about something as illegitmet as getting a job from a customer....you try not to ponder the hyprocity in that statement for too long.
The new manager gets up from the teller booth and walks towards a door with the word \'Manager\' on it. Hmmmmm, maybe you should have just gone over there first, but it doesn\'t matter at this point.
They are gone for approximately 10 minutes before they walk out with a new golden badge with their name on it.
I guess the manager is just special like that....
They come back around to face you outside of the booth.
"Alright," they begin, "let\'s get down to business."
''')
q2 = input('''
You look at the new manager. You are amazed that such a simpleton as yourself has so much power...maybe you should use this incredible ability to persuade elsewhere, maybe your crush will say yes to going out.
But forget about that right now, you have business to take care of.
You have two options
1) Follow the new manager and successfully enter your complaint. You made them so they will probably listen and take your concerns into consideration.
2) Use your incredbily persuasive abilities to get a personal teller at B.O.M.B, this will definitely come in handy...personal transactions, no lines, just pure bliss and easy banking (something that will never exist in modern society).
''')
while q2 not in '12':
q2 = input('''
That was not an option for your adventure. Try again:
1) Follow the new manager and successfully enter your complaint. You made them so they will probably listen and take your concerns into consideration.
2) Use your incredbily persuasive abilities to get a personal teller at B.O.M.B, this will definitely come in handy...personal transactions, no lines, just pure bliss and easy banking (something that will never exist in modern society).
''')
if q2 == '1':
print('''
"I just have a couple of suggestions on how to fight instead of fleeing west," you state casually to the manager
They look at you quizically. "Uhh what? We aren\'t fleeting anywhere. What the fuck are you ranting about?"
"Nothing..." you say underneath your breath, "Anyway, take me to your corridor."
The smiles and motions for you to follow them. Strangely, the manager leads you past the door with the actual \'Manager\' label on it and into a dark room deep within the office. You had no idea it was actually this large. It looked so small on the outside.
Eventually you reach a door with a strange orange glow coming out of its cracks. You feel warm... no...hot... it\'s considerably warm back here. You hope that this door is\'t actually a furnace meant for your beautiful bod.
The manager turns around and says, "Welcome, we can sit down and speak here" as they turn the doornob. You notice that the doorknob looks incredibly warm...it\'s fucking glowing from all of the heat that its holding. You wonder how the manager is holding it so confidently and without any sense of pain. Maybe their neurons aren\'t on today.
They open the door and you step in to find that it\'s hot as all fuck in there...but not because there is a large furnace...no it\'s just the thermostat. It reads 100 degrees Fahrenheit. You are confused at the heat, but decide not to say anything about it.
You take a sit in right-most chair in front of the large oak wood desk and brown leather recliner. The managers sits in the recliner and intertwines thier hands. Villanous like...weird.
"How can I help you this fine afternoon?" The manager smirks at you.
''')
q3 = input('''
You have three options:
1) Attempt to ignore how hot it is in the room. You are wearing your Fav sweater so it\'s probably just you and tell them about your complaints.
2) Ask about the goddamn heat. No human should work in these conditions and the manager cannot be working properly with such high temperatures. Quite frankly, you\'re concerned that they are\'t doing okay.
3) Just get up and leave. You've had enough of B.O.M.B. From their poor services to inconsdiderate temperatures, you just cannot stand to be in such a hostile environment. You shall take your business elsewhere.
''')
while q3 not in '123':
q3 = input('''
That was not an option for your adventure. Try again:
1) Attempt to ignore how hot it is in the room. You are wearing your Fav sweater so it\'s probably just you and tell them about your complaints.
2) Ask about the goddamn heat. No human should work in these conditions and the manager cannot be working properly with such high temperatures. Quite frankly, you\'re concerned that they are\'t doing okay.
3) Just get up and leave. You've had enough of B.O.M.B. From their poor services to inconsdiderate temperatures, you just cannot stand to be in such a hostile environment. You shall take your business elsewhere.
''')
if q3 == '1':
print('''
"Yeah, so, complaints." The manager takes out a notepad and a fancy ass pen. They look as though they genuinely care about what you have to say and want to actually change how the company is run.
"My first complaint is how you all just threw out my fucking application. It does not make any sense to have one if you don\'t plan on using it in anyway." The manager scribbles down (hopefully) everything you just stated.
"My next one is about the staff....uhh well I had you as my teller, and I\'m sure you do fine work in most circumstances, but your attitude and dispostion is all over the place. You work at a bank for christ sake, you should just keep the same face and attitude for everything. I know it may be boring, but just chill out"
More scribbling
"And finally, uhh I shouldn\'t be able to walk up and make an random teller the new manager. Like don\'t you all have any regulations or some shit?"
The manager looks up at you after scribbling some final notes.
"Well, these are some pretty good suggestions. B.O.M.B will take these into consideration. We thank you for your time. Now, get out."
You stare back at the manager with confusion on your face and a distinct feeling of disrespect deep within your cheest. How dare they. But, honestly, you\'re over this, and decide to get up and leave.
As you\'re walking out, you turn back to the manager and say "Fuck you." Nice. Very Classsy of you...now you won't get any type of exclusive, private bank teller nice ass shit. Good going.
''')
elif q3 =='2':
print('''
"Yo, what's up with the heat?"
The manager looks up at you, wide-eyed. They look terrified at one question...weird.
"Umm.... look just ignore the heat, it's a.....precautionary measure."
You stare at the manager. That made no sense, and as much as your curiosity neurons are firing, you decide not to push it. You've spent too much of your time here, and you need to get back to Russell, your 50 pound, 2-year old Bernese Mountain Dog. He's so fucking cute. You ponder pulling out your phone and showing pictures of Russell.
You squint at the manager, but decide to just tell them your complaints.
They scribble each down and look back up at you.
"Listen bud, next time you're in someone else's work space...just don't question thier envrionment. They surely know what they are doing."
That bullshit sounds suspicious....but you think back to Russell. He really needs to eat.
You get up from your chair, continuing to think about that cuddly son of a bitch (literally), and just walk out of the building and to your car. This has been a roller coaster of emotion and you just want to cuddle Russell again. He loves you for who you are and he doesn't care how hot or cold it is.
''')
else:
print('''
You walk out of the builing, go to your car, and turn on the ignition.
You realized that you just wasted at least six hours of your life, and those could have been spent playing on a swing set in your nearby park.
It's a nice ass park and those swings have leather cushioning. You have never felt so pretentious and royal sitting upon a swing set before.
After taking one last look at the builing before pulling out of the driveway, you remember your time here and decide that adulthood is not for you. You'll spend the rest of your days living like the Queen of England, sitting upon your swingy throne.
''')
else:
print('''
"Sooo, here's the thing," you begin, slyly, "I actually don't give two shits about your lame ass, good for nothing bank jobs. How about instead of following you to my death, you just give me my own personal teller who wil do what I say and need and will give me thier undivided attention as soon as I walk in the bank."
The manager looks at you. They are impressed, no one has ever persuaded them to do two unncessarily wild things in a few minutes.
"You know you have quite the persuasive skills. Maybe you should be a politician. I'm sure you could win all of your races. Anyway, as long as you don't make a mess of any of this, and you don't say shit about you giving me this position, and I'll see what I can do for you."
You smile.
You might just be the next President of the United States. And maybe the next monarch of England...you're sure the Queen wouldn't mind ruinging centries worth of lineage and power for a sweet, simpleton, American...despite the history between the US and UK. While you're at it, go ahead and run for Prime Minister of Canada.
''')
q3 = input('''
You have two options:
1) Push it further. Just take the job as CEO of B.O.M.B. You can make millions from this.
2) Take the personal teller, find some fancy attire and go run for President of the United States. Donald Trump is doing a terrible job anyway, and you're confident you can do better.
''')
while q3 not in '12':
q3 = input('''
That was not an option for your adventure. Try again:
1) Push it further. Just take the job as CEO of B.O.M.B. You can make millions from this.
2) Take the personal teller, find some fancy attire and go run for President of the United States. Donald Trump is doing a terrible job anyway, and you're confident you can do better.
''')
if q3 == '1':
print('''
"How about I do you one better?" You smirk at the manager and they immediately look as if they had just finished watching the Slience of the Lambs.
"Uh....what do you mean?"
"Well, I gave YOU the position of manager...so I'm going to give myself the position of CEO."
The manager's face relaxes. They actually look as though it is plausible for you to become the new CEO of B.O.M.B.
"...Ummm, sure. We can do that."
Damn. I can't believe that actually happened...and I'm the freakin narrator. Anyway, you look shocked, but you also aren't completely surprised. You lowkey have a superpower...use it wisely young grasshopper.
The manager motions for you to follow them into a room where they immediately call the corporate branch and inform them of the new CEO replacement. B.O.M.B needed one anyway, and you surely are better than the current one.
After a few minutes on the phone, the manager looks back at you and informs you that you will be flown up to New York in three months and that you have that amount of time to get packed and ready to move. They also inform you that you will have an apartment provided to you with your own driver.
You're fucking elated. From being a broke ass motherfucker to CEO of one of the most sucessful (although unorganized as fuck) banks in American history. Pat yourself on the back, bud. You're gonna do big things.
You leave prouder and richer than ever before. You get into your car excited by the fact that you plan on buying that Tesla you've always wanted.
''')
else:
print('''
You smile and shake the manager's hand.
"I'll take the personal teller, and I promise to endorse this bank when I become a Government official."
The manager is pleased with themselves for persuading you to do something rather than the other way around.
"Well then, pleasure doing business with you.
You leave the building and immediately go to sign up to run for the upcomming election. You pull random people off of the streets to come help you run your campaign. They agree without a second thought.
''')
elif q1 == '2':
print('''
You are tired of the bullshit B.O.M.B has given you. You eye the 'Manager' office and the teller looks worried of what you might do.
Without a second thought you run towards the office and break down the door.
The lights in the room are bright as all hell, and once your eyes adjust, you're confused as fuck and can't quite understand what you're looking at.
The room is large. Larger than it should be given the distance between the back wall of the teller's area and the size of the actual building. You look around at about a million squirells running around in lab coats in goggles. They work on various machinery that doesn't look man-made. It's definitely more advance than anything you've ever seen and it all seems to work so effortlessly you wonder why the squirrels are event there.
"What the Fuck." You say. You should really watch your mouth... I don't think the squirrels like swearing.
The manager comes after you and attempts to take you out of the room.
"Hey, listen," they grab at you, "Just ignore everything you see here. Don't as any questions and don't say shit. Or I will have to kill you."
You are too mesmerized by the squirrels to pay attention to the teller behind you. You walk forward, deeper into the room. Your quarter-fancy shoes tap loudly against the pristine white tiled floors. Immediately all of the squirrels stop in place and swiftly and abruptly turn their heads to face you.
One of the squirrels emerges from the back. You aren't sure where, because the room is so frickin' massive. This squirrel is black and is wearing a small suit that its obviously much more expensive than anything you could ever own, and much less afford.
The Black Squirrel stares at you for a moment. You are intimidated. The squirrel then slowly turns his head and glares at the teller behind you. They screech and stumble quickly out the door, slamming it behind them.
The Black Squirrel turns back to you.
"In the short time we have been here," a deep, very masculine, soothing voice (one very similar to James Earl Jones's voice) emerges from the Squirrel, "I have never seen someone bold enough to actually speak to the manager. Banks are known for thier unrully managers."
He chuckles. A few other laughs come from some of the other squirrels.
"What brings you here, traveller?"
His voice is so calming that you don't register that it's werid for a squirrel to speak English.
''')
q2 = input('''
You have two options:
1) Engage the Squirrel. He is obviously too intelligent and too mysterious for you not to have a conversation with him. And plus, that voice.
2) Leave. This is weird, and you should have noped out of this bank a long ass time ago
''')
while q2 not in '12':
q2 = input('''
That was not an option for your adventure. Try again:
1) Engage the Squirrel. He is obviously too intelligent and too mysterious for you not to have a conversation with him. And plus, that voice.
2) Leave. This is weird, and you should have noped out of this bank a long ass time ago
''')
if q2 == '1':
print('''
"Uh, I just wanted to speak to the manager," your voice waivers. You're intimidated as all hell, but you still want to hear him talk.
"Ah, yes, well, as you can see here.... well, maybe not, but nonetheless, we are the ones who run B.O.M.B."
"How? none of this makes sense to me?"
"Well, we are quite technologically advanced. We are not from this planet, but rather are from one much better a few million light years away. But we came here because you humans have really fucked up the earth, and we're here to fix it, although its incredibly hard to do, due to the shit ton of damage you all have done. And what better way to do that than go through your money. We know how you all like to kill for it."
Damn....well now even I feel bad. He makes you feel shitty too, so at least I'm not alone.
"Now, I feel bad."
"Hahaha," he chuckles, "well, I am sorry, friend, I did not mean to do that. But listen, you are curious and resilient, and I think I want you to work for me."
Lmao, you just got a goddamn job offer from a squirrel...actually you should take it, like he's definitely the smartest thing you will ever meet.
"Uhh, sure? I am in need of a better job anyway."
"Great! You shall be paid well, more than ever in human history. You are now the richest human alive. Congratulations."
...now I'm jealous
"Anyway, you can come in sometime next week and we'll get you trained to work with us. Try not to be too intimidated by us, we will lower our vocabulary and use english when we're around you."
"Thanks?"
"You're greatly welcomed, human."
The squirrell smiles and returns to his duty. Another squirrel comes up to you and gives you instructions on how to proceed then sends you out the door.
As you walk out the building, you look back at the teller, who is drenched in sweat and looks increadibly shakey. You begin to worry about your new job offer.
Nonetheless, you continue to your car, grateful for the opportunity. And you're rich as fuck. So it's been a good day.
''')
else:
print('''
You decide to attempt to leave the room, but to your detriment, the Squirrel is upset that you did not answer his question and find it highly unclassy.
He orders the other squirrels to sieze your body and use you for dinner.
He didn't want to do this, and doesn't condone eating other intelligent species, but that was rude as fuck, and honestly, I don't blame him.
You are dead.
''')
else:
print('''
NO. Just NO.
You're done. I'm done. Let's just leave. This bullshit isn't worth it anymore.
Get in the Car. We're leaving.
-Yours Truly,
The Narrator
''')
print('''
------FIN------
''')
|
bc3d7511c7a16e665d8c214c0c82cc5a60bb23e2
|
wzqwsrf/python-practice
|
/Object-Oriented-Programming/1.py
| 399 | 4.15625 | 4 |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Wangzhenqing <wangzhenqing1008@163.com>
# Date: 2015年01月22日11:25:08
"""
Problem 1: What will the output of the following program.
"""
class A:
def f(self):
return self.g()
def g(self):
return 'A'
class B(A):
def g(self):
return 'B'
a = A()
b = B()
print a.f(), b.f()
print a.g(), b.g()
"""
Output
A B
A B
"""
|
16f4edb0c5b02b9b37231bc5b76678789a634f40
|
loidbitw/Anton
|
/MachineLearning/w1/ex1_multi.py
| 2,094 | 3.796875 | 4 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from ex1_utils import *
## ================ Part 1: Feature Normalization ================
print('Loading data ...','\n')
print('Plotting Data ...','\n')
data = pd.read_csv("ex1data2.txt",names=["size","bedrooms","price"])
s = np.array(data.size)
r = np.array(data.bedrooms)
p = np.array(data.price)
m = len(r)
s = np.vstack(s)
r = np.vstack(r)
X = np.hstack((s,r))
print('First 10 examples from the dataset: \n')
print(" size = ", s[:10],"\n"," bedrooms = ", r[:10], "\n")
input('Program paused. Press enter to continue.\n')
print('Normalizing Features ...\n')
X = featureNormalize(X)
X = np.hstack((np.ones_like(s),X))
## ================ Part 2: Gradient Descent ================
print('Running gradient descent ...\n')
alpha = 0.05
num_iters = 400
theta = np.zeros(3)
theta, hist = gradientDescent(X, p, theta, alpha, num_iters)
fig = plt.figure()
ax = plt.subplot(111)
plt.plot(np.arange(len(hist)),hist ,'-b')
plt.xlabel('Number of iterations')
plt.ylabel('Cost J')
plt.show()
print('Theta computed from gradient descent: \n')
print(theta,'\n')
normalized_specs = np.array([1,((1650-s.mean())/s.std()),((3-r.mean())/r.std())])
price = np.dot(normalized_specs,theta)
print('Predicted price of a 1650 sq-ft, 3 br house (using gradient descent):\n ',
price)
input('Program paused. Press enter to continue.\n')
## ================ Part 3: Normal Equations ================
print('Solving with normal equations...\n')
data = pd.read_csv("ex1data2.txt",names=["sz","bed","price"])
s = np.array(data.sz)
r = np.array(data.bed)
p = np.array(data.price)
m = len(r) # number of training examples
s = np.vstack(s)
r = np.vstack(r)
X = np.hstack((s,r))
X = np.hstack((np.ones_like(s),X))
theta = normalEqn(X, p)
print('Theta computed from the normal equations: \n')
print(theta)
print('\n')
price = np.dot([1,1650,3],theta)
print('Predicted price of a 1650 sq-ft, 3 br house (using normal equations): \n',
price)
|
5c27f34225efd79008f3986570f9cd9858c96886
|
kritikadusad/Basic-Pattern-Matching
|
/basic_pattern_matching.py
| 1,248 | 4.0625 | 4 |
def naive(p, t):
""" Returns a list of indeces of chars in given word
matching given text.
p is the pattern
t is the given text
Example:
>>> naive("ATGC", "AATGCTTTATGC")
[1, 8]
"""
occurences = []
for i in range(len(t) - len(p) + 1):
match = True
for j in range(len(p)):
if t[i + j] != p[j]:
match = False
break
if match:
occurences.append(i)
return occurences
def naive_2mm(p, t):
"""
Returns a list of indeces of chars in given word
matching given text. This function can take upto
2 mismatches.
p is the pattern
t is the given text
Example:
>>> naive_2mm("ATGC", "AAAGCTTTTATCC")
[1, 9]
"""
occurences = []
for i in range(len(t) - len(p) + 1):
match = True
error = 0
for j in range(len(p)):
if t[i + j] != p[j]:
error += 1
if error > 2:
match = False
break
if match:
occurences.append(i)
return occurences
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print("\nAll tests have passed.\n")
|
4594840795c44ed870fb8a50a6f185adf36caee1
|
parthivpatel1106/Python_hackerrank_programs
|
/find_a_string.py
| 241 | 4.03125 | 4 |
string=input()
substring=input()
count=0
print(string[2:5]) #to check the substrings
print(string[4:7]) #to check the substrings
for i in range(len(string)-1):
if(substring==string[i:len(substring)+i]):
count=count+1
print(count)
|
0788204bfd8ccbe2bc7a31cf047a6f282959cc60
|
aniketchanana/python-exercise-files
|
/fileio/file_modes.py
| 412 | 3.671875 | 4 |
# file modes
"w"
"r"
"r+"
"a"
# with open("demo1.txt","w") as file:
# # file.seek(0)
# file.write("Hello i am aniket")
# # file.write("ll")
# # print(file.__repr__())
# with open("demo.txt","r") as file:
# print(file.)
# print(dict(a=1,b=2))
sen = "Hello i am aniket chanana"
# print(sen.count(" "))
# file = open("demo.txt","r")
# file.readlines
print(sen.replace("l","-"))
print(sen)
|
fdbc030f408d6133b7b1d45ad43d3f3bd1f3f470
|
Filipsnk/Learning
|
/Statistical_tests.py
| 9,741 | 3.765625 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STATISTICAL TESTS
1. NORMALITY TESTS
2. CORRELATION TESTS
3. STATIONARY TESTS
4. PARMAETRIC STATISTICAL HYPOTHESIS TESTS
5. NON PARAMETRIC STATISTICAL TESTS
Normality tests
Shapiro- Wilk test
Assumptions
1. observations are independent
Interpretation:
H0: the sample has a Gaussian Distribution
H1: the sample does not have a Gaussian Distribution
"""
from scipy.stats import shapiro
import matplotlib.pyplot as plt
data = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
plt.hist(data)
stat,p = shapiro(data)
print('stat= %.3f, p= %.3f' %(stat,p))
if p > 0.05:
print('Probably Gaussian')
else:
print('Probably not Gaussian')
"""
D'Agostino K^2 test
Assumptions:
1. Observations in each sample are independent
Interpretation:
H0: the sample has a Gaussian Distribution
H1: the sample does not have a Gaussian Distribution
"""
from scipy.stats import normaltest
stat, p = normaltest(data)
print('stat =%.4f, p=%.4f' %(stat,p))
if p > 0.05:
print('Probably Gaussian')
else:
print('Probably not Gaussian')
"""
Anderson Darling Test
Assumptions:
1.Observations in each sample are independent
Interpretation:
H0: the sample has a Gaussian Distribution
H1: the sample does not have a Gaussian Distribution
"""
from scipy.stats import anderson
result = anderson(data)
print('Anderson stat= %.4f' %(result.statistic))
result.critical_values
result.significance_level
for i in range(len(result.critical_values)):
a,b = result.critical_values[i],result.significance_level[i]
if result.statistic < a:
print('Probably Gaussian distribution at the %.1f%% level' %(b))
else:
print('Probably not a Gasussian distribution at the %.1f%% level' %(b))
"""
Correlation test
Pearson correlation test
Assumptions:
1. Observations in each sample are independent and identically distributed
2. Observations in each sample are normally distributed
3. Observations in each sample has the same variance
Interpretation:
H0: the two samples are idependent
H1: there is a dependency between the samples
"""
from scipy.stats import pearsonr
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [0.353, 3.517, 0.125, -7.545, -0.555, -1.536, 3.350, -1.578, -3.537, -1.579]
plt.hist(data1)
plt.hist(data2)
stat, p = pearsonr(data1,data2)
print('stat= %.3f, p-value= %.3f' %(stat,p))
if p > 0.05:
print('Probably independent')
else:
print('Not idependent')
## generate data until normally distributed
random_data = []
normal = False
count = 0
data = []
k = 0
while k < 10:
for i in range(0,10):
data = random.random()
random_data.append(data)
stat, p = shapiro(random_data)
if p > 0.05:
print('Data is normally distributed. Well done')
break
else:
print('failed')
random_data = []
k+=1
"""
Spearman's Rank Correlation
Assumptions
1. Observations in each sample are independent and identically distributed
Interpretation:
H0: two samples are independent
H1: there is a dependency between the samples
"""
from scipy.stats import spearmanr
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [0.353, 3.517, 0.125, -7.545, -0.555, -1.536, 3.350, -1.578, -3.537, -1.579]
stat, p = spearmanr(data1, data2)
print('stat= %.4f, p-value= %.4f' %(stat,p))
if p > 0.05:
print('Probably independent')
else:
print('Probably dependent')
"""
Kendal Rank Correlation
Test whether two samples have a monotonic relationship
Assumptions:
1) observations in each sample are independent and identically distributed
2) observations in each sample can be ranked
Interpretation:
1) two samples are independent
2) there is a dependency between the samples
"""
from scipy.stats import kendalltau
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [0.353, 3.517, 0.125, -7.545, -0.555, -1.536, 3.350, -1.578, -3.537, -1.579]
stat, p = kendalltau(data1, data2)
print('stat=%.3f, p=%.3f' % (stat, p))
if p > 0.05:
print('Probably independent')
else:
print('Probably dependent')
"""
Chi squared test
tests whether two categorical variables are related or independent
Assumptions:
1) obsevations used in the calculation of the contingency table are independent
2) 25 or more examples in each cell of the contingency table
Interpretation:
H0: the two samples are independent
H1: there is dependency between the samples
"""
from scipy.stats import chi2_contingency
table = [[10, 20, 30],[6, 9, 17]]
stat, p, dof, expected = chi2_contingency(table)
print('stat=%.3f, p=%.3f' % (stat, p))
if p > 0.05:
print('Probably independent')
else:
print('Probably dependent')
"""
Parametric statistical tests
Student's t-test
This tests check whether the means of two independent samples are significantly different
H0: the means of two samples are equal
H1: the means of two sample are not equal
"""
from scipy.stats import ttest_ind
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [1.142, -0.432, -0.938, -0.729, -0.846, -0.157, 0.500, 1.183, -1.075, -0.169]
stat, p = ttest_ind(data1, data2)
print('stat=%.3f, p=%.3f' % (stat, p))
if p > 0.05:
print('Probably the same distribution')
else:
print('Probably different distributions')
"""
ANOVA
tests whether the means of two or more independent samples are significantly different
Assumptions:
1) Observations in each sample are independent and identically distributed
2) observations in each sample are normally distributed
3) observations in each sample have the same variance
Interpretation:
H0: the means of the sample are equal
H1: one or more of the means of the samples are unequal
"""
from scipy.stats import f_oneway
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [1.142, -0.432, -0.938, -0.729, -0.846, -0.157, 0.500, 1.183, -1.075, -0.169]
data3 = [-0.208, 0.696, 0.928, -1.148, -0.213, 0.229, 0.137, 0.269, -0.870, -1.204]
stat, p = f_oneway(data1, data2, data3)
print('stat=%.3f, p=%.3f' % (stat, p))
if p > 0.05:
print('Probably the same distribution')
else:
print('Probably different distributions')
"""
Non parametric test
Mann-Whitney U test
Tests whether the distributions of two samples are equal
Assumptions:
1) Observations are independent
2) Observations in each sample can be ranked
Interpretation:
H0: the distributions of both samples are equal
H1: the distributions of both samples are not equal
"""
from scipy.stats import mannwhitneyu
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [1.142, -0.432, -0.938, -0.729, -0.846, -0.157, 0.500, 1.183, -1.075, -0.169]
stat, p = mannwhitneyu(data1, data2)
print('stat=%.3f, p=%.3f' % (stat, p))
if p > 0.05:
print('Probably the same distribution')
else:
print('Probably different distributions')
"""
Wilcoxon Signed-Rank Test
Tests whether the distributions of two paired samples are equal or not.
Assumptions
Observations in each sample are independent and identically distributed (iid).
Observations in each sample can be ranked.
Observations across each sample are paired.
Interpretation
H0: the distributions of both samples are equal.
H1: the distributions of both samples are not equal.
"""
from scipy.stats import wilcoxon
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [1.142, -0.432, -0.938, -0.729, -0.846, -0.157, 0.500, 1.183, -1.075, -0.169]
stat, p = wilcoxon(data1, data2)
print('stat=%.3f, p=%.3f' % (stat, p))
if p > 0.05:
print('Probably the same distribution')
else:
print('Probably different distributions')
"""
Kruskal-Wallis H Test
Tests whether the distributions of two or more independent samples are equal or not.
Assumptions
Observations in each sample are independent and identically distributed (iid).
Observations in each sample can be ranked.
Interpretation
H0: the distributions of all samples are equal.
H1: the distributions of one or more samples are not equal.
"""
from scipy.stats import kruskal
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [1.142, -0.432, -0.938, -0.729, -0.846, -0.157, 0.500, 1.183, -1.075, -0.169]
stat, p = kruskal(data1, data2)
print('stat=%.3f, p=%.3f' % (stat, p))
if p > 0.05:
print('Probably the same distribution')
else:
print('Probably different distributions')
"""
Friedman Test
Tests whether the distributions of two or more paired samples are equal or not.
Assumptions
Observations in each sample are independent and identically distributed (iid).
Observations in each sample can be ranked.
Observations across each sample are paired.
Interpretation
H0: the distributions of all samples are equal.
H1: the distributions of one or more samples are not equal.
"""
from scipy.stats import friedmanchisquare
data1 = [0.873, 2.817, 0.121, -0.945, -0.055, -1.436, 0.360, -1.478, -1.637, -1.869]
data2 = [1.142, -0.432, -0.938, -0.729, -0.846, -0.157, 0.500, 1.183, -1.075, -0.169]
data3 = [-0.208, 0.696, 0.928, -1.148, -0.213, 0.229, 0.137, 0.269, -0.870, -1.204]
stat, p = friedmanchisquare(data1, data2, data3)
print('stat=%.3f, p=%.3f' % (stat, p))
if p > 0.05:
print('Probably the same distribution')
else:
print('Probably different distributions')
|
07aac60531b98f8f33cc49d3aa6f48133aaff77e
|
ayushbansal323/TE
|
/python/class.py
| 232 | 3.65625 | 4 |
class mycomplex:
def __init__(self,a,b):
self.r = a
self.c = b
def getitinstring(self):
return f"{a.r} + {a.c}i"
a=mycomplex(4,5)
print(a.getitinstring())
class myclass:
r = 1
c = 2
a=myclass()
print(f"{a.r} + {a.c}i")
|
6e49fd62ab09d68cd4f6e6e326820e113e1f0e0f
|
Tranqui11ion/Crypto-scraper
|
/menu.py
| 1,441 | 3.6875 | 4 |
import logging
import csv
from app import coins
logger = logging.getLogger('scraping.menu')
USER_CHOICE = '''Enter one of the following
- 'p' print coins
- 'e' export to file
- 'q' to exit
Enter your choice: '''
def print_coins():
logger.info("Printing coins...")
for coin in coins:
print(coin)
def export_coins_to_csv():
logger.info("Exporting coins to file...")
Details = ['Coin Names']
rows = []
with open('Coins.csv', 'w', encoding='utf-8') as f:
write = csv.writer(f, lineterminator = '\n')
write.writerow(Details)
for coin in coins:
write.writerow([coin.coin_name])
print(coin)
# def print_cheapest_books():
# logger.info("Find the best book by price...")
# cheapest_books = sorted(books, key=lambda x: x.price)[:10]
# for book in cheapest_books:
# print(book)
#
# books_generator = (x for x in books)
#
# def print_next_book():
# logger.info("Find the next book from the generator...")
# print(next(books_generator))
user_choices = {
'p': print_coins,
'e': export_coins_to_csv
}
def menu():
user_input = input(USER_CHOICE)
while user_input != 'q':
if user_input in 'pe':
user_choices[user_input]()
else:
print('***You have not input a valid selection***')
user_input = input(f'\n\n{USER_CHOICE}')
logger.debug("Terminating program...")
menu()
|
1a19726bf4473a3c888474bde865c8bbd81ac482
|
dkraczkowski/opyapi
|
/opyapi/schema/formatters/boolean.py
| 373 | 3.5625 | 4 |
from typing import Any
def format_boolean(value: Any) -> bool:
if isinstance(value, str):
value = value.lower()
if value in (0, 0.0, "0", False, "no", "n", "nope", "false"):
return False
if value in (1, 1.0, "1", True, "ok", "yes", "y", "yup", "true"):
return True
raise ValueError("Passed value cannot be formatted to boolean.")
|
810eda6bbbc263748d11416825b07f37c982ba99
|
LucyCo/small-exercises
|
/squares.py
| 224 | 3.734375 | 4 |
def squares(x):
return [x**2 for x in range(1, x+1)]
def dict_squares(x):
return {x: x**2 for x in range(1, x+1)}
def main():
print squares(3)
print dict_squares(3)
if __name__ == '__main__':
main()
|
9ed672d115c966ef6323c2bffc284482b94dfd7f
|
Ashkaneslamiii/Pytthon
|
/Untitled-6.py
| 216 | 3.953125 | 4 |
def fibonaci (n):
if n<0:
print("Incorrect Input ")
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fibonaci(n-1) + fibonaci(n-2)
print(fibonaci(9))
|
0f058bf3474d3b1b6975d08660e132389174a84a
|
Fr4nc3/code-hints
|
/leetcode/FrequencyInArray.py
| 1,319 | 3.84375 | 4 |
# Given an array of integers a, your task is to calculate the digits that occur the most number of times in the array.
# Return the array of these digits in ascending order.
# Example
# For a = [25, 2, 3, 57, 38, 41], the output should be solution(a) = [2, 3, 5].
# Here are the number of times each digit appears in the array:
# 0 -> 0
# 1 -> 1
# 2 -> 2
# 3 -> 2
# 4 -> 1
# 5 -> 2
# 6 -> 0
# 7 -> 1
# 8 -> 1
# The most number of times any number occurs in the array is 2,
# and the digits which appear 2 times are 2, 3 and 5. So the answer is [2, 3, 5].
from collections import defaultdict
import operator
def solution(a):
numCount = defaultdict(list)
for e in a:
e_s = str(e)
for ei in e_s:
i = int(ei)
if i in numCount.keys():
numCount[i] +=1
else:
numCount[i] = 1
sorted_d = dict(sorted(numCount.items(), key=lambda kv:
(kv[1], kv[0]), reverse=True)) # dict(sorted(numCount.items(), key=operator.itemgetter(1),reverse=True))
asw = []
i =0
print(sorted_d)
for k, v in sorted_d.items():
if v >= i:
i = v
asw.append(k)
return sorted(asw)
|
dc2b0be67886b61cb063c9a71ef9b7f8f5a9ceb7
|
hz336/Algorithm
|
/LeetCode/DP/H Russian Doll Envelopes.py
| 2,922 | 4.28125 | 4 |
"""
You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the
width and height of one envelope is greater than the width and height of the other envelope.
What is the maximum number of envelopes can you Russian doll? (put one inside other)
Note:
Rotation is not allowed.
Example:
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
"""
"""
计数型DP
Time Complexity: O(N^2)
"""
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
if envelopes is None or len(envelopes) == 0:
return 0
envelopes.sort() # envelopes.sort(key=lambda: x[0], x[1])
length = len(envelopes)
f = [1] * length
for curr in range(length):
for prev in range(curr):
if envelopes[prev][0] < envelopes[curr][0] and envelopes[prev][1] < envelopes[curr][1]:
f[curr] = max(f[curr], f[prev] + 1)
return max(f)
import bisect
"""
Dynamic Programming + Binary Search
Time Complexity: O(nlogn)
"""
class Solution_v1:
"""
@param: envelopes: a number of envelopes with widths and heights
@return: the maximum number of envelopes
"""
def maxEnvelopes(self, envelopes):
# write your code here
height = [a[1] for a in sorted(envelopes, key=lambda x: (x[0], -x[1]))]
len_height = len(height)
min_last = [math.inf] * (len_height + 1)
min_last[0] = -math.inf
for i in range(len_height):
# find the first number in minLast >= nums[i]
index = self.binary_search(min_last, height[i])
min_last[index] = height[i]
for i in range(len_height, 0, -1):
if min_last[i] != math.inf:
return i
return 0
def binary_search(self, min_last, target):
start, end = 0, len(min_last) - 1
while start + 1 < end:
mid = start + (end - start) // 2
if min_last[mid] < target:
start = mid
else:
end = mid
if min_last[start] >= target:
return start
else:
return end
"""
Dynamic Programming + Binary Search
Time Complexity: O(nlogn)
"""
class Solution:
"""
@param: envelopes: a number of envelopes with widths and heights
@return: the maximum number of envelopes
"""
def maxEnvelopes(self, envelopes):
# write your code here
height = [a[1] for a in sorted(envelopes, key=lambda x: (x[0], -x[1]))]
min_last = [0] * len(height)
start, end = 0, 0
for h in height:
i = bisect.bisect_left(min_last, h, start, end)
min_last[i] = h
if i == end:
end += 1
return end
|
accf949ca8d60c5aba8be637dc2a763eccde4971
|
GedasLuko/Python
|
/circle.py
| 424 | 4.1875 | 4 |
#Gediminas Lukosevicius
#October 3rd, 2016 ©
#The circle module has functions that perform calculations related to circles
import math
#the area functions accepts a circle's radius as an argument and returns the
#are of the circle
def area(radius):
return math.pi * radius ** 2
#the circumference function accepts a circle's radius and returns the
#circle's circumference.
def circumference(radius):
return 2 * math.pi * radius
|
2a2c9affa62e27201bca1902c52dee30cee3097e
|
justinharringa/aprendendo-python
|
/2020-10-04/tete/80.py
| 601 | 3.984375 | 4 |
# Usuario Lista
# 3 []
# 2 [3]
# 4 [2,3]
# 5 [2,3,4]
# 1 [2,3,4,5]
# [1,2,3,4,5]
numeros = []
for _ in range(5):
print(f'a lista agora é: {numeros}')
numero = int(input("me de um numero rapaz: "))
lugar = len(numeros)
for index, valor in enumerate(numeros):
# se for menor, tem que colocar antes
if numero < valor:
lugar = index
break
# se for maior, tem que colocar antes
numeros.insert(lugar, numero)
print(numeros)
|
973a01f2885aa639a017f1989bee0f6f8a735e2a
|
balrog-nona/learning_python
|
/git_training/git_calculator.py
| 865 | 3.546875 | 4 |
"""
nacvik odstranovani konfliktu
"""
class StringCalculator:
def add(self, a):
if a:
return 0
else:
if a[0] == "/":
delimiter = a[2]
else:
delimiter = "^"
if "\n" in a:
a = a.replace("\n", delimiter)
if delimiter in a:
a = a.split(delimiter)
soucet = 0 # komentar
for i in a:
try:
if int(i) > 0:
soucet += int(i)
else:
raise Exception("negatives not allowed")
continue
except ValueError:
pass
return soucet
else:
return int(a)
print(add(7)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.