blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1fddd1d58c196ffcd4a7c30d50c5061b75c8c4cb | Shunto/jaran_api | /rurubu_get_data.py | 9,059 | 3.53125 | 4 | import sys, getopt
import urllib.request
from bs4 import BeautifulSoup
from xml.dom.minidom import parseString
import MeCab
import re
url_base = "https://www.rurubu.travel"
s_url = ""
region_id = ""
pre_id = ""
l_area_id = ""
s_area_id = ""
d_area_id = ""
#inn_id = ""
rurubu_inn_data = []
rurubu_inn_urls = []
rurubu_inn_names = []
max_count = 30
c_count = 0
n_count = 0
page_numbers = [1]
last_page = 0
def usage():
print("NAME: rurubu_get_data.py -- scrape data from rurubu web pages")
print("USAGE: python3 rurubu_get_data.py url")
print("-h --help - show the usage of rurubu_get_data.py")
print("-c --count - limit the number of search results, maximum number = 30")
print("-n --page_numbers - specify page numbers you search")
print("-r --region_id - specify the region id")
print("-p --pref_id - specify the prefecture id")
print("-l --l_area_id - specify the larege area id")
print("-s --s_area_id - specify the small area id")
print("-d --d_area_id - specify the detailed area id")
#print("-i --inn_id - ")
print("")
print("EXAMPLES: ")
print("python3 rurubu_get_data.py https://rurubu.travel/A08/")
print("")
print("python3 rurubu_get_data.py -c 10 -n 2 https://rurubu.travel/A08")
print("")
print("python3 rurubu_get_data.py -c 42 -n 2,7 https://rurubu.travel/A08")
print("")
print("python3 rurubu_get_data.py -c 150 -n 1-3,21-23 https://rurubu.travel/A08")
print("")
print("python3 rurubu_get_data.py -c 10 -r A08 https://rurubu.travel")
print("")
print("python3 rurubu_get_data.py -c 10 -r A08")
print("")
sys.exit(2)
def main():
global s_url
global c_count
global max_count
global page_numbers
global region_id
global pre_id
global l_area_id
global s_area_id
global d_area_id
global inn_id
try:
opts, args = getopt.getopt(sys.argv[1:], "hc:n:r:p:l:s:d:i:", ["help", "count", "page_numbers", "region_id", "pref_id", "l_area_id", "s_area_id", "d_area_id", "inn_id"])
arg = sys.argv[-1]
if len(sys.argv) < 2:
usage()
if "http" in arg:
s_url = sys.argv[-1]
url = s_url
else:
url = url_base
except:
usage()
for opt, arg in opts:
if opt == "-h":
usage()
if opt in ("-c", "--count"):
max_count = int(arg)
if opt in ("-n", "--page_numbers"):
page_numbers = []
pattern = "([0-9]+)(\-[0-9]+)?"
matches = re.findall(pattern, arg)
for match in matches:
if match:
if "-" in match[1]:
for i in range(int(match[0]), int(match[1][1:])+1):
page_numbers.append(i)
else:
page_numbers.append(int(match[0]))
if opt in ("-r", "--region_id"):
region_id = arg
url = url + "/" + region_id
if opt in ("-p", "--pref_id"):
pref_id = arg
url = url + "/" + pref_id
if opt in ("-l", "--l_area_id"):
l_area_id = arg
url = url + "/" + l_area_id
if opt in ("-s", "--s_area_id"):
s_area_id = arg
url = url + "/" + s_area_id
if opt in ("-d", "--d_area_id"):
d_area_id = arg
url = url + "/" + d_area_id
'''if opt in ("-i", "--inn_id"):
inn_id = arg
url = url + "/" + inn_id + "/top.html?ref=regular"
print(url)
getRurubuInnData(url)
print(rurubu_inn_data)
break'''
#url = formRurubuUrl()
getRurubuLastPage(url)
for page_num in page_numbers:
breaker = False
if page_num != 1:
url = s_url + "/" + str(page_num) + ".htm"
print("the rurubu page currently searching : " + url)
getRurubuInnUrls(url)
while True:
getRurubuInnData(rurubu_inn_urls[c_count])
c_count += 1
if c_count == max_count:
breaker = True
break
if c_count == len(rurubu_inn_urls):
break
if breaker:
break
#print(rurubu_inn_urls)
print("the last page number : {0}".format(last_page))
print("the number of searched results : {0}".format(c_count))
print(rurubu_inn_data)
def getRurubuInnData(url):
try:
#url_main = url
#url_reviews = "https://www.jalan.net/yad"
getRurubuMainData(url)
#getRurubuReviewsData(url_reviews)
except urllib.error.HTTPError as error:
pass
def rurubuHtmlParser(url):
try:
html = urllib.request.urlopen(url)
soup = BeautifulSoup(html, "html.parser")
return soup
except urllib.error.HTTPError as error:
pass
def getRurubuLastPage(url):
global last_page
try:
pattern = "^([0-9]+)\.htm$"
soup = rurubuHtmlParser(url)
#last_page = int(soup.find("ul", {"class": "pageGuid"}).find("li", {"class": "last"}).getText())
match = re.search(pattern, soup.find("li", {"class": "last"}).find("a")["href"])
if match:
last_page = match.group(1)
else:
print("no last_page")
except urllib.error.HTTPError as error:
print("no last_page")
pass
## 検索結果のリンク先のURL
def getRurubuInnUrls(url):
global rurubu_inn_urls
global rurubu_inn_names
try:
soup = rurubuHtmlParser(url)
for inn_link in soup.find_all("a", {"class": "hotelName"}):
rurubu_inn_urls.append(url_base + inn_link["href"])
rurubu_inn_names.append(removeBadChars(inn_link.get_text()))
#inn_link = soup.find_all("a", {"class": "hotelName"})[5]:
#rurubu_inn_urls.append(url_base + inn_link["href"])
#count = len(rurubu_inn_urls)
except urllib.error.HTTPError as error:
pass
'''
取るべきデータ
取ってあるデータ
値段(最大・最小)
'''
def getRurubuMainData(url):
global rurubu_inn_data
try:
soup = rurubuHtmlParser(url)
## 値段の取得
min_cost = soup.find("span", {"itemprop": "lowPrice"})
max_cost = soup.find("span", {"itemprop": "highPrice"})
data = []
data.append(rurubu_inn_names[c_count])
data.append(removeBadChars(min_cost.get_text()))
data.append(removeBadChars(max_cost.get_text()))
# 詳細ページからデータを取得
detail_link = soup.find("div", {"class": "data"}).find("a", {"class" : "addAbox"})
if not detail_link == None:
url_detail = url_base + detail_link["href"]
getRurubuDetailPageData(url_detail)
data.append(rurubu_detail_data)
rurubu_inn_data.append(data)
except urllib.error.HTTPError as error:
pass
def getRurubuDetailPageData(url):
global rurubu_detail_data
try:
# print(url)
soup = rurubuHtmlParser(url)
## レジャー施設とコンビニのデータ
leisures = []
conveni = []
for content in soup.find("div", {"id" : "tabbody-detail"}).find_all("tr"):
title = content.th.get_text()
if title == 'レジャーランド' :
leisures.append(title) #content.td
elif title == 'コンビニエンスストア':
conveni.append(title) #content.td
rurubu_detail_data = []
rurubu_detail_data.append(leisures)
rurubu_detail_data.append(conveni)
except urllib.error.HTTPError as error:
pass
pass
def getRurubuReviewsData(url):
try:
soup = rurubuHtmlParser(url)
divs = soup.find_all("div", {"class": "user-kuchikomi"})
dict = {}
for div in divs:
reviews = div.findChildren("p", {"class": "text"})
for review in reviews:
rurubuStrParser(review.get_text(), dict)
print(dict)
if keyword_flg:
if dict.get(keyword):
print("keyword '" + keyword + "' appears " + str(dict[keyword]) + " times in the reviews.")
else:
print("keyword '" + keyword + "' doen't appear in the reviews.")
#print(review.get_text())
except urllib.error.HTTPError as error:
pass
def rurubuStrParser(str, dict):
mt = MeCab.Tagger("-d /usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd")
parsed = mt.parseToNode(removeBadChars(str))
while parsed:
word = parsed.surface
if word not in dict:
dict.setdefault(word, 1)
else:
dict[word] += 1
parsed = parsed.next
def removeBadChars(str):
bad_chars = [",", ".", "、","。","*", ";", " ", " ", "\u3000", "\n"]
for i in bad_chars:
str = str.replace(i, "")
return str
#review_text = " ".join(i for i in review.get_text() if not i in bad_chars)
if __name__ == "__main__":
main()
|
69545ea5114d009c039f75321fd29f237c073fbe | chao-shi/lclc | /042_trap_rain_h/main.py | 1,045 | 3.921875 | 4 | class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
vol = 0
peak = height.index(max(height))
highest = 0
for i in range(peak + 1):
if height[i] < highest:
# here we know we have highest on the left
# and we for sure have something no smaller
# than highest on the right (because we haven't reach
# mid point yet). So highest - height[i] is guaranteed
vol += highest - height[i]
else:
# we update highest even it is equal
# because same height separate the water body
highest = height[i]
highest = 0
for i in range(len(height) - 1, peak - 1, -1):
if height[i] < highest:
vol += highest - height[i]
else:
highest = height[i]
return vol |
6febfe6a09ffb7851e8ec2dae3c675dbaca92e01 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2900/60749/261540.py | 91 | 3.9375 | 4 | str1=input()
count=0
for h in str1:
if not h==" ":
count+=1
print(count,end="") |
22cfe42d38fd1c2c1f148e65294284976acc92f2 | ruoyzhang/AI_public_perception_survey_data_analysis | /CN/consolidation.py | 2,055 | 4.375 | 4 | import pandas as pd
def group_columns(dataset):
"""
a function to group together columns
returns a dictionary
keys refer to the question number
values refer to the actual column names
"""
# locating the columns to be reorganised
cols = dataset.columns[6:(len(dataset.columns)-1)]
# setting vars to represent the questions for easy ref
questions = {}
for question in cols:
key = question.split(".")[0]
if key not in questions.keys():
questions[key] = [question]
else:
questions[key].append(question)
return(questions)
def consolidate_mc(dataset, questions, q_number):
"""
a function to consolidate the multiple columns involved in a single multiple choice question
dataset: the pandas Dataframe object
questions: the 'questions' dict returned by the function 'group_columns'
q_number: int or str, the question number to deal with
"""
q_number = str(int(q_number))
q_answers = []
for _, row in dataset[questions[q_number]].iterrows():
answers = [elem for elem in row if not pd.isnull(elem)]
answers = [answer.split('.')[0] for answer in answers]
q_answers.append(answers)
return(q_answers)
def simplify_sgq(dataset, q_number):
"""
function to simply single choice questions
we get rid of the text and only keep the ref(ind)
dataset: the dataset, a pandas Dataframe object
q_number: int or str, the question number to deal with
"""
# reformating the q_number variable
q_number = int(q_number)
q_number = "q{:02}".format(q_number)
# converting
answers = [answer.split('.')[0] for answer in dataset[q_number]]
return(answers)
def convert_to_list(dataset, q_number):
"""
function to convert str-fied lists back into lists
dataset: the dataset, a pandas Dataframe object
q_number: int or str, the question number to deal with
"""
# reformating the q_number variable
q_number = int(q_number)
q_number = "q{:02}".format(q_number)
# conversion
to_return = [ans.replace('[', '').replace(']','').replace('\'', '').split(',') for ans in dataset[q_number]]
return(to_return)
|
a01485f350af1ee0bd05aecd10824749f4548dc4 | zelikris/popeye | /popeye/web_server/listing_exec_app/objects/matrix.py | 7,849 | 4 | 4 | """This module provides the matrix class.
IMPORTANT NOTICE: Don't use vector, cross, etc. as variable names
We have lowercase classes for sake of usability
"""
from numbers import Number
from vector import vector
class matrix(object):
"""matrix class.
Attirbutes:
values (Vector[]): vector rows
"""
def __init__(self, *args):
"""
Constructs a matrix.
Initialized with one of the following sets of args:
Series of Numbers (only one row)
Series of lists/vectors
List of list of vectors
"""
self.values = []
# Returns [] if no args
if len(args) > 0:
# If args are a series of Numbers
if isinstance(args[0], Number):
self.values = [vector(*args)]
# If args are a series of lists or vectors
elif isinstance(args[0], list) or isinstance(args[0], vector):
# If args[0] is a list of lists, unpack it
if any(isinstance(arg, list) or isinstance(arg, vector) for arg in args[0]):
args = args[0]
for arg in args:
# If args is a list of list, cast to vector
if isinstance(arg, list):
arg = vector(arg)
elif not isinstance(arg, vector):
raise TypeError(
str(arg) + ' is not a list or a vector')
if len(arg) != len(args[0]):
raise IndexError("args aren't the same length")
self.values.append(arg)
else:
raise TypeError(
str(args[0]) + ' is not a Number, list or vector')
def __add__(self, other):
"""Overloads + operator.
Args:
other (matrix, Number): matrix or Number to be added to self
Returns:
matrix: The sum of self and other
"""
if isinstance(other, matrix):
my_height, my_width = dim(self)
other_height, other_width = dim(other)
# My width must be the other height, my height the other width
if my_width == other_height and my_height == other_width:
new_matrix = []
for i in range(my_width):
new_matrix.append(self.values[i] + other.values[i])
return matrix(new_matrix)
else:
raise ValueError("matrices have different dimensions")
elif isinstance(other, Number):
return matrix([other + row for row in self.values])
else:
raise TypeError('only matrices or Numbers can be added to matrices')
def __eq__(self, other):
"""Overloads == operator.
Args:
other (matrix): matrix to compare self to
Returns:
bool: if self and mat are equal
"""
if isinstance(other, matrix):
if dim(other) == dim(self):
for a, b in zip(other.values, self.values):
if a != b:
return False
return True
else:
raise ValueError('matrices have different dimensions')
else:
raise TypeError('matrices can only be compared to other matrices')
def __getitem__(self, index):
"""Gets a single entry in the matrix by (row, col).
Args:
index: (row, col) index of entry to get
Returns:
Number: entry found in self at index
"""
row, col = index
return self.values[row][col]
def __iter__(self):
for row in self.values:
yield row
def __len__(self):
"""Return the total number of elements in self.
Returns:
int: total number of elements
"""
if len(self.values) == 0:
return 0
return len(self.values) * len(self.values[0])
def __mul__(self, other):
"""Overloads * operator.
Checks if other is a matrix or Number, and performs matrix multiply or dot product
as appropriate.
Args:
other (matrix, Number): matrix or Number by which to multiply self
Returns:
matrix: self multiplied by other
"""
if isinstance(other, matrix):
my_height, my_width = dim(self)
other_height, other_width = dim(other)
# My width must be the other height, my height the other width
if my_width == other_height and my_height == other_width:
new_matrix = []
for i in range(my_height):
row = []
for j in range(other_width):
msum = 0
for k in range(my_width):
msum += self[i,k] * other[k,j]
row.append(msum)
new_matrix.append(row)
return matrix(new_matrix)
else:
raise ValueError("matrices have different dimensions")
elif isinstance(other, Number):
return matrix([other * row for row in self.values])
else:
raise TypeError('only matrices or Numbers can multiply matrices')
def __ne__(self, other):
"""Overloads != operator
Args:
other (matrix): matrix to compare self to
Returns:
bool: if self and other are not equal
"""
return not self == other
def __radd__(self, other):
"""Implements reflective addition.
Args:
other (matrix, Number): matrix or Number to be added to self
Returns:
matrix: The sum of self and other
"""
return self + other
def __repr__(self):
"""Returns a simple string representation of self.
Returns:
string: simple representatino of self
"""
return 'matrix: ' + str(self.values)
def __rmul__(self, other):
"""Implements reflective multiplication
Args:
other (matrix, Number): matrix or Number by which to multiply self
Returns:
matrix: self multiplied by other
"""
return self * other
def __setitem__(self, index, val):
"""Sets a single entry in the matrix by index.
Args:
index: (row, col) index of entry to set
val (Number): value to set entry to
"""
row, col = index
if isinstance(val, Number):
if (row, col) <= dim(self):
self.values[row][col] = val
else:
raise IndexError('index is out of bounds')
else:
raise TypeError('value must be a Number')
def __str__(self):
"""Returns a pretty representation of self.
Returns:
string: pretty representation of self
"""
out = []
for value in self.values:
out.append(str(value))
return '\n'.join(out)
def _col(self, num):
"""Returns the matrix column with the given index.
Args:
num (int): column index
Returns:
Number[]: matrix column with given index
"""
return [row[num] for row in self.values]
def _row(self, num):
"""Returns the matrix row with the given index.
Args:
num (int): row index
Returns:
Number[]: matrix row with given index
"""
return self.values[num]
def dim(mat):
"""Gets matrix dimensions.
Args:
mat (matrix): matrix to get dimensions of
Returns:
list: dimensions of the matrix
"""
return len(mat.values[0]), len(mat.values)
|
4d3ba54a2b7e4445bfb039d8deb18b68dfabf639 | MrRuban/lectures_devops2 | /Python/samples3/networking/tcp_udp/5.1.1.py | 480 | 3.734375 | 4 | #!/usr/bin/env python3
"""
Обратный DNS клиент
"""
#https://docs.python.org/3/library/socket.html#socket.gethostbyaddr
import socket
try:
result = socket.gethostbyaddr("66.249.71.15")
print("Primary hostname:", end=' ')
print(result[0])
# Display the list of available addresses that is also returned
print("\nAddresses:", end=' ')
for item in result[2]:
print(item)
except socket.herror as e:
print("Couldn't look up name:", e) |
695afc25a5196b4f6546844b17de4b37e2b64734 | 1181888200/python-demo | /day1/five.py | 942 | 4 | 4 | # -*- coding:utf-8 -*-
# 字符串格式
# 在Python中,采用的格式化方式和C语言是一致的,用%实现
name = input("请输入您的名字:")
sex = input("请输入你的性别:")
age = input("请输入您的年龄:")
age = int(age)
chu = ('先生' if sex=='男' else '女士')
print("欢迎 %s %s光临,您的年龄是:%d" %(name,chu,age))
# 常见的占位符
# %s 字符串
# %d 整数
# %f 浮点数
# %x 十六进制整数
# 另一种格式化字符串的方法是使用字符串的format()方法,它会用传入的参数依次替换字符串内的占位符{0}、{1}……,
name = input("请输入您的名字:")
sex = input("请输入你的性别:")
age = input("请输入您的年龄:")
print("欢迎 {0}光临,性别:{1},您的年龄是:{2}".format(name,sex,age))
# 格式化 保留几位小数
print("您的成绩是{0},比上一级进步了{1:.1f}%".format(80,70.1234)) |
4d347d45929aae977ed45bf513985a5ac75adf6f | JulyKikuAkita/PythonPrac | /cs15211/PermutationsII.py | 6,452 | 3.890625 | 4 | __source__ = 'https://leetcode.com/problems/permutations-ii/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/permutations-ii.py
# Time: O(n!)
# Space: O(n)
# Brute Force Search
#
# Description: Leetcode # 47. Permutations II
#
# Given a collection of numbers that might contain duplicates, return all possible unique permutations.
#
# For example,
# [1,1,2] have the following unique permutations:
# [1,1,2], [1,2,1], and [2,1,1].
#
# Companies
# LinkedIn Microsoft
# Related Topics
# Backtracking
# Similar Questions
# Next Permutation Permutations Palindrome Permutation II
#
import unittest
# 56ms 99.84%
class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permuteUnique(self, nums):
solutions = [[]]
for num in nums:
next = []
for solution in solutions:
for i in xrange(len(solution) + 1): # need to + 1 for the case solution is empty
candidate = solution[:i] + [num] + solution[i:]
if candidate not in next:
next.append(candidate)
solutions = next
return solutions
class TestMethods(unittest.TestCase):
def test_Local(self):
print Solution().permuteUnique([1, 1, 2])
#print Solution().permuteUnique([1, -1, 1, 2, -1, 2, 2, -1])
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
//permutation usually use boolean[] to track if element is used
//permutation forloop index start with 0
//use start index result in multiple duplication as below example of backtrackErr
//Use HashSet to remove duplicate
# 5ms 54.65%
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
backtrack(list, new ArrayList<>(), nums, new boolean[nums.length]);
return list;
}
//############ wrong example below #########################
//start index does not work in permutation
//[[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
private void backtrackErr(List<List<Integer>> list, List<Integer> tempList, int [] nums, int start){
if (tempList.size() == nums.length) {
list.add(new ArrayList<>(tempList));
return;
}
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (!set.contains(nums[i])) {
tempList.add(nums[i]);
set.add(nums[i]);
backtrackErr(list, tempList, nums, i + 1);
tempList.remove(tempList.size() - 1);
}
}
}
//############ wrong example above #########################
//[[1,1,2],[1,2,1],[2,1,1]]
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, boolean[] used){
if (tempList.size() == nums.length) {
list.add(new ArrayList<>(tempList));
return;
}
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (!used[i] && !set.contains(nums[i])) {
tempList.add(nums[i]);
used[i] = true;
set.add(nums[i]);
backtrack(list, tempList, nums, used);
tempList.remove(tempList.size() - 1);
used[i] = false;
}
}
}
}
# Sort array instead of use hash set
# 5ms 54.65%
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
backtrack(list, new ArrayList<>(), nums, new boolean[nums.length]);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, boolean[] used){
if (tempList.size() == nums.length) {
list.add(new ArrayList<>(tempList));
return;
}
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) continue;
if (!used[i]) {
tempList.add(nums[i]);
used[i] = true;
backtrack(list, tempList, nums, used);
tempList.remove(tempList.size() - 1);
used[i] = false;
}
}
}
}
# 3ms 98.56%
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
if (nums.length == 0) {
return new ArrayList<>();
}
return permuteUnique(nums, 0);
}
private List<List<Integer>> permuteUnique(int[] nums, int index) {
List<List<Integer>> result = new ArrayList<>();
if (index == nums.length) {
result.add(new ArrayList<>());
return result;
}
for (List<Integer> list : permuteUnique(nums, index + 1)) {
for (int i = 0; i <= list.size(); i++) {
List<Integer> newList = new ArrayList<>(list);
newList.add(i, nums[index]);
result.add(newList);
if (i < list.size() && list.get(i) == nums[index]) {
break;
}
}
}
return result;
}
}
# 3ms 98.56%
class Solution {
List<List<Integer>> ans;
public List<List<Integer>> permuteUnique(int[] nums) {
ans = new ArrayList();
permute(nums, 0);
return ans;
}
void permute(int[] nums, int l) {
if (l == nums.length) {
List<Integer> tmp = new ArrayList();
for (int t: nums) {
tmp.add(t);
}
ans.add(new ArrayList(tmp));
return;
} else{
for (int i = l ; i < nums.length; i++) {
int next = nums[i];
if (i > l) {
boolean skip = false;
for (int j = l; j < i; j++) {
if (nums[j] == next) {
skip = true;
break;
}
}
if (skip) continue;
}
swap(nums, l, i);
permute(nums, l + 1);
swap(nums, l, i);
}
}
}
public void swap(int[] s, int i, int j) {
int temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
'''
|
fada1884c8be84b5f5af3321b6b69348deb76c48 | huwenqing0606/Nonlinear-Optimization-in-Machine-Learning | /4-Backpropagation/plotGD.py | 4,666 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 14:30:29 2020
@author: huwenqing
"""
import numpy as np
import matplotlib.pyplot as plt
from activations import Sigmoid, ReLU, Tanh, Exponential
from fullnetwork import onelayer, fullnetwork
from backpropagation import backpropagation
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
#number of hidden layers#
L=3
#network size for each hidden layer n[0]=n_1, ..., n[L-1]=n_L#
n=np.random.randint(1, 5, size=L)
#activation function#
sigma=Sigmoid()
#number of iterations#
N=100
#set the network#
network=fullnetwork(L=L, n=n, activation=sigma)
#set the initial weight and bias#
weight, bias=network.setparameter()
#choose one layer from from [1, L-1]#
weightindex_startlayer=np.random.randint(1, L, size=None)
#its next layer#
weightindex_nextlayer=weightindex_startlayer+1
#the two weights taken from randomly sample two neurons from each of the above layers, from [1, width of that layer]#
weightindex_neuron_startlayer=np.random.randint(1, n[weightindex_startlayer-1]+1, size=2)
weightindex_neuron_nextlayer=np.random.randint(1, n[weightindex_nextlayer-1]+1, size=2)
#set training data (x,y)#
x=np.random.normal(0,1,1)
y=np.random.normal(0,1,1)
#plot the gd trajectory via backpropagation#
def plot_gd_trajectory(w1_init, w2_init, learningrate):
Loss=[]
w_1=[]
w_2=[]
w_1.append(float(w1_init))
w_2.append(float(w2_init))
weight[weightindex_startlayer][weightindex_neuron_nextlayer[0]-1][weightindex_neuron_startlayer[0]-1]=w1_init
weight[weightindex_startlayer][weightindex_neuron_nextlayer[1]-1][weightindex_neuron_startlayer[1]-1]=w2_init
networkoutput, outputsequence, preoutputsequence=network.output(float(x), weight, bias)
Loss.append(float(0.5*(y-float(networkoutput))**2))
for i in range(N):
#calculate the gradient with respect to current weight and bias#
backprop=backpropagation(L=L,
n=n,
activation=sigma,
weight=weight,
bias=bias,
outputsequence=outputsequence,
preoutputsequence=preoutputsequence)
delta=backprop.error(y)
gradweight, gradbias=backprop.grad(x, delta)
#update the weights and the loss values#
weight[weightindex_startlayer][weightindex_neuron_nextlayer[0]-1][weightindex_neuron_startlayer[0]-1]=w_1[i]-learningrate*gradweight[weightindex_startlayer][weightindex_neuron_nextlayer[0]-1][weightindex_neuron_startlayer[0]-1]
weight[weightindex_startlayer][weightindex_neuron_nextlayer[1]-1][weightindex_neuron_startlayer[1]-1]=w_2[i]-learningrate*gradweight[weightindex_startlayer][weightindex_neuron_nextlayer[1]-1][weightindex_neuron_startlayer[1]-1]
networkoutput, outputsequence, preoutputsequence=network.output(float(x), weight, bias)
Loss.append(float(0.5*(y-float(networkoutput))**2))
w_1.append(weight[weightindex_startlayer][weightindex_neuron_nextlayer[0]-1][weightindex_neuron_startlayer[0]-1])
w_2.append(weight[weightindex_startlayer][weightindex_neuron_nextlayer[1]-1][weightindex_neuron_startlayer[1]-1])
return w_1, w_2, Loss
if __name__ == "__main__":
w1_init=np.random.normal(0,1,1)
w2_init=np.random.normal(0,1,1)
learningrate=1
w_1, w_2, Loss=plot_gd_trajectory(w1_init, w2_init, learningrate)
print("w1=", w_1)
print("w2=", w_2)
print("Loss=", Loss)
fig = plt.figure()
ax=Axes3D(fig)
line=ax.plot([],[],'b:')
point=ax.plot([],[],'bo',markersize=10)
images=[]
def init():
line=ax.plot([],[],'b:',markersize=8)
point=ax.plot([],[],'bo',markersize=10)
return line,point
def anmi(i):
ax.clear()
line =ax.plot(w_1[0:i], w_2[0:i], Loss[0:i],'b:', markersize=8)
point = ax.plot(w_1[i-1:i], w_2[i-1:i], Loss[i-1:i],'bo', markersize=10)
return line,point
anim = animation.FuncAnimation(fig, anmi, init_func=init,
frames=N, interval=100, blit=False,repeat=False)
anim.save('GDtrajectory'+'_n='+str(n)+'_activation='+str(sigma.name)+'_layer'+
str(weightindex_startlayer)+'_neuron'+str(weightindex_neuron_startlayer[0])+str(weightindex_neuron_nextlayer[0])
+'_neuron'+str(weightindex_neuron_startlayer[1])+str(weightindex_neuron_nextlayer[1])+'.gif', writer='imagemagick')
|
92d523fc31fec6ebc2cb08ed934369462af49ef9 | CodyBuilder-dev/Algorithm-Coding-Test | /problems/programmers/lv3/pgs-12978.py | 1,228 | 3.515625 | 4 | """
제목 : 배달
아이디어 : 결국, 출발점으로부터 모든 다른 점까지의 최단거리 완전 탐색
(1) 출발점에서 한 도착점까지 최단거리 구하기
-
(2) 모든 도착점에 대해 반복하기
아이디어 : 아니면 그냥 BFS를 돌면서, 최소가 될때마다 갱신?
- '경주로 건설' 문제의 쉬운맛 버전인듯
"""
from math import inf
from collections import deque
def solution(N, road, K):
graph = [[inf]*(N+1) for _ in range(N+1)]
cost = [[inf]*(N+1) for __ in range(N+1)]
for r in road:
s,e,v = r
if v < graph[s][e]:
graph[s][e],graph[e][s] = v,v
cost[s][e], cost[e][s] =v,v
for i in range(1,N+1):
cost[i][i] = 0
dq = deque([1])
while dq:
current = dq.popleft()
for i,next in enumerate(graph[current]):
if next != inf: #연결되어 있는 경우
if cost[1][current] + cost[current][i] <= cost[1][i]:
cost[1][i] = cost[1][current] + cost[current][i]
dq.append(i)
return len(list(filter(lambda x:x<=K,cost[1])))
# return graph
print(solution(5,[[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]],3))
|
cfe17e8faffeac62ab6d4e5c752d095dcb39dd1d | yasmineholb/holbertonschool-machine_learning | /math/0x06-multivariate_prob/1-correlation.py | 479 | 3.625 | 4 | #!/usr/bin/env python3
""" correlation """
import numpy as np
def correlation(C):
""" Function that calculates a correlation matrix """
if not isinstance(C, np.ndarray):
raise TypeError("C must be a numpy.ndarray")
if len(C.shape) != 2 or C.shape[0] != C.shape[1]:
raise ValueError("C must be a 2D square matrix")
d = np.diag(C)
ch = d.reshape(-1, 1)
Sqrt = np.sqrt(ch)
SD = np.matmul(Sqrt, Sqrt.T)
corr = C / SD
return corr
|
45baa628e682fd6ad55a6d21f7444f47401ea3c9 | zhourunliang/algorithm | /python/linked_list.py | 3,277 | 3.828125 | 4 | class Node(object):
def __init__(self, element=-1):
self.element = element
self.next = None
def __repr__(self):
return str(self.element)
"""
链表
存取是 O(1)
插入删除也是 O(1)
python list 有两个部件
数组 存储数据在链表中的地址
链表 实际存储数据
"""
class LinkedList(object):
def __init__(self):
self.head = None
def log_list(self):
node = self.head
s = ''
while node is not None:
s += (str(node.element) + ' > ')
node = node.next
print(s)
# O(1)
def is_empty(self):
return self.head is None
def length(self):
index = 0
node = self.head
while node is not None:
index += 1
node = node.next
return index
def find(self, element):
node = self.head
while node is not None:
if node.element == element:
break
node = node.next
return node
def _node_at_index(self, index):
i = 0
node = self.head
while node is not None:
if i == index:
return node
node = node.next
i += 1
return None
def element_at_index(self, index):
node = self._node_at_index(index)
return node.element
# O(n)
def insert_before_index(self, position, element):
before_node = self._node_at_index(position-1)
cur_node = self._node_at_index(position)
# 在中间
if before_node is not None:
node = Node(element)
node.next = cur_node
before_node.next = node
else:
node = Node(element)
node.next = cur_node
return node
# O(n)
def insert_after_index(self, position, element):
cur_node = self._node_at_index(position)
after_node = self._node_at_index(position+1)
if after_node is not None:
node = Node(element)
cur_node.next = node
node.next = after_node
else:
node = Node(element)
cur_node.next = node
return node
# O(1)
def first_object(self):
node = self._node_at_index(0)
return node
# O(n)
def last_object(self):
node = self._node_at_index(self.length()-1)
return node
# O(n)
def append(self, element):
node = Node(element)
if self.head is None:
self.head.next = node
else:
last_node = self.last_object()
last_node.next = node
node.front = last_node
def test():
li = LinkedList()
li.head = Node(1)
for i in range(2, 6):
li.append(i)
li.log_list()
print('first_object', li.first_object())
print('last_object', li.last_object())
li.insert_after_index(2,8)
print('insert_after_index')
li.log_list()
li.insert_before_index(2,9)
print('insert_before_index')
li.log_list()
print('element_at_index', li.element_at_index(2))
print('find', li.find(8))
print('length', li.length())
print('is_empty', li.is_empty())
if __name__ == '__main__':
test()
|
7a63abc8c28d0f801aeabb454d20d536b03aee1e | alans09/PythonAcademyExercises | /Lekcia11/cvicenie_context.py | 723 | 3.8125 | 4 | import re
class Splitter:
def __init__(self, text):
self.text = text
def __enter__(self):
return self.text
def __exit__(self, *args):
res = re.match(
r"^([\w\s]*)--(.*)--([\w\s]*).$",
self.text
)
print(
[
res.group(1).strip(),
res.group(2).strip(),
res.group(3).strip()
]
)
text = "There should be one-- and preferably only one --obvious way to do it."
# vytvor objekt splitter, a do premennej za AS
# vloz hodnotu, ktoru vrati metoda __enter__()
#
# with Splitter(text) as lopata:
# print(f"XY: {lopata}")
lopata = Splitter(text)
print(lopata.__exit__()) |
a900716fb6b8bd1fae1a061c5575b7fc8a7ffe3f | LittltZhao/code_git | /009_Palindrome_Number.py | 333 | 3.90625 | 4 | # -*- coding:utf-8 -*-
def isPalindrome(x):#转化为字符串占用了新的空间
s1=str(x)
s2=s1[::-1]
return s1==s2
def isPalindrome2(x):#通用解法
if x<0:
return False
temp=x
res=0
while temp:
res=res*10+temp%10
temp=temp/10
return res==x
print isPalindrome2(123201)
|
8f02ec1c38dfdc1c2193598ae8a8b5fe046e87ea | AndreasWintherMoen/SchoolAssignments | /TDT4110/Oving1/Tetraeder/Tetraeder.py | 306 | 4.09375 | 4 | import math
height = float(input("Skriv inn en høyde: "))
a = 3.0 / math.sqrt(6) * height
area = math.sqrt(3) * a**2
volume = (math.sqrt(2) * a**3) / 12.0
print("Et tetraeder med høyde ", height, " har areal ", round(area, 2))
print("Et tetraeder med høyde ", height, " har volum ", round(volume, 2))
|
13f88c2d7f0ee041f9e53614d1b0cae71f608d8b | SelkieAnna/de-computational-practicum | /main.py | 2,355 | 3.6875 | 4 | import plotter
import math
from tkinter import *
def main():
window = Tk()
head = Label(window, text = "This application is designed to plot the equation y' = cos(x) - y.")
note = Label(window, text = "All graph tabs must be closed in order for the main window to work correctly.")
lbl_inp_gr = Label(window, text = "Input for the graphs:")
inp = Frame(window)
xz = Frame(inp)
xzl = Label(xz, text = "x0")
xzi = Entry(xz)
yz = Frame(inp)
yzl = Label(yz, text = "y0")
yzi = Entry(yz)
xm = Frame(inp)
xml = Label(xm, text = "x max")
xmi = Entry(xm)
nu = Frame(inp)
nul = Label(nu, text = "n")
nui = Entry(nu)
lbl_inp_err = Label(window, text = "Input for the total error:")
inp_err = Frame(window)
nz = Frame(inp_err)
nzl = Label(nz, text = "n0")
nzi = Entry(nz)
nm = Frame(inp_err)
nml = Label(nm, text = "n max")
nmi = Entry(nm)
bttn = Button(window, text = "Plot")
head.pack()
note.pack()
lbl_inp_gr.pack()
xzl.pack(side = LEFT)
xzi.pack(side = RIGHT)
xz.pack()
yzl.pack(side = LEFT)
yzi.pack(side = RIGHT)
yz.pack()
xml.pack(side = LEFT)
xmi.pack(side = RIGHT)
xm.pack()
nul.pack(side = LEFT)
nui.pack(side = RIGHT)
nu.pack()
inp.pack()
lbl_inp_err.pack()
nzl.pack(side = LEFT)
nzi.pack(side = RIGHT)
nz.pack()
nml.pack(side = LEFT)
nmi.pack(side = RIGHT)
nm.pack()
inp_err.pack()
bttn.pack()
plot = plotter.Plotter(lambda x, c: (math.sin(x) + math.cos(x)) * 0.5 + c * math.exp(-x),
lambda x0, y0: math.exp(x0) * ((math.cos(x0) + math.sin(x0)) * 0.5),
lambda x, y: math.cos(x) - y)
bttn.configure(command = lambda: execute(plot, xzi, yzi, xmi, nui, nzi, nmi))
window.mainloop()
def execute(plot, xzi, yzi, xmi, nui, nzi, nmi):
try:
x0 = float(xzi.get())
y0 = float(yzi.get())
xmax = float(xmi.get())
n = int(nui.get())
except ValueError:
print("Wrong input")
else:
try:
n0 = int(nzi.get())
nmax = int(nmi.get())
except ValueError:
n0 = None
nmax = None
finally:
plot.plot(x0, y0, xmax, n, n0, nmax)
if __name__ == '__main__':
main() |
90a5081ba82facf8188b5a61b8eb38d2435e7822 | Mahadev0317/Codekata | /print elements lesser than N.py | 115 | 3.515625 | 4 | n=int(input())
l=list(map(int,input().split()))
lis=[]
for i in l:
if i<n:
lis.append(i)
print(*sorted(lis))
|
302f638eaf83f3915992b7ddf3668b6453db91d4 | nkrishnappa/ProgrammingLanguageCourse | /Practice Problems/0.2-List/Two-Sum.py | 759 | 3.859375 | 4 | # Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
a = [1, 2, 3, 4, 5 , -3, -4, -6, 10, 20]
number = 6
my_list = []
def twoSum(array:list, number:int) -> tuple:
global my_list
for element_x in range(len(array) - 2):
for element_y in range(element_x, len(array) - 1):
if array[element_x] + array[element_y] == number:
my_tuple = ()
print(f"{element_x:2} - {array[element_x]:2}, {element_y:2} - {array[element_y]:2} ")
my_tuple += (element_x, element_y)
my_list.append(my_tuple)
#return element_x, element_y - function will exit at first match
twoSum(a, number)
print(my_list) |
e81e4102701c9a6aba55f8a82b7b7381931053a7 | nikhilgajam/Python-Programs | /Addition of matrix program normal method in python.py | 997 | 4.28125 | 4 | print("Matrix Addition Program\n")
row = int(input("Enter rows: "))
col = int(input("Enter columns: "))
a = []
b = []
c = []
# To make entered dimensional matrix
for i in range(row):
a.append(col*[0])
for i in range(col):
b.append(col*[0])
for i in range(row):
c.append(col*[0])
print(c)
print("\nEnter matrix 1 elements: ")
for i in range(row):
for j in range(col):
print("Enter row", i, "column", j, ": ", end="")
a[i][j] = int(input())
print("\nEnter matrix 2 elements: ")
for i in range(row):
for j in range(col):
print("Enter row", i, "column", j, ": ", end="")
b[i][j] = int(input())
for i in range(row):
for j in range(col):
c[i][j] = a[i][j] + b[i][j]
print("\nResultant Matrix: \n")
for i in range(row):
for j in range(col):
print(c[i][j], end="\t")
print() |
1d714622a5f7d72f5aa131204b191a941f80491b | rrbarioni/advent-of-code | /src/day1.py | 1,709 | 3.828125 | 4 | def solve_part1(entries):
'''
Given a list of integer values, what is the product of the two values whose
sum is equal to 2020?
'''
entries = [int(e) for e in entries]
n = 2020
d = {}
for e in entries:
if e not in d:
d[e] = 1
else:
d[e] += 1
for e_i in entries:
e_j = n - e_i
if e_j in d:
if (e_i != e_j) or d[e_i] > 1:
prod = e_i * e_j
return prod
def solve_part2(entries):
'''
Given a list of integer values, what is the product of the three values
whose sum is equal to 2020?
'''
entries = [int(e) for e in entries]
n = 2020
d = {}
for e in entries:
if e not in d:
d[e] = 1
else:
d[e] += 1
for i in range(len(entries)):
e_i = entries[i]
for j in range(i+1, len(entries)):
e_j = entries[j]
e_k = n - e_i - e_j
if e_k in d:
all_diff = (e_i != e_j) and (e_i != e_k) and (e_j != e_k)
ij_eq = (e_i == e_j) and (d[e_i] > 1)
ik_eq = (e_i == e_k) and (d[e_i] > 1)
jk_eq = (e_j == e_k) and (d[e_j] > 1)
# for "n" not divisible by 3, this case will never happen
all_eq = (e_i == e_j) and (e_i == e_k) and (d[e_i] > 2)
if all_diff or ij_eq or ik_eq or jk_eq or all_eq:
prod = e_i * e_j * e_k
return prod
if __name__ == '__main__':
entries = open('inputs/day1.txt').readlines()
print('part 1: %s' % solve_part1(entries))
print('part 2: %s' % solve_part2(entries))
|
0f1061f0dd5194eb6c9e14f716a0f9610b68071e | ptemplin/PyNLPTools | /extraction/wordfrequency.py | 1,063 | 4.5625 | 5 | def word_frequency(document, word_to_frequency = {}):
"""
Computes the frequencies of words in a given document adding to the existing mapping.
:param document: to compute word frequencies for
:param word_to_frequency: existing mapping of words to frequencies from other documents
:return: the modified word_to_frequency map and the total count of words in the document
"""
count = 0
for word in document:
count += 1
if word in word_to_frequency:
word_to_frequency[word] += 1
else:
word_to_frequency[word] = 1
return word_to_frequency, count
def word_frequency_documents(documents):
"""
Computes the frequencies of words in a list of documents.
:param documents: list to use
:return: mapping of words to their frequencies and the total word count
"""
word_to_frequency = {}
count = 0
for document in documents:
w2f, doc_count = word_frequency(document, word_to_frequency)
count += doc_count
return word_to_frequency, count
|
51cc0f96c2390da54a153a4b147d4133435b6f16 | n3z0xx/tp_labs1-3 | /37.py | 601 | 4.1875 | 4 | # 37. Из англ букв составить 13 элем-ую рандомную строку и убрать все
# неуникальные, заменив уникальные символом 0 (ноль). Вывести оставшиеся с их индексами.
import random
import string
s = ''.join(random.choice(string.ascii_lowercase) for _ in range(13))
print(s)
known = []
not_uniq = []
for i in s:
if i not in known:
known.append(i)
else:
not_uniq.append(i)
a = [i for i in s if i not in not_uniq]
#print(''.join(a))
print({s.index(i): i for i in a}) |
60a83b1026b33d16b6f6bbdb4024b9160dc95355 | ashokpal100/python_written_test | /python/number/add_digit_sum.py | 179 | 4 | 4 |
number=int(raw_input("enter any no: "))
sum = 0
temp = number
while number > 0:
rem = number % 10
sum += rem
number //= 10
print("Sum of all digits of", temp, "is", sum, "\n") |
637c586967c320c6f06462fbb34741d7db078f69 | yeliuyChuy/leetcodePython | /557ReverseWordsInAString.py | 318 | 3.65625 | 4 | class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s2 = s.split(" ")
answer = []
for ch in s2:
answer.append(ch[::-1])
return ' '.join(answer) #character that joins the elements to make the lise a whole new string |
84d49c8061f77d4d942f9975f43a5d4dff77da5f | soraef/nlp100 | /6/50.py | 1,087 | 3.703125 | 4 | import re
file_path = "../data/nlp.txt"
def load_file(path):
with open(path) as f:
data = f.read()
return data
# テキストを分割
def split_text(text):
return re.findall(r"(.*?[.;:?!])\s\n?(?=[A-Z])", text)
text = load_file(file_path)
sentences = split_text(text)
for sentence in sentences:
print(sentence)
#
# 出力(一部)
#
# Natural language processing (NLP) is a field of computer science, artificial intelligence, and linguistics concerned with the interactions between computers and human (natural) languages.
# As such, NLP is related to the area of humani-computer interaction.
# Many challenges in NLP involve natural language understanding, that is, enabling computers to derive meaning from human or natural language input, and others involve natural language generation.
# The history of NLP generally starts in the 1950s, although work can be found from earlier periods.
# In 1950, Alan Turing published an article titled "Computing Machinery and Intelligence" which proposed what is now called the Turing test as a criterion of intelligence. |
68f5f06d47c0cdf7ab2bb32f19924c674fdfbd41 | Sangee23-vani/python | /section_3/strings.py | 268 | 3.859375 | 4 | name = 'Sangi'
print('Hello {}'.format(name))
result = 35678.76546783
print('The result is {r:1.3f}'.format(r=result))
print('The result is {}'.format(result))
print('Hello {}'.format('Jeyasri'))
print('The {q} {b} {f}.'.format(f = 'fox', q = 'quick', b = 'brown')) |
2a7aaab972c520a16aaa28df67f00b776264be14 | vishalsingh8989/karumanchi_algo_solutions_python | /Chapter 4 stacks/prefixtoinfix.py | 627 | 3.796875 | 4 |
ops = ["*" , "/" , "-", "+", "^"]
def postfixtoinfix(expression):
res = ""
stack = []
for i in xrange(len(expression) - 1, -1 , -1):
#print(expression[i])
if expression[i] in ops:
op1 = stack.pop()
op2 = stack.pop()
stack.append("(" + op1 + "" + expression[i] + "" + op2 + ")")
else:
stack.append(expression[i])
return stack.pop()
if __name__ == "__main__":
expression = "*+AB-CD"
print(postfixtoinfix(expression))
expression = "*-A/BC-/AKL"
print(postfixtoinfix(expression))
print(postfixtoinfix(expression)) |
2d125d3d345364189ac98a7d9f7d0b73c455b3ff | Vaishnav95/bridgelabz | /functional_programs/simple_array.py | 679 | 4.1875 | 4 | """
2D Array
a. Desc -> A library for reading in 2D arrays of integers, doubles, or booleans from
standard input and printing them out to standard output.
b. I/P -> M rows, N Cols, and M * N inputs for 2D Array. Use Java Scanner Class
c. Logic -> create 2 dimensional array in memory to read in M rows and N cols
d. O/P -> Print function to print 2 Dimensional Array. In Java use PrintWriter with
OutputStreamWriter to print the output to the screen.
"""
from utils import Util
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
array_object = Util()
result_matrix = array_object.array_2d(rows, columns)
print(result_matrix)
|
a55da555b043f939b9106277afa4a67fedff107f | shankarapailoor/Project-Euler | /Project Euler/p10-20/p15.py | 1,130 | 3.796875 | 4 | #solved by combinatorics, but this is a coded algorithm using DP
def f1():
arr = []
for i in range(0, 20):
temp = []
for k in range(0, 20):
temp.append(k)
arr.append(temp)
return arr
def find_routes(start, finish):
num_paths = {}
if start[0] < 20 and start[1] < 20:
if (start[0]+1, start[1]) in num_paths:
print 'I am in the if loop'
num_paths[start] += num_paths[(start[0]+1, start[1])]
elif (start[0], start[1]+1) in num_paths:
print 'I am in the elif loop'
num_paths[start] += num_paths[(start[0], start[1]+1)]
else:
print 'I am in the else loop'
num_paths.update(find_routes((start[0]+1, start[1]), finish))
num_paths.update(find_routes((start[0], start[1]+1), finish))
num_paths[start] = num_paths[(start[0], start[1]+1)] + num_paths[(start[0]+1, start[1])]
elif start[1] <= 20 and start[0]==20:
print "I am out of the else loop"
num_paths[start] = 1
elif start[0] <= 20 and start[1]==20:
print "I am out of the else loop"
num_paths[start] = 1
return num_paths
if __name__=='__main__':
start = (10, 10)
end = (20, 20)
x = find_routes(start, end)
print x[start]
|
470096826ddb1b3588d8bfb0ee89d4cd1a5f2b8f | FarzanaEva/Data-Structure-and-Algorithm-Practice | /InterviewBit Problems/String/minimum_parenthese.py | 1,153 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 9 23:15:31 2021
@author: Farzana Eva
"""
"""
PROBLEM STATEMENT:
Given a string A of parantheses ‘(‘ or ‘)’.
The task is to find minimum number of parentheses ‘(‘ or ‘)’ (at any positions) we must add to make the resulting parentheses string valid.
An string is valid if:
Open brackets must be closed by the corresponding closing bracket.
Open brackets must be closed in the correct order.
Problem Constraints
1 <= |A| <= 105
A[i] = '(' or A[i] = ')'
Input Format
First and only argument is an string A.
Output Format
Return a single integer denoting the minimumnumber of parentheses ‘(‘ or ‘)’ (at any positions) we must add in A to make the resulting parentheses string valid.
Example Input
Input 1:
A = "())"
Input 2:
A = "((("
Example Output
Output 1:
1
Output 2:
3
Example Explanation
Explanation 1:
One '(' is required at beginning.
Explanation 2:
Three ')' is required at end.
"""
def solve(A):
left = 0
right = 0
for i in range(len(A)):
if A[i] =="(": right += 1
elif right > 0: right -= 1
else: left += 1
return left+right
|
3dd5ca9627832db5cfc422c540491f0499a23a1a | Physopholy/learningmathmethods | /gamma-phi.py | 3,458 | 3.59375 | 4 | import numpy as np
#just comment out inputs/routines not needed
print('Enter guesses for unknown variables.')
#t=float(input("Enter T(degC):"))
t=45
t=273+t
#p=float(input("Enter P(bar):"))
p=1.35
#x1=float(input("Enter x1:"))
x1=.259
x2=1-x1
#y1=float(input("Enter y1:"))
y1=.735
y2=1-y1
#psat1=float(input("Enter Psat1(bar):"))
psat1=2.34218
#psat2=float(input("Enter Psat2(bar):"))
psat2=.44265
#b1=float(input("Enter b1 from binaryinteractions.py:"))
b1=-609.83
#b2=float(input("Enter b2 from binaryinteractions.py:"))
b2=-765.94
#b12=float(input("Enter b12 from binaryinteractions.py:"))
b12=-680.65
del12=2*b12-b1-b2
#a=float(input("Enter A_prime for margules eqn.:"))
a=0.93
def margules(x,a_prime): #returns gamma for the given x
g=2.718281828459045**(a_prime*(1-x)**2)
return(g)
g1=margules(x1,a)
g2=margules(x2,a)
def gammaphi(y1,y2,p,t,x1,x2,g1,g2,psat1,psat2):
def phi_solver(b,p,psat,y,del12,t): #just a subroutine for phi
phi=2.718281828459045**((b*(p-psat)+p*(1-y)**2*del12)/(83.1451*t))
return(phi)
def obj(y,p,b,del12,t,x,gamma,psat): #function to be rooted
lhs=y*p*2.718281828459045**((b*(p-psat)+p*(1-y)**2*del12)/(83.1451*t))
rhs=x*gamma*psat
f=lhs-rhs
return(f)
def deriv(y,dy,p,dp,b,del12,t,x,gamma,psat): #centered-difference approximation
f_0=obj(y-dy,p-dp,b,del12,t,x,gamma,psat)
#print('f_0=',f_0)
f_1=obj(y+dy,p+dp,b,del12,t,x,gamma,psat)
#print('f_1=',f_1)
dy_dx=(f_1-f_0)/(2*(dy+dp))
#print('dydx=',dy_dx)
return(dy_dx)
phi1=phi_solver(b1,p,psat1,y1,del12,t) #these lines just initialize error
phi2=phi_solver(b2,p,psat2,y2,del12,t)
Fyp=np.array([[obj(y1,p,b1,del12,t,x1,g1,psat1)],[obj(y2,p,b2,del12,t,x2,g2,psat2)]])
error=np.linalg.norm(Fyp)
index=0
#x=np.array([[y1],[p]])
while error>0.000001 and index<100:
index=index+1
print(index)
dobj1_dy1=deriv(y1,.00000001,p,0,b1,del12,t,x1,g1,psat1) #check these
dobj1_dp=deriv(y1,0,p,.00000001,b1,del12,t,x1,g1,psat1)
dobj2_dy1=deriv(y2,-.00000001,p,0,b2,del12,t,x2,g2,psat2)
dobj2_dp=deriv(y2,0,p,.00000001,b2,del12,t,x2,g2,psat2)
x=np.array([[y1],[p]])
print('x',x)
Fyp=np.array([[obj(y1,p,b1,del12,t,x1,g1,psat1)],[obj(y2,p,b2,del12,t,x2,g2,psat2)]])
print('fyp',Fyp)
jacob=np.array([[dobj1_dy1,dobj1_dp],[dobj2_dy1,dobj2_dp]])
print('jacob',jacob)
jinv=np.linalg.inv(jacob)
print('jinv',jinv)
x=x-np.dot(jinv,Fyp)
print('x',x)
#start here, need to figure out how to slice numpy array x
y1=float(x[0])
print('y1',y1)
y2=1-y1
print('y2',y2)
p=float(x[1])
print('p',p)
Fyp=np.array([[obj(y1,p,b1,del12,t,x1,g1,psat1)],[obj(y2,p,b2,del12,t,x2,g2,psat2)]])
error=np.linalg.norm(Fyp)
print('error',error)
phi1=phi_solver(b1,p,psat1,y1,del12,t)
phi2=phi_solver(b2,p,psat2,y2,del12,t)
return(p,t,y1,y2,phi1,phi2,x1,x2,g1,g2,psat1,psat2,index)
answer=gammaphi(y1,y2,p,t,x1,x2,g1,g2,psat1,psat2)
p=answer[0]
t=answer[1]
y1=answer[2]
y2=answer[3]
phi1=answer[4]
phi2=answer[5]
x1=answer[6]
x2=answer[7]
g1=answer[8]
g2=answer[9]
psat1=answer[10]
psat2=answer[11]
print('P(bar)=',p)
print('T(K)=',t)
print('y1=',y1)
print('y2=',y2)
print('phi1=',phi1)
print('phi2=',phi2)
print('x1=',x1)
print('x2=',x2)
print('gamma_1= ',g1)
print('gamma_2= ',g2)
print('Psat1(bar)= ',psat1)
print('Psat2(bar)= ',psat2)
print('Steps taken:',answer[12])
|
96dc8d8f2b112303f238e309b85c58ba4d15b941 | williamjzhao/ackermann_func | /ackermann.py | 909 | 4 | 4 | def ackermann(m, n):
if m == 0:
n = n+1
# print("Base Case: " + str(n) + "")
return n
elif m > 0 and n == 0:
# print("Calling Ackermann of " + str(m-1) + " and " + str(n))
result = ackermann(m-1, 1)
# print("Result is " + str(result) + "")
return result
elif m > 0 and n > 0:
# print("Recursive parameter step! Must compute Ackermann of " + str(m) + " and " + str(n-1))
recursive = ackermann(m, n-1)
# print("Recursive step done, Ackermann of " + str(m) + " and " + str(n-1) + " is: " + str(recursive))
# print("Calling Ackermann of " + str(m-1) + " and " + str(recursive))
result = ackermann(m-1, recursive)
# print("Result is: " + str(result) + "\n")
return result
print("Running Ackermann function on 3, 3")
answer = ackermann(3, 3)
print("\n\nFinal Answer is: " + str(answer))
|
98d48c010e27011118d91421f51d6cc04fd7ca40 | Babatunde13/30-days-of-code-python-ECX | /Python Files/day_25.py | 776 | 4.15625 | 4 | def desc_triangle(a, b, c):
'''
A function named desc_triangle
Parameters: a, b and c, the lenght of each size of the triangle.
Returns: The type of triangle and the value of it's area
'''
# Using Hero's Formula
s = (a + b + c) / 2
area = (s * (s-a) * (s - b) * (s - c)) ** 0.5
if a == b == c: # Checks if all sides are equal
return "Equilateral Triangle", area
elif a == b or a == c or b == c: # Checks if any two sides are equal
return "Iscocelles Triangle", area
else: # If first two are False, then triangle is a scalene triangle.
k = sorted([a, b, c])
if k[0] ** 2 + k[1] ** 2 == k[2] ** 2:
return "Right andled Scalene triangel", area
return "Scalene Triangle", area
|
a40cdca5fdd8b93c6c0509d59c3f3fef7038e701 | Elendeer/homework | /python/5th/test_1.py | 330 | 3.671875 | 4 | #!/usr/bin/python3
import random
def getPi(times):
hints = 0
for i in range(1, times + 1):
y = random.random()
x = random.random()
if x * x + y * y <= 1:
hints += 1
Pi = hints / times * 4
return Pi
if __name__ == '__main__':
times = int(input())
print(getPi(times))
|
809716a3819e3e4721363e34da6c5aecb51befde | sbrodehl/hashcode2021 | /Practice Round/solver/scoring.py | 2,279 | 3.65625 | 4 | #!/usr/bin/env python3
import logging
from dataclasses import dataclass, field
from .parsing import parse_input, parse_output
LOGGER = logging.getLogger(__name__)
@dataclass
class Score:
scores: list = field(default_factory=list)
total: int = 0
def add(self, diff_ingredients_sq):
self.scores.append(diff_ingredients_sq)
self.total += diff_ingredients_sq * diff_ingredients_sq
def set_log_level(args):
if args.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
def compute_score(file_in, file_out):
"""
Compute score (with bonus) of submission
:param file_in: input file
:param file_out: output file (solution)
:return: Score
"""
# read input and output files
m, teams, pizzas = parse_input(file_in)
deliveries = parse_output(file_out, (m, teams, pizzas))
s = Score()
for d in deliveries:
# check if all pizzas are available
if not all(not pizzas[pid].delivered for pid in d.pizza_ids):
LOGGER.error(f"Delivery contains already delivered pizzas! ({d})")
break
# check if enough pizzas are delivery for the team
if not d.complete():
LOGGER.error(f"Delivery contains not enough pizzas! ({d})")
break
# check amount of deliveries per team size
if teams[d.team_size] <= 0:
LOGGER.error(f"More deliveries than teams found for size {d.team_size}!")
break
teams[d.team_size] -= 1 # decrease seen deliveries for the team size
# now compute actual score
s.add(len(d.ingredients))
return s
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='print score', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file_in', type=str, help='input file e.g. a_example.in')
parser.add_argument('file_out', type=str, help='output file e.g. a_example.out')
parser.add_argument('--debug', action='store_true', help='set debug level')
args = parser.parse_args()
set_log_level(args)
score = compute_score(args.file_in, args.file_out)
print("Score for {}: {} points".format(args.file_out, score.total))
|
4df3a902fcc70ac01aaaba94b5d623cd87a17202 | Priyankakore21/Dailywork | /PYTHON Training/day4/practice/constant.py | 477 | 4.125 | 4 | #we define some options
LOWER, UPPER, CAPITAL = 1,2,3
name = 'jane'
#we use our constants when assigning these values
print_style = UPPER
#... and when checking them:
if print_style == LOWER:
print(name.lower())
elif print_style == UPPER:
print(name.upper())
elif print_style == CAPITAL:
print(name.capitailze())
else:
#nothing prevents us from accidently setting print_style to 4, 90 or
#'spoon' so we put in this fallback just in case:
print('unknown style opton')
|
4483aa10e156a3852095d7a9131a409174a51c00 | vinuv296/luminar_python_programs | /Advanced_python/test/pgm10.py | 312 | 3.546875 | 4 | # import re
# x='^a+[a-zA-A]+b$' # check ending with a
# r="antb"
# mat=re.fullmatch(x,r)
# if mat is not None:
# print("valid")
# else:
# print("invalid")
import re
x='[A-Z]+[a-z]+$' # check ending with a
r="Geva"
mat=re.fullmatch(x,r)
if mat is not None:
print("valid")
else:
print("invalid") |
3ddd46d1d36d182beda5de8c371f49049f4a8656 | sampathweb/game_app | /card_games/blackjack/rules.py | 2,857 | 3.828125 | 4 | #!/usr/bin/env python
"""
A package to wrap the rules of BlackJack.
"""
from __future__ import print_function
import random
class BlackJack:
def __init__(self, play_computer=True, level=0):
self.play_computer = play_computer
self.level = level
self.card_suits = ['spade', 'heart', 'diamond', 'club']
self.card_faces = {str(numb): numb for numb in range(2, 11)}
for face in ('jack', 'king', 'queen'):
self.card_faces[face] = 10
self.card_faces['ace'] = 1
self._reset_board()
def _face_value(self, face_numb):
'''Returns card value for the card. Card needs to be of format (face, suit)'''
return self.card_faces[face_numb]
def get_hand_value(self, hand):
hand_values = [0]
for face, suit in hand:
card_value = self._face_value(face)
hand_values = [value + card_value for value in hand_values]
if face == 'ace':
hand_values_ace = [value + 10 for value in hand_values if value <= 11]
hand_values += hand_values_ace
# Exclude all values > 21
hand_values.sort(reverse=True) # Highest number First
for value in hand_values:
hand_value = value
if hand_value <= 21: # Found the highest number <= 21
break
return hand_value
def _reset_board(self):
'''Initiailizes the available cards and the hands of Player and Dealer'''
self.player_hand = []
self.dealer_hand = []
self.card_deck = [(face, suit) for suit in self.card_suits for face in self.card_faces.keys()]
random.shuffle(self.card_deck) # Shuffle the card deck
# Draw two cards for Player and Dealer
self.player_hand.append(self._pick_card())
self.player_hand.append(self._pick_card())
self.dealer_hand.append(self._pick_card())
self.dealer_hand.append(self._pick_card())
def _pick_card(self):
'''Draws a Card from the Deck and return the card'''
return self.card_deck.pop()
def draw_card_player(self):
self.player_hand.append(self._pick_card())
def player_hand_value(self):
return self.get_hand_value(self.player_hand)
def dealer_hand_value(self):
return self.get_hand_value(self.dealer_hand)
def game_result(self):
dealer_value = self.dealer_hand_value()
player_value = self.player_hand_value()
if player_value > 21:
result = 'bust'
elif dealer_value > 21:
result = 'won'
elif player_value > dealer_value:
result = 'won'
elif dealer_value > player_value:
result = 'lost'
elif player_value == dealer_value:
result = 'push'
else:
result = None
return result
|
3b103d9ac6191940686a69536097cc0ebde007a7 | JackZander/Python-Note | /1.4.3Python小程序/m1.2EchoName.py | 231 | 3.71875 | 4 | name = input("输入姓名:")
print("{}同学,学好Python,前途无量!".format(name))
print("{}大侠,学好Python,前途无量!".format(name[0]))
print("{}哥哥,学好Python,前途无量!".format(name[1:]))
|
87b097d7b4dd04c3f2085472e9dd1c079a8104e7 | stostat/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 133 | 3.75 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
new_dic = {doub: v*2 for doub, v in a_dictionary.items()}
return new_dic
|
9b822bac22a7fe93695c86c879dea97f537680d1 | Aminaba123/LeetCode | /166 Fraction to Recurring Decimal.py | 3,008 | 4.0625 | 4 | """
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
"""
__author__ = 'Daniel'
class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
The key is the remainder
:type numerator: int
:type denominator: int
:rtype: str
"""
sign = 1 if numerator*denominator >= 0 else -1
numerator = abs(numerator)
denominator = abs(denominator)
int_part = numerator/denominator
frac_part = numerator-int_part*denominator
if frac_part:
decimal_part = self.frac(numerator-int_part*denominator, denominator)
ret = str(int_part)+"."+decimal_part
else:
ret = str(int_part)
if sign < 0:
ret = "-" + ret
return ret
def frac(self, num, deno):
"""
real fraction part
"""
ret = []
d = {}
i = 0
while num:
num *= 10
q = num/deno
r = num%deno
if (q, r) in d:
ret.append(")")
ret.insert(d[(q, r)], "(")
return "".join(ret)
ret.append(str(q))
d[(q, r)] = i
i += 1
num -= q*deno
return "".join(ret)
class Solution_error:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
int_part = numerator/denominator
fract_part = numerator-int_part*denominator
if fract_part:
decimal_part = self.frac(numerator-int_part*denominator, denominator)
ret = str(int_part)+"."+decimal_part
else:
ret = str(int_part)
return ret
def frac(self, num, deno):
"""
real fraction part
"""
ret = []
d = {}
i = 0
while num:
l = 0 # the number of added 0
while num < deno:
num *= 10
l += 1
r = num/deno
if r in d:
ret.append(")")
ret.insert(d[r]-(l-1), "(")
return "".join(ret)
for _ in xrange(l-1):
ret.append("0")
i += 1
ret.append(str(r))
d[r] = i
i += 1
num -= r*deno
return "".join(ret)
if __name__ == "__main__":
assert Solution().fractionToDecimal(1, 333) == "0.(003)"
assert Solution().fractionToDecimal(1, 90) == "0.0(1)"
assert Solution().fractionToDecimal(-50, 8) == "-6.25"
assert Solution().fractionToDecimal(7, -12) == "-0.58(3)" |
c85e9161e7c5bc2ba49479d7300069c5f42313ad | tinadrew/ECE573_HW | /HW1/ECE573-S18_Drew_HW1/Q4/Q4_GenerateArray.py | 849 | 3.9375 | 4 | """Tina Drew - 035006375
ECE573 - Spring 2018
Homework 1
This Code is to provide a data set for the Question 4 of homework #1
It create a set random floating point numbers and prints the to file.
The size of the list or array is based on the user input value of N.
"""
import random
def getFilePath():
import tkinter as tk
from tkinter import filedialog
global fileNew
root = tk.Tk()
root.withdraw()
fileNew = filedialog.askopenfilename()
return fileNew
getFilePath()
afile = open(fileNew, "w" )
#Writes random vairables for file. Based on code from:
#https://stackoverflow.com/questions/14907759/random-number-file-writer
for i in range(int(input('How many random numbers?: '))):
a = random.uniform(-100, 100)
line = '%.2f' %a +'\n'
afile.write(line)
print(line)
afile.close()
#print('all done') |
b941a64f9d1e7cf0fe09d4e6cf180261603b86cc | marble-git/python-laoqi | /chap4/sqrt_to_lt_2.py | 468 | 4.25 | 4 | #coding:utf-8
'''
filename:sqrt_to_lt_2.py
chap:4
subject:11
conditions:input a int number > 2
solution:sqrt the number until < 2 ,times, .2f
'''
import math
integer = input('Enter an integer > 2 : ')
if integer.isdigit() and (rst:=int(integer)) > 2:
count = 0
while rst >= 2:
count += 1
rst = math.sqrt(rst)
print(f'sqort_times: {count},result:{rst:.2f}')
else:
print('Input is not integer or not gt 2.')
|
306d28ab735a3a2f0f60dfeb95e9629084da9b4b | scohen40/wallbreakers_projects | /Leetcode/week_1/p0344_reverse_string.py | 541 | 3.8125 | 4 | from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if len(s) > 1:
slen = len(s)
for i in range(slen // 2):
s[i], s[slen - 1 - i] = s[slen - 1 - i], s[i]
"""
Runtime: O(N/2)
Space: O(1)
Runtime: 216 ms, faster than 56.34% of Python3 online submissions for Reverse String.
Memory Usage: 17.3 MB, less than 94.19% of Python3 online submissions for Reverse String.
"""
|
371a6921887be714784c3e5b9eafb62f8f7356ab | brpandey/fast-hangman-2.0 | /Hangman.py | 2,088 | 3.796875 | 4 | from HangmanGame import HangmanGame
from HangmanLetterStrategy import HangmanLetterStrategy
from HangmanSettings import HangmanSettings
class Hangman:
"""
Abstraction to represent a real hangman game that can be played (is playable)
"""
def __init__(self, settings):
self._settings = settings
self._display = settings.display
def play(self, secret, maxincorrect):
"""
Play this hangman by setting up,
then running the game with the strategy. Returns the score
Args:
self
secret - the secret hangman word
maxincorrect - the number of maximal wrong guesses
Returns:
score - game score
"""
game, strategy = self.__setup(secret, maxincorrect)
self.__run(game, strategy)
score = game.current_score()
return score
def __setup(self, secret, maxincorrect):
"""
(Private method)
Setup the Hangman by setting up a Game object and a Strategy object
Args:
self
secret - the secret hangman word
maxincorrect - the number of maximal wrong guesses
Returns:
game - HangmanGame
strategy - HangmanStrategy
"""
self._display.normal("(SHHH!!) hangman secret: {}\n".format(secret))
game = HangmanGame(secret, maxincorrect)
strategy = HangmanLetterStrategy(game, self._settings)
return game, strategy
def __run(self, game, strategy):
"""
(Private method)
Runs the hangman game. While game is not finished, keep guessing (playing)
"""
while game.game_status() == game.status_keep_guessing:
guess, error = strategy.next_guess(game)
if guess == None and error != None:
self._display.simple("Aborting current game... [{}]".format(error))
break
guess.make_guess(game)
self._display.simple(game)
self._display.simple("")
self._display.simple("")
if __name__ == '__main__':
settings = HangmanSettings()
display = settings.display
max_incorrect = settings.max_incorrect
secret = "asterisk"
hangman = Hangman(settings)
score = hangman.play(secret, max_incorrect)
display.simple("Hangman.py: Given secret {}, score is {}".format(secret, score))
|
da2e9c221cab191a10bfef733792b39679d1cb7f | daniel-reich/ubiquitous-fiesta | /xzisrRDwWT8prHtiQ_9.py | 190 | 3.671875 | 4 |
def difference_two(lst):
pairs = []
for i, x in enumerate(sorted(lst)):
for y in lst[i+1:]:
if y == x + 2:
pairs.append([x,y])
return pairs
|
236a572145e6058ad6dac38dd207b672c10a9194 | droconnel22/QuestionSet_Python | /HackerRank/python_practice/alphabet_rangoli.py | 347 | 3.828125 | 4 |
import string
def print_rangoli(size):
alphabet = list("abcdefghijklmnopqrstuvwxyz")
interval = 1
for _ in range(0,size*size):
for i in range(0,size*size):
print("-", end = '')
print()
# your code goes here
return alphabet
if __name__ == '__main__':
n = 5
print_rangoli(n) |
e9e7dbbdff4957b0ef715b330a90978fec4a9f86 | Argonauta666/coding-challenges | /leetcode/monthly-challenges/2021-mar/w1-set-mismatch.py | 879 | 3.6875 | 4 | # https://leetcode.com/problems/set-mismatch/
"""
Topic: Cyclic Sort
"""
from typing import List
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
# sort the number using cyclic sort
i = 0
while i < len(nums):
# if not sorted
if nums[i] != i + 1:
correctIndex = nums[i] - 1
# if it is not the same as the number from previous index
if nums[i] != nums[correctIndex]:
nums[i], nums[correctIndex] = nums[correctIndex], nums[i]
else:
i += 1
else:
i += 1
# traverse the array to find the duplicate
i = 0
while i < len(nums):
if nums[i] != i + 1:
return [nums[i], i + 1]
i += 1
return [-1, -1]
|
c4cd23cbaf9fd802a8d5afd7019a46b33276a901 | zjuzpz/Algorithms | /PalindromePartitioning.py | 1,200 | 3.6875 | 4 | """
131. Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
"""
# O(2 ^ n)
# O(n)
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
if not s:
return [[""]]
res = []
self.recur(res, [], s)
return res
def recur(self, res, cur, s):
if not s:
res.append(cur[:])
return
for i in range(len(s)):
if self.isPalidrome(s[0: i + 1]):
cur.append(s[0: i + 1])
self.recur(res, cur, s[i + 1:])
cur.pop()
def isPalidrome(self, s):
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i, j = i + 1, j - 1
return True
if __name__ == "__main__":
s = "kwtbjmsjvbrwriqwxadwnufplszhqccayvdhhvscxjaqsrmrrqng\
muvxnugdzjfxeihogzsdjtvdmkudckjoggltcuybddbjoizu"
print(len(Solution().partition(s)))
|
4864bc4bb33f44dd21329893f0e496189ee3ed47 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2109/60762/241603.py | 130 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
s=input()
re=0
for i in range (0,len(s)):
re+=int(s[i])
print(int(re//10+re%10))
|
ae4cd590eb1e5308d1aa35580b89e87146bb0fa3 | satoshun-algorithm-example/atcoder | /abc107/b.py | 772 | 3.5 | 4 | def grid_compression(a, h, w):
hh = []
for i in range(h):
ok = True
for j in range(w):
if a[i][j] == '#':
ok = False
break
if ok:
hh += [i]
ww = []
for i in range(w):
ok = True
for j in range(h):
if a[j][i] == '#':
ok = False
break
if ok:
ww += [i]
aa = []
for i in range(h):
if i in hh:
continue
aa.append('')
for j in range(w):
if j in ww:
continue
aa[-1] += a[i][j]
return '\n'.join(aa)
h, w = map(int, input().split())
a = []
for _ in range(h):
a += [list(input())]
print(grid_compression(a, h, w))
|
6c73e1155dece199d48ac5462676467eb8550ff9 | icelighting/leetcode | /数组与字符串/最长前缀.py | 1,324 | 3.65625 | 4 | '''编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。'''
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 1 :
return strs[0]
if not strs:
return " "
minL = min([len(item) for item in strs])
end = 0
while end < minL:
for i in range(1,len(strs)):
if strs[i][end] != strs[i-1][end]:
if end == 0:
return " "
else:
return strs[0][:end]
end += 1
return strs[0][:end]
def case2(self,strs):
res = ""
if len(strs) == 0:
return ""
for each in zip(*strs): # zip()函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
if len(set(each)) == 1:#利用集合创建一个无序不重复元素集
res += each[0]
else:
return res
return res
if __name__ == '__main__':
str = ["a","a"]
solute = Solution()
print(solute.longestCommonPrefix(str))
print(solute.case2(str)) |
d21f86fa6b9ab04c3e8eff343a191c39ae2bb5e9 | landeaux/fifteen-solver | /fifteen-solver.py | 15,748 | 3.671875 | 4 | """
Loyd's Fifteen puzzle - solver and visualizer
Note that solved configuration has the blank (zero) tile in upper left
Use the arrows key to swap this tile with its neighbors
"""
import poc_fifteen_gui
class Puzzle:
"""
Class representation for the Fifteen puzzle
"""
def __init__(self, puzzle_height, puzzle_width, initial_grid=None):
"""
Initialize puzzle with default height and width
Returns a Puzzle object
"""
self._height = puzzle_height
self._width = puzzle_width
self._grid = [[col + puzzle_width * row
for col in range(self._width)]
for row in range(self._height)]
if initial_grid != None:
for row in range(puzzle_height):
for col in range(puzzle_width):
self._grid[row][col] = initial_grid[row][col]
def __str__(self):
"""
Generate string representaion for puzzle
Returns a string
"""
ans = ""
for row in range(self._height):
ans += str(self._grid[row])
ans += "\n"
return ans
#####################################
# GUI methods
def get_height(self):
"""
Getter for puzzle height
Returns an integer
"""
return self._height
def get_width(self):
"""
Getter for puzzle width
Returns an integer
"""
return self._width
def get_number(self, row, col):
"""
Getter for the number at tile position pos
Returns an integer
"""
return self._grid[row][col]
def set_number(self, row, col, value):
"""
Setter for the number at tile position pos
"""
self._grid[row][col] = value
def clone(self):
"""
Make a copy of the puzzle to update during solving
Returns a Puzzle object
"""
new_puzzle = Puzzle(self._height, self._width, self._grid)
return new_puzzle
########################################################
# Core puzzle methods
def current_position(self, solved_row, solved_col):
"""
Locate the current position of the tile that will be at
position (solved_row, solved_col) when the puzzle is solved
Returns a tuple of two integers
"""
solved_value = (solved_col + self._width * solved_row)
for row in range(self._height):
for col in range(self._width):
if self._grid[row][col] == solved_value:
return (row, col)
assert False, "Value " + str(solved_value) + " not found"
def update_puzzle(self, move_string):
"""
Updates the puzzle state based on the provided move string
"""
zero_row, zero_col = self.current_position(0, 0)
for direction in move_string:
if direction == "l":
assert zero_col > 0, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col - 1]
self._grid[zero_row][zero_col - 1] = 0
zero_col -= 1
elif direction == "r":
assert zero_col < self._width - 1, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col + 1]
self._grid[zero_row][zero_col + 1] = 0
zero_col += 1
elif direction == "u":
assert zero_row > 0, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row - 1][zero_col]
self._grid[zero_row - 1][zero_col] = 0
zero_row -= 1
elif direction == "d":
assert zero_row < self._height - 1, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row + 1][zero_col]
self._grid[zero_row + 1][zero_col] = 0
zero_row += 1
else:
assert False, "invalid direction: " + direction
##################################################################
# Phase one methods
def lower_row_invariant(self, target_row, target_col):
"""
Check whether the puzzle satisfies the specified invariant
at the given position in the bottom rows of the puzzle (target_row > 1)
Returns a boolean
"""
# Check if tile zero is positioned at (i,j).
if self._grid[target_row][target_col] != 0:
return False
# Check if all tiles in rows i+1 or below are positioned at their solved location.
if target_row + 1 < self._height:
for row in range(target_row + 1, self._height):
for col in range(self._width):
solved_value = (col + self._width * row)
if solved_value != self.get_number(row, col):
return False
# All tiles in row i to the right of position (i,j) are positioned at
# their solved location.
if target_col + 1 < self._width:
for col in range(target_col + 1, self._width):
solved_value = (col + self._width * (target_row))
if solved_value != self.get_number(target_row, col):
return False
return True
def position_tile(self, target_row, target_col, target_tile, move_string, col0 = False):
"""
Helper function that positions a target_tile to (target_row, target_col)
and returns the move_string that will get it there
"""
if col0:
if (target_tile[1] > target_col) and (target_tile[0] == target_row):
move_string += "r" * (target_tile[1] - 1)
for _ in range(target_tile[1] - 2):
move_string += "ulldr"
move_string += "ulld"
return move_string
# if the target tile is above target row
if target_tile[0] < target_row:
move_string += "u" * (target_row - target_tile[0])
# if target tile is to the right of target column
if target_tile[1] > target_col:
move_string += "r" * (target_tile[1] - target_col)
for _ in range(target_tile[1] - target_col - 1):
move_string += "ulldr" if target_tile[0] > 0 else "dllur"
move_string += "ulld" if target_tile[0] > 0 else "dluld"
# if target tile is to the left of target column
if target_tile[1] < target_col:
move_string += "l" * (target_col - target_tile[1])
for _ in range(target_col - target_tile[1] - 1):
move_string += "drrul"
if target_tile[1] == target_col:
move_string += "ld"
if col0:
puzzle_clone = self.clone()
puzzle_clone.update_puzzle(move_string)
if puzzle_clone.current_position(0, 0) == (target_row, 0):
return move_string
puzzle_clone = self.clone()
puzzle_clone.update_puzzle(move_string)
zero = puzzle_clone.current_position(0, 0)
for _ in range(target_row - zero[0]):
move_string += "druld"
# if target tile is to the left of zero tile
else:
if not col0:
move_string += "l" * (target_col - target_tile[1])
for _ in range(target_col - target_tile[1] - 1):
move_string += "urrdl"
else:
move_string += "l" * (target_col - target_tile[1] + 1)
for _ in range(target_col - target_tile[1]):
move_string += "urrdl"
return move_string
def solve_interior_tile(self, target_row, target_col):
"""
Place correct tile at target position
Updates puzzle and returns a move string
"""
move_string = ""
target_tile = self.current_position(target_row, target_col)
move_string = self.position_tile(target_row, target_col, target_tile, move_string)
self.update_puzzle(move_string)
return move_string
def solve_col0_tile(self, target_row):
"""
Solve tile in column zero on specified row (> 1)
Updates puzzle and returns a move string
"""
move_string = "ur"
target_tile = self.current_position(target_row, 0)
if target_tile != (target_row - 1, 0):
move_string = self.position_tile(target_row - 1, 1, target_tile, move_string, True)
move_string += "ruldrdlurdluurddlur"
move_string += "r" * (self._width - 2)
self.update_puzzle(move_string)
return move_string
#############################################################
# Phase two methods
def row0_invariant(self, target_col):
"""
Check whether the puzzle satisfies the row zero invariant
at the given column (col > 1)
Returns a boolean
"""
# check whether tile zero is at (0,j)
if self._grid[0][target_col] != 0:
return False
# check whether tiles to right of zero tile are solved
for row in range(2):
for col in range(target_col + 1, self._width):
solved_value = (col + self._width * row)
if solved_value != self.get_number(row, col):
return False
# check whether the tile at (1,j) is solved
if (target_col + self._width) != self.get_number(1, target_col):
return False
# check whether all tiles from in rows 2 and below are solved
for row in range(2, self._height):
for col in range(self._width):
solved_value = (col + self._width * row)
if solved_value != self.get_number(row, col):
return False
return True
def row1_invariant(self, target_col):
"""
Check whether the puzzle satisfies the row one invariant
at the given column (col > 1)
Returns a boolean
"""
# check whether tile zero is at (1,j)
if self._grid[1][target_col] != 0:
return False
# check whether all positions below this position are solved
if not self.lower_row_invariant(1, target_col):
return False
# check whether all positions to the right of this position are solved
for col in range(target_col + 1, self._width):
if col != self.get_number(0, col):
return False
return True
def solve_row0_tile(self, target_col):
"""
Solve the tile in row zero at the specified column
Updates puzzle and returns a move string
"""
move_string = "ld"
temp = ""
target_tile = self.current_position(0, target_col)
if target_tile != (0, target_col - 1):
# reposition the target tile to position (1,j−1) with tile zero in position (1,j−2).
if target_col - target_tile[1] == 1:
move_string += "uld"
if target_tile[0] == 0:
move_string += "u"
temp = "dru"
move_string += "l" * (target_col - target_tile[1] - 1)
move_string += temp
if target_col - target_tile[1] > 2:
for count in range(target_col - target_tile[1] - 2):
if target_tile[0] == 0:
move_string += "ur" if count > 0 else ""
move_string += "rdl"
else:
move_string += "urrdl"
if (target_col - target_tile[1] != 1) and (target_tile[0] == 0) and (target_col - target_tile[1] <= 2):
move_string += "ld"
move_string += "urdlurrdluldrruld"
self.update_puzzle(move_string)
return move_string
def solve_row1_tile(self, target_col):
"""
Solve the tile in row one at the specified column
Updates puzzle and returns a move string
"""
move_string = ""
temp = ""
target_tile = self.current_position(1, target_col)
# if the target tile is above target row
if target_tile[0] == 0:
move_string += "u"
temp = "dru" if target_tile[1] != target_col else ""
else:
temp = "ur"
move_string += "l" * (target_col - target_tile[1])
move_string += temp
for _ in range(target_col - target_tile[1] - 1):
move_string += "rdlur"
self.update_puzzle(move_string)
return move_string
###########################################################
# Phase 3 methods
def solve_2x2(self):
"""
Solve the upper left 2x2 part of the puzzle
Updates the puzzle and returns a move string
"""
move_string = "lu"
if self.get_number(1, 0) == 1:
move_string += "rdlu"
elif self.get_number(0, 0) == 1:
move_string += "rdlurdlu"
self.update_puzzle(move_string)
return move_string
def solve_puzzle(self):
"""
Generate a solution string for a puzzle
Updates the puzzle and returns a move string
"""
move_string = ""
# Find out where the zero tile is, save coordinates
zero_row, zero_col = self.current_position(0, 0)
if zero_row == 0:
if self.row0_invariant(0):
return ""
if (zero_row, zero_col) != (self._height - 1, self._width - 1):
move_string += "d" * (self._height - zero_row - 1)
move_string += "r" * (self._width - zero_col - 1)
self.update_puzzle(move_string)
zero_row, zero_col = self.current_position(0, 0)
for _ in range(self._height - 2):
while zero_col > 0:
move_string += self.solve_interior_tile(zero_row, zero_col)
zero_row, zero_col = self.current_position(0, 0)
move_string += self.solve_col0_tile(zero_row)
zero_row, zero_col = self.current_position(0, 0)
for _ in range(self._width - 2):
while zero_col > 1:
if zero_row == 1:
move_string += self.solve_row1_tile(zero_col)
zero_row, zero_col = self.current_position(0, 0)
else:
move_string += self.solve_row0_tile(zero_col)
zero_row, zero_col = self.current_position(0, 0)
move_string += self.solve_2x2()
return move_string
# Start interactive simulation
poc_fifteen_gui.FifteenGUI(Puzzle(4, 4))
|
0769d3cd2170d8af918a5bc9dc48275d1b413dcd | agarwalsanket/TheBalancePuzzle | /balances.py | 10,401 | 3.875 | 4 | import turtle
import os
__author__ = "Sanket Agarwal"
"""
This program is the implementation of the problem stated in HW7.
Authors: Sanket Agarwal (sa3250@rit.edu)
"""
class Beam:
"""
Beam class contains data about a beam.
"""
__slots__ = 'beam', 'beam_name_objects', 'beam_draw'
def __init__(self, li_beam, draw):
"""
Constructor for the Beam class.
:param li_beam: list of constituent weights/beams for a particular beam.
:param draw: flag which controls if a beam is to be drawn (=true) or not (=false)
"""
self.beam = {}
self.beam_draw = {}
if draw == 'false':
self.makebeam(li_beam)
elif draw == 'true':
self.makebeam_draw(li_beam)
else:
print("improper inputs")
def makebeam(self, li_beam):
"""
This function creates a beam object if it is part of a bigger beam.
:param li_beam: list of constituent weights/beams for a particular beam.
:return: None
"""
if li_beam is []:
return None
beam_name = li_beam.pop(0)
count = 0
for i in range(len(li_beam)):
self.beam[li_beam[i + count]] = li_beam[i + 1 + count]
count += 1
if (i + count + 1) > (len(li_beam) - 1):
self.beam["name"] = beam_name
break
def makebeam_draw(self, li_beam):
"""
This function creates a beam object so that it can be drawn later.
:param li_beam: list of constituent weights/beams for a particular beam.
:return: None
"""
if li_beam is []:
return None
beam_name_draw = li_beam.pop(0)
count = 0
for i in range(len(li_beam)):
self.beam_draw[li_beam[i + count]] = li_beam[i + 1 + count]
count += 1
if (i + count + 1) > (len(li_beam) - 1):
self.beam_draw["name"] = beam_name_draw
break
@staticmethod
def weight(beam):
"""
This function computes the weight of a beam.
:param beam: Beam object whose weight is to be computed.
:return: Weight of the beam object.
"""
sum_weight = 0
for k in beam:
if k != 'name':
sum_weight += int(beam[k])
return sum_weight
def draw(self, name_dict_dict, beams_list, absent_weight, unit_v, unit, t):
"""
This is the function to be invoked for the drawing of beam.
:param name_dict_dict: A dictionary of dictionaries containing data about beam.
:param beams_list: A list of dictionaries containing data about beam.
:param absent_weight: Missing weight
:param unit_v: Length of vertical beam.
:param t: Turtle object
:return: None
:pre: (0,0) relative facing East, pen up
:post: (0,0) relative facing East, pen up
"""
writable_unit = 30
reverse_beams_list = beams_list[::-1]
t.penup()
t.left(90)
t.pendown()
t.forward(-unit_v)
t.penup()
t.right(90)
for i in range(len(reverse_beams_list)):
for k in reverse_beams_list[i]:
if k != 'name':
t.pendown()
t.forward(int(k) * unit)
t.penup()
if reverse_beams_list[i][k] in name_dict_dict:
self.draw(name_dict_dict, [name_dict_dict[reverse_beams_list[i][k]]], absent_weight,
unit_v * 1.5, unit/3, t)
t.penup()
t.left(90)
t.forward(1.5 * unit_v)
t.right(90)
t.forward(-(int(k) * unit))
elif int(reverse_beams_list[i][k]) == -1:
reverse_beams_list[i][k] = absent_weight
t.left(90)
t.pendown()
t.backward(unit_v)
t.penup
t.backward(writable_unit)
t.pendown()
t.write(reverse_beams_list[i][k], font=("Arial", 12, "bold"))
t.penup()
t.forward(unit_v + writable_unit)
t.right(90)
t.forward(-(int(k) * unit))
else:
t.left(90)
t.pendown()
t.backward(unit_v)
t.penup
t.backward(writable_unit)
t.pendown()
t.write(reverse_beams_list[i][k], font=("Arial", 12, "bold"))
t.penup()
t.forward(unit_v + writable_unit)
t.right(90)
t.forward(-(int(k) * unit))
break
class Weight:
"""
Weight class to compute torque and missing weights for a beam.
"""
__slots__ = 'weight', 'beam_name_dict_with_obj', 'beam_dict_list', 'name_dict_dict', 'absent_weight'
def __init__(self, beam_name_dict_with_obj, beam_dict_list, name_dict_dict):
"""
Constructor function for the Weight class.
:param beam_name_dict_with_obj: Dictionary of dictionaries containing data of beam.
:param beam_dict_list: A list of dictionaries containing data about beam.
:param name_dict_dict: Dictionary of dictionaries containing data of beam.
"""
self.beam_dict_list = beam_dict_list
self.beam_name_dict_with_obj = beam_name_dict_with_obj
self.name_dict_dict = name_dict_dict
self.absent_weight = 0
self.balance()
def balance(self):
"""
Function to compute whether a beam is balanced or not, and if not, to compute the missing weight.
:return: None
"""
for i in range(len(self.beam_dict_list)):
calculate_balance = 'true'
balance = 0
for k in self.beam_dict_list[i]:
if k != 'name':
if self.beam_dict_list[i][k] in self.beam_name_dict_with_obj:
self.beam_dict_list[i][k] = Beam.weight(self.beam_name_dict_with_obj.get(
self.beam_dict_list[i][k]).beam)
if int(self.beam_dict_list[i][k]) == -1:
k_temp = k
balance = 0
temp = i
partial_sum_weight = 0
print("The beam " + self.beam_dict_list[temp][
'name'] + " has an empty pan, at distance " + k_temp)
for k in self.beam_dict_list[temp]:
if k != 'name' and self.beam_dict_list[temp][k] != '-1':
if self.beam_dict_list[temp][k] in self.beam_name_dict_with_obj:
self.beam_dict_list[temp][k] = Beam.weight(self.beam_name_dict_with_obj.get(
self.beam_dict_list[temp][k]).beam)
partial_sum_weight += int(k) * int(self.beam_dict_list[temp][k])
self.beam_dict_list[temp][k_temp] = str(-partial_sum_weight // int(k_temp))
self.absent_weight = self.beam_dict_list[temp][k_temp]
print("It should be filled with weight of " + self.beam_dict_list[temp][
k_temp] + " units to be balanced. Now " + self.beam_dict_list[temp][
'name'] + " will also be balanced")
break
if calculate_balance != 'false':
balance += int(k) * int(self.beam_dict_list[i][k])
if balance == 0:
print(self.beam_dict_list[i]['name'] + ' is balanced')
else:
print(self.beam_dict_list[i]['name'] + ' is not balanced')
for i in range(len(self.beam_dict_list)):
for k in self.beam_dict_list[i]:
if self.beam_dict_list[i][k] in self.beam_name_dict_with_obj:
self.beam_dict_list[i][k] = self.beam_name_dict_with_obj.get(self.beam_dict_list[i][k])
def main():
"""
Main function of the implementation.
:return: None
"""
while 1:
file_puzzle = input("Enter the file name having the description of the Balance Puzzle ")
if not os.path.isfile(file_puzzle):
print("File does not exist")
else:
break
beams_name_obj_dict = {}
name_beam_dict = {}
beams_list = []
beams_name_obj_dict_draw = {}
name_beam_dict_draw = {}
beams_list_draw = []
with open(file_puzzle) as beam:
for line in beam:
li_beam_local = line.split()
if len(li_beam_local) % 2 == 0:
print("Invalid entries in line ", li_beam_local)
lextent = 0
rextent = 0
li_name = li_beam_local[0]
li_temp = li_beam_local[1::2]
for i in range(len(li_temp)):
if int(li_temp[i]) < lextent:
lextent = int(li_temp[i])
if int(li_temp[i]) > rextent:
rextent = int(li_temp[i])
beam = Beam(li_beam_local, 'false')
beams_name_obj_dict[line.split()[0]] = beam
name_beam_dict[line.split()[0]] = beam.beam
beams_list.append(beam.beam)
print("Length of beam ", li_name, "is: ", (abs(lextent) + abs(rextent)))
print("Left extent of beam ", li_name, "is: ", lextent, " and the right extent is: ", rextent)
with open(file_puzzle) as beam:
for line in beam:
li_beam_local_draw = line.split()
beam_draw = Beam(li_beam_local_draw, 'true')
beams_name_obj_dict_draw[line.split()[0]] = beam_draw
name_beam_dict_draw[line.split()[0]] = beam_draw.beam_draw
beams_list_draw.append(beam_draw.beam_draw)
wt = Weight(beams_name_obj_dict, beams_list, name_beam_dict)
beam_draw.draw(name_beam_dict_draw, beams_list_draw, wt.absent_weight, 10, 30, turtle)
turtle.exitonclick()
if __name__ == "__main__":
main()
|
8b0d30bada286585d934528aa1d91e7ae299d325 | ankerfeng/deerhack | /Email.py | 1,590 | 3.6875 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Created on 2014年12月6日
@author: bkwy.org
'''
import re
import urllib2
from urllib import urlopen
def GetUrl():
urls = []
for i in xrange(65, 91):
urls.append("http://homepage.hit.edu.cn/names/"+chr(i))
#print "http://homepage.hit.edu.cn/names/"+chr(ord(word)+i)
return urls
def Purl(urladdr):
http = urlopen(urladdr)
#print http.read()
http = http.read()
regex = re.compile(r'"/pages/.+?"')
theUrls = regex.findall(http)
i = 0
while i < len(theUrls):
theUrls[i] = theUrls[i].replace('"', '')
#print theUrls[i]
i += 1
return theUrls
def Email(urladdr):
f = open('email.txt', 'a')
http = urlopen(urladdr)
#print http.read()
http = http.read()
regex = re.compile(r'<a href="mailto:.+?">.+?</a></td>')
theEmails = regex.findall(http)
for theEmail in theEmails:
regex = re.compile(">.+?<")
theEmail = regex.findall(theEmail)
theEmail = theEmail[0].replace('>', '')
theEmail = theEmail.replace('<', '')
f.write(theEmail+'\n')
print theEmail
f.close()
if __name__ == '__main__':
f = open('email.txt', 'a')
f.write("=====================\n")#如果挂掉的时候需要手动从上次接着跑的时候,这个会起到一个标记的作用
f.close()
urls = GetUrl()
for url in urls:
print url
theUrls = Purl(url)
for purl in theUrls:
print purl
Email("http://homepage.hit.edu.cn"+purl)
|
deebe833189905aea943ae22ca59f094e90d23fa | MarianoSaez/regexes-ayg | /8_cp.py | 266 | 3.953125 | 4 | #!/usr/bin/python3
import re
regex = re.compile(r"([A-Z]{1}[\d]{4}[A-Z]{3}|[\d]{4})$")
while True:
cp = input("\ncodigo postal: ")
if regex.match(cp):
print("Codigo postal Existe")
break
print('El codigo postal es invalido')
|
ae9d362359010cc619dfd499f1a37532babf4872 | kammitama5/Python6_11_16 | /first.py | 1,036 | 4.0625 | 4 | ##Welcome message --> game begin
print 'Welcome to my game. This game is sweet.'
##ask the player for his name
player_name = raw_input('What\'s is your name: ')
## check/ask for player name and display it
if player_name == '':
print'\n'
print 'You entered an empty string!'
else:
print 'Your name is {}'.format(player_name)
## check/ask for player age and display it
page = raw_input('What is your age: ')
if page.isdigit():
page = int(page)
print 'Your age is {}'.format(page)
print'\n'
else:
print 'Not a real age'
print'\n'
## list gamestuff var and ask them to choose
gamestuff = ['dragons','dungeons','mazes','the single life']
while True:
print 'What shall we do?'
for item in gamestuff:
print '* {}'.format(item)
## choose gamestuff or else not an answer (or exit to quit)
choice = raw_input('>>>')
if choice.lower() in ['exit','quit']:
print 'You have chosen to quit.'
break;
if choice not in gamestuff:
print 'come on now. That is not a choice.'
else:
print 'you chose "{}"'.format(choice)
|
2c006793172e757d2005b5f427e3e2966a7ae631 | ram5550/Luminardjango | /Luminarproject/flowcontrols/assignment2.py | 462 | 3.984375 | 4 | #Date of birth
bdate=int(input("enter your birth date"))
bmonth=int(input("enter your birth month"))
byear=int(input("enter your birth year"))
curdate=int(input("enter current date"))
curmonth=int(input("enter current month "))
curyear=int(input("enter current year"))
#bday 26-08-2019
#cday 24-07-2020
age=curyear-byear
if(bmonth>=curmonth):
age=age-1
if(bmonth==curmonth):
if(bdate>curdate):
age=age-1
print("you are",age,"years old") |
d28e684eda7a19d86b951b041ba09ccadaa80aec | agiri801/python_key_notes | /_sample_/File_01.py | 645 | 3.515625 | 4 | # Program extracting all columns
# name in Python
"""import xlrd
loc = ('Data')
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
# For row 0 and column 0
sheet.cell_value(0, 0)
for i in range(sheet.ncols):
print(sheet.cell_value(0, i))
"""
import datetime
timestamp = datetime.datetime.fromtimestamp(43673.0)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
'''
fname=input('Enter file name:')
with open(fname) as f:
data=f.readlines() # Here it will read data line by line
for row in data: # Here it make loop to read and separate the data into feilds
row=row.rstrip('\n')
feilds=row.split(',') '''
|
2dbea96827e4f4bc64cc68bd7a9bd88cd3d4de8c | serputko/Recursive_algorythms_tasks | /1_to_n.py | 116 | 3.765625 | 4 | def recursion(n):
if n == 1:
return '1'
return recursion(n-1) + ' ' + str(n)
print(recursion(10))
|
38d4d5ad464eac11e010e0b07f8fb4e8df29bbc1 | mylons/pypatterns | /idioms/examples.py | 1,380 | 3.953125 | 4 | __author__ = 'lyonsmr'
#white space is everything
####4 spaces is standard indent.
#don't mix spaces and tabs for indents
#boolean values True and False
a = True
b = False
if a == b:
print "a == b"
elif a != b:
print "a != b"
else:
print "this shouldn't happen, but this is a common if, else if, and else block"
#example:
if True:
#do this
print "hi"
#how to hash
d = {}
value = 4
d['key'] = value
#test if it's in there
if 'key' in d:
print d['key']
#open file and loop throuhg it
#write to an output file too
f = open("/tmp/this_file_better_be_there.txt", "w")
f.write("blah\n")
f.close()
f = open("/tmp/this_file_better_be_there.txt", "r")
for line in f:
print line
#traditional for loop in python:
#for (int i = 0; i < 40; i++) -- C equiv
for i in xrange(40):
#prints 0-39 on new lines
print i
while True:
#do w/e we have here
if True:
#break from a loop
break
else:
#continue a loop
continue
"""
functions in python
"""
def add_params(param1, param2):
#param1 and param2 are some type of variable passed to
#this function
return param1 + param2
#example call
add_params(1, 2)
#when calling this function, you do not have to specify param2
def add_params2(param1, param2=2):
return param1 + param2
#example call
add_params2(1, param2=9)
#or
add_params2(1, 2)
|
38bad9c130eb6d1537fbd1947e289b7561c6dfdb | hyuntaedo/Python_generalize | /practice/general_input.py | 1,041 | 3.515625 | 4 | import sys
#print("python","java",file=sys.stdout) #출력
#print("python","java",file=sys.stderr) #error 처리
#scores = {"수학":0,"영어":50,"코딩":100}
#for subject, score in scores.items(): # key, value를 쌍으로 튜플로 보내줌
# print(subject.ljust(8),str(score).rjust(4),sep=":") #ljust는 왼쪽정렬
#(8)은 8개의 공간을 만들고 난 다음에 정렬을 한다는 뜻
#print("python","java", sep=",",end="?")
# sep안의 값을 선언하면 " "안의값이 찍힌다
# end는 안의 문장을 출력되게한다
#print("\n무엇이 더 재밌을 까요")
#은행 대기 순번표
#001,002,003...
#for number in range(1,21):
# print("대기번호 : " + str(number).zfill(3))
#zfill은 값이 없는 빈 공간은 0으로 채워달라는 말임
#표준입력
answer = input("아무값이나 입력하세요 : ")
answer = 10
print(type(answer))
print("입력하신 값은 " + answer + "입니다")
#사용자 값으로 받은 값은 무조건 문자열로 드가진다 |
85b96d3983eb1391604fe96f454099584335ef5a | paulc1600/Python-Problem-Solving | /H15_PowerSum_hp.py | 7,709 | 4.0625 | 4 | #!/bin/python3
# ---------------------------------------------------------------------#
# Source: HackerRank
# Purpose: Find the number of ways that a given integer, X, can be
# expressed as the sum of the Nth powers of unique, natural
# numbers.
#
# For example, if X = 13 and N = 2, we have to find all
# combinations of unique squares adding up to 13. The only
# solution is 2^2 + 3^2
#
# Function Description
# Complete the powerSum function in the editor below. It should return an integer that represents the
# number of possible combinations.
#
# powerSum has the following parameter(s):
# o X: the integer to sum to
# o N: the integer power to raise numbers to
#
# ---------------------------------------------------------------------
# PPC | 08/27/2019 | Original code.
# ---------------------------------------------------------------------
import math
import os
import random
import re
import sys
from multiprocessing import *
global nbrWays
global sSetLimit
# This code splits 1 huge range into mostly even partions
# ---------------------------------------------------------------------
def rangeSplitter(myTotal, nbrSplits, rem2end):
job_ranges = []
bIdx = 0
eNbr = 0
delta = round(myTotal // nbrSplits)
lint = myTotal % nbrSplits
# Handle all but last partial split here
for bIdx in range(nbrSplits):
one_range = []
sNbr = eNbr + 1
if bIdx == 0 and rem2end == False:
eNbr = eNbr + delta + lint # First split has extra records
else:
eNbr = eNbr + delta
one_range = [sNbr, eNbr + 1] # Adjust for Python
job_ranges.append(one_range)
# Handle myTotal not splitting evenly / create last partial group
if rem2end == True and eNbr < myTotal:
sNbr = eNbr + 1
eNbr = myTotal # Last split has extra records
one_range = [sNbr, eNbr + 1] # Adjust for Python
job_ranges.append(one_range)
return job_ranges
# This code based on the original work of vibhu4agarwal
# https://www.geeksforgeeks.org/find-distinct-subsets-given-set/
# ---------------------------------------------------------------------
def processSubsets(myNbr, myJobQueue, myStart, myEnd, myArray, myX):
global nbrWays
sizePower = len(myArray)
jvector = []
# Prepare vector Array One Time
oneVector = 0b00000000000000000000000000000000
for jIdx in range(sizePower):
myVector = oneVector + (2**jIdx)
jvector.append(myVector)
print()
print("Call: ", myNbr, " -------------------------------------")
print(" Range: ", myStart, myEnd)
print(" Target for Sum: ", myX)
for i in range(myStart, myEnd):
# consider each element in the set (n = length arr)
# Example of n = 3, i = 0:7, j = 0:2
# (1 << j) = 001, 010, 100
# i = 0 000 ___
# i = 1 001 __C
# i = 2 010 _B_
# i = 3 011 _BC
# i = 4 100 A__
# i = 5 101 A_C
# i = 6 110 AB_
# i = 7 111 ABC
subsetSum = 0
for j in range(sizePower):
# Check if jth bit in the i is set.
# If the bit is set, we consider jth element from arrPowers
# and sum up it's value into a subset total
if (i & jvector[j]) != 0:
subsetSum = subsetSum + myArray[j]
# Once finish with any subset -- just sum it and check it
if subsetSum == myX:
nbrWays = nbrWays + 1
myJobQueue.put([myNbr, nbrWays])
print("Call: ", myNbr, " ---- completed. NbrWays = ", nbrWays)
return nbrWays
# ---------------------------------------------------------------------
# Python3 program to find all subsets of given set. Any repeated subset
# is considered only once in the output
#
def powerSum(myX, myN):
global nbrWays
global sSetLimit
arrPowers = []
myJobRanges = []
# Create Array of all powers of myN smaller than myX
# for myN value 2 and myX value 13 would be [1, 4, 9]
pos = 1
while pos ** myN <= myX:
arrPowers.append(pos ** myN)
pos = pos + 1
# Calculate all possible subsets
print(arrPowers)
sizePower = len(arrPowers)
print("Need bit vector width =", sizePower)
# Number subsets that give you X
nbrWays = 0
# Run counter i from 000..0 to 111..1 (2**n)
# For sets of unique numbers the number unique subsets
# (including NULL) always 2**n. Python range statement will
# drops the null subset from count.
totSS = 2**sizePower
print("Will create ", totSS, " subsets of Power array.")
result = 0
# Parallel process above 4M subsets
nbrJobs = (totSS // sSetLimit) + 1
print("Will run as ", nbrJobs, " job.")
nbrCPU = cpu_count()
print("System has ", nbrCPU, " cpu.")
# Build queue to gather results from every subsets job (results multiple subsets)
qJobResults = Queue()
if nbrJobs == 1:
# One job (typically X < 500) probably faster without multiprocessing
print("Will run as 1 job.")
ssStart = 0
ssEnd = totSS
callNbr = 1
processSubsets(callNbr, qJobResults, ssStart, ssEnd, arrPowers, myX)
result = nbrWays
else:
# More than one job (typically X > 500 or > 4M subsets)
procs = []
callNbr = 0
# Must be false if nbrJobs == number of unique ranges
myJobRanges = rangeSplitter(totSS, nbrJobs, False)
print(myJobRanges)
for oneJob in myJobRanges:
callNbr = callNbr + 1
# Build Out range job parameters
MyStart = oneJob[0] # Start Range
MyEnd = oneJob[1] # End Range
proc = Process(target=processSubsets, args=(callNbr, qJobResults,
MyStart, MyEnd,
arrPowers, myX))
# proc = Process(target=print("hi"))
procs.append(proc)
proc.start()
print("Job ", callNbr, ": ", proc, proc.is_alive())
# Waite for all jobs to complete
jobDone = 0
print("Job completed count = ", jobDone)
while jobDone != myJobRanges:
result = []
print("In loop ..")
for proc in procs:
print(jobDone, " | ", result, " | ", proc, proc.is_alive())
result = qJobResults.get()
print("Polled Q ..")
for proc in procs:
print(jobDone, " | ", result, " | ", proc, proc.is_alive())
if len(result) != 0:
print("Job Completed: ", result)
jobDone = jobDone + 1
print("Job completed count = ", jobDone)
# complete the processes
for proc in procs:
proc.join()
print(proc, proc.is_alive())
return
# --------------------------------------------------
# Driver Code
# --------------------------------------------------
if __name__ == '__main__':
global sSetLimit
global nbrWays
sSetLimit = 1024 * 8 # Test Value
# sSetLimit = 1024 * 1024 * 4 # Normal Value
X = 180
N = 2
TotWays = powerSum(X, N)
print("X = ", X, " N = ", N, " Result = ", nbrWays)
|
962b94399e132c4c08efed9d256db34338e0417d | svikk92/examples | /Python/usefulmethods.py | 1,194 | 4.1875 | 4 | for num in range(5):
print(num)
for num in range(2, 5):
print(num)
for num in range(2, 10, 2):
print(num)
my_list = list(range(5, 15, 3))
print(my_list)
# use of enumerate
name = 'abcdef'
for item in enumerate(name):
print(item)
for index, letter in enumerate(name):
print(f"index = {index} , letter = {letter}")
# zip the lists
list_a = [1, 2, 3]
list_b = ['a', 'b', 'c']
list_c = ['x', 'y', 'z']
for item in zip(list_a, list_b, list_c):
print(item)
# ignores extra elements
list_a = [1, 2, 3, 4, 5]
list_b = ['a', 'b', 'c']
list_c = ['x', 'y', 'z']
for item in zip(list_a, list_b, list_c):
print(item)
# in keyword works with iterable objects
print(2 in [1, 2])
print('k1' in {'k1': 1, 'k2': 2})
# min and max
print(min(list_a))
print(max(list_a))
# shuffle the list(operates in-place)
from random import shuffle
my_list = list(range(0, 10))
print(my_list)
shuffle(my_list)
print(my_list)
# return a random integer
from random import randint
my_num = randint(1, 100)
print(my_num)
result = input('Enter a number : ')
print(result)
print(type(result))
result = int(input('Enter another number : '))
print(result)
print(type(result)) |
13c5a6c03baa060d8a82d0a308aa55884021244f | yuexishuihan/yuexishuihan.github.io | /Python基础/re/re_05.py | 111 | 3.703125 | 4 | #数量词
import re
a = 'python 1111java678php'
r = re.findall('[a-z]{3,6}',a)
#贪婪与非贪婪(?)
print(r) |
23dfc141078d9e383503b24673154a05da567c67 | GustavoLeao2018/aula-algoritimos-estudos | /exercicio_4/Teste.py | 332 | 3.671875 | 4 | from Deque import Deque
from random import randint
deque = Deque(5)
for i in range(5):
deque.push_front(randint(0, 100))
print(deque)
print(deque.peek_front())
print(deque.peek_back())
print("Final:")
print(deque)
print(deque.pop_back())
print(deque)
print("Começo:")
print(deque)
print(deque.pop_first())
print(deque)
|
beec3f3ad0d379bc2cc0d21aca23f6c3156444d2 | schedpy/schedpy | /schedpy/utils.py | 7,699 | 3.953125 | 4 | from calendar import monthrange
from datetime import date, timedelta
class ScheduleSelectionError(Exception):
"""Schedule selection exception"""
pass
def add_months(given_date, months, days):
"""Function to add months (positive or non-positive) to the date given.
Parameters
==========
given_date: The given date.
months: Number of months to be added.
days: Number of days to go back from the final date.
Returns
=======
Final computed date after n months.
Examples
========
>>> from schedpy.utils import add_months
>>> from datetime import date
>>> d = date(2019, 12, 1)
>>> add_months(d, 2, 1)
datetime.date(2020, 1, 31)
>>> add_months(d, 3, 1)
datetime.date(2020, 2, 29)
"""
month = given_date.month - 1 + months
year = given_date.year + (month // 12)
month = month % 12 + 1
day = min(given_date.day, monthrange(year, month)[1])
return date(year, month, day) - timedelta(days)
def get_week_start_date(given_date, start_day):
""" Function to get the start date of the week depending on the start day.
Parameters
==========
given_date: The given date.
start_day: Start day of the week.
Returns
=======
Week's start date.
Examples
========
>>> from schedpy.utils import get_week_start_date
>>> d = date(2019, 12, 1)
>>> get_week_start_date(d, 1)
datetime.date(2019, 11, 26)
>>> get_week_start_date(d, 3)
datetime.date(2019, 11, 28)
"""
days_diff = 7 + given_date.weekday() - start_day
if given_date.weekday() - start_day >= 0:
days_diff = given_date.weekday() - start_day
return given_date - timedelta(days_diff)
def end_date_after_n_weeks(start_date, n, start_day):
"""Function to get the end date after n weeks.
Parameters
==========
start_date: given start date.
n: Number of weeks.
start_day: Start day of the week.
Returns
=======
End date of the week after n weeks from the start date.
Examples
========
>>> from schedpy.utils import end_date_after_n_weeks
>>> from datetime import date, timedelta
>>> end_date_after_n_weeks(date(2019, 12, 13), 5, 0)
datetime.date(2020, 1, 12)
>>> end_date_after_n_weeks(date(2019, 12, 1), 3, 5)
datetime.date(2019, 12, 20)
"""
return get_week_start_date(start_date, start_day) + timedelta(7 * n - 1)
def start_date_before_n_weeks(end_date, n, start_day):
"""Function to get the start date before n weeks.
Parameters
==========
end_date: given end date.
n: Number of weeks.
start_day: Start day of the week.
Returns
=======
Start date of the week before n weeks from the end date.
Examples
========
>>> from schedpy.utils import start_date_before_n_weeks
>>> from datetime import date, timedelta
>>> start_date_before_n_weeks(date(2019, 12, 13), 3, 3)
datetime.date(2019, 11, 28)
>>> start_date_before_n_weeks(date(2019, 1, 13), 3, 3)
datetime.date(2018, 12, 27)
"""
return get_week_start_date(end_date, start_day) + timedelta(-7 * (n - 1))
def get_period_window(start_date, period, period_value, today_date, start_day):
"""Function to get the period window containing the active window and today's date.
Parameters
==========
start_date: given start date.
period: May be Months, Weeks or Days.
period_value: Number of period (Months, Weeks or Days)
today_date: The date you want to start with.
start_day: Start day of the week.
Returns
=======
Tuple containing start and end date.
Examples
========
>>> from schedpy.utils import get_period_window, add_months
>>> from datetime import date, timedelta
>>> start_date = date(2019, 12, 3)
>>> today_date = date(2020,10, 14)
>>> get_period_window(start_date, "MONTHS", 3, today_date, 2)
(datetime.date(2020, 9, 3), datetime.date(2020, 12, 2))
>>> get_period_window(start_date, "DAYS", 5, today_date, 4)
(datetime.date(2020, 10, 10), datetime.date(2020, 10, 15))
>>> get_period_window(start_date, "WEEKS", 6, today_date, 0)
(datetime.date(2020, 9, 21), datetime.date(2020, 11, 1))
"""
if period == "MONTHS":
end_date = add_months(start_date, period_value, 1)
while today_date > end_date:
start_date = end_date + timedelta(1)
end_date = add_months(start_date, period_value, 1)
elif period == "WEEKS":
end_date = end_date_after_n_weeks(start_date, period_value, start_day)
while today_date > end_date:
start_date = end_date + timedelta(1)
end_date = end_date_after_n_weeks(start_date, period_value, start_day)
elif period == "DAYS":
end_date = start_date + timedelta(period_value)
while today_date > end_date:
start_date = end_date + timedelta(1)
end_date = start_date + timedelta(period_value)
return start_date, end_date
def get_active_period_window(active_period, active_type, active_value, start_day, start_date, end_date):
"""Function to get active period window from period window.
Parameters
==========
active_period: May be Months, Weeks or Days.
active_type: May be First or Last.
active_value: Number of active_period (Months, Weeks or Days).
start_day: Start day of the week.
start_date: Start date of the period window.
end_date: End date of the period window.
Returns
=======
Tuple containing active start and end date.
Examples
========
>>> from schedpy.utils import get_active_period_window
>>> from datetime import date, timedelta
>>> get_active_period_window("MONTHS", "LAST", 2, 0, date(2019, 12, 1), date(2020, 2, 3))
(datetime.date(2019, 12, 4), datetime.date(2020, 2, 3))
>>> get_active_period_window("WEEKS", "LAST", 2, 0, date(2019, 12, 1), date(2020, 2, 3))
(datetime.date(2020, 1, 27), datetime.date(2020, 2, 3))
>>> get_active_period_window("WEEKS", "FIRST", 2, 0, date(2019, 12, 1), date(2020, 2, 3))
(datetime.date(2019, 12, 1), datetime.date(2019, 12, 8))
>>> get_active_period_window("MONTHS", "FIRST", 2, 0, date(2019, 12, 1), date(2020, 2, 3))
(datetime.date(2019, 12, 1), datetime.date(2020, 1, 31))
>>> get_active_period_window("DAYS", "FIRST", 21, 0, date(2019, 12, 1), date(2020, 2, 3))
(datetime.date(2019, 12, 1), datetime.date(2019, 12, 21))
>>> get_active_period_window("DAYS", "LAST", 21, 0, date(2019, 12, 1), date(2020, 2, 3))
(datetime.date(2020, 1, 14), datetime.date(2020, 2, 3))
"""
active_start_date = start_date
active_end_date = end_date
if active_period == "MONTHS":
if active_type == "FIRST":
active_end_date = add_months(start_date, active_value, 1)
elif active_type == "LAST":
active_start_date = add_months(end_date + timedelta(1), -active_value, 0)
elif active_period == "WEEKS":
if active_type == "FIRST":
active_end_date = end_date_after_n_weeks(start_date, active_value, start_day)
elif active_type == "LAST":
active_start_date = start_date_before_n_weeks(end_date, active_value, start_day)
elif active_period == "DAYS":
if active_type == "FIRST":
active_end_date = start_date + timedelta(active_value - 1)
elif active_type == "LAST":
active_start_date = end_date - timedelta(active_value - 1)
if active_start_date < start_date or active_end_date > end_date:
raise ScheduleSelectionError("Active date range overflow")
return active_start_date, active_end_date
|
6c2ff1b3e427324a6deffad96b0e2a9b3d51027f | wc83/catelogue | /find_nearest.py | 232 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 19 16:06:30 2018
@author: william
"""
def find_nearest(array,value):
import numpy as np
idx = (np.abs(array-value)).argmin()
return (array[idx],idx) |
9a2bd24d916f0636a5173bd7e8349cbde3c30202 | APARNAS1998/luminardjango1 | /object oriented/employee constructor.py | 263 | 3.5625 | 4 | class Employee:
def __init__(self,name,ID,salary):
self.name=name
self.ID=ID
self.salary=salary
def printval(self):
print(self.name,self.ID,self.salary)
obj=Employee('aparna',2301,2340000)
obj.printval()
|
c484f3eec58d9562c5a0bf3c6af13f454c4771ca | Tiberius24/Python_Training | /HTLCS - 9.22 Exercises.py | 13,648 | 4.34375 | 4 | # HTLCS 9.22 Exercises
# My name: Don Trapp
# Problem 1
# What is the result of each of the following:
# print("Python"[1])
# print ('Strings are sequences of characters.'[5])
# print (len("wonderful"))
# print("Mystery"[:4])
# print("p" in "Pineapple")
# print('apple' in 'Pineapple')
# print('pear' not in 'Pineapple')
# print('apple' > 'pineapple')
# print('pineapple' < 'Peach')
# Problem 2
# In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack,
# Mack, Nack, Ouack, Pack, and Quack. This loop tries to output these names in order.
# prefixes = "JKLMNOPQ"
# suffix = "ack"
# suffix2 = "uack"
#
# for p in prefixes:
# if p != 'O' and p != 'Q':
# print(p + suffix)
# else:
# print(p + suffix2)
# Problem 3
# Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text -
# perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.
# Write a function that counts the number of alphabetic characters (a through z, or A through Z) in your text and then
# keeps track of how many are the letter ‘e’. Your function should print an analysis of the text like this:
# import string
#
# def count(q):
# lower = string.ascii_lowercase
# upper = string.ascii_uppercase
#
# charCount = 0
# eCount = 0
# for i in q:
# if i in lower or i in upper:
# charCount = charCount + 1
# if i == "e":
# eCount = eCount + 1
# charPercent = int((eCount / charCount)*100)
# print("This speech contains", charCount, "alphabetic characters, of which", eCount, "("+str(charPercent)
# + "%) are 'e'.")
#
#
# def main():
#
# quote = '''Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in
# Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war,
# testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great
# battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who
# here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.
# But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground.
# The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract.
# The world will little note, nor long remember what we say here, but it can never forget what they did here.
# It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far
# so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these
# honored dead we take increased devotion to that cause for which they gave the last full measure of devotion --
# that we here highly resolve that these dead shall not have died in vain -- that this nation, under God,
# shall have a new birth of freedom -- and that government of the people, by the people, for the people,
# shall not perish from the earth.
#
# Abraham Lincoln
# November 19, 1863'''
#
# count(quote)
# if __name__ == '__main__':
# main()
# Problem 4
# Print out a neatly formatted multiplication table, up to 12 x 12.
# print("n", '\t', "n*1", '\t', "n*2", '\t', "n*3", '\t', "n*4", '\t', "n*5", '\t', "n*6", '\t', "n*7", '\t', "n*8", '\t',
# "n*9", '\t', "n*10", '\t', "n*11", '\t', "n*12") # table column headings
# print("--", '\t', "----", '\t', "----", '\t', "----", '\t', "----", '\t', "----", '\t', "----", '\t', "----", '\t',
# "----", '\t', "----", '\t', "----", '\t', "----", '\t', "----",)
#
# for x in range(13): # generate values for columns
# print(x, '\t', 1 * x, '\t', 2 * x, '\t', 3 * x, '\t', 4 * x, '\t', 5 * x, '\t', 6 * x, '\t', 7 * x, '\t', 8 * x,
# '\t', 9 * x, '\t', 10 * x, '\t', 11 * x, '\t', 12 * x)
# Problem 5
# Write a function that will return the number of digits in an integer.
# def numDigits(n):
# answer = len(str(n))
# return answer
#
# print(numDigits(123456789))
# Problem 6
# Write a function that reverses its string argument.
# def reverse(astring):
# variable = ""
# for i in astring:
# variable = i + variable
# return variable
#
# print(reverse("Johnny Apple Seed"))
# Problem 7
# Write a function that mirrors its argument.
# def reverse(astring):
# variable = ""
# for i in astring:
# variable = i + variable
# return variable
#
# def mirror(mystr):
# reflection = reverse(mystr)
# if mystr == reverse(reflection):
# answer = (mystr+reflection)
# else:
# False
# return answer
#
# print(mirror("apple"))
# Problem 8
# Write a function that removes all occurrences of a given letter from a string.
# def remove_letter(theLetter, theString):
# answer = ''
# for i in theString:
# if i not in theLetter:
# answer = answer + i
# return answer
#
# print(remove_letter("t", "The President of the United States"))
# Problem 9
# Write a function that recognizes palindromes. (Hint: use your reverse function to make this easy!).
# def reverse(astring):
# variable = ""
# for i in astring:
# variable = i + variable
# return variable
#
# def is_palindrome(myStr):
# check = reverse(myStr)
# if myStr == check:
# return True
# else:
# return False
#
# print(is_palindrome("abba"))
# Problem 10
# Write a function that counts how many times a substring occurs in a string.
# 85%
# def count(substr, theStr):
# i = 0
# answer = 0
# found = False
# while i < len(theStr):
# if substr in theStr and substr != theStr:
# answer = answer + 1
# # j = i + 1
# i = i + 1
# theStr = theStr[i:]
#
# else:
# i = i + 1
# return answer
# print(count("aaa", "aaaaaa"))
# 100%
# def count(substr, theStr):
# i = 0
# answer = 0
# start = 0
# while i < len(theStr):
# if substr in theStr:
# a = theStr.find(substr,start)
# if a == -1:
# break
# answer += 1
# start = a+1
# else:
# i = i + 1
# return answer
# print(count("aaa", "aaaaaa"))
# Question 11
# Write a function that removes the first occurrence of a string from another string.
# def remove (substr, theStr):
# i = 0
# start = 0
# r_len = len(substr)
# found = False
# while i < len(theStr) and found is not True:
# if substr in theStr:
# start = theStr.find(substr)
# if start == -1:
# break
# strLen = len(theStr)
# answer = theStr[:start]+theStr[start+r_len:]
# found = True
# else:
# answer = theStr
# found = True
# return answer
# test = "bicycle"
# r_test = "cyc"
#
# print(remove(r_test, test))
# Question 12
# Write a function that removes all occurrences of a string from another string.
# def remove_all(substr, theStr):
# i = 0
# start = 0
# r_len = len(substr)
# found = False
# while i < len(theStr) and found is not True:
# if substr in theStr:
# start = theStr.find(substr)
# if start == -1:
# break
# strLen = len(theStr)
# answer = theStr[:start] + theStr[start+r_len:]
# theStr = answer
# i += 1
# else:
# answer = theStr
# found = True
# return answer
# test = "python rocks on"
# r_test = "on"
#
# print(remove_all(r_test, test))
# Question 13
# Here is another interesting L-System called a Hilbert curve. Use 90 degrees:
# import turtle
#
# def applyRule (lhch):
# rhstr = ""
# if lhch == "L":
# rhstr = "+RF-LFL-FR+"
# elif lhch == "R":
# rhstr = "-LF+RFR+FL-"
# else:
# rhstr = lhch
# return rhstr
#
# def processStr(oldStr):
# newStr = ""
# # iter = 0
# # checker = len(oldStr)
# for ch in oldStr:
# # iter = iter + 1
# newStr = newStr + applyRule(ch)
# # iterCheck = checker - iter
# return newStr
#
# def createLSystem(numIters, axiom):
# startString = axiom
# endString = ""
# for i in range(numIters):
# endString = processStr(startString)
# startString = endString
# return endString
#
# def drawLSystem (h, instructions, angle, distance):
# for cmd in instructions:
# if cmd == "F":
# h.fd(distance)
# elif cmd == "B":
# h.bk(distance)
# elif cmd == "+":
# h.rt(angle)
# elif cmd == "-":
# h.lt(angle)
#
# def main():
#
# inst = createLSystem(4, "L")
# # check = len(inst)
# print(inst)
#
# wn = turtle.Screen()
# wn.bgcolor("light green")
# wn.setworldcoordinates(-250, -250, 250, 250)
#
# honey = turtle.Turtle()
# honey.color("chocolate")
# honey.shape("turtle")
# honey.speed(20)
#
# honey.pu()
# honey.goto(-50,50)
# honey.pd()
#
# drawLSystem(honey, inst, 90, 5)
#
# wn.exitonclick()
#
# if __name__ == '__main__':
# main()
# Question
# Here is a dragon curve. Use 90 degrees
# import turtle
#
# def applyRule (lhch):
# rhstr = ""
# if lhch == "X":
# rhstr = "X+YF+"
# elif lhch == "Y":
# rhstr = "-FX-Y"
# else:
# rhstr = lhch
# return rhstr
#
# def processStr(oldStr):
# newStr = ""
# for ch in oldStr:
# newStr = newStr + applyRule(ch)
# return newStr
#
# def createLSystem(numIters, axiom):
# startString = axiom
# endString = ""
# for i in range(numIters):
# endString = processStr(startString)
# startString = endString
# return endString
#
# def drawLSystem (h, instructions, angle, distance):
# for cmd in instructions:
# if cmd == "F":
# h.fd(distance)
# elif cmd == "B":
# h.bk(distance)
# elif cmd == "+":
# h.rt(angle)
# elif cmd == "-":
# h.lt(angle)
#
# def main():
#
# inst = createLSystem(10, "FX")
# print(inst)
#
# wn = turtle.Screen()
# wn.bgcolor("light green")
# wn.setworldcoordinates(-250, -250, 250, 250)
#
# honey = turtle.Turtle()
# honey.color("chocolate")
# honey.shape("turtle")
# honey.speed(20)
#
# honey.pu()
# honey.goto(-50,50)
# honey.pd()
#
# drawLSystem(honey, inst, 90, 5)
#
# wn.exitonclick()
#
# if __name__ == '__main__':
# main()
# Question 18
# Write a function that implements a substitution cipher. In a substitution cipher one letter is substituted for
# another to garble the message. For example A -> Q, B -> T, C -> G etc. your function should take two parameters,
# the message you want to encrypt, and a string that represents the mapping of the 26 letters in the alphabet.
# Your function should return a string that is the encrypted version of the message.
# import string
#
# def encrypt(vari, shift):
# upperCase = string.ascii_uppercase
# lowerCase = string.ascii_lowercase
# output = ""
# for ch in vari:
# if ch in upperCase or ch in lowerCase:
# value = ord(ch)
# newCh = ""
# if value <= 90:
# value = value + shift
# if value > 90:
# value = value - 26
# newCh = chr(value)
# output = output + newCh
# else:
# value = value + shift
# if value > 122:
# value = value - 26
# newCh = chr(value)
# output = output + newCh
# else:
# output = output + ch
# return output
# print(encrypt("Linkin", 6))
# Question 19
# Write a function that decrypts the message from the previous exercise. It should also take two parameters.
# The encrypted message, and the mixed up alphabet. The function should return a string that is the same as
# the original unencrypted message.
# import string
#
# def decryption(vari, shift):
# upperCase = string.ascii_uppercase
# lowerCase = string.ascii_lowercase
# output = ""
# for ch in vari:
# if ch in upperCase or ch in lowerCase:
# value = ord(ch)
# if value <= 90:
# value = value - shift
# if value < 65:
# value = value + 26
# newCh = chr(value)
# output = output + newCh
# else:
# value = value - shift
# if value < 97:
# value = value + 26
# newCh = chr(value)
# output = output + newCh
# else:
# output = output + ch
# return output
#
# print(decryption("Nkrru, Cuxrj!", 6))
|
4202307f49374e35982f7de0b877fe8fb1d80a66 | BobbyAD/Intro-Python-II | /src/item.py | 383 | 3.546875 | 4 | '''
create item file
let player hold list of items
let room hold list of items
player can pick up items out of current_room
player can drop items in to current_room
'''
class Item:
def __init__(self, name, description):
self.name = name
self.description = description
def __str__(self):
return f"{self.name}: {self.description}" |
90b35ad573136177c266f7d71fef758e0927ac48 | vubon/Python-core | /list example/sort_system.py | 164 | 3.796875 | 4 | letters = ["a","u","v","c","b","d","e","g","r","s","l","i","j","m","o","n","p","q","t","f","h","y","x","w","z","k"]
lett = sorted(letters)
print(" \n" .join(lett))
|
e25ee41952793b2e6602b26b1270f29ea5800b18 | imsrv01/programs | /datastructure/heap.py | 3,049 | 3.96875 | 4 |
class MaxHeap:
def __init__(self,items=[]):
self.heap=[0]
for i in range(len(items)):
self.heap.append(items[i])
self.__floatUp(len(self.heap)-1)
# 2 - Place it at correct position - Float UP
# a. get parent
# b. Compare with parent, if greater than swap & floatup parent..
# Exit condition - if element is first element .. i,e i <= 1 , just return .. do nothing..
def __floatUp(self, index):
parent = index/2
if index <= 1:
return
elif self.heap[index] > self.heap[parent]:
self.__swap(index, parent)
self.__floatUp(parent)
def __swap(self, left, right):
self.heap[left], self.heap[right] = self.heap[right], self.heap[left]
# Get max/min element in heap
# -- return first element in list..
def peek(self):
if self.heap[1]:
return self.heap[1]
else:
return False
# Add new element -
# 1 - Add to end of array - list append
# 2 - Place it at correct position - Float UP
# a. get parent
# b. Compare with parent, if greater than swap & floatup parent..
# Exit condition - if element is first element .. i,e i <= 1 , just return .. do nothing..
def push(self,data):
self.heap.append(data)
self.__floatUp(len(self.heap)-1)
# Remove element- Only top element can be removed..
# 1. If heap size > 2
# swap last element with first element
# remove last element from list
# heapify
# 2. If heap size == 2
# remove last element
# 3. else return False
def pop(self):
if len(self.heap) > 2:
self.__swap(1, len(self.heap)-1)
max = self.heap.pop()
self.__heapify(1)
elif len(self.heap) == 2:
max = self.heap.pop()
else:
max = False
return max
# Heapify - Place a given element at it correct position
# 1. Get left and right child
# 2. largest = index
# 3. If left child > largest, make left child largest
# 4. if right child > largest , make right child largest
# 5. If left/right child is greater than index
# a. swap index and largest
# b. heapify largest
def __heapify(self, index):
left = 2*index
right = 2*index + 1
largest = index
if left < len(self.heap) and self.heap[left] > self.heap[largest]:
largest = left
if right < len(self.heap) and self.heap[right] > self.heap[largest]:
largest = right
if largest != index:
self.__swap(largest, index)
self.__heapify(largest)
maxheap = MaxHeap([2,32,5,17,98,12])
print(maxheap.heap)
print('PEEK - ', maxheap.peek())
#maxheap.push(88)
#print('PUSH - ', maxheap.heap)
print('POP - ', maxheap.pop())
print(maxheap.heap)
print('POP - ', maxheap.pop())
print(maxheap.heap)
print('POP - ', maxheap.pop())
print(maxheap.heap)
print('POP - ', maxheap.pop())
|
ff23ce33164845445b872590df3fc97832ed5c27 | gabriellaec/desoft-analise-exercicios | /backup/user_069/ch34_2019_09_28_01_51_31_030903.py | 180 | 3.765625 | 4 | valor = float(input('Qual o valor do depósito? '))
juros = float(input('Qual a taxa de juros? '))
mes = [valor]
i = 0
while 23 >= i:
mes.append(mes[i - 1]*juros)
print(mes)
|
42b94b64408fd2bf5fcaae4a87bb7558aff41f7d | jli124/leetcodeprac | /BFS/hw4/105ConstructBTfromPreorderandInorder.py | 1,346 | 3.875 | 4 | #105. Construct Binary Tree from Preorder and Inorder Traversal
#Given preorder and inorder traversal of a tree, construct the binary tree.
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
DFS
"""
#-------------------------------------------------------------------------------
# Soluton - O(n)
#-------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if len(preorder)==0:
return None
root=TreeNode(preorder[0])
middle=inorder.index(preorder[0])
root.left=self.buildTree(preorder[1:middle+1],inorder[:middle])
root.right=self.buildTree(preorder[middle+1:],inorder[middle+1:])
return root
#-------------------------------------------------------------------------------
# Solution
#-------------------------------------------------------------------------------
|
3edaa447eb008b8344a8c1ebb7a83ad496e02558 | jasonmahony/python | /guessing_game.py | 421 | 4.1875 | 4 | #!/usr/bin/python
import random
number = random.randint(1, 9)
guess = None
while (guess != number):
guess = raw_input('Guess a number between 1 and 9 or "exit" to end the game: ')
if guess == "exit":
print "Ending the game..."
break
guess = int(guess)
if guess > number:
print "Too high."
elif guess < number:
print "Too low."
else:
print "You're right!" |
232b548d454aea36f3191c4464c25ffb8b01707f | mingmang17/Algorithm-Team-Notes | /정렬/chap06_p_176.py | 695 | 3.6875 | 4 | #계수정렬 : 데이터의 크기가 한정되어 있는 경우에만 사용이 가능하지만 매우 빠르게 동작한다.
#모든 원소의 값이 0보다 크거나 같다고 가정
array = [7,5,9,0,3,1,6,2,9,1,4,8,0,5,2]
# 모든 범위를 포함하는 리스트 선언(모든값은 0으로 초기화)
count = [0] * (max(array) + 1) #0부터 시작하기 때문에
for i in range(len(array)):
count[array[i]] += 1 # 각 데이터에 해당하는 인덱스의 값 증가
for i in range(len(count)): # 리스트에 기록된 정렬 정보 확인
for j in range(count[i]):
print(i, end=' ') # 띄어쓰기를 구분으로 등장한 횟수만큼 인덱스 출력 |
34c47790102588d2563cb39ba022d95334acb51f | anurag9099/assignment | /keywordFilter.py | 458 | 3.5625 | 4 | import re
import sys
import pprint
path = sys.argv[1]
with open(path, 'r') as file:
corpus = file.read().replace('\n', '')
def filter_key(key, corpus):
pattern = "[^.]*"+key+"[^.]*\."
r = re.findall(pattern, corpus, re.IGNORECASE)
return r
key = str(input("Enter Filter Keyword:\n"))
result = filter_key(key,corpus)
if result == []:
print("Invalid Keyword!!!")
else:
pprint.pprint(result, width=200)
|
95783d06a3f682ea893c0d7092936681e7ff51a6 | knee-rel/Python-For-Everybody-Specialization | /Py4e_files/exercise_11.py | 302 | 3.875 | 4 | import re
filename = input('Enter filename: ')
try:
open_file = open(filename)
except:
print('File not found:',filename)
quit()
num_sum = 0
for line in open_file:
numbers = re.findall('[0-9]+', line)
for number in numbers:
num_sum = num_sum + int(number)
print(num_sum)
|
c9b64530a48e28285c10220f72e98e6ed18cea79 | galarzafrancisco/dhamma-scraper | /main.py | 2,855 | 3.703125 | 4 | # ========================================
#
# Definitions
#
# ========================================
url = 'https://www.dhamma.org/en/schedules/schbhumi'
lookup_location = 'Blackheath'
lookup_dates = '27 Jan - 07 Feb' # test
# lookup_dates = '09 Feb - 20 Feb'
sleep_period = 60 # Time in seconds between pings
# ========================================
#
# Imports
#
# ========================================
# Parsing
import requests
from bs4 import BeautifulSoup
# General
import os, time
from datetime import datetime
def get_row_text(lookup_dates, lookup_location):
'''
Function to scrape the website.
Looks for rows with the dates & location defined above (ie: '27 Jan - 07 Feb' and 'Blackheath')
and returns the text of the row
'''
# Ping the url
response = requests.get(url)
# Parse the HTML response
html = response.content
soup = BeautifulSoup(html, features='html.parser')
# Find the row we're interested on
rows = [row.text.replace('\n', ' ') for row in soup.findAll('tr')]
rows = [row for row in rows if lookup_dates in row and lookup_location in row]
row_text = rows[0]
return row_text
if __name__ == '__main__':
'''
This is the main function. This gets executed when you run 'python main.py'
'''
# Write a log entry when app starts
with open('log.txt', 'a') as f:
timestamp = datetime.now()
f.write("{} - Start\n".format(timestamp))
# Get the first response from the website
text = get_row_text(lookup_dates, lookup_location)
# Loop forever
while True:
log_entry = ''
# Sleep to avoid pinging the url too frequently
time.sleep(sleep_period)
# Check the website again
ping_timestamp = datetime.now()
new_text = get_row_text(lookup_dates, lookup_location)
# Check if the application is open or not. Proxy for this is the text 'applications accepted starting...'
if 'applications accepted starting' in new_text.lower():
status = 'closed'
else:
status = '>>> OPEN!!! <<<'
# Check if the website has changed since the last time. This may be an indication that the applications are now open.
if new_text == text:
log_entry += "{} - {} - Website hasn't changed\n".format(ping_timestamp, status)
else:
text = new_text
log_entry += '\n\n\n----------------------------------\n'
log_entry += "{} - {} - Website has changed!!!!\n".format(ping_timestamp, status)
log_entry += new_text
log_entry += '\n----------------------------------\n'
# Print log entry and write it to a log file
print(log_entry)
with open('log.txt', 'a') as f:
f.write(log_entry)
|
57e819ab2e12efa4279216b6bdc8bc549052d56c | danielhrisca/daily_coding_problem | /challanges/problem_1.py | 663 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 20:46:03 2018
@author: daniel
Given a list of numbers and a number k, return whether any two numbers from the
list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
"""
def problem_1(numbers, target_sum):
candidates = set()
for number in numbers:
if number in candidates:
return True
else:
candidates.add(target_sum - number)
return False
assert problem_1([10, 15, 3, 7], 17) is True
assert problem_1([10, 15, 3, 7], 20) is False
print('all fine')
|
ae201cc75c6afcc3b95326042a8a4d0df857929a | manicmaniac/Project_Euler | /python/Problem21.py | 803 | 3.734375 | 4 | # coding:utf-8
"""
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
"""
def amicables(limit):
numbers = [0] * limit
for i in range(1, limit):
for j in range(i * 2, limit, i):
numbers[j] += i
for i, j in enumerate(numbers):
if j < limit and i == numbers[j] != j:
yield i
if __name__ == '__main__':
print(sum(amicables(10000)))
|
05dbf53a183af06dbe2ff284264ebdd1efe45bb0 | group9BSE1/BSE-2021 | /src/Chapter 8/Exercise 5.py | 325 | 4.28125 | 4 | # prompts the user to enter to file path and the executes it
text = input("Enter the file name: ")
file = open(text)
count = 0
for line in file:
words = line.split()
if len(words) < 3:
continue
if words[0] != "From":
continue
print(words[2])
count = count + 1
print(f"there were {count}")
|
7f63ba01a106de323fb850b7c3c65b3454da49bc | nykkkk/hello-world | /BFS.py | 1,958 | 3.734375 | 4 |
class Graph: #图
def __init__(self):
self.adj = {}
def add_edge(self, u, v): #临接结点
if self.adj[u] is None:
self.adj[u] = []
self.adj[u].append(v)
class BFSResult: #宽度优先结果
def __init__(self):
self.level = {} #存储各层结点
self.parent = {} #父节点
def bfs(g, s):
r = BFSResult()
r.parent = {s: None}
r.level = {s: 0}
i = 1
frontier = [s]
while frontier:
next = []
for u in frontier:
for v in g.adj[u]:
if v not in r.level:
r.level[v] = i
r.parent[v] = u
next.append(v)
frontier = next
i += 1
return r
def find_shortest_path(bfs_result, v):
source_vertex = [vertex for vertex, level in bfs_result.level.items() if level == 0]
# 初始结点
# print(source_vertex)
v_parent_list = []
v_parent_list.append(v)
if v != source_vertex[0]:
v_parent = bfs_result.parent[v]
v_parent_list.append(v_parent)
while v_parent != source_vertex[0] and v_parent != None:
v_parent = bfs_result.parent[v_parent]
v_parent_list.append(v_parent)
return v_parent_list
# def draw_BFS(g, s):
if __name__ == "__main__":
g = Graph()
g.adj = {
"s": ["a", "x"],
"a": ["z","s"],
"d": ["f","c","x"],
"c": ["x","d","f","v"],
"v": ["f","c"],
"f": ["c","d","v"],
"x": ["s","d","c"],
"z": []
}
bfs_result = bfs(g, 's')
# print(bfs_result.level)
vals = bfs_result.level.values()
for a in range(len(bfs_result.level)):
print(list(bfs_result.level)[a], end='')
print(" : ",end="")
print(list(vals)[a])
find_list1 = find_shortest_path(bfs_result, 'v')
find_list1.reverse()
print(find_list1)
|
135ba190c8dbf769aea5f9260b43cab152750f58 | shubh3794/DS-ADA | /Trees and LL/LLoper.py | 5,105 | 4.03125 | 4 | import sys
from BaseClass import Node
from random import randint
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def insertBeg(self,data):
temp = Node(data)
temp.next = self.head
self.head = temp
if self.head.next == None:
self.tail = self.head
return self.head
def insertEnd(self,data):
temp = Node(data)
temp.next = None
self.tail.next = temp
self.tail = temp
return self.tail
def insertAtPos(self,data,pos):
temp = Node(data)
count = 1
curr = self.head
while count < pos-1:
curr = curr.next
count += 1
storeNext=curr.next
curr.next = temp
temp.next = storeNext
def delete(self):
if self.head.next == None:
self.tail = None
self.head = self.head.next
return self.head
def printLL(self):
curr = self.head
while curr !=None:
print curr
curr = curr.next
##This does not reverses the linked list, this just prints the reverse list
def reversePrint(self,x):
if x == None:
return
self.reversePrint(x.next)
print x
##This actually reverses linked list physically
def reverseLLInPlace(self,x,end):
if x == None:
return
if x.next==None:
self.head=x
temp = x.next
x.next = end
end = x
self.reverseLLInPlace(temp,x)
##function reverse LL in pair of k, for example 1-2-3-4-5-6 becomes
##3-2-1-6-5-4
def reverseK(self,x,count,k,end):
if count>k or x==None:
return end
if count <=k:
temp = x.next
x.next = end
end = x
return self.reverseK(temp,count+1,k,end)
def revK(self,k):
curr = self.head
cnt = 0
previ = None
while curr != None:
temp = curr
count = 0
while curr!=None and count != k:
count += 1
curr = curr.next
m = self.reverseK(temp,1,k,curr)
if temp.value == self.head.value:
self.head=m
previ = m
else:
previ.next = m
previ = m
cnt = 0
if previ != None:
while cnt < k-1 and previ!=None:
previ = previ.next
cnt += 1
a = LinkedList()
b = LinkedList()
for i in range(1,8):
a.insertBeg(i)
a.reverseLLInPlace(a.head,None)
a.revK(3)
a.printLL()
print "\nholalala"
for i in range(3,9,1):
b.insertBeg(i)
a.reverseLLInPlace(a.head,None)
b.reverseLLInPlace(b.head,None)
result = LinkedList()
##http://www.geeksforgeeks.org/sum-of-two-linked-lists/
def addtwoLL(a,b,result,carry):
if a==None or b==None:
if a==None and b != None:
sumi=b.value+carry
res = sumi%10
carry = sumi/10
result.insertBeg(res)
return addtwoLL(None,b.next,result,carry)
if b==None and a != None:
sumi=a.value+carry
res = sumi%10
carry = sumi/10
result.insertBeg(res)
return addtwoLL(a.next,None,result,carry)
if a==None and b==None and carry>9:
res = carry%10
carry = carry/10
result.insertBeg(res)
addtwoLL(None,None,result,carry)
if a==None and b==None and carry<=9:
result.insertBeg(carry)
return result
else:
sumi = a.value+b.value+carry
res = sumi%10
carry = sumi/10
result.insertBeg(res)
return addtwoLL(a.next,b.next,result,carry)
x = addtwoLL(a.head,b.head,result,0)
x.printLL()
##LL to test merge sort functions
sortLL = LinkedList()
sortLL.insertBeg(5)
sortLL.insertBeg(9)
sortLL.insertBeg(6)
sortLL.insertBeg(8)
sortLL.insertBeg(5)
def findMid(x):
if x==None:
return
if x.next==None:
return x
slow = x
fast = x
while fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
return slow
def mergeSortLL(x):
if x.next==None:
return x
mid = findMid(x)
temp = mid.next
mid.next = None
a = mergeSortLL(x)
b = mergeSortLL(temp)
return merge(a,b)
def merge(head,mid):
if head == None:
return mid
if mid == None:
return head
curr = Node()
temp = curr
while head!=None and mid!= None:
if head.value<=mid.value:
temp.next = head
head = head.next
else:
temp.next=mid
mid=mid.next
temp= temp.next
if head==None and mid != None:
temp.next = mid
else:
temp.next = head
return curr.next
s= mergeSortLL(sortLL.head)
print s.next
print "\n yayaya \n"
while s != None:
print s
s = s.next
|
b50ac2af82d585feb9759e3a1bda535521ee143a | 95subodh/Leetcode | /191. Number of 1 Bits.py | 289 | 3.78125 | 4 | #Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
ans=0
while n>0:
if n&1:
ans+=1
n/=2
return ans |
09e1f78a0ef9a95712783c2ba73474818b2ceeef | ihf-code/python | /session_04/answers/B8.py | 224 | 4.3125 | 4 | #B8 - Create a list of 5 numbers. Write a for loop which appends the
# square of each number to the new list
numbers = [2, 5, 8, 9, 10]
sqr_numbers = []
for i in numbers:
sqr_numbers.append(i ** 2)
print(sqr_numbers)
|
7d9fe9b4ed53d3c8ddd6dbd3f3fb18fa3ce98038 | drakotech/python_course | /show_notes/class_poly_func.py | 619 | 3.5 | 4 | # Building Polymorphic Functions in Python
class Heading:
def __init__(self, content):
self.content = content
def render(self):
return f'<h1>{self.content}</h1>'
class Div:
def __init__(self, content):
self.content = content
def render(self):
return f'<div>{self.content}</div>'
div_one = Div('Some content')
heading = Heading('My Amazing Heading')
div_two = Div('Another div')
def html_render(tag_object):
print(tag_object.render())
html_render(div_one)
#<div>Some content</div>
html_render(div_two)
#<div>Another div</div>
html_render(heading)
#<h1>My Amazing Heading</h1>
|
4206b232f0a2dbfa2fa4eb3b05c11fcef085fe69 | zhanghongwei125828/python_data | /day1/6-作业.py | 2,089 | 3.890625 | 4 | # day1-作业
################################################################################
# 1--使用while循环输出1 2 3 4 5 6 7 8 9 10
'''
num = 1
while num <= 10:
print(num)
num += 1
'''
################################################################################
# 2--使用while循环输出1 2 3 4 5 6 7 8 9 10 等于7的时候是一个空格
'''
num = 0
while num < 10:
num += 1
if num == 7:
print(' ')
else:
print(num)
'''
# 不打印7 方法1
'''
num = 0
while num < 10:
num += 1
if num == 7:
continue
print(num)
'''
# 不打印7 方法2
'''
num = 0
while num < 10:
num += 1
if num == 7:
pass
else:
print(num)
'''
################################################################################
# 3 --求出1-100相加数的和
'''
count = 0
num = 0
while count <= 100:
num = count + num
count += 1
print(num)
'''
################################################################################
# 4 -- 输出1-100内的所有奇数
# 方法1:
'''
count = 1
while count < 101:
print(count)
count += 2
'''
# 方法2:
'''
count = 1
while count < 101:
if count % 2 == 1:
print(count)
count += 1
'''
################################################################################
# 5 -- 输出1-100内的所有偶数
'''
count = 1
while count < 101:
if count % 2 == 0:
print(count)
count += 1
'''
################################################################################
# 6 -- 判断用户输入用户名密码(用户名:zhangsan ; 密码:abc123!),正确退出循环打印"登陆成功",三次用户名或密码输入错误退出并打印"您输入的用户名或密码不正确,请重新输入"
'''
count = 1
while count < 4:
count += 1
name = input("请输入用户名 ")
pwd = input("请输入密码: ")
if name == "zhangsan" and pwd == "abc123!":
print("登陆成功")
break
else:
print("您输入的用户名或密码不正确,请重新输入")
continue
''' |
f715c268bffb5cf9189fff334b398feb7bfb876f | GuilhermeRamous/python-exercises | /funcao_pura.py | 171 | 3.515625 | 4 | def double_stuff(lista):
lista_nova = []
for i in lista:
lista_nova.append(i * 2)
return lista_nova
lista = [1, 2, 3, 4]
print(double_stuff(lista))
|
c59915516fa461fcfaab1c9272fea0c045e50076 | ARASKES/Python-practice-2 | /Practice2 tasks/Lesson_15/Task_15_4.py | 1,198 | 3.921875 | 4 | def most_frequent(numbers):
most_frequent_element = 0
max_count = 0
for element in numbers:
count = 0
for el in numbers:
if el == element:
count += 1
if count > max_count:
max_count = count
most_frequent_element = element
return most_frequent_element
N = int(input())
lines = []
for i in range(N):
lines.append(input())
rows = []
for line in lines:
row = []
number = ""
for char in line:
if char == " ":
row.append(int(number))
number = ""
else:
number += char
row.append(int(number))
row.sort()
rows.append(row)
medians = []
for row in rows:
median = row[len(row) // 2]
medians.append(median)
print(median, end=" ")
print()
modes = []
for row in rows:
mode = most_frequent(row)
modes.append(mode)
print(mode, end=" ")
print()
medians.sort()
print(medians[len(medians) // 2])
print(most_frequent(modes))
rows_united = []
for row in rows:
for number in row:
rows_united.append(number)
rows_united.sort()
print(rows_united[len(rows_united) // 2])
print(most_frequent(rows_united))
|
8f03736163dbbb76168a24c37162746cbc212704 | tadejpetric/math_stuff | /zeroes.py | 3,361 | 3.90625 | 4 | import math
def is_prime(num):
for i in range(2, math.ceil(math.sqrt(num))):
if not num % i:
return False
return True
def field_in():
field = int(input("input the size of field Z: "))
if not is_prime(field):
print("this is not a field")
return field
def polynomial_in():
polynomial = input("Enter polynomial F[x,y]: ")
polynomial = polynomial.replace(' ', "")
polynomial = polynomial.replace('-', "+-")
polynomial = polynomial.split('+')
result = []
for term in polynomial:
if len(term) == 0:
continue
temp = {'num': 0, 'x': 0, 'y': 0}
prev = 0 # 0 for num, 1 x, 2 y
number = ""
x = "0"
y = "0"
for character in term:
if character == '^':
if prev == 1:
x = ""
else:
y = ""
continue
if character == '-':
continue
if prev == 0:
if character != 'x' and character != 'y':
number += character
else:
if character == 'x':
prev = 1
x = "1"
elif character == 'y':
prev = 2
y = "1"
elif prev == 1:
if character != 'y':
x += character
else:
prev = 2
y = "1"
elif prev == 2:
if character != 'x':
y += character
else:
prev = 1
x = "1"
try:
temp['num'] = int(number)
if term[0] == '-':
temp['num'] *= -1
except ValueError:
temp['num'] = 1 if term[0] != '-' else -1
temp['x'] = int(x)
temp['y'] = int(y)
result.append(temp)
return result
def calculate(poly, x, y, field):
result = 0
for term in poly:
result += term['num'] * x**term['x'] * y**term['y']
return result % field
def display(polynomial, field):
for row in range(field - 1, -1, -1):
print("{0:2}".format(row)+'|', end="")
for column in range(field):
value = calculate(polynomial, column, row, field)
if value == 0:
print(u"\u2588\u2588", end="")
else:
print(' ', end="")
print()
print('-' * (2*(field+3)))
print(' |', end="")
for i in range(field):
print(str(i)[0]+(" "), end="")
print('\n ', end="")
for i in range(field):
if i > 9:
print(i % 10, end=" ")
else:
print(' ', end="")
print()
def ui_loop():
field = field_in()
polynomial = polynomial_in()
while True:
display(polynomial, field)
option = input("Q quit, F new field, P new polynomial, A new everything: ")
if option.upper() == 'Q':
break
if option.upper() == 'F':
field = field_in()
if option.upper() == 'P':
polynomial = polynomial_in()
if option.upper() == 'A':
field = field_in()
polynomial = polynomial_in()
if __name__ == '__main__':
ui_loop()
|
da90feaed2277bb219798133d9b5aba221d22ddb | jaykhedekar7/D-A-in-python | /linearsort.py | 236 | 4 | 4 | def linearSort(arr, target):
length = len(arr)
for value in range(length):
if arr[value] == target:
print("Value found in position: ", value)
else:
print("Not found")
|
bdecc90ac4a9682b4fb0ea3980e1d067dcb595e0 | cryanperkins/PublicCode | /phonebook.py | 1,560 | 4.1875 | 4 | __author__ = 'Ryan Perkins'
phonebook = {}
#The intro asks the user who he is looking for and then directs the user to the next function.
def intro():
search = raw_input('Who are you looking for?')
return check_dict(search)
#This function checks to see if the person requested is in the phonebook and if he is then it prints the contact information and returns back to the intro.
#If the person is not in the phone book it then directs the user to the replay function.
def check_dict(search):
if search in phonebook:
print phonebook[search]['name']
print phonebook[search]['address']
print phonebook[search]['number']
#intro()
# else:
# replay()
#return data_entry()
#This function asks the user for the contact information to save it in the dictionary and then goes back to the intro.
def data_entry():
name = raw_input('Enter the name.')
address = raw_input('Enter the address.')
number = raw_input('Enter the phone number.')
phonebook[name] = {'name': name, 'address': address, 'number': number}
intro()
#This function is used when the contact is not found in the phonebook.
# It then asks if the user wants to enter the contact information.
def replay():
ask_user = raw_input("Individual not found. Would you like to add contact information?\n type 'y' for yes or 'n' for no.").lower()
if ask_user == 'y':
return data_entry()
else:
print "Thanks for using the phonebook."
def main():
intro()
if __name__ == '__main__':
intro() |
cfdd54fd36b0d87ebe645c3d767685d84639b12b | r-harini/Code | /Machine_Learning/Regression/Simple_Linear_Regression/template.py | 698 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing dataset
dataset=pd.read_csv('Salary_Data.csv')
X=dataset.iloc[:, :-1].values
y=dataset.iloc[:,1].values
#Splitting dataset into train and test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train,y_test= train_test_split(X,y, test_size=1/3, random_state=0)
"""#Feature scaling
from sklearn.preprocessing import StandardScaler
sc_X=StandardScaler()
X_train=sc_X.fit_transform(X_train)
X_test=sc_X.transform(X_test)"""
#Fitting simple linear regression to the training set
from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(X_train, y_train)
|
c1fe5e1f46a552c6053ea8d5cc774e06f0b3c03b | laughtLOOL/grok-learning-answers | /introduction to programming 2 (python)/1/Up the lift.py | 273 | 3.78125 | 4 | cur_floor = input('Current floor: ')
des_floor = input('Destination floor: ')
floor_change = int(des_floor) - int(cur_floor)
cur_floor = int(cur_floor)
for i in range(floor_change):
print('Level ' + str(cur_floor))
cur_floor += 1
print('Level ' + str(des_floor)) |
7a7ce19b1fa99d063e68220dac7482cdab518d4b | athulkumarr/Sudoku-Solver | /sudokuSolver.py | 1,857 | 3.5625 | 4 | def solve_sudoku(self, board: List[List[str]]) -> None:
def get_block(i, j):
return 3*(i//3)+j//3
def next_empty_cell(i,j):
j += 1
if j == 9:
j = 0
i += 1
if i == 9: return None
if board[i][j] != '.':
return next_empty_cell(i, j)
else:
return i, j
def fill_cell(i,j):
k = get_block(i,j)
for n in range(1, 10):
n = str(n)
if n not in cols[j] and n not in rows[i] and n not in blocks[k]:
board[i][j] = n
rows[i].add(n)
cols[j].add(n)
blocks[k].add(n)
end = next_empty_cell(i,j)
if end == None: return True
ni, nj = end
# fill the next cell by backtracking
if fill_cell(ni, nj): return True
# this digit did not work, remove it from the cell
board[i][j] = '.'
rows[i].remove(n)
cols[j].remove(n)
blocks[k].remove(n)
return False
rows, cols, blocks = [set() for _ in range(9)], [set() for _ in range(9)], [set() for _ in range(9)]
for i in range(9):
for j in range(9):
n = board[i][j]
rows[i].add(n)
cols[j].add(n)
blocks[get_block(i,j)].add(n)
i,j = next_empty_cell(0,-1)
fill_cell(i, j)
board = [["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]]
solve_sudoku(board)
|
d9f05e4040dec49497885e3cab62487e4f92323c | spfantasy/LeetCode | /260_Single_Number_III/260.py | 755 | 3.578125 | 4 | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
total = 0
# get xor of two single numbers
for num in nums:
total ^= num
# get the last digit with '1'
# which is the last digit that num1 and num2 are different from each other
# a&(a-1) mark digit of last '1' and after with '0'
# (a&(a-1))^a captures '1' in the above part
lastbit = (total & (total - 1)) ^ total
num1 = 0
num2 = 0
#xor by making two groups depending on last digit
for num in nums:
if num & lastbit:
num1 ^= num
else:
num2 ^= num
return [num1, num2] |
e25180d7569fc970f36617ccb97a7fd8ff32f904 | Justinandjohnson/Python | /Hack.py | 449 | 3.609375 | 4 | import hashlib
import re
import fileinput
n = input('Enter Filename: ');
f = open(n, 'r')
for line in f:
p = line.strip()
if len(p) < 6:
print(p + " not valid")
continue
h = hashlib.sha1(p).hexdigest()[6:]
passwords = open('combo_not.txt', 'r')
found = False
for password in passwords:
if re.search(h,password):
print(p + " found")
found = True
break
if not found:
print(p + " *NOT* found") |
2f901ba4252e6ab908775c76878a5cbd34363856 | ElshadaiK/Competitive-Programming | /merge_two_sorted_linked_lists.py | 956 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
res = ListNode()
ptr = res
x = l1
y = l2
while(x and y):
if(x.val < y.val):
res.next = x
res = res.next
x = x.next
elif(y.val < x.val):
res.next = y
res = res.next
y = y.next
else:
res.next = y
res = res.next
y = y.next
res.next = x
res = res.next
x = x.next
if(x):
res.next = x
if(y):
res.next = y
return ptr.next
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.