blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2b1115ca7ffe7b8ad2f0088f4d31598609481fac | ckim42/spd-problems | /five.py | 1,005 | 4.1875 | 4 | '''Given a singly-linked list, find the middle value in the list'''
from linkedlist import LinkedList
def middle_value(linked_list):
size = 0
node = linked_list.head
while node is not None:
size += 1
node = node.next
if size % 2 == 0:
return None
node = linked_list.head
for _ in range(size // 2):
node = node.next
return node.data
'''Rotate a singly-linked list counterclockwise by k nodes, where k is a given integer'''
def rotate_links(linked_list, k):
if linked_list.is_empty():
return #return None
for i in range(k):
checking = linked_list.tail
linked_list.delete(checking.data)
linked_list.prepend(checking.data)
return linked_list
argument_list = LinkedList(['A', 'B', 'C', 'D', 'E'])
rotation_list = LinkedList([4, 5, 6, 7])
k = 3
if __name__ == "__main__":
print('middle value:')
print(middle_value(argument_list))
print('rotate:')
print(rotate_links(rotation_list, 3)) |
6216c1807dd08cc679acbc25a456447ab07c7610 | bingyang-hu/Full-Stack-Web-Developer | /Python/Tuple_Set_Boolean.py | 255 | 3.78125 | 4 | # Booleans
True
False
0
1
#Tuples
t=(1,2,3)
print (t[1])
#Set
x=set()
x.add(1)
x.add(2)
x.add(4)
x.add(4)
x.add(0.1)
# Set is unordered and only takes in unique element.
print(x)
converted=set([1,1,1,1,1,1,1,2,2,2,2,2,4,4])
print(converted)
|
2b0c87aa8f40e76839a1a7e6022807199bf1183d | rwu8/MIT-6.00.2x | /Week 1/Lecture 3 - Graph Problems/Exercise2.py | 1,209 | 4.3125 | 4 | # Consider our representation of permutations of students
# in a line from Exercise 1. (The teacher only swaps the positions
# of two students that are next to each other in line.) Let's
# consider a line of three students, Alice, Bob, and Carol
# (denoted A, B, and C). Using the Graph class created in the
# lecture, we can create a graph with the design chosen in
# Exercise 1: vertices represent permutations of the students
# in line; edges connect two permutations if one can be made
# into the other by swapping two adjacent students.
#
# We construct our graph by first adding the following nodes:
from graph import *
nodes = []
nodes.append(Node("ABC")) # nodes[0]
nodes.append(Node("ACB")) # nodes[1]
nodes.append(Node("BAC")) # nodes[2]
nodes.append(Node("BCA")) # nodes[3]
nodes.append(Node("CAB")) # nodes[4]
nodes.append(Node("CBA")) # nodes[5]
g = Graph()
for n in nodes:
g.addNode(n)
# Write the code that adds the appropriate edges to the graph
# in this box.
g.addEdge(Edge(nodes[0], nodes[1]))
g.addEdge(Edge(nodes[0], nodes[2]))
g.addEdge(Edge(nodes[1], nodes[4]))
g.addEdge(Edge(nodes[2], nodes[3]))
g.addEdge(Edge(nodes[3], nodes[5]))
g.addEdge(Edge(nodes[4], nodes[5]))
print(g) |
8e9966e480c780f0c325fe0117eebafa09f4f359 | SamruddhiShetty/basics_python | /design_door_mat.py | 1,299 | 3.734375 | 4 | # basics_python
if __name__=="__main__":
N, M= map(int, input().split())
size=N-2
size2=((M-2)//2)//3
i=1
space=size2
while i<=size:
print('-'*space*3+'.|.'*i+'-'*space*3)
i=i+2
space -=1
size3=(M-7)//2
print('-'*size3+'WELCOME'+'-'*size3)
i=size
space=1
while i>=0:
print('-'*space*3+'.|.'*i+'-'*space*3)
i=i-2
space +=1
# the above code is without the use of string alignment functions
#this code uses string alignment function
if __name__=="__main__":
N, M= map(int, input().split())
size=N-2
i=1
pattern='.|.'
while i<=size:
print((pattern*i).center(M,'-'))
i=i+2
print('WELCOME'.center(M,'-'))
i=size
while i>=0:
print((pattern*i).center(M,'-'))
i=i-2
output:-
Size: 11 x 33
---------------.|.---------------
------------.|..|..|.------------
---------.|..|..|..|..|.---------
------.|..|..|..|..|..|..|.------
---.|..|..|..|..|..|..|..|..|.---
-------------WELCOME-------------
---.|..|..|..|..|..|..|..|..|.---
------.|..|..|..|..|..|..|.------
---------.|..|..|..|..|.---------
------------.|..|..|.------------
---------------.|.---------------
|
ff70ec652392aa248c02d0db4a11ad696a8efaae | prajwal041/ProblemSolving | /Learning/mustdo/long_substring.py | 268 | 3.609375 | 4 | s = "malayalam"
l=[]
f=[]
for i in range(len(s)-1):
l.append(s[i:])
for i in range(len(l)):
if s[i] in s[i+1:]:
f.append(s[i])
print(''.join(f))
'''
Longest subset in the string from Leetcode
Input: s = "banana"
Output: "ana"
T ~ O(n)
S ~ O(n)
'''
|
94f626e51391ace109c51d5616bbdc168c2ab3c4 | Asunqingwen/LeetCode | /简单/下一个更大元素1.py | 1,862 | 3.984375 | 4 | """
给定两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。
示例 1:
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
示例 2:
输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。
对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。
提示:
nums1和nums2中所有元素是唯一的。
nums1和nums2 的数组大小都不超过1000。
"""
from typing import List
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
if not nums2 or not nums1:
return [-1] * len(nums1)
stack = [nums2[0]]
hashMap = {}
i = 1
while i < len(nums2):
while stack and nums2[i] > stack[-1]:
hashMap[stack[-1]] = nums2[i]
stack.pop()
stack.append(nums2[i])
i += 1
while stack:
hashMap[stack.pop()] = -1
res = [hashMap[num] for num in nums1]
return res
if __name__ == '__main__':
nums1 = [4, 1, 2]
nums2 = [1, 3, 4, 2]
sol = Solution()
print(sol.nextGreaterElement(nums1, nums2))
|
5fc77b299735e528681ef38ce2ff319ec836f911 | bhargav1000/timetable-generator | /tictactoe.py | 4,098 | 3.921875 | 4 | from random import randint
board = []
for x in range(3):
board.append(["_"] * 3)
def print_board(board):
for row in board:
print (" ".join(row))
def random_o(board):
return randint(0, len(board)-1)
def row_check(board, row, col, player, tag):
if board[row][col] == tag:
if board[row][col+1] == tag:
if board[row][col+2] == tag:
if player == "bot":
print ("I win!")
print
return 11
else:
print ("You win!")
print
return 12
def col_check(board, row, col, player, tag):
if board[row][col] == tag:
if board[row+1][col] == tag:
if board[row+2][col] == tag:
if player == "bot":
print ("I win!")
print
return 21
else:
print ("You win!")
print
return 22
def dia_check(board, row, col, player, tag):
if board[row][col] == tag:
if board[row+1][col+1] == tag:
if board[row+2][col+2] == tag:
if player == "bot":
print
print ("I win!")
print
return 31
else:
print
print ("You win!")
print
return 32
bot_count = 0
pl_count = 0
i = 100
v = 100
def bot_place(board):
bot_row = random_o(board)
bot_col = random_o(board)
if board[bot_row][bot_col] == "_":
board[bot_row][bot_col] = "X"
else:
bot_place(board)
def pl1_stat(pl, count):
if pl >= count:
if row_check(board, 0, 0, "player", "O") == 12:
return 12
elif col_check(board, 0, 0, "player", "O") == 22:
return 22
elif dia_check(board, 0, 0, "player", "O") == 32:
return 32
elif row_check(board, 1, 0, "player", "O") == 12:
return 12
elif col_check(board, 0, 1, "player", "O") == 22:
return 22
elif row_check(board, 2, 0, "player", "O") == 12:
return 12
elif col_check(board, 0, 2, "player", "O") == 22:
return 22
else:
pl1_stat(pl, count+1)
def pl2_stat(pl, count):
if pl >= count:
if row_check(board, 0, 0, "bot", "X") == 11:
return 11
elif col_check(board, 0, 0, "bot", "X") == 21:
return 21
elif dia_check(board, 0, 0, "bot", "X") == 11:
return 11
elif row_check(board, 1, 0, "bot", "X") == 21:
return 21
elif col_check(board, 0, 1, "bot", "X") == 11:
return 11
elif row_check(board, 2, 0, "bot", "X") == 21:
return 21
elif col_check(board, 0, 2, "bot", "X") == 11:
return 11
else:
pl1_stat(pl, count+1)
while i > 0:
print ("My turn:")
bot_place(board)
bot_count += 1
print
print (print_board(board))
if pl2_stat(bot_count, 3) == 11 or pl2_stat(bot_count, 3) == 21 or pl2_stat(bot_count, 3) == 31:
print ("bot wins!")
break
if bot_count >= 5:
print ("Draw!")
break
print ("Your turn:")
pl_row = int(input("Enter row:"))
pl_row -= 1
print
pl_col = int(input("Enter col:"))
pl_col -= 1
pl_count += 1
print
if board[pl_row][pl_col] != "_":
print ("You can't do that, enter again")
pl_row -= int(input("Enter row:"))
pl_row = 1
print
pl_col -= int(input("Enter col:"))
pl_col = 1
print
else:
board[pl_row][pl_col] = "O"
print (print_board(board))
if pl1_stat(pl_count, 2) == 12 or pl1_stat(pl_count, 3) == 22 or pl1_stat(pl_count, 3) == 32:
print ("Player wins!")
break
if pl_count >= 5:
print ("Draw!")
break
print (print_board(board))
|
795029abbdb3d8341d34c9b42dcbc8da633424b7 | ashutoshkarna03/movie_recommender | /movie_recommender_using_correlation.py | 2,857 | 3.640625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pprint import pprint
import seaborn as sns
sns.set_style('white')
# load user data
column_names = ['user_id', 'item_id', 'rating', 'timestamp']
user_data = pd.read_csv('data/u.data', sep='\t', names=column_names)
# check the head of df
print('user data frame: ')
pprint(user_data.head())
# read the movie title data and attach this to user data frame in separate column
movie_titles = pd.read_csv('data/Movie_Id_Titles')
print('movie title data frame: ')
pprint(movie_titles.head())
user_data = pd.merge(user_data, movie_titles, on='item_id')
print('user data after adding movie title: ')
pprint(user_data.head())
# lets create another data frame which contains number of ratings and average ratings of each movie
# add mean rating of each movie
ratings = pd.DataFrame(user_data.groupby('title')['rating'].mean())
pprint(ratings.head())
# also add number of ratings
ratings['no_of_ratings'] = pd.DataFrame(user_data.groupby('title')['rating'].count())
pprint(ratings.head())
# visualize movie data
# histogram of no_of_ratings
plt.figure(figsize=(10, 4))
ratings['no_of_ratings'].hist(bins=70)
plt.show()
# histogram of average ratings
plt.figure(figsize=(10, 4))
ratings['rating'].hist(bins=70)
plt.show()
# joint plot of average ratings vs no of ratings
sns.jointplot(x='rating', y='no_of_ratings', data=ratings, alpha=0.5)
plt.show()
# Now let's create a matrix that has the user ids on one access and the movie title on another axis
movie_mat = user_data.pivot_table(index='user_id', columns='title', values='rating')
pprint(movie_mat.head())
# let's try recommendation for movie `Star Wars (1977)`
# let's grab the user's rating for this movie
starwars_user_ratings = movie_mat['Star Wars (1977)']
pprint(starwars_user_ratings.head(10))
# get the movies similar to starwars using co-relation
similar_to_starwars = movie_mat.corrwith(starwars_user_ratings)
corr_starwars = pd.DataFrame(similar_to_starwars, columns=['Correlation'])
corr_starwars.dropna(inplace=True)
pprint(corr_starwars.head())
# let's check the result by sorting Correlation
pprint(corr_starwars.sort_values('Correlation', ascending=False).head(10))
# we find lots of movie having Correlation 1, but the number of ratings would be less than 100, so we need to filter out those also
corr_starwars = corr_starwars.join(ratings['no_of_ratings'])
pprint(corr_starwars.head())
corr_starwars = corr_starwars[corr_starwars['no_of_ratings'] > 100]
pprint(corr_starwars.sort_values('Correlation', ascending=False).head())
recommendation_for_starwars = corr_starwars.sort_values('Correlation', ascending=False).head().index
print('##############################')
pprint(recommendation_for_starwars)
print('##############################')
# similarly recommendation for other movies can also be made
|
2572ca5fdbc4a467ed0b586680a77ba15bfa7bbe | jon450-star/python1 | /venv/lists_and_nat.py | 342 | 3.5 | 4 |
def run():
# squares = []
# for i in range(1,101):
# if i % 3 !=0:
# squares.append(i**2)
#print(squares)
#squares = [i**2 for i in range(1,101) if i%4 != 0]
#print(squares)
squares2 = [i**1 for i in range(1,50000) if i%4==0 and i%6==0 and i%9==0]
print(squares2)
if __name__=="__main__":
run() |
0b048afa948acaf2d6c41b314540380fa15af8b8 | luceinaltis/Algorithms | /HackerRank_Fraudulent_Activicity_Notifications.py | 1,126 | 3.515625 | 4 | def getMedian(count, d):
mid = d // 2
l = 0
r = -1
median = 0
# odd
for idx, val in enumerate(count):
l = r + 1
r += val
if l <= mid and mid <= r:
median = idx
break
if d % 2 == 0:
# even
l = 0
r = -1
for idx, val in enumerate(count):
l = r + 1
r += val
if l <= (mid+1) and (mid+1) <= r:
median += idx
median /= 2
break
return median
def getFraudNotificationCount(n, d, expenditure):
count = [0] * 201
notiCnt = 0
for idx, val in enumerate(expenditure[:-1]):
count[val] += 1
if idx - d >= 0:
count[expenditure[idx - d]] -= 1
if idx + 1 - d >= 0:
median = getMedian(count, d)
if 2*median <= expenditure[idx+1]:
notiCnt += 1
return notiCnt
if __name__ == '__main__':
n, d = list(map(int, input().split()))
expenditure = list(map(int, input().split()))
cnt = getFraudNotificationCount(n, d, expenditure)
print(cnt)
|
0515a70632b79e6cfb31fa8afc62de491e80cd0a | ddarkeh/CodingClub | /challenges/challenge5/Phrkr/clock.py | 1,274 | 4.15625 | 4 | # Import required modules.
import time, re
# User inputs time.
userInput = input("Enter the time (HH:MM:SS): ")
# Loop is repeated if the user input does not match the regex pattern.
while not re.match("(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)", userInput):
print("Error! Please enter the time in the correct format (HH:MM:SS)")
userInput = input("Enter the time (HH:MM:SS): ")
#Splits the user input using ":" as the divider and gives them separate variables so they can be modified.
userHH, userMM, userSS = userInput.split(":")
while True:
if int(userSS) > 59:
userSS = 00 # Changes seconds to 00 when they go above 59
userMM = int(userMM) + 1 # Increases minutes be 1 when seconds rise above 59.
if int(userMM) > 59:
userMM = 00 # Changes minute to 00 when it goes above 59.
userHH = int(userHH) + 1 # Increases hour by 1 when minutes rise above 59.
if int(userHH) > 23:
userHH = 00 # Changes hour to 00 when it rises above 23.
formatTime = str(userHH).zfill(2) + ":" + str(userMM).zfill(2) + ":" + str(userSS).zfill(2) # zfill used to pad leading zero to single digits.
print(formatTime, end='\r') # end='\r' used to replace previous line
userSS = int(userSS) + 1
time.sleep(1)
|
1cf7bac6c5d3032c1c053709f4e5552f52ddf5bd | downy158/codecamp | /section6.py | 980 | 4 | 4 | # 입력값!
original = input("what is your name?")
# 직접 점검하기
original = input("what is your name?")
if len(original) != 0:
print(original)
else:
print("empty")
# 조금 더 점검하기
original = input("what is your name?")
if len(original) != 0 and original.isalpha():
print(original)
else:
print("empty")
# 단어분석
pyg = 'ay'
original = input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
print(original)
else:
print('empty')
# 모음으로 시작하는 단어 번역
pyg = 'ay'
original = input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in {'a','i','e','o','u'}:
new_word = word+pyg
print(new_word)
else:
strlen = len(word)
new_word = word[strlen::-1] # 반대로 출력하기.. 수정
print(new_word)
else:
print('empty')
|
653d53af35c62bbc24475992d12c092f7a1ebc6f | dkhaosanga/class_python_labs_031218 | /numbers.py | 1,361 | 4.375 | 4 | # Integers: Integers are whole numbers,
# Floating numbers are numbers with decimals. Both
# positive and negative numbers
#Arithmetic operators:
# addition +, integers and floats can be mixed and matched
# subtraction -, integers and floats mixed and matched
# multiplication *, mixed and matched, you can mutiply variable with integers
# division /, will always print as a floats
# floor division //, rounds down, takes off everything after the decimal
# modulus operators %, gives you the remainder, helpful to determine even or odds print % 2
# print(20 % 4)
# print(40 % 9)
# Exponents **, print(20 ** 3), cubed
# +=, -=, *= so you don't have to reassign a variable
# number = 10
# number += 5
# print(number) will equal 15
#lab 3 - hammer
# When asking for time with hour and am or pm ask with this: (HH:AM/PM)
# meridan is the AM/PM
time = input("what time is it? ")
time_split = time.split(':') #automatically if you put just () it will be a space
hour = int(time_split[0])
meridian = (time_split[1]) #.lower(), you can put in after input
if hour in range (7,10):
if meridian == 'am':
print("it's breakfast")
else:
print("it's dinner") #taking hours and then if theres any other meridian it will print dinner
elif hour in range (10,12) and meridian == "pm" or (hour == 12 or hour in range (1,5) and meridian == "am"):
|
feafb858caa38a45d5ed7070eb063ed3c1f36c48 | quento/660-Automated | /odd-or-even.py | 663 | 4.28125 | 4 |
def number_checker(num, check):
"Function checks if a number is a multiple of 4 and is odd or even. "
if num % 4 == 0:
print(num, "Is a multiple of 4")
elif num % 2 == 0:
print(num, "Is an even number")
else:
print(num,"You picked an odd number.")
if num % check == 0:
print(num, "divide evenly by", check)
else:
print(num, "does not divide evenly by", check)
def main():
# Get numeric input from user.
num = int(input("Give me a number to check: "))
check = int(input("give me a number to divide by: "))
# Call function to check number.
number_checker()
if __name__ == '__main__': main()
|
b5b15e7102a2806889bf52328a4c5cf3ce4b8192 | gaoyucai/Python_Project | /算法练习/快速排序_练习1.py | 624 | 3.734375 | 4 | # Author:GaoYuCai
def quick_sort_x(data,left,right):
if left < right:
mid=partition(data,left,right)
quick_sort_x(data,left,mid-1)
quick_sort_x(data,mid+1,right)
def partition(data,left,right):
tmp=data[left]
while left < right:
while left < right and data[right] >= tmp:
right-=1
data[left]=data[right]
while left <right and data[left] <= tmp:
left+=1
data[right]= data[left]
data[left]=tmp
return left
def quick_sort(data):
return quick_sort_x(data,0,len(data)-1)
data=[43,7,4,2,0,10,9]
quick_sort(data)
print(data)
|
2d1e81360f51d70f3c4e8fc4d7f1bc8a307ccf46 | michael-act/guessKNTL | /application/kntlquiz.py | 261 | 3.5 | 4 | def mask_word(word):
keyword = 'KENTEL'.replace('E', 'O')
mask_word = list(word[:])
for i in range(6):
if word[i] != keyword[i]:
mask_word[i] = '*'
return ''.join(mask_word)
check_game = lambda real_word, answer: True if real_word == answer else False |
cb131577388aed489ac2ae355728e7542eb8db20 | KojoBoat/Global-code | /my_maths.py | 508 | 4.09375 | 4 | #function that takes arguments
def calculate(operation,num1,num2):
if (operation == 'Add'):
cal = num1 + num2
elif (operation == 'Sub'):
cal = num1-num2
elif (operation == 'Mul' ):
cal = num1 * num2
elif (operation == 'Div'):
cal = num1 / num2
return cal
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = input ("Which operation do you want to perform? \n")
print(calculate(operation,num1,num2))
|
6058ec01c170a5d4a5896820cdb09f09a36b14e8 | tigerjoy/SwayamPython | /old_programs/cw_08_07_20/grade.py | 277 | 4.03125 | 4 | marks = float(input("Enter average marks of the student: "))
if (marks>=90):
print("Grade : A")
elif (marks>=80):
print("Grade : B")
elif (marks>=70):
print("Grade : C")
elif (marks>=60):
print("Grade : D")
elif (marks>=50):
print("Grade : E")
else:
print("Fail")
|
83f8c807a583722b686599c3e8e338ec36c1e658 | hbrinkhuis/HTBR.AoC2020 | /day1.py | 860 | 3.703125 | 4 | import stdfuns
values = stdfuns.open_file_lines('day1.txt')
# convert to int
intvalues = sorted(list(map(lambda x: int(x), values)))
print('calculating part 1...')
found = False
for x in intvalues:
for y in intvalues[::-1]:
if x + y == 2020:
print('found pair!', x, y)
print('answer is:', x * y)
found = True
break
if x + y < 2020:
break
if found:
break
print('calculating part 2...')
found = False
for i, x in enumerate(intvalues):
for y in intvalues[i::]:
for z in intvalues[::-1]:
if x + y + z == 2020:
print('found triplet!', x, y, z)
print('answer is:', x * y * z)
found = True
if z <= y:
break
if found:
break
if found:
break
|
7ea458effebdb3f798ceecdb220b9ff6912ec405 | Lumiras/Treehouse-Python-Scripts | /Beginning_python/object_oriented/game.py | 3,319 | 3.625 | 4 | import sys
from character import Character
from monster import Dragon
from monster import Troll
from monster import Goblin
class Game:
def setup(self):
self.player = Character()
self.monsters = [
Goblin(),
Troll(),
Dragon()
]
self.monster = self.get_next_monster()
def get_next_monster(self):
try:
return self.monsters.pop(0)
except IndexError:
return None
def monster_turn(self):
#see if monster attacks
if self.monster.attack():
#if so, tell player
print("The {} attacks!".format(self.monster))
#check if player wants to dodge
trydodge = input("Do you want to try to dodge? Y/N").lower()
#if so, see if dodge suceeds
if trydodge == 'y':
if self.player.dodge():
#if so, move on.org
print("you dodged the monster!")
#if not, -1 hp
else:
print("You got hit!")
self.player.hp -= 1
else:
print("{} hit you for 1 point!".format(self.monster))
self.player.hp -= 1
#if monster does not attack, tell player
else:
print("The {} misses! You're lucky!".format(self.monster))
def player_turn(self):
#let player attack, rest, or quit
choice = input("Do you want to [A]ttack, [R]est, or [Q]uit?").lower()
#if attack
if choice == 'a':
print("You attack the {}".format(self.monster))
#see if attack succeeds
if self.player.attack():
#if so, see if monster dodges
if self.monster.dodge():
#if dodged, print that
print("The monster dodged your attack!")
#if not dodged, subtract HP from monster
else:
print("You hit the {}!".format(self.monster))
self.monster.hp -= 1
#if attack fails, tell player
else:
print("your attack failed!")
#if rest
elif choice == 'r':
self.player.rest()
#if quit
elif choice == 'q':
sys.exit()
else:
#run this method again
print("That's not a valid option")
self.player_turn()
def cleanup(self):
if self.monster.hp <= 0:
#add exp to player
self.player.exp += self.monster.exp
#print congrats message
print("Congratulations! You slayed the monster!")
#get new monster
self.player.levelup()
self.monster = self.get_next_monster()
def __init__(self):
self.setup()
while self.player.hp and (self.monster or self.monsters):
print('\n' + '='*20)
print (self.player)
self.monster_turn()
print('-'*20)
self.player_turn()
print('-'*20)
self.cleanup()
print('\n' + '='*20)
if self.player.hp:
print("You win!")
elif self.monsters or self.monster:
print("You lose!")
sys.exit()
Game()
|
b411a0821028415683a92b5e3417f7dcb618ff0d | Avani1992/database_pytest | /xml_depth.py | 563 | 3.875 | 4 | import xml.etree.ElementTree as etree
maxdepth = 0
d = dict()
def depth(elem, level):
global maxdepth
print(type(elem))
print(level)
# if (elem in d):
# d[elem] = d[elem] + maxdepth
# else:
# d[elem] = maxdepth
#
# print(max(d.values()))
# your code goes here
if __name__ == '__main__':
n = int(input())
xml = ""
for i in range(n):
xml = xml + input() + "\n"
tree = etree.ElementTree(etree.fromstring(xml))
depth(tree.getroot(), -1)
print(maxdepth) |
821a24ca71f30f9743edb2684da71a1279f577f5 | danhhoainam/algo_expert | /python/easy/prob_015_ceasar_encrypt/solution.py | 188 | 3.734375 | 4 | def ceasar_encrypt(str, key):
result = ""
for char in str:
new_pos = (ord(char) + key - 97) % 26 + 97
result += chr(new_pos)
return result
print(ceasar_encrypt("abcxyz", 3)) |
55f48aff0bc258783bf6e1cf91b4668bf5e7b3de | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/scott_bromley/lesson03/strformat_lab.py | 2,725 | 4.40625 | 4 | #!/usr/bin/env python3
# string formatting exercises
def main():
print(task_one())
print(task_two())
print(formatter((2, 3, 5, 7, 9))) #task three
print(task_four())
task_five()
task_six()
def task_one(file_tuple=None):
'''
given a tuple, produce a specific string using string formatting
:return: formatted string
'''
if file_tuple is None:
file_tuple = (2, 123.4567, 10000, 12345.67)
return "file_{:03d} : {:.2f}, {:.2e}, {:.2e}".format(file_tuple[0], file_tuple[1], file_tuple[2], file_tuple[3])
def task_two(file_tuple=None):
'''
given a tuple, produce a specific string using string formatting
:return: f-string
'''
if file_tuple is None:
file_tuple = (2, 123.4567, 10000, 12345.67)
return f"file_{file_tuple[0]:03} : {file_tuple[1]:{8}.{5}}, {file_tuple[2]:.2e}, {file_tuple[3]:.2e}"
def formatter(in_tuple):
'''
dynamically build format string to reflect tuple size in output
:return: formatted string
'''
l = len(in_tuple)
# return ("the {} numbers are: " + ", ".join(["{}"] * l)).format(l, *in_tuple)
return f"the {l} numbers are: {', '.join(str(num) for num in in_tuple)}"
def task_four(file_tuple=None):
'''
use index numbers from tuple to specify positions in print formatting
:return: f-string
'''
if file_tuple is None:
file_tuple = (4, 30, 2017, 2, 27)
return f"{file_tuple[3]:02} {file_tuple[4]} {file_tuple[2]} {file_tuple[0]:02} {file_tuple[1]}"
def task_five():
'''
create f-string that displays "The weight of an orange is 1.3 and the weight of a lemon is 1.1" from a provided list
:return: None
'''
fruit_weight = ['oranges', 1.3, 'lemons', 1.1]
print(f"The weight of an {fruit_weight[0][:-1]} is {fruit_weight[1]} and the weight of a {fruit_weight[2][:-1]} is {fruit_weight[3]}")
print(f"The weight of an {fruit_weight[0][:-1].upper()} is {fruit_weight[1] * 1.2} and the weight of a {fruit_weight[2][:-1].upper()} is {fruit_weight[3] * 1.2}")
return None
def task_six():
'''
print a table of several rows, each with a name, an age and a cost
:return: None
'''
scotch = ["Glenmorangie", "Balvenie Single Malt", "Macallan Lalique", "Glenfiddich", "Ardbeg"]
ages = ["18 years", "50 years", "62 years", "30 years", "10 years"]
price = ["$130.00", "$50,000.00", "$47,285.00", "$799.00", "$90.00"]
print(f"SCOTCH:{'':<30}AGE:{'':<20}PRICE:{'':>20}")
for scotch, age, price in zip(scotch, ages, price):
print(f"{scotch:<30}{age:^20}{price:>17}")
return None
if __name__ == "__main__":
print("Running", __file__)
main()
else:
print("Running %s as imported module", __file__) |
ab99cf2567191e956391213f4d7809914c286335 | williammarino/learn_python | /ex33.py | 682 | 4.15625 | 4 | import sys
#i = 0
#numbers = []
#while i < 6:
# print "At the top i is %d" % i
# numbers.append(i)
#
# i += 1
# print "Numbers now:", numbers
# print "At the bottom i is %d" % i
#print "The Numbers: "
#
#for num in numbers:
# print num
def number_range(maxn, step):
f = 0
numbers = []
while f < maxn:
print "At the top f is %d" % f
numbers.append(f)
f += step
print "Numbers are now:", numbers
print "At the bottom f is %d" % f
def number_range_using_for(max, step):
#elements = range(0, max, step)
for item in elements:
print "Item: %d" % item
print elements
#number_range(10,2)
number_range_using_for(24,2)
if __name__ == "__main__":
print sys.argv |
78648a5e0080ca19fcdac1cf25dbdfbe4be28409 | liugingko/LeetCode-Python | /Leetcode/LeetCode2/868. Transpose Matrix.py | 410 | 3.53125 | 4 | # @Time :2018/7/9
# @Author :LiuYinxing
class Solution:
def transpose(self, A):
A[::] = zip(*A)
return A
def transpose1(self, A):
if len(A) == 0: return []
r, c = len(A), len(A[0])
return [[A[i][j] for i in range(r)] for j in range(c)]
if __name__ == '__main__':
solu = Solution()
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(solu.transpose(A)) |
6aa27ba37311b9ce0b9c80c8c5cef214ec4c2ea8 | lucasboscatti/algorithms_numeric_calculus | /met_bissecao.py | 720 | 3.609375 | 4 | import math
def f(x):
# Solve the equation
y = 3*x - math.cos(x) # Escreva aqui a função
return y
a0 = 0 # Intervalo inicial
b0 = 1 # Intervalo final
erro = 0.01 # 𝜀 > 0 (precisão);
if f(a0) * f(b0) < 0:
stop = False
x0 = (a0 +b0)/2
i = 0
while stop == False:
if f(a0) * f(x0) < 0:
a0 = a0
b0 = x0
else:
a0 = x0
b0 = b0
x1 = (a0 +b0)/2
if abs(x1 - x0) < erro:
stop = True
print(f'x = {x1}, com iterations = {i+2} e erro relativo menor que 𝜀 = {erro}')
else:
x0 = x1
i += 1
|
901a8ecd76bff0c19cb34d13c8a9430dae7d35f4 | wing1king/python_xuexi | /阶段1-Python核心编程/06-文件操作/hm_10_批量重命名.py | 578 | 3.890625 | 4 | # 需求1: 把code文件所有的文件重命名 python_xxxx
# 需求2: 删除python_ 重命名: 1.构造条件的数据 2.书写if
import os
# 构造条件的数据
flag = 2
# 1. 找到所有文件: 获取code文件夹的目录列表 -- listdir()
file_list = os.listdir()
# 2. 构造名字
for i in file_list:
if flag == 1:
# new_name = 'python_' + 原文件i
new_name = 'py_' + i
print(new_name)
elif flag == 2:
# 删除前缀
num = len('hm_')
new_name = i[num:]
# 3. 重命名
os.rename(i, new_name) |
f02e79f8961ae22791e6497e1019c95f85b51ce7 | vqpv/stepik-course-58852 | /4 Условный оператор/4.3 Вложенные и каскадные условия/6.py | 384 | 4.09375 | 4 | num1 = int(input())
num2 = int(input())
char_inp = input()
if char_inp == "+":
print(num1 + num2)
elif char_inp == "-":
print(num1 - num2)
elif char_inp == "*":
print(num1 * num2)
elif char_inp == "/":
if num2 != 0:
print(num1 / num2)
else:
print("На ноль делить нельзя!")
else:
print("Неверная операция")
|
47fc90b26730db94d9edfea8d50f32ee50a06b82 | jonataseo/PythonStudys | /chapter12/ch3.py | 264 | 3.828125 | 4 | class Triangle:
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return (self.base * self.height) / 2
if __name__ == "__main__":
triangle = Triangle(5, 3)
print(triangle.area()) |
67729cea4245d9cae418e88ce8767a144b2c4eb6 | alu-rwa-prog-1/final_project_part1-serge-pacifique | /item.py | 346 | 3.921875 | 4 | # Creating a class
class Item:
""" This is a Item class with its characteristics
"""
def __init__(self, title="", genre="", no_item=0, donor_name="", selling_price=0):
self.title = title
self.genre = genre
self.no_item = no_item
self.donor_name = donor_name
self.selling_price = selling_price
|
e00c042569d0e233ac35b1551581365eaf049d91 | yaroslavche/python_learn | /3 week/3.2.7.py | 1,161 | 3.796875 | 4 | # Напишите программу, которая считывает строку с числом n, которое задаёт количество чисел, которые нужно считать.
# Далее считывает n строк с числами Xi, по одному числу в каждой строке. Итого будет n+1 строк.
# При считывании числа Xi программа должна на отдельной строке вывести значение f(Xi). Функция f(x) уже реализована и
# доступна для вызова.
# Функция вычисляется достаточно долго и зависит только от переданного аргумента x. Для того, чтобы уложиться в
# ограничение по времени, нужно избежать повторного вычисления значений.
# Sample Input:
# 5
# 5
# 12
# 9
# 20
# 12
# Sample Output:
# 11
# 41
# 47
# 61
# 41
n = int(input())
s = {}
for i in range(n):
x = int(input())
if x not in s:
s[x] = f(x)
print(s[x])
|
e7d197977b3f45a1dfc7af83039e6b6e01b95d83 | Yigang0622/LeetCode | /first_unique_char.py | 1,192 | 3.5 | 4 | # LeetCode
# first_unique_char
# Created by Yigang Zhou on 2020/7/21.
# Copyright © 2020 Yigang Zhou. All rights reserved.
# 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 - 1。
#
# 示例:
# s = "leetcode"
# 返回
# 0
# s = "loveleetcode"
# 返回
# 2
# 提示:你可以假定该字符串只包含小写字母。
class Solution(object):
occurrence = [0] * 26
exist = [-1] * 26
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return -1
for i in range(len(s)):
self.occurrence[self.char_to_index(s[i])] += 1
if self.exist[self.char_to_index(s[i])] == -1:
self.exist[self.char_to_index(s[i])] = i
temp_index = 999
for i in range(len(self.occurrence)):
if self.occurrence[i] == 1 and self.exist[i] < temp_index:
temp_index = self.exist[i]
if temp_index == 999:
return -1
else:
return temp_index
def char_to_index(self, c):
return ord(c) - 97
print(Solution().firstUniqChar("cc"))
|
a93096fbedef8698630b11169efa2da7abbe1ff7 | bannavarapu/Competetive_Programming | /competetive_programming/week1/day3/is_balanced.py | 744 | 3.796875 | 4 | def is_balanced(root):
if root is None:
return True
else:
depths=[]
nodes=[]
nodes.append((root,0))
while len(nodes):
current_node,depth=nodes.pop()
if(current_node.left is None and current_node.right is None):
if depth not in depths:
depths.append(depth)
if(len(depths)>2):
return False
if(len(depths)==2 and abs(depths[0]-depths[1])>1):
return False
if(current_node.left is not None):
nodes.append((current_node.left,depth+1))
if(current_node.right is not None):
nodes.append((current_node.right,depth+1))
|
2fcf0b5c2123b37e06a33bc30af4bfc8637b6dcd | NBESS/Python_102 | /python-exercise6.py | 285 | 4.125 | 4 | # Convert the user's input of temperature in celsius to fahrenheit, and display output
# User's input in celsius
temp_in_c = int(input('Temperature in C? '))
# Convert to fahrenhit
temp_in_f = (temp_in_c * 9/5) + 32
message = f'{temp_in_f} F'
# Output in fahrenheit
print(message) |
a6907751d7ad797b12878b0cedc876bd351d7c49 | rsprenkels/100daysOfPython | /kattis/ostgotska/ostgotska.py | 404 | 3.515625 | 4 | class Ostgotska:
def run(self):
wordlist = input().split()
words_with_ae = 0
for word in wordlist:
if word.find('ae') >= 0:
words_with_ae += 1
if (words_with_ae / len(wordlist)) >= 0.40:
print('dae ae ju traeligt va')
else:
print('haer talar vi rikssvenska')
if __name__ == '__main__':
Ostgotska.run() |
77a376de6fb3edb068843fbebad7f08e4820c9eb | vanstek/daily-kata | /Format a string of names like 'Bart, Lisa & Maggie'.py | 647 | 4.25 | 4 | #Format a string of names like 'Bart, Lisa & Maggie'.
#Level: 6 kyu
'''
Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
'''
def namelist(names):
out = ''
print(names)
if names == []:
return out
for i, val in enumerate(names):
print(val['name'])
if i == (len(names) - 1):
out += (val['name'])
return out
elif i == (len(names) - 2):
out += (val['name'] + ' & ')
else:
out += (val['name'] + ', ')
|
d959a85f3790c015c82f0feb6752dfdd43f8ddee | ZhangLockerberg/Learning-Materials | /DataStructureAlgroithm-master/01_introduction/project_unscramble_cs_problem/submit/01_submit/Task4.py | 1,527 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that
1. make outgoing calls
but never
a.send texts,
b.receive texts
c.receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
outgoingcallset = set([record[0] for record in calls])
receivingcallset = set([record[1] for record in calls])
outgoingtextset = set([record[0] for record in texts])
receivingtextset = set([record[1] for record in texts])
outgoincalllist = list (outgoingcallset)
#print(outgoincalllist)
################
# checking the ruls
# make outgoing calls
# but never
# a.send texts,
# b.receive texts
# c.receive incoming calls.
################
ans = []
for num in outgoincalllist:
if num not in outgoingtextset and num not in receivingtextset and num not in receivingcallset:
ans.append(num)
#print(ans)
#in lexicographic order
ans = sorted(ans)
print('These numbers could be telemarketers:')
for num in ans:
print(num)
|
cdea15d5020e727258ec784e32f0178591b0d5ac | JaySurplus/online_code | /leetcode/python/410_Split_Array_Largest_Sum.py | 1,766 | 3.734375 | 4 | """
410. Split Array Largest Sum
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
Note:
Given m satisfies the following constraint: 1 <= m <= length(nums) <= 14,000.
Examples:
Input:
nums = [7,2,5,10,8]
m = 2
Output:
18
Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.
"""
import heapq
class Solution(object):
def split(self,item ):
s = -item[0]
nums = item[1]
if len(nums) == 1:
return [(-s,nums)]
max_sum = s
l = 0
r = s
for i in range(len(nums)):
if max(l+nums[i],r-nums[i]) < max_sum:
l += nums[i]
r -= nums[i]
max_sum = max(l,r)
else:
return [(-l,nums[:i]),(-r,nums[i:])]
def splitArray(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: int
"""
if len(nums) == 1:
return nums[0]
l = []
heapq.heappush(l,(-sum(nums),nums))
while m > 1:
m -= 1
item = heapq.heappop(l)
res = self.split(item)
if len(res) == 1:
return -res[0][0]
else:
heapq.heappush(l,res[0])
heapq.heappush(l,res[1])
return -heapq.heappop(l)[0]
if __name__ == '__main__':
nums = [7, 2, 5, 10, 8,21,33,32]
m = 4
sol = Solution()
res = sol.splitArray(nums, m)
print("Output:\n%d" % (res))
|
b62b6c87d74db3c0ca1f239c2f3a7ad6e1999dff | danteC94/prueba_comandos | /games_prueba/dama_game.py | 1,626 | 3.5625 | 4 | class DamaGameStart(object):
def __init__(self):
super(DamaGameStart, self).__init__()
self.playing = True
self.turn = 'White'
self.board_status = [
['b', ' ', 'b', ' ', 'b', ' ', 'b', ' '],
[' ', 'b', ' ', 'b', ' ', 'b', ' ', 'b'],
['b', ' ', 'b', ' ', 'b', ' ', 'b', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', 'w', ' ', 'w', ' ', 'w', ' ', 'w'],
['w', ' ', 'w', ' ', 'w', ' ', 'w', ' '],
[' ', 'w', ' ', 'w', ' ', 'w', ' ', 'w']]
def play(self, x, y, w, z):
if(
self.turn == 'White' and
self.playing and
self.board_status[x][y] == 'w'
):
self.board_status[x][y] = ' '
self.board_status[w][z] = 'w'
self.turn = 'Black'
elif(
self.turn == 'Black' and
self.playing and
self.board_status[x][y] == 'b'
):
self.board_status[x][y] = ' '
self.board_status[w][z] = 'b'
self.turn = 'White'
@property
def board(self):
result = ''
for x in xrange(0, 8):
for y in xrange(0, 8):
result += self.board_status[x][y]
result += '\n'
return result
# if self.board_status[w - 1][z - 1] == 'b':
# self.board_status[x][y] = ' '
# self.board_status[w - 1][z - 1] = ' '
# self.board_status[w][z] = 'w'
# self.turn = 'Black' |
f749b752874821a237819b83a822e49d8f91ec1f | v-luck/leetcode | /001two_sum.py | 778 | 3.78125 | 4 | class Solution(object):
def twoSum(self, nums, target):
#this list is used for the final return product
list = []
#loop through all numbers in list to run check statement
for index, value in enumerate(nums):
second_value = target - value
#checks for difference value
if second_value in nums:
#checks if the indexes are the same which cancels the operation
if nums.index(second_value) == index:
continue
list.append(index)
list.append(nums.index(second_value))
break
return list
# This is a test object to run the class
dog = Solution()
print(dog.twoSum([-3, 4, 3, 90], 0))
|
7778aa604fbd7cb8f0d0202b267bc46dd3c90b0e | Zjx01/IBI1_2018-19 | /Practicum7/game of 24.py | 4,020 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 2 23:06:54 2019
@author: Jessi
"""
from fractions import Fraction
n=input("please input the number to compute 24(use ',' to divide them):" )
a=n.split(',')#to a a list
bl=[int(i) for i in a]
#b=list(map(int,a))
#we need to judge whether the number we print in is qualified, ranged in(1,24)
for i in bl:
if i in range(1,24):
i==i
else:
break
print("the number should range from 1 to 24")
count = 0 #to store the recursion times
#n is len(bl)
def dfs(n):
global count
count = count +1
if n == 1:
if(float(bl[0])==24):
return 1#to judge whether the final calculating result is equal to 24
else:
return 0
#select two different numbers
for i in range(0,n):#select the random 2 numbers to do the calculation
for j in range(i+1,n):#eg.when i=0
a = bl[i]#a store the first element
b = bl[j]#from the rest, eg.b store the second element
bl[j] = bl[n-1]#replace the second with the value of the final element
bl[i] = a+b
if(dfs(n-1)==1):#it call the function again, and this time the final element is reduced because of the reduced length,which prevent the repetitiness
return 1#at every step it have 4 operation(+-*/),if the operators choosen can not achieve the goal it goes back to the former step and rechoose an operator,and so on
bl[i] = a-b
if(dfs(n-1)==1):
return 1
bl[i] = b-a
if(dfs(n-1)==1):
return 1
bl[i] = a*b
if(dfs(n-1)==1):
return 1
if a>=1:#the number divisor can not be 0
#floats are not precise
bl[i] = Fraction(b,a)
if(dfs(n-1)==1):
return 1
if b>=1:
bl[i] = Fraction(a,b)
if(dfs(n-1)==1):
return 1
#Backtracking
bl[i] = a
bl[j] = b#if the number you choose can not succeed, get back and change
return 0
if (dfs(len(bl))):
print('Yes')
else:
print('No')
print('Recursion times:',count)
"""
#to choose 2 numbers from the array and choose (+-*/)
#do the binary calculation of the two numbers
#Change list: remove the two Numbers in this array and put the calculatuon result into the list
#the new list will also undergo the former procedure
n=input("please input the number to compute 24(use ',' to divide them):" )
a=n.split(',')#
b=[int(i) for i in a]
#b=list(map(int,a))
#we need to judge whether the number we print in is qualified, ranged in(1,24)
for i in b:
if i in range(1,24):
i==i
else:
break
print("the number should range from 1 to 24")
import itertools
c=b[:]
recursion=0
def function(c):#change the function
l=itertools.combinations(c,2)
#to obtain all the combinations types of the chosen number
c=b[:]
s=list(l)
for elem in s:#the number in one combinition
d=[elem[0]+elem[1],elem[0]-elem[1],elem[0]*elem[1],elem[0]/elem[1],elem[1]-elem[0],elem[1]/elem[0]]
print ('the deposition with the chosen two number',d)
c.remove(elem[0])
c.remove(elem[1])
s.remove(elem)
#we need to pay attention to the a=0
for i in range(len(d)):
c.append(d[i])
if len(c)==1:hen there is only one number left, use a large loop to determine if the last value is equal to 24
print(c[0]==24)
recursion+=1
function(c)
function(c)
print('recursion=',recursion)
"""
|
f9664c0f7f2939908af3768e34d6c3c55a8c1e45 | wangleiliugang/data | /aid1805/Process/day03/queue0.py | 562 | 3.84375 | 4 | from multiprocessing import Queue
# 创建消息队列对象
q = Queue(3)
# 存放消息
# q.put('hello1')
# q.put('hello2')
# q.put('hello3')
i = 0
while True:
# 判断队列是否满了
if q.full():
print("queue is full!")
break
q.put('hello' + str(i))
i += 1
print("当前队列有%d条消息" % q.qsize())
for i in range(q.qsize()):
print("获取消息内容为:%s" % q.get())
print(" Queue is empty?", q.empty())
# print(q.get(False)) # 表示不阻塞
# print(q.get(True,3)) # 表示超时等待时间为3秒
|
8ad46835081260cf70dcb1d410a4ef92575c27b1 | mernst32/Py-SCSO-Compare | /extract_line_from_files/core.py | 4,912 | 3.890625 | 4 | import os
def search_file(filename, query, copy=False):
"""
Searches file for the given query.
:param filename: the name of the file to be searched
:param query: the query to search for
:param copy: whether the first line of the file should be added to the found lines
:return: a list of the found lines, after being sanitized
"""
found = []
with open(filename, 'r', encoding="utf-8") as ifile:
if copy:
line = ifile.readline().replace("//", "", 1)
found.append(line.strip())
for line in ifile:
i = line.find(query)
if i is not -1:
line = line[i:]
chars = ":;,()\"{}<>"
tags = ["</a>", "<br/>", "<br>", "</pre>", "<pre>"]
for tag in tags:
line = line.replace(tag, "")
for char in chars:
line = line.replace(char, "")
line = line.strip()
j = line.find(" ")
if j is not -1:
line = line[:j]
found.append(line)
return found
def scan_file(file, query, copy=False, out="", verbose=False):
"""
Scans one file for the given query and save the found lines.
:param file: the file to be scanned
:param query: then query to be searched for
:param copy: whether the first line of the file should be added
:param out: Where to save the gotten lines
:param verbose: print more data
"""
if len(out) == 0:
if copy:
print("SC_Filepath,\"First Line\",Stackoverflow_Links")
else:
print("SC_Filepath,Stackoverflow_Links")
result = search_file(file, query, copy)
if len(result) > 0:
if copy:
for res in result[1:]:
print(file + "," + result[0] + "," + "\""
+ res + "\"")
else:
for res in result:
print(file + "," + "\"" + res + "\"")
else:
with open(out, 'w', encoding="utf-8") as ofile:
if verbose:
print("scan: {0}".format(os.path.join(file)))
if copy:
ofile.write("SC_Filepath,\"First Line\",Stackoverflow_Links\n")
else:
ofile.write("SC_Filepath,Stackoverflow_Links\n")
result = search_file(file, query, copy)
if len(result) > 0:
if copy:
for res in result[1:]:
ofile.write(file + "," + result[0] + "," + "\"" + res + "\"\n")
else:
for res in result:
ofile.write(file + "," + "\"" + res + "\"\n")
def scan_dirs(rootdir, query, copy=False, out="", verbose=False):
"""
Scan the files in the qiven rootdir for the query and save the found lines.
:param rootdir: the dir whose files will be scanned
:param query: the query to be searched for
:param copy: whether the first line of the files should be copied
:param out: where to save the gotten lines
:param verbose: print more data
:return:
"""
if len(out) == 0:
if copy:
print("SC_Filepath,\"First Line\",Stackoverflow_Links")
else:
print("SC_Filepath,Stackoverflow_Links")
for subdir, dir, files in os.walk(rootdir):
for file in files:
result = search_file(os.path.join(subdir, file), query, copy)
if len(result) > 0:
if copy:
for res in result[1:]:
print(os.path.join(subdir, file) + "," + result[0] + "," + "\""
+ res + "\"")
else:
for res in result:
print(os.path.join(subdir, file) + "," + "\"" + res + "\"")
else:
with open(out, 'w', encoding="utf-8") as ofile:
if copy:
ofile.write("SC_Filepath,\"First Line\",Stackoverflow_Links\n")
else:
ofile.write("SC_Filepath,Stackoverflow_Links\n")
for subdir, dir, files in os.walk(rootdir):
for file in files:
if verbose:
print("scan: {0}".format(os.path.join(subdir, file)))
delimeter = ','
result = search_file(os.path.join(subdir, file), query, copy)
if len(result) > 0:
if copy:
for res in result[1:]:
ofile.write(os.path.join(subdir, file) + "," + result[0] + "," + "\"" + res + "\"\n")
else:
for res in result:
ofile.write(os.path.join(subdir, file) + "," + "\"" + res + "\"\n") |
fe5f52dac6738332f45067b148d2c1a791d0d157 | sungillee90/python-exercise | /FromJClass/SquareList.py | 220 | 3.84375 | 4 | def square_list(nums_list):
i = 0
while i < len(nums_list):
nums_list[i] = nums_list[i] *nums_list[i]
i += 1
return nums_list
square_list([1, 2, 3, 4, 5])
print(square_list([1, 2, 3, 4, 5])) |
d4b3eff5ca1a466cfb1d182c6800b9396ddb86c5 | 989709/rpsls | /multiplication_table.py | 261 | 3.5 | 4 | #coding:gbk
"""
Ŀ꣺forǶףʵžų˷
ߣľ
"""
def name(sum):
for i in range(1,10):
for j in range(1,10):
sum=i*j
if i>=j:
print("%sx%s=%s"%(i,j,sum),end=" ")
print()
return name
name(sum)
|
eead24c21fb998bbfbfebc0964080336ac605928 | chyjuls/Computing-in-Python-IV-Objects-Algorithms-GTx-CS1301xIV-Exercises | /Extra_Course_Practice_Problems/practice_problem_16.py | 1,105 | 4.28125 | 4 | #Write a function called count_squares. This function
#should take as input a list of integers, and return as
#output a single integer. The number the function returns
#should be the number of perfect squares it found in the
#list of integers. You may assume every number in the list
#is between 1 and 1 billion (1,000,000,000).
#
#For example:
#
# count_squares([1, 2, 3, 4, 5, 6, 7, 8, 9]) -> 3
# count_squares([1, 4, 9, 16, 25, 36, 49, 64]) -> 8
# count_squares([2, 3, 5, 6, 7, 8, 10, 11]) -> 0
#
#For this problem, 0 is considered a square.
#
#Hint: Don't get caught up trying to "remember" how to
#calculate if a number is a square: we've never done it
#before, but we've covered all the tools you need to do it
#in one of several different ways.
#Write your function here!
#The lines below will test your code. Feel free to modify
#them. If your code is working properly, these will print
#the same output as shown above in the examples.
# print(count_squares([1, 2, 3, 4, 5, 6, 7, 8, 9]))
# print(count_squares([1, 4, 9, 16, 25, 36, 49, 64]))
# print(count_squares([2, 3, 5, 6, 7, 8, 10, 11])) |
74c0c9a189abe8430d5d684ba730f26489348450 | loyy77/python_exercise | /continue.py | 307 | 3.671875 | 4 | ## Filename continue.py
while True:
s=input("请输入一个长度大于3 的单词以计算单词的长度")
if s=="quit":
print("程序退出")
break
elif len(s)<3:
print("这么短的单词你也好意思!")
continue
print("单词长度为%d"%len(s))
|
fd657e06a6152b616773e859320860ad3cd31aea | mwhooker/a-posteriori | /lambda/fixed_point.py | 808 | 3.9375 | 4 |
def factorial(n):
"""
>>> factorial(5)
120
"""
if n == 1:
return n
return n * factorial(n - 1)
lfactorial = lambda n: 1 if n == 0 else n * lfactorial(n - 1)
#print (lambda f: (lambda n: 1 if n == 0 else n * f(n - 1))(f))
#Y = lambda f: f(Y(f))
Y = lambda f: f(lambda x: Y(f)(x))
almost_factorial = lambda f: lambda n: 1 if n == 0 else n * f(n - 1)
factorial = Y(almost_factorial)
print factorial(5)
part_factorial = lambda self, n: 1 if n == 0 else n * self(self, n - 1)
print part_factorial(part_factorial, 5)
part_factorial = lambda self: lambda n: 1 if n == 0 else n * self(self)(n - 1)
factorial = part_factorial(part_factorial)
print factorial(5)
part_factorial = lambda self: lambda n: 1 if n == 0 else n * self(n - 1)(part_factorial)
print part_factorial(5)
|
b221e49b53a2cb74f31188d7cf0055a56728fce9 | Alkhithr/Mary | /think-python/chapter14_files/store_anagrams.py | 1,413 | 3.875 | 4 | # If you download my solution to Example 12-2 from http://thinkpython2.com/code/anagram_sets.py,
# you'll see that it creates a dictionary that maps from a sorted string of letters to the list of words that can be spelled with those letters.
# For example, 'opst' maps to the list ['opts', 'post', 'pots', 'spot', 'stop', 'tops'].
#
# Write a module that imports anagram_sets and provides two new functions:
# store_anagrams should store the anagram dictionary in a “shelf”;
# read_anagrams should look up a word and return a list of its anagrams.
# Solution: http://thinkpython2.com/code/anagram_db.py
from anagram_sets import *
import dbm
import os
import pickle
anagram_db = 'store_anagram'
def store_anagrams(d):
anagrams = return_anagram_sets_in_order(d)
dout = dbm.open(anagram_db, 'n')
for anagram in anagrams:
dout[anagram] = pickle.dumps(anagrams)
return anagrams
def read_anagrams(word):
din = dbm.open(anagram_db, 'r')
return pickle.loads(din[word])
if __name__ == '__main__':
# assert store_anagrams()
# assert read_anagrams()
if os.path.exists(anagram_db):
os.remove(anagram_db)
d = dict()
d['opts'] = ['opts', 'post', 'pots', 'spot', 'stop', 'tops']
stored_anagrams = store_anagrams(d)
print(stored_anagrams)
print('opts', read_anagrams('opts'))
print(read_anagrams('post'))
print(read_anagrams('tops'))
|
86586b66875e7ae2f81cb7c3b7a14758f0af1ecd | fwparkercode/IntroProgrammingNotes | /Notes/Spring2019/snowD.py | 2,090 | 3.625 | 4 | """
Pygame base template
by Aaron Lee 2019
"""
import random
import pygame
pygame.init() # do not put anything pygame above this line
# Define some colors (red, green, blue)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BROWN = (150, 100, 50)
screen_width = 700
screen_height = 500
size = (screen_width, screen_height) # width, height
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Window Bar Name")
done = False # condition for my game loop
clock = pygame.time.Clock() # Used to manage how fast the screen updates
snow_list = []
for i in range(500):
x = random.randrange(screen_width)
y = random.randrange(screen_height)
speed = random.randrange(1, 5)
snow_list.append([x, y, speed])
print(snow_list)
depth = 0
def draw_tree(x, y):
pygame.draw.rect(screen, BROWN, [60 + x, 400 -230 + y, 30, 45])
pygame.draw.polygon(screen, GREEN, [[150 + x, 400 - 230 + y], [75 + x, 250 - 230 + y], [x, 400 - 230 + y]])
pygame.draw.polygon(screen, GREEN, [[140 + x, 350 - 230 + y], [75 + x, y], [10 + x, 350 - 230 + y]])
# -------- Main Program Loop -----------
while not done:
# --- Main event loop (user inputs)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
# --- Drawing code should go here
screen.fill(BLACK)
for x in range(0, screen_width, 200):
draw_tree(x, 300)
for i in range(len(snow_list)):
snow_list[i][1] += snow_list[i][2]
if snow_list[i][1] > screen_height:
snow_list[i][1] = -7
snow_list[i][0] = random.randrange(screen_width)
depth += 0.01
pygame.draw.ellipse(screen, WHITE, [snow_list[i][0], snow_list[i][1], 2 * snow_list[i][2] , 2 * snow_list[i][2]])
pygame.draw.rect(screen, WHITE, [0, screen_height - depth, screen_width, depth + 1])
pygame.display.flip() # Update the screen with what we've drawn.
clock.tick(60) # frames per second
# Close the window and quit.
pygame.quit()
|
e644de71f4f7c6925fe19c75e1c53477697c6dcc | wangyendt/LeetCode | /Contests/201-300/week 277/2149. Rearrange Array Elements by Sign/Rearrange Array Elements by Sign.py | 616 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: wangye(Wayne)
@license: Apache Licence
@file: Rearrange Array Elements by Sign.py
@time: 2022/01/23
@contact: wang121ye@hotmail.com
@site:
@software: PyCharm
# code is far away from bugs.
"""
from typing import *
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
r1, r2 = [], []
for n in nums:
if n > 0:
r1.append(n)
else:
r2.append(n)
ret = []
for s1, s2 in zip(r1, r2):
ret.append(s1)
ret.append(s2)
return ret
|
a622ea7829a952b29a6aa4d0fb77568f31b95abe | sai-advaith/CompSim-Coursework | /Checkpoint_2/test.py | 1,501 | 3.96875 | 4 | import numpy as np
from radioactive import Radioactive
if __name__ == "__main__":
"""
Main method
"""
N = int(input("number of the Iodine-128: "))
if (N<=0):
raise ValueError("Negative or zero atoms is not appropriate") #exception handling for negative or zero atoms
decay_constant = float(input("decay constant: "))
if (decay_constant <= 0):
raise ValueError("Not possible") #negative decay constants
t_step = float(input("timestep: "))
if (t_step <= 0):
raise ValueError("Inappropriate value of timestep") #negative timestep will result in negative half life which makes no sense
matrix = [[0 for _ in range(N)] for _ in range(N)] # matrix with undecayed atoms of size N*N, 0 => Undecayed 1 => Decayed
iodine = Radioactive(decay_constant,matrix,t_step) #creating iodine object
half = np.log(2) / decay_constant # half life of the element based on its decay constant
k = iodine.decay() # this will decay the atom and store its simulated half life in a variable
print(str(iodine)) # printing the visualization of the atom
print("Initial number of undecayed nuclei: ", N*N,"\n") # number of inital undecayed nuclei
print("Final number of undecayed nuclei: ",N*N - iodine.decayed(),"\n") # final number of undecayed nuclei
print("Simulation value of half-life: ",k,"\n") # printing the returned value of decay()
print("Actual value of half-life: ",half,"\n") # previously calculatedls
|
d0c59c48e95c2a34883002aa53e70115414a56a2 | MaciejAZak/Credit_Calculator | /Problems/Lucky 7/task.py | 120 | 3.765625 | 4 | n = int(input())
for n in range(1, n + 1):
number = int(input())
if number % 7 == 0:
print(number ** 2) |
6ddac7d6624ef361a8a68aed522d337979bf4327 | arindammangal19/Tkinter_Framework_Module | /tkinter_Student_Detail_Application.py | 1,147 | 3.703125 | 4 |
from tkinter import *;
from tkinter import messagebox;
tk = Tk();
tk.geometry("1600x900");
tk.title("GUI3");
tk['bg'] = 'red';
obj_frame = Frame(tk, width=900, height=400);
obj_frame.place(x=200, y=200);
obj_label = Label(text="Student Detail Application", font=("arial", 20, "bold")).place(x=600, y=50);
obj_label = Label(obj_frame, text="Name :", font=("arial", 14, "underline")).place(x=100, y=50);
obj_entry = Entry(obj_frame).place(x=250, y=50);
obj_label = Label(obj_frame, text="Stream :", font=("arial", 14, "underline")).place(x=100, y=100);
obj_entry = Entry(obj_frame).place(x=250, y=100);
obj_label = Label(obj_frame, text="Age :", font=("arial", 14, "underline")).place(x=100, y=150);
obj_entry = Entry(obj_frame).place(x=250, y=150);
obj_label = Label(obj_frame, text="Contact no. :", font=("arial", 14, "underline")).place(x=100, y=200);
obj_entry = Entry(obj_frame).place(x=250, y=200);
def btn():
messagebox.showinfo(title="Login Credential Status: ", message="Data saved successfully");
obj_btn = Button(obj_frame, text="Submit", font=("arial", 14, "bold"), command=btn).place(x=450, y=300);
mainloop();
|
9406a1cdb0fdf9e0ed499fad11a88b1b2c2b2cc4 | yashvirsurana/INF2A-NaturalLanguageProcessing | /Inf2a-2/pos_tagging.py | 2,978 | 3.640625 | 4 | # File: pos_tagging.py
# Template file for Informatics 2A Assignment 2:
# 'A Natural Language Query System in Python/NLTK'
# John Longley, November 2012
# Revised November 2013 and November 2014 with help from Nikolay Bogoychev
# PART B: POS tagging
from statements import *
# The tagset we shall use is:
# P A Ns Np Is Ip Ts Tp BEs BEp DOs DOp AR AND WHO WHICH ?
# Tags for words playing a special role in the grammar:
function_words_tags = [('a','AR'), ('an','AR'), ('and','AND'),
('is','BEs'), ('are','BEp'), ('does','DOs'), ('do','DOp'),
('who','WHO'), ('which','WHICH'), ('Who','WHO'), ('Which','WHICH'), ('?','?')]
# upper or lowercase tolerated at start of question.
function_words = [p[0] for p in function_words_tags]
# English nouns with identical plural forms (list courtesy of Wikipedia):
unchanging_plurals = ['bison','buffalo','deer','fish','moose','pike','plankton',
'salmon','sheep','swine','trout']
def noun_stem (s):
"""extracts the stem from a plural noun, or returns empty string"""
# add code here
if (s in unchanging_plurals):
return s
if (s.endswith('men')):
return s[:-2] + 'an'
else:
return verb_stem(s)
def tag_word (lx,wd):
"""returns a list of all possible tags for wd relative to lx"""
# add code here
list1 = []
tagz = []
if (wd in lx.getAll('P')):
add(tagz,'P')
if (wd in lx.getAll('A')):
add(tagz,'A')
lexicon_N = lx.getAll('N')
if (wd in lexicon_N):
add(tagz,'Ns')
if (noun_stem (wd) in lexicon_N):
add(tagz,'Np')
lexicon_I = lx.getAll('I')
if (wd in lexicon_I):
add(tagz,'Ip')
if (verb_stem(wd) in lexicon_I):
add(tagz,'Is')
lexicon_T = lx.getAll('T')
if (wd in lexicon_T):
add(tagz,'Tp')
if (verb_stem(wd) in lexicon_T):
add(tagz,'Ts')
#N_singular = noun_stem (wd)
#if (N_singular in lx.getAll('N')):
# add(tagz,'Ns')
#if ((wd in lx.getAll('N')) and not(N_singular in lx.getAll('N'))):
# add(tagz,'Np')
#if (wd in unchanging_plurals):
# add(tagz,'Ns')
# add(tagz,'Np')
#I_singular = verb_stem(wd)
#if (I_singular in lx.getAll('I')):
# add(tagz,'Ip')
#if ((wd in lx.getAll('I')) and not(I_singular in lx.getAll('I'))):
# add(tagz,'Is')
#T_singular = verb_stem(wd)
#if (T_singular in lx.getAll('T')):
# add(tagz,'Tp')
#if ((wd in lx.getAll('T')) and not(I_singular in lx.getAll('T'))):
# add(tagz,'Ts')
for x in function_words_tags:
if (wd == x[0]):
add(tagz, x[1])
return tagz
def tag_words (lx, wds):
"""returns a list of all possible taggings for a list of words"""
if (wds == []):
return [[]]
else:
tag_first = tag_word (lx, wds[0])
tag_rest = tag_words (lx, wds[1:])
return [[fst] + rst for fst in tag_first for rst in tag_rest]
# End of PART B.
|
eeeadcb83649495cea84b4e7a2247355eed8328e | lemirser/MachineLearning | /test.py | 1,610 | 3.90625 | 4 | from functools import reduce
def multiply_by2(li: list) -> list:
return li * 2
def odd_only(li: list) -> list:
return li % 2 != 0
def accumulator(acc: int, item: int) -> int:
return acc + item
my_list = [2, 4, 6, 8]
new_list = [1, 2, 3, 4, 5, 6]
my_set = {i for i in range(0, 10)}
user_info = ["name", "age", "gender"]
user_details = ["dru", 10, "male"]
user_info2 = ["name", "age", "gender"]
user_details2 = [["dru", 10, "male"], ["test", 30, "male"]]
new_det = {}
# map computes the iterable and return the output based on the condition of the given function
# print(list(map(multiply_by2, [1, 2, 3])))
# filter return all the True value based on the condition of the given function
# print(list(filter(odd_only, [1, 2, 3, 4, 5])))
# zip combines iterable into a tuple inside a list
# print(list(zip(my_list, new_list)))
# reduce
# print(reduce(accumulator, my_list, 0))
# list comprehensions
# print([["".join(i + str(item)) for i in "hello"] for item in new_list])
# set comprehension
my_set = {i for i in range(0, 10)}
# print(my_set)
# dictionary comprehension
my_dict = {key: value ** 2 for key, value in enumerate(range(0, 10))}
user = {k: v for k, v in zip(user_info, user_details)}
# print(my_dict)
# print(user)
for index, row in enumerate(user_details2):
for item in user_info2:
new_det[index] = dict(name=row[0], age=row[1], gender=row[2])
print(new_det)
my_dict = {num: num * 2 for num in [1, 2, 3]}
print(my_dict)
some_list = ["a", "b", "c", "b", "d", "m", "n", "n"]
duplicates = {i for i in some_list if some_list.count(i) > 1}
print(duplicates)
|
196d862418320d71609bb3af71e8999f160785aa | black-organisation/python | /mihirfybsc5.py | 109 | 3.84375 | 4 | a=int(input("enter number"))
square=a*a
print(square)
b=int(input("enter number"))
circle=3.14
print(circle)
|
3937b01a10c8a6312aaf5cb21a34f7dbca92996b | alephist/edabit-coding-challenges | /python/accumulating_product.py | 329 | 4.1875 | 4 | """
Accumulating Product
Create a function that takes a list and returns a list of the accumulating product.
https://edabit.com/challenge/iMRN9YGK4mcYja9rY
"""
from itertools import accumulate
from typing import List
def accumulating_product(lst: List[int]) -> List[int]:
return list(accumulate(lst, lambda a, b: a * b))
|
fd48715a1f650c70bace81ed1141d8f269ec0375 | yiyada77/algorithm | /Python/101-isSymmetric.py | 746 | 4 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def recursion(left, right):
if left and not right:
return False
elif not left and right:
return False
elif not left and not right:
return True
else:
return left.val == right.val and recursion(left.left, right.right) and recursion(left.right, right.left)
if not root:
return True
else:
return recursion(root.left, root.right)
|
3fe19d8a0d6b51fe211d18aef83e9c60d84aaa82 | fereidoon/sql | /012_sql.py | 171 | 3.578125 | 4 | import sqlite3
with sqlite3.connect("cars.db") as conn:
c=conn.cursor()
c.execute("SELECT * FROM inventory WHERE make='Ford'")
for r in c.fetchall():
print(r[0],r[1]) |
eb4fae93d7398e0da49044a7a163096482d4891a | EduardoAlbert/python-exercises | /Mundo 1 - Fundamentos/016-021 Utilizando Módulos/ex018.py | 365 | 4.03125 | 4 | from math import radians, sin, cos, tan
ang = float(input('Digite o ângulo que você deseja: '))
sen = sin(radians(ang))
print('O ângulo de {} tem o SENO de {:.2f}'.format(ang, sen))
cos = cos(radians(ang))
print('O ângulo de {} tem o COSSENO de {:.2f}'.format(ang, cos))
tan = tan(radians(ang))
print('O ângulo de {} tem a TANGENTE DE {:.2f}'.format(ang, tan)) |
12f5d01d52d362de09e3a464a55b183c09d62a0d | DavidBitner/Aprendizado-Python | /Curso/ExMundo2/Ex069Break4Dados.py | 1,045 | 3.859375 | 4 | mDezoito = hCadastrados = mVinte = 0
continuar = ' '
while True:
print('-' * 20)
print('CADASTRE UMA PESSOA')
print('-' * 20)
idade = int(input('Digite a idade: '))
sexo = str(input('Digite o sexo [F/M/O]: ')).strip()
print('-' * 20)
if sexo not in 'FfMmOo':
print('Sexo invalido, tente novamente!')
else:
if idade > 18:
mDezoito += 1
if sexo in 'Mm':
hCadastrados += 1
if sexo in 'Ff' and idade < 20:
mVinte += 1
while continuar not in 'SsNn':
continuar = str(input('Deseja continuar? [S/N]: '))
if continuar not in 'SsNn':
print('Opção invalida, tente novamente!')
else:
break
if continuar in 'Nn':
print('\n\n')
break
continuar = ' '
print('====== FIM DO PROGRAMA ======')
print(f'{mDezoito} pessoas tem mais de 18 anos!')
print(f'{hCadastrados} homens foram cadastrados!')
print(f'{mVinte} mulheres tem menos de 20 anos!')
|
ebefd9d3d3d7139e0e40489bb4f3a022ee790c19 | vatasescu-predi-andrei/lab2-Python | /Lab 2 Task 2.3.py | 215 | 4.28125 | 4 | #task2.3
from math import sqrt
a=float(input("Enter the length of side a:"))
b=float(input("Enter the length of side b:"))
h= sqrt(a**2 + b**2)
newh=round(h, 2)
print("The length of the hypotenuse is", newh)
|
f100d44d079197b5b64a9876f05c7db8182188c4 | rishika3/1BM17CS075-PIP | /posneg.py | 123 | 4.0625 | 4 | >>> a=10
>>> if a<0:
print(a,"is negative")
elif a>0:
print(a,"is positive")
else:
print(a,"is zero")
20 is positive
|
d0fc999b22d56a1f49c0f4d490b1dd7c563606d4 | dhrubach/python-code-recipes | /simple_array/e_primes_to_n.py | 629 | 3.875 | 4 | ###################################################
# LeetCode Problem Number : 204
# Difficulty Level : Easy
# URL : https://leetcode.com/problems/count-primes/
###################################################
from typing import List, Union
class PrimeNumber:
def generate_primes(self, n: int) -> Union[int, List[int]]:
primes = []
is_prime = [False, False] + [True] * (n - 1)
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(i * i, n + 1, i):
is_prime[j] = False
return [len(primes), primes]
|
fe7c646d20a080627b042d2bbb8c3189e91ad259 | jasoncg/pytimer | /timer.py | 1,529 | 4.0625 | 4 | #
# jasoncg
# 2015-02-23
#
# timer.py
#
# A simple timer supporting the Python "with" statement
#
import time
class Timer():
"""
Use in a "with" statement:
with timer.Timer():
perform_expensive_calculation()
May also print the current progress:
with timer.Timer() as t:
perform_expensive_calculation_1()
t.print_progress()
perform_expensive_calculation_2()
"""
def __init__(self, name=None, silent=False):
self.silent = silent
if name is not None:
if not self.silent:
print("Start %s" % (name))
name = name+" "
else:
name = ""
self.name = name
def __enter__(self):
self.reset()
return self
def __exit__(self, type, value, traceback):
end = time.time()
if not self.silent:
print("%sTook %s seconds\n" % (self.name, end-self.start))
def reset(self):
# Reset the start to now
self.start = time.time()
self.elapsed = time.time()
def get_progress(self):
# Get the current time elapsed since start
return time.time() - self.start
def print_progress(self, message=None):
if message is None:
message = ""
else:
message = message+" "
print("%s%s%s seconds\n" % (self.name, message, self.get_progress()))
def get_elapsed(self):
# Get the current time elapsed since start
newelapsed = time.time()
e = newelapsed - self.elapsed
self.elapsed = newelapsed
return e
def print_elapsed(self, message=None):
if message is None:
message = ""
else:
message = message+" "
print("%s%s%s seconds\n" % (self.name, message, self.get_elapsed()))
|
0874e53bc5f9eb1b313ea330d78055a737163b58 | Hossamsaad99/Graduation-Project | /Lstm Model/utilities/prediction.py | 1,783 | 3.703125 | 4 | import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
def predict(predictions, y_test, training_data_len, close_df):
"""
Testing the model and validating its predictions
Args:
(np array) predictions - variable to store the result of (model.predict(test_data))
(np array) x_test - reshaped array to test the model with
(np array) y_test - to validate the model on
(int) training_data_len - the number to split the data with into train and test
close_df - a data frame of the close price after resetting the index
Returns:
validation_df - a df contains the predicted prices and the real data
"""
# getting the real prediction values instead of the price change in each prediction....
# reshaping the close_df to be the same shape as the model output
close_df = np.array(close_df).reshape(-1, 1)
# real test data without last value
test_df = np.delete(close_df[training_data_len:, :], -1, 0)
# real test data shifted
test_df_shifted = close_df[training_data_len+1:, :]
# the logic of reversing the data from difference to real
real_data_prediction = predictions + test_df
# Calculate/Get the value of MSE
mse = mean_squared_error(predictions, y_test)
print("MSE value:", mse)
# Calculate/Get the value of MAE
mae = mean_absolute_error(predictions, y_test)
print("MAE value:", mae)
# creating a new df to assign the predictions to its equivalent days and comparing them to the real data
validation_df = pd.DataFrame(real_data_prediction, columns=["predictions"])
validation_df['real data'] = test_df_shifted
print(validation_df)
return validation_df
|
61e5c07636a63148ba104bf249d88e8cc3892e9e | Peterprombutr/githubvscode | /TowerOfHanoi.py | 2,674 | 3.828125 | 4 | import turtle
#Hanoi tower
class Disk(object):
def __init__(self,name="",xpos=0,ypos=0,height=20,width=40):
self.dname = name
self.dxpos = xpos
self.dypos = ypos
self.dheight = height
self.dwidth = width
def showdisk(self):
turtle.lt(90)
turtle.penup()
turtle.goto(self.dxpos,self.dypos)
turtle.pendown()
turtle.rt(90)
for x in range(2):
turtle.fd(self.dwidth/2)
turtle.lt(90)
turtle.fd(self.dheight)
turtle.lt(90)
turtle.fd(self.dwidth/2)
def newpos(self,xpos,ypos):
self.dxpos = xpos
self.dypos = ypos
def cleardisk(self):
turtle.pencolor("WHITE")
self.showdisk()
turtle.pencolor("BLACK")
class Pole(object):
def __init__(self,name="",xpos=0,ypos=0,thick=10,length=100):
self.pname = name
self.stack = []
self.toppos = 0
self.pxpos = xpos
self.pypos = ypos
self.pthick = thick
self.plength = length
def showpole(self):
turtle.lt(90)
turtle.penup()
turtle.goto(self.pxpos,self.pypos)
turtle.pendown()
turtle.rt(90)
for x in range(2):
turtle.fd(self.pthick/2)
turtle.lt(90)
turtle.fd(self.plength)
turtle.lt(90)
turtle.fd(self.pthick/2)
def pushdisk(self,disk):
disk.newpos(self.pxpos,self.toppos)
disk.showdisk()
self.stack.append(disk)
self.toppos += disk.dheight
self.toppos += 1
def popdisk(self):
d = self.stack.pop()
d.cleardisk()
self.toppos -= 1
self.toppos -= d.dheight
return d
class Hanoi(object):
def __init__(self,n=3,start="A",workspace="B",destination="C"):
self.startp = Pole(start,0,0)
self.workspacep = Pole(workspace,150,0)
self.destinationp = Pole(destination,300,0)
self.startp.showpole()
self.workspacep.showpole()
self.destinationp.showpole()
for i in range(n):
self.startp.pushdisk(Disk("d"+str(i),0,i*150,20,(n-i)*30))
def move_disk(self,start,destination):
disk = start.popdisk()
destination.pushdisk(disk)
def move_tower(self,n,s,d,w):
if n == 1:
self.move_disk(s,d)
else:
self.move_tower(n-1,s,w,d)
self.move_disk(s,d)
self.move_tower(n-1,w,d,s)
def solve(self):
self.move_tower(3,self.startp,self.destinationp,self.workspacep)
def main():
Hanoi().solve()
main() |
f085afcc7e04b9a49413c3aee46ca5163fc3ec94 | JuanJMendoza/PythonCrashCourse | /Ch7: User Input and While Loops/pizzaToppings.py | 955 | 3.953125 | 4 | pizza_toppings = "\nHello, what kind of pizza toppings would you like? "
pizza_toppings += "\nWhen you're finished adding toppings type 'quit'. "
active = True
total_toppings = []
while active:
toppings = input(pizza_toppings).title()
if toppings.lower() == 'quit':
active = False
thank_you = "Thank you, we've added "
for topping in range(0, len(total_toppings)):
if(len(total_toppings)>1):
if(topping == len(total_toppings)-1):
thank_you += "and " + total_toppings[topping]
print(thank_you,"to your pizza.")
else:
thank_you += total_toppings[topping] + ", "
else:
print(thank_you,total_toppings[topping],"to your pizza.")
else:
if not (toppings in total_toppings):
total_toppings.append(toppings)
print(f"Added {toppings} to your pizza.")
|
09c8a41eaee8fe65cc23c9f97648e1bda9808911 | afarizap/holbertonschool-higher_level_programming | /0x0A-python-inheritance/10-main.py | 360 | 3.53125 | 4 | #!/usr/bin/python3
Square = __import__('10-square').Square
s = Square(13)
print(s)
print(s.area())
print(issubclass(Square, Rectangle))
try:
s = Square(13)
print(s.size)
except Exception as e:
print("[{}] {}".format(e.__class__.__name__, e))
try:
s = Square("13")
except Exception as e:
print("[{}] {}".format(e.__class__.__name__, e))
|
c034b64ce95b5b989c9a2db2a97ab52f061ebb16 | bopopescu/Python-13 | /Cursos Python/Exercícios Python - Curso em video - Guanabara/Exercício Python #036 - Aprovando Empréstimo.py | 430 | 3.8125 | 4 | casa = float(input('Valor da casa: R$'))
salario = float(input('Salário do comprador: R$'))
anos = float(input('Quantos anos de financiamento? '))
prestacao = casa / (anos * 12)
minimo = salario * 30 / 100
print(f'Para pagar uma casa de R${casa:.2f} em {anos}', end='')
print(f' a pestação será de R${prestacao:.2f}')
if prestacao <= minimo:
print('Empréstico pode se CONCEDIDO!')
else:
print('Empréstimo NEGADO')
|
b8afa6c4d23f909dcaa78333a2bea32e0ec39134 | CheKey30/leetcode | /0153/153.py | 685 | 3.53125 | 4 | ```
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
```
class Solution:
def findMin(self, nums: List[int]) -> int:
min_val = float("inf")
l,r = 0, len(nums)-1
while l<=r:
mid = (l+r)//2
if nums[mid]>nums[r]:
if min_val>nums[l]:
min_val = nums[l]
l = mid+1
else:
if min_val>nums[mid]:
min_val = nums[mid]
r = mid-1
return min_val |
967d2c3f3b04f6d600787ab3361d172390e50400 | bsmedberg/chooseyourown-example | /chooseyourown.py | 7,475 | 4.03125 | 4 | """
An text-only adventure game written in Python.
"""
import random
import time
import textwrap
import re
def p(text):
"""Print `text` with word wrapping. This makes it easier to work with
triple-quoted strings."""
# first remove duplicate whitespace
text = " ".join(text.split())
print textwrap.fill(text)
def doorclang():
p("The door closes behind you as you enter the castle!")
return 4
def magicmirror():
p("""
You touch the magic mirror and are sucked in! Who knows where you'll
end up.
""")
return random.choice([6, 7, 16, 12, 17, 19])
def ogre():
p("""
"Good evening!" says the ogre. "If you want to rescue the prince,
you must answer this riddle: A doctor and a boy were fishing. The
boy was the doctor's son, but the doctor was not the boy's father.
Who was the doctor?"
""")
answer = raw_input("What do you say? ").lower()
if answer.find("mother") == -1 and answer.find("mom") == -1:
p("""
The ogre frowns: "That is not the answer I desire. You may not
pass." The ogre throws you down the grand staircase.
""")
return 14
p("""
The ogre smiles: "Correct! Congratulations, you may pass."
""")
return 20
def lockeddoor9():
print "The East door out of the courtyard is locked!"
return 9
def lockeddoor10():
print "The door West to the courtyard is locked!"
return 10
def wine():
print "You fall asleep after the wine. It'll take a little while to wake up again."
for i in range(10):
time.sleep(1)
print "%i..." % (i,)
print "Maybe don't do that again."
return 16
# A dictionary of rooms in the maze.
#
# Each room has:
# "description": "text to print"
# "paths": [ ("N", "description", nextroom)... ]
# `nextroom` can either be a number (of the next room) or a function which
# is called and returns the next room to go to.
rooms = {
1: {
"description": """The southern door to the castle is ajar.""",
"paths": [
("G", "Go into the castle", doorclang),
],
},
2: {
"description": """
You are at the end of a hallway. There is an outside window
to the West.""",
"paths": [
("N", "Open the door North to the guest bedroom.", 7),
("E", "Go East", 3),
],
},
3: {
"description": "You are in a long dark hallway.",
"paths": [
("E", "Go East", 4),
("W", "Go West", 2),
],
},
4: {
"description": "The castle door is closed. No turning back now!",
"paths": [
("E", "Go East", 5),
("W", "Go West", 3),
],
},
5: {
"description": """You are in a corner hallway. There is a slimy spot
on the floor.""",
"paths": [
("N", "Go North", 10),
("W", "Go West", 4),
],
},
6: {
"description": "You are at the end of a hall with a red magic mirror.",
"paths": [
("T", "Touch the mirror", magicmirror),
("N", "Go North", 11),
],
},
7: {
"description": """You are in the guest bedroom. There is a blue magic
mirror here.""",
"paths": [
("T", "Touch the mirror", magicmirror),
("S", "Go South", 2),
],
},
8: {
"description": """The halls turns here. To the east you can see the
courtyard.""",
"paths": [
("N", "Go North", 13),
("E", "Go East to the courtyard", 9),
],
},
9: {
"description": "You are in the castle courtyard.",
"paths": [
("N", "Go North", 14),
("E", "Go East", lockeddoor9),
("W", "Go West", 8),
],
},
10: {
"description": "You are in the dining room. It's pretty messy.",
"paths": [
("N", "Go North", 15),
("E", "Go East", 11),
("S", "Go South", 5),
("W", "Go West through a door into the courtyard", lockeddoor10),
],
},
11: {
"description": "You are in a service hall near the dining room.",
"paths": [
("S", "Go South", 6),
("W", "Go West", 10),
],
},
12: {
"description": """You are in the princess's bedroom. There is a green
magic mirror.""",
"paths": [
("T", "Touch the mirror", magicmirror),
("E", "Go East out the door", 13),
],
},
13: {
"description": "You are in a hallway near two bedrooms.",
"paths": [
("N", "Go North to the master bedroom", 17),
("W", "Go West to the princess's bedroom", 12),
("S", "Go South down the hall.", 8),
],
},
14: {
"description": "You are in a great hall north of the courtyard.",
"paths": [
("N", "Go North up the grand staircase.", 18),
("S", "Go South to the courtyard.", 9),
],
},
15: {
"description": "You are in the kitchen.",
"paths": [
("E", "Go East to the pantry.", 16),
("S", "Go South to the dining room", 10),
],
},
16: {
"description": "You are in the pantry. There is a purple magic mirror.",
"paths": [
("W", "Drink a bottle of wine", wine),
("T", "Touch the mirror", magicmirror),
("W", "Go West to the kitchen", 15),
],
},
17: {
"description": "You are in the master bedroom. There is an orange magic mirror.",
"paths": [
("T", "Touch the mirror", magicmirror),
("S", "Go South out of the bedroom", 13),
],
},
18: {
"description": """You are at the top of the grand staircase. There is
an ogre blocking the door north to the music room.""",
"paths": [
("O", "Approach the ogre.", ogre),
("E", "Go East along the balcony over the great hall.", 19),
("S", "Go South down the grand staircase.", 14),
],
},
19: {
"description": """You are on the balcony over the grand hallway. There
is a silver magic mirror on the wall.""",
"paths": [
("T", "Touch the mirror", magicmirror),
("W", "Go the top of the grand staircase", 18),
],
},
20: {
"description": """You have found your prince in the music room! May you
live happily ever after. Good luck!""",
},
}
print "You need to rescue your prince! He is somewhere in the castle here."
# Set the starting room
room = 1
while True:
roomdata = rooms[room]
print
p(roomdata['description'])
# if we're at room 20, we're done!
if room == 20:
break
keymap = {}
keys = []
for key, description, nextroom in roomdata["paths"]:
keymap[key] = nextroom
keys.append(key)
print " %s: %s" % (key, description)
print "? ",
while True:
key = raw_input().upper()
if key in keymap:
break
print "Choose %s: " % ("/".join(keys),),
nextroom = keymap[key]
if isinstance(nextroom, int):
room = nextroom
else:
# if nextroom isn't an int, it's a function we call
room = nextroom()
|
ec26e6f6a810363d98453ecb6a29ad3d8a7ac754 | Azureki/LeetCode | /116. Populating Next Right Pointers in Each Node.py | 2,170 | 3.828125 | 4 | # Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if not root:
return
self.solve(root.left, root.right)
def solve(self, left, right):
if not left:
return
left.next = right
self.solve(left.left, left.right)
self.solve(right.left, right.right)
self.solve(left.right, right.left)
class Solution2:
# @param root, a tree link node
# @return nothing
def connect(self, root):
# Level order traversal does not satisfy this problem which calls for only constant extra space
# if root:
# queue = [ root ]
# while queue:
# for i in range(len(queue) - 1):
# queue[i].next = queue[i+1]
#
# newLevel = []
# for node in queue:
# if node.left:
# newLevel.append(node.left)
#
# if node.right:
# newLevel.append(node.right)
#
# queue = newLevel
# O(1) space 2 Pointer solution: https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/37472/A-simple-accepted-solution
# Use the next at parent nodes to thread child nodes at the next level
if root and root.left:
pre = root # Parent node
while pre.left: # child node at the next level
cur = pre
while cur:
cur.left.next = cur.right
if cur.next: # The problem assumes this is a perfect binary tree, no need to check cur.right
cur.right.next = cur.next.left
cur = cur.next
# Finished connecting one level, go to the beginning of next level
pre = pre.left
|
2fbefcdbc42b2f3f0572f2e623716ddb4338539b | PDXDevCampJuly/atifar | /pre_assignment_stuff/sorting.py | 3,547 | 4.4375 | 4 | # Implimentation of various sorting algorithms for our_lists
##########################
def selection_sort(our_list):
"""
Look through the our_list. Find the smallest element. Swap it to the front.
Repeat.
"""
def find_min(in_list):
""" Return the index of the minimum element in the argument."""
smallest = in_list[0]
smallest_index = 0
for i in range(len(in_list)):
if in_list[i] < smallest:
smallest = in_list[i]
smallest_index = i
return smallest_index
for i in range(len(our_list)):
# Find smallest element of unsorted sublist
smallest_index = find_min(our_list[i:])
# Swap smallest item found in unsorted sublist with i-th element
if smallest_index > 0:
our_list[smallest_index + i], our_list[i] = our_list[i], our_list[smallest_index + i]
return our_list
def insertion_sort(our_list):
"""
Insert (via swaps) the next element in the sorted our_list of the previous
elements.
"""
# Traverse list from second element to the end
for i in range(1, len(our_list)):
for j in range(i, 0, -1):
if our_list[j] < our_list[j - 1]:
our_list[j], our_list[j - 1] = our_list[j - 1], our_list[j]
return our_list
def merge_sort(our_list):
"""
Our first recursive algorithm.
"""
# Base case: If input list length is == 1, return it
if len(our_list) == 1:
return our_list
# Make two recursive merge_sort() calls on two ~halves of the list
# Roughly half length of the list
half_length = len(our_list) // 2
left_list = merge_sort(our_list[:half_length])
right_list = merge_sort(our_list[half_length:])
# Merge the two sublists
sorted_list = []
while len(left_list) > 0 and len(right_list) > 0:
if left_list[0] < right_list[0]:
sorted_list.append(left_list.pop(0))
else:
sorted_list.append(right_list.pop(0))
if len(left_list) == 0:
sorted_list += right_list
if len(right_list) == 0:
sorted_list += left_list
return sorted_list
def get_unsorted_list(test_file):
"""
:param test_file: string
:return: list of items to sort
"""
unsorted_list = []
with open(test_file, "r") as f:
file_contents_list = f.readline().strip("[]").split(",")
return(list(map(eval, file_contents_list)))
# Test files of lists to sort
test_files = [
'char10.txt',
# 'char100.txt',
# 'char1000.txt',
'float10.txt',
# 'float100.txt',
# 'float1000.txt',
'int10.txt',
# 'int100.txt',
# 'int1000.txt',
]
# Path prefix to test files
prefix = "./lists_to_sort/"
for test_file in test_files:
unsorted_list = get_unsorted_list(prefix + test_file)
# Save original unsorted list
orig_unsorted_list = unsorted_list
print("Unsorted list:", unsorted_list, "\n")
# Run selection sort - will also sort 'unsorted_list'
sorted_list = selection_sort(unsorted_list)
print("Selection sort:", sorted_list)
# Restore 'unsorted_list'
unsorted_list = orig_unsorted_list
# Run insertion sort - will also sort 'unsorted_list'
sorted_list = insertion_sort(unsorted_list)
print("Insertion sort:", sorted_list)
# Restore 'unsorted_list'
unsorted_list = orig_unsorted_list
# Run merge sort - will also sort 'unsorted_list'
sorted_list = merge_sort(unsorted_list)
print("Merge sort:", sorted_list)
print()
|
e3bd5fa86e85fb4cabad89462ee054559fdb409c | jiaquan1/cracking-the-coding-interview-189-python | /Chapter8-recursion-and-dynamic-programming/81triplestep.py | 631 | 3.65625 | 4 | #leetcode 70
import collections
def triple_step(n):
if n<0:
return 0
if n==0:
return 1
else:
memo = collections.defaultdict()
memo[-1]=0
memo[0]=1
memo[1]=1
def helper(n):
if n in memo:
return memo[n]
memo[n]= helper(n-1)+helper(n-2)+helper(n-3)
return memo[n]
helper(n)
return memo[n]
import unittest
class Test(unittest.TestCase):
def test_triple_step(self):
self.assertEqual(triple_step(3), 4)
self.assertEqual(triple_step(7), 44)
if __name__ == "__main__":
unittest.main()
|
19d8f669cb5e6f92f2e968b7143f049d98d06fe4 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2561/61094/310882.py | 167 | 3.703125 | 4 | n = int(input())
while(n>0):
s1 = input()
N = int(s1[0])
if(s1=='3 21'):
print(4)
elif(s=='1 5 6'):
print(5)
else:
print(s) |
38126e157ec0e14aa026e1fc4301b1c6ef47c4a6 | rknyx/algorithms_advanced | /two_sat_np_complete/two_sat.py | 6,075 | 3.703125 | 4 | #python3
# Problem description
# 2SAT problem is special case of n-sat problem and is reduced to linear graph-algorithm
# We should introduce implication for each "or" clause: x || y. The implication is x => y.
# we build implicaitons in form: !x => y which means "if x is zero, y should be one"
# now we build directed graph: each edge corresponds to an implication.
# After than - determine if any strongly connected component (SCC) contains both variable and it's negation
# if such component exists - formula is unsatisfiable. Else - sort SCC in topological order and for each SCC
# assign 1 for variables and 0 for their negations. Solution is ready.
from sys import stdin
import sys
import threading
from collections import deque
import numpy
import warnings
import resource
warnings.filterwarnings("ignore")
sys.setrecursionlimit(10**9) # max depth of recursion
threading.stack_size(2**26)
resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))
EMPTY = -999999999
GLOBAL_DATA = None
GLOBAL_POST_NUMBERS = None
GLOBAL_VISITED = None
GLOBAL_LAST_POST_NUMBER = None
def dfs_recursive(vertex_num):
global GLOBAL_DATA
global GLOBAL_POST_NUMBERS
global GLOBAL_VISITED
global GLOBAL_LAST_POST_NUMBER
GLOBAL_VISITED[vertex_num] = True
for child in (c for c in GLOBAL_DATA[vertex_num] if not GLOBAL_VISITED[c]):
dfs_recursive(child)
GLOBAL_LAST_POST_NUMBER += 1
GLOBAL_POST_NUMBERS[vertex_num] = GLOBAL_LAST_POST_NUMBER
def explore_non_recursive(data, vertex_num, visited):
scc = []
stack = deque([vertex_num])
while len(stack) > 0:
curr = stack.pop()
if visited[curr]:
continue
scc.append(curr)
visited[curr] = True
stack.extend(reversed(data[curr]))
return scc
def bulk_deadress(vertices, base_size):
return [num + 1 if num < base_size else -(num - base_size + 1) for num in vertices]
class Graph:
def __init__(self, size=None):
if size is not None:
self._data = [[] for _ in range(size * 2)]
self._size = size
def _address(self, num):
return num - 1 if num > 0 else abs(num) + self._size - 1
def _bulk_address(self, nums):
return (x - 1 if x > 0 else abs(x) + self._size - 1 for x in nums)
def deaddress(self, num):
return num + 1 if num < self._size else -(num - self._size + 1)
def add_implication(self, source, dest):
minus_addr_source, minus_addr_dest, addr_source, addr_dest = self._bulk_address([-source, -dest, source, dest])
data = self._data
if source != dest:
data[minus_addr_source].append(addr_dest)
data[minus_addr_dest].append(addr_source)
else:
data[minus_addr_source].append(addr_source)
@staticmethod
def reversed_of(other):
graph = Graph()
graph._size = other._size
other_data = other._data
curr_data = [[] for _ in range(len(other_data))]
graph._data = curr_data
for vertex_num in (x for x in range(len(other_data)) if len(other_data[x]) > 0):
neighbors = other_data[vertex_num]
for neighbor in neighbors:
curr_data[neighbor].append(vertex_num)
return graph
def build_topological_paths(self):
global GLOBAL_DATA
global GLOBAL_POST_NUMBERS
global GLOBAL_VISITED
global GLOBAL_LAST_POST_NUMBER
data = self._data
data_len = len(data)
post_numbers = numpy.ndarray(data_len, numpy.int64)
post_numbers.fill(EMPTY)
visited = numpy.zeros(data_len, numpy.bool_)
max_post_number = -1
GLOBAL_DATA = data
GLOBAL_POST_NUMBERS = post_numbers
GLOBAL_VISITED = visited
GLOBAL_LAST_POST_NUMBER = max_post_number
for curr_vertex in range(data_len):
if visited[curr_vertex]:
continue
dfs_recursive(curr_vertex)
vertices_by_post_numbers = numpy.ndarray(len(post_numbers), numpy.int64)
for vertex_number, post_number in enumerate(post_numbers):
vertices_by_post_numbers[post_number] = vertex_number
return reversed(vertices_by_post_numbers)
def process_input(inp):
lines = stdin.readlines() if inp is None else inp.split("\n")
variables_count, clauses_count = map(int, lines[0].split(" "))
graph = Graph(variables_count)
max_vertex = 0
for clause in lines[1:]:
left, right = map(int, clause.split(" "))
graph.add_implication(left, right)
max_vertex = max(max_vertex, abs(left), abs(right))
return graph
def calc_scc(graph):
scc = []
reversed_graph = Graph.reversed_of(graph)
vertices_to_traverse = reversed_graph.build_topological_paths()
visited = numpy.zeros(len(graph._data), numpy.bool_)
for vertex in vertices_to_traverse:
if visited[vertex]:
continue
curr_css = explore_non_recursive(graph._data, vertex, visited)
scc.append(curr_css)
return scc
def calc_satisfaibility(graph):
data_size = len(graph._data)
result = numpy.ndarray(data_size, numpy.int64)
result.fill(EMPTY)
processed_in_other_scc = numpy.zeros(data_size, numpy.bool_)
scc = calc_scc(graph)
for component in scc:
deadressed = bulk_deadress(component, graph._size)
for vertex in deadressed:
index = abs(vertex) - 1
if processed_in_other_scc[index]:
continue
if result[index] == -vertex:
return "UNSATISFIABLE"
result[index] = vertex
for vertex in deadressed:
processed_in_other_scc[abs(vertex) - 1] = True
return result
def main(inp=None):
graph = process_input(inp)
if "UNSATISFIABLE" == graph:
return graph
res = calc_satisfaibility(graph)
if "UNSATISFIABLE" == res:
return res
return "SATISFIABLE\n" + " ".join(map(str, res[res != EMPTY]))
if __name__ == '__main__':
print(main()) |
29b0056b3532ac7d9fde1e7a1b002a938f864fb5 | makkksimka/devil_my_cry | /numbers1.py | 230 | 3.96875 | 4 | a = float(input("Input first number: "))
b = float(input("Input second number: "))
c = float(input("Input third number: "))
d = float(input("Input fourth number: "))
sum1 = a + b
sum2 = c + d
print("{:.2f}".format(sum1 / sum2))
|
e18e01f68e0639f6cafdb4b5485476508759673e | diallog/PY4E | /chapter6/ex1.py | 199 | 4 | 4 | # Create a script that iterates through a string backwards
testString = 'Jefferson City'
strLength = len(testString)
index = -1
while index >= (-1 * strLength):
print(testString[index])
index = index -1
|
2d7923015983ff182d014acb10db560d28a01d26 | dishantsethi1/python-practise | /functions.py | 1,776 | 3.96875 | 4 | from functools import reduce
#def average(a,b):
#return (a+b)/2
#x=average(10,20)
#print(x)
def calc(a,b): #defining a function
x=a+b
y=a-b
z=a*b
q=a/b
return x,y,z,q #as tuple
result=calc(10,5)
#print(result)
#global and local usage
r=1
def display():
r=2
print(r)
print(globals()['r']) #to access global r
#print(r)
t=display
#t() #another way to invoke
#function inside another
def display1(name):
def message():
return "hello "
result=message()+name
return result
#print(display1("dishant"))
#function as parameter
def display2(fun):
return "hello "+fun
def name1():
return "dishant"
#print(display2(name1()))
#lambda
'''l=lambda x:'yes ' if x%2==0 else 'no' #short functions
print(l(10))
c=lambda a,b:a+b
print(c(10,20))'''
lst2=[10,2,44,35,67]
res=list(filter(lambda x:x%2==0,lst2)) #filter
#print(res)
lst3=[2,3,4,5]
res1=list(map(lambda n:n*2,lst3)) # map
#print(res1)
lst4=[5,10,15,20] #reduce using from functools import reduce
res2=reduce(lambda x,y:x+y,lst4)
#print(res2)
#decorator
def decor(fun):
def inner():
result=fun()
return result*2
return inner
def num():
return 5
resu=decor(num) #can also use @decor
#print(resu())
#generators
def customg(x,y):
while x<y:
yield x
x+=1
#custom ranges same as range
res4=customg(4,8)
for i in res4:print(i)
|
ab5ad00248e6508eb2c960bc91700103f93d87b5 | sahasra09/Number-Detective | /NumberDetective.py | 613 | 3.984375 | 4 | import random
print("NUMBER DETECTIVE")
print("Hola! Ready for the challenge?")
ND = random.randint(1, 15)
print("Guess a number from 1 to 15. Lets see if luck favours you!:")
chance = 0
while chance < 5:
guess = int(input("Enter your guess:- "))
if guess == ND:
print("Congratulation YOU WON!!!")
break
if guess < ND:
print("Your guess was too low: Guess a number higher than", guess)
else:
print("Your guess was too high: Guess a number lower than", guess)
chance+=1
if not chance < 5:
print("YOU LOSE!!! The number is", ND) |
5e0dd77d2e34a0551b6327c987270b0ae3187300 | alperenalbay/python-project | /python-görevleri/Covid-19 Risk.py | 445 | 3.8125 | 4 | yaş = (input("75 yaşından ve büyük sigara bağımlısımısınız? : ")).strip().title()
kronik = (input("kronik rahatsızlığınız var mı? : ")).strip().title()
bağışıklık = (input("bağışıklık sitemi zayıf mı? : ")).strip().title()
risk = ((yaş == "Hayır") and (kronik == "Hayır") and (bağışıklık == "Hayır"))
if risk == False :
print("Covid olmanız riskli!")
else:
print("Covid sizin için riskli değil.")
|
4e6175ad7efa6f64b109b55b6c537dcdcafd5edc | james-williams-code/fundamentals | /algorithms/problems/week1/merge_k_sorted_lists/merge_k_requirements.py | 2,178 | 3.78125 | 4 | '''
Merge_K_sorted_arrays
Problem Statement:
This is a popular facebook problem.
Given K sorted arrays arr, of size N each, merge them into a new array res, such that res is a sorted array.
Assume N is very large compared to K. N may not even be known. The arrays could be just sorted streams, for instance, timestamp streams.
All arrays might be sorted in increasing manner or decreasing manner. Sort all of them in the manner they appear in input.
Note:
Repeats are allowed.
Negative numbers and zeros are allowed.
Assume all arrays are sorted in the same order. Preserve that sort order in output.
It is possible to find out the sort order from at least one of the arrays.
Input/Output Format For The Function:
Input Format:
There is only one argument: 2D Integer array arr.
Here, arr[i][j] denotes value at index j of ith input array, 0-based indexing. So, arr is K * N size array.
Output Format:
Return an integer array res, containing all elements from all individual input arrays combined.
Input/Output Format For The Custom Input:
Input Format:
The first line of input should contain an integer K. The second line should contain an integer N, denoting size of each input array.
In next K lines, ith line should contain N space separated integers, denoting content of ith array of K input arrays, where jth element in this ith line is nothing but arr[i][j], i.e. value at index j of ith array, 0-based indexing.
If K = 3, N = 4 and arr = [
[1, 3, 5, 7],
[2, 4, 6, 8],
[0, 9, 10, 11]
], then input should be:
3
4
1 3 5 7
2 4 6 8
0 9 10 11
Output Format:
There will be (N*K) lines of output, where ith line contains an integer res[i], denoting value at index i of res.
Here, res is the result array returned by solution function.
For input K = 3, N = 4 and arr = [
[1, 3, 5, 7],
[2, 4, 6, 8],
[0, 9, 10, 11]
], output will be:
0
1
2
3
4
5
6
7
8
9
10
11
Constraints:
1 <= N <= 500
1 <= K <= 500
-10^6 <= arr[i][j] <= 10^6, for all valid i,j
Sample Test Case:
Sample Input:
K = 3, N = 4
arr[][] = { {1, 3, 5, 7},
{2, 4, 6, 8},
{0, 9, 10, 11}} ;
Sample Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
'''
|
4e01bc1a36c5de49e5dfd2686cb16f35e37d6bca | bishnusilwal/python-files | /7.print_fractional_part_of_real_number.py | 226 | 3.921875 | 4 | #Lab_Excersie_2
#Q.7 Given a positive real number, print its fractional part.
userInput = float(input("Enter a number "))
initialNum = int(userInput)
fractionalPart = userInput - initialNum
print(fractionalPart)
|
62c8298f3e309d19d0e50cd1c505add12fd8e778 | kangli-bionic/algorithms-4 | /binary_tree/in_order_morris.py | 778 | 3.859375 | 4 | def inorderTraversalMorris(self, root: TreeNode) -> List[int]:
'''
Morris-Traversal restructures Graph according to in-Order traversal.
For example the root is always after the most right leaf of the left subtree. -> If you have left -> do that
rekusive in order: easiest
iterative in order: fastest
morris in order: constant space
'''
ret = []
current = root
while current:
if current.left:
pre = current.left
while pre.right:
pre = pre.right
newcurrent = current.left
current.left = None
pre.right = current
current = newcurrent
else:
ret.append(current.val)
current = current.right
return ret
|
84ed9981c3ed50ff37d25aa46443e6a9ff5b5c9c | RachanaCHulikatti/new_part1 | /newone.py | 148 | 3.9375 | 4 |
hieght = int(input("enter the hieght >>:"))
wieght = int(input("enter the wieght >>:"))
BMI = wieght/(hieght*hieght)
print("the BMI is ", BMI)
|
36944a01f3e94076eb477613008a7deb1d4a963e | smyrn/jetbrains_academy | /Credit Calculator/Problems/The logarithmic value/task.py | 179 | 3.75 | 4 | from math import log
value1 = abs(int(input()))
value2 = int(input())
if value2 <= 1:
print(f'{round(log(value1), 2)}')
else:
print(f'{round(log(value1, value2), 2)}')
|
6605bf413f60134e632ea2de851ea894ee7f0fa6 | sam1208318697/Leetcode | /Leetcode_env/2019/6_20/Binary_Tree_Level_Order_Traversal.py | 1,773 | 3.75 | 4 | # 102. 二叉树的层次遍历
# 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
# 例如:
# 给定二叉树: [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# 返回其层次遍历结果:
# [
# [3],
# [9,20],
# [15,7]
# ]
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 此为递归做法
def levelOrder(self, root: TreeNode):
res = []
if not root:
return res
def loop(nodes_list):
nodes = [] # 存放了下次需要遍历的全部节点
cur = [] # 存放了当前一行的所有节点,之后会将这个保存到res中
# 循环遍历当前一排的节点,并依次序生成下一排的节点列表
for node in nodes_list:
cur.append(node.val)
if node.left:
nodes.append(node.left)
if node.right:
nodes.append(node.right)
# 将当前一排的节点保存到最终结果中
res.append(cur)
# 判断是否已经到了最终一排,
if nodes == []:
return
# 递归循环
loop(nodes)
list = []
list.append(root)
loop(list)
return res
root = [3,9,20,0,0,15,7]
nodes =[]
for node in root:
nodes.append(TreeNode(node))
nodes[0].left = nodes[1]
nodes[0].right = nodes[2]
nodes[1].left = nodes[3]
nodes[1].right = nodes[4]
nodes[2].left = nodes[5]
nodes[2].right = nodes[6]
sol = Solution()
print(sol.levelOrder(nodes[0])) |
80d5358947c7509d828a24bba30b31a90de8f778 | Matheus-Nazario/Calculo_em_python | /sabendo_tipos_primitivos_informações_possiveis.py | 958 | 4.03125 | 4 | dados = input("Qual é a informação que vc deseja descobrir o tipo primitivo e as informações possivéis, digite a baixo:\n")
print("\n")
print("\n")
print("O tipo primitivo: ", type(dados))
print("--------------------------------")
print('A informação tem espaço?', dados.isspace())
print("--------------------------------")
print('A informação só tem número?', dados.isnumeric())
print("--------------------------------")
print('A informação só tem alfabeto?', dados.isalpha())
print("--------------------------------")
print('A informação tem alfabeto ou número?', dados.isalnum())
print("--------------------------------")
print('A informação está em letra maíuscula?', dados.isupper())
print("--------------------------------")
print('A informação está em letra minúscula?', dados.islower())
print("--------------------------------")
print('A informação está capitalizada?', dados.istitle()) #maiusculo e minusculo juntos.
|
e533458e95f51527aef084e83c5aa90061e0987f | bigguyG/APIGames | /iss.py | 1,392 | 3.515625 | 4 | import requests
import json
import urllib.parse
import time
address=input('Enter current location:')
#Obtain and print relevant Google Maps API data
google_api='http://maps.googleapis.com/maps/api/geocode/json?'
url=google_api+urllib.parse.urlencode({'address':address})
json_data=requests.get(url).json()
json_status=json_data['status']
print ('API Status: ' + json_status)
#find location type from Google
location_type=json_data['results'][0]['geometry']['location_type']
print ('Location is:',location_type)
# get latitude and longitude parameters
lat=str(json_data['results'][0]['geometry']['location']['lat'])
long=str(json_data['results'][0]['geometry']['location']['lng'])
print ('Latitude:',lat)
print('Longitude:',long)
#Obtain and print relevant ISS data
iss_api = 'http://api.open-notify.org/iss-pass.json?'
iss_url = iss_api+('lat='+lat+'&lon='+long)
iss_data = requests.get(iss_url).json()
#obtain next flyover time and duration
flyover=int(iss_data['response'][0]['risetime'])
duration=int(iss_data['response'][0]['duration'])
print ('Unix timestamp for next risetime of ISS:',flyover)
#print converted data
print('The next time that the ISS will be visible in your region will be:',(time.ctime(flyover)))
print('The ISS will be visible for a total of approximately:',int(duration/60),'minutes and',duration%60,'seconds')
|
2c952fa7f4b5f7f471cac021aaa4f3bb8190995e | jlaw8504/lp3thw | /ex7_sd1.py | 1,318 | 4.125 | 4 | # Print out text, "Mary had a little lamb."
print("Mary had a little lamb.")
# print out text, "Its fleece was white as snow" using format method
print("Its fleece was white as {}.".format('snow'))
# print out text, "And everywhere that Mary went."
print("And everywhere that Mary went.")
# print out "." ten times using multiplication operator
print("." * 10) # what'd that do?
# set end1 variable to the character C
end1 = "C"
# set end2 variable to the character h
end2 = "h"
# set end3 variable to the character e
end3 = "e"
# set end4 variable to the character e
end4 = "e"
# set end5 variable to the character s
end5 = "s"
# set end6 variable to the character e
end6 = "e"
# set end7 variable to the character B
end7 = "B"
# set end8 variable to the character u
end8 = "u"
# set end9 variable to the character r
end9 = "r"
# set end10 variable to the character g
end10 = "g"
# set end11 variable to the character e
end11 = "e"
# set end12 variable to the character r
end12 = "r"
# watch that comma at the end. try removing it to see what happens
# print out concatenation of end1 through end6
# set end character to single space instead of newline
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ')
# print out concatenation of end7 through end 12
print(end7 + end8 + end9 + end10 + end11 + end12)
|
ca22a4d79d84a2d0dbaaf0f6f48104998cfb2307 | rackdon/Pyker | /API Rest/classes/deck_of_cards.py | 955 | 3.515625 | 4 | # coding=utf-8
import random
from card import Card
class Deck_of_cards:
def __init__(self):
self.__number_of_cards = 52
self.current_card = 0
self.faces = ('As', 'Dos', 'Tres', 'Cuatro', 'Cinco', 'Seis', 'Siete',
'Ocho', 'Nueve', 'Diez', 'Jota', 'Reina', 'Rey')
self.suits = ('Corazones', 'Diamantes', 'Tréboles', 'Picas')
self.deck = [Card(self.faces[i % 13], self.suits[i/13]) for i in
range(self.__number_of_cards)]
def shuffle(self):
for position in range(len(self.deck)):
second = random.randrange(self.__number_of_cards)
self.deck[position], self.deck[second] = \
self.deck[second], self.deck[position]
def deal_hand(self):
hand = [self.deal_card() for i in range(2)]
return hand
def deal_card(self):
self.current_card += 1
return self.deck[self.current_card - 1]
|
6dee0f8aff74d29aed5f6384ad958dae27ba3a52 | ALaDyn/Smilei | /validation/easi/__init__.py | 29,631 | 3.609375 | 4 | class Display(object):
"""
Class that contains printing functions with adapted style
"""
def __init__(self):
self.terminal_mode_ = True
# terminal properties for custom display
try:
from os import get_terminal_size
self.term_size_ = get_terminal_size()
except:
self.term_size_ = [0,0];
self.terminal_mode_ = False
# Used in a terminal
if self.terminal_mode_:
self.seperator_length_ = self.term_size_[0];
self.error_header_ = "\033[1;31m"
self.error_footer_ = "\033[0m\n"
self.positive_header_ = "\033[1;32m"
self.positive_footer_ = "\033[0m\n"
self.tab_ = " "
# Not used in a terminal
else:
self.seperator_length_ = 80;
self.error_header_ = ""
self.error_footer_ = ""
self.positive_header_ = ""
self.positive_footer_ = ""
self.tab_ = " "
# Seperator
self.seperator_ = " "
for i in range(self.seperator_length_-1):
self.seperator_ += "-"
def message(self,txt):
print(self.tab_ + txt)
def error(self,txt):
print(self.error_header_ + self.tab_ + txt + self.error_footer_)
def positive(self,txt):
print(self.positive_header_ + self.tab_ + txt + self.positive_footer_)
def seperator(self):
print(self.seperator_)
display = Display()
class SmileiPath(object):
def __init__(self):
from os import environ, path, sep
from inspect import stack
if "self.smilei_path.root" in environ :
self.root = environ["self.smilei_path.root"]+sep
else:
self.root = path.dirname(path.abspath(stack()[0][1]))+sep+".."+sep+".."+sep
self.root = path.abspath(self.root)+sep
self.benchmarks = self.root+"benchmarks"+sep
self.scrips = self.root+"scripts"+sep
self.validation = self.root+"validation"+sep
self.references = self.validation+"references"+sep
self.analyses = self.validation+"analyses"+sep
self.workdirs = self.root+"validation"+sep+"workdirs"+sep
self.SMILEI_TOOLS_W = self.workdirs+"smilei_tables"
self.SMILEI_TOOLS_R = self.root+"smilei_tables"
self.COMPILE_ERRORS = self.workdirs+'compilation_errors'
self.COMPILE_OUT = self.workdirs+'compilation_out'
self.exec_script = 'exec_script.sh'
self.exec_script_output = 'exec_script.out'
self.output_file = 'smilei_exe.out'
class ValidationOptions(object):
def __init__(self, **kwargs):
# Get general parameters from kwargs
self.verbose = kwargs.pop( "verbose" , False )
self.compile_only = kwargs.pop( "compile_only" , False )
self.bench = kwargs.pop( "bench" , "" )
self.omp = kwargs.pop( "omp" , 12 )
self.mpi = kwargs.pop( "mpi" , 4 )
self.nodes = kwargs.pop( "nodes" , 0 )
self.resource_file = kwargs.pop( "resource-file", "" )
self.generate = kwargs.pop( "generate" , False )
self.showdiff = kwargs.pop( "showdiff" , False )
self.nb_restarts = kwargs.pop( "nb_restarts" , 0 )
self.max_time = kwargs.pop( "max_time" , "00:30:00" )
self.compile_mode = kwargs.pop( "compile_mode" , "" )
self.log = kwargs.pop( "log" , "" )
self.partition = kwargs.pop( "partition" , "jollyjumper" )
self.account = kwargs.pop( "account" , "" )
if kwargs:
raise Exception(diplay.error("Unknown options for validation: "+", ".join(kwargs)))
from numpy import array, sum
self.max_time_seconds = sum(array(self.max_time.split(":"),dtype=int)*array([3600,60,1]))
def copy(self):
v = ValidationOptions()
v.__dict__ = self.__dict__.copy()
return v
def loadReference(references_path, bench_name):
import pickle
from sys import exit
try:
try:
with open(references_path + bench_name + ".txt", 'rb') as f:
return pickle.load(f, fix_imports=True, encoding='latin1')
except:
with open(references_path + bench_name + ".txt", 'r') as f:
return pickle.load(f)
except:
display.error("Unable to find the reference data for "+bench_name)
exit(1)
def matchesWithReference(data, expected_data, data_name, precision, error_type="absolute_error"):
from numpy import array, double, abs, unravel_index, argmax, all, flatnonzero, isnan
# ok if exactly equal (including strings or lists of strings)
try:
if expected_data == data:
return True
except:
pass
# If numbers:
try:
double_data = array(double(data), ndmin=1)
if precision is not None:
error = abs( double_data-array(double(expected_data), ndmin=1) )
if error_type == "absolute_error":
pass
elif error_type == "relative_error":
try:
error /= double_data
if isnan( error ).any():
raise
except Exception as e:
display.error( "Error in comparing with reference: division by zero (relative error)" )
return False
else:
print( "Unknown error_type = `"+error_type+"`" )
return False
if type(precision) in [int, float]:
max_error_location = unravel_index(argmax(error), error.shape)
max_error = error[max_error_location]
if max_error < precision:
return True
print("Reference quantity '"+data_name+"' does not match the data (required precision "+str(precision)+")")
print("Max error = "+str(max_error)+" at index "+str(max_error_location))
else:
try:
precision = array(precision)
if (error <= precision).all():
return True
print("Reference quantity '"+data_name+"' does not match the data")
print("Error = ")
print(error)
print("Precision = ")
print(precision)
print("Failure at indices "+", ".join([str(a) for a in flatnonzero(error > precision)]))
except Exception as e:
print( "Error with requested precision (of type %s). Cannot be compared to the data (of type %s)"%(type(precision), type(error)) )
return False
else:
if all(double_data == double(expected_data)):
return True
print("Reference quantity '"+data_name+"' does not match the data")
except Exception as e:
print("Reference quantity '"+data_name+"': unable to compare to data")
print( e )
return False
_dataNotMatching = False
class Validation(object):
def __init__(self, **kwargs):
# Obtain options
self.options = ValidationOptions(**kwargs)
# Find smilei folders
self.smilei_path = SmileiPath()
# Get the current version of Smilei
from os import environ
from subprocess import check_output
self.git_version = check_output( "cd "+self.smilei_path.root+" && echo `git log -n 1 --format=%h`-", shell=True ).decode()[:-1]
if 'CI_COMMIT_BRANCH' in environ:
self.git_version += environ['CI_COMMIT_BRANCH']
else:
self.git_version += check_output("cd "+self.smilei_path.root+" && echo `git rev-parse --abbrev-ref HEAD`", shell=True ).decode()[:-1]
# Get the benchmark-specific resources if specified in a file
from json import load
self.resources = {}
if self.options.resource_file:
with open(self.options.resource_file, 'r') as f:
self.resources = load( f )
if self.options.verbose:
print("Found resource file `"+self.options.resource_file+"` including cases:")
for k in self.resources:
print("\t"+k)
print("")
# Define commands depending on host
from socket import gethostname
from .machines import Machine, MachineLLR, MachinePoincare, MachineRuche, MachineIrene
self.HOSTNAME = gethostname()
if "llrlsi-gw" in self.HOSTNAME:
self.machine_class = MachineLLR
elif "poincare" in self.HOSTNAME:
self.machine_class = MachinePoincare
elif "ruche" in self.HOSTNAME:
self.machine_class = MachineRuche
elif "irene" in self.HOSTNAME:
self.machine_class = MachineIrene
else:
self.machine_class = Machine
self.machine = self.machine_class( self.smilei_path, self.options )
# Define sync()
import os
if hasattr(os, 'sync'):
self.sync = os.sync
else:
import ctypes
self.sync = ctypes.CDLL("libc.so.6").sync
def compile(self):
from sys import exit
from os import chdir, sep, stat, remove, rename
from os.path import exists
from .tools import mkdir, date, date_string
from shutil import copy2
from subprocess import CalledProcessError
if self.options.verbose:
display.seperator()
print(" Compiling Smilei")
display.seperator()
SMILEI_W = self.smilei_path.workdirs + "smilei"
SMILEI_R = self.smilei_path.root + "smilei"
# Get state of smilei bin in root folder
chdir(self.smilei_path.root)
STAT_SMILEI_R_OLD = stat(SMILEI_R) if exists(SMILEI_R) else ' '
# CLEAN
# If no smilei bin in the workdir, or it is older than the one in smilei directory,
# clean to force compilation
mkdir(self.smilei_path.workdirs)
self.sync()
if exists(SMILEI_R) and (not exists(SMILEI_W) or date(SMILEI_W)<date(SMILEI_R)):
self.machine.clean()
self.sync()
def workdir_archiv() :
# Creates an archives of the workdir directory
exe_path = self.smilei_path.workdirs+"smilei"
if exists(exe_path):
ARCH_WORKDIR = self.smilei_path.validation+'workdir_'+date_string(exe_path)
rename(self.smilei_path.workdirs, ARCH_WORKDIR)
mkdir(self.smilei_path.workdirs)
try:
# Remove the compiling errors files
if exists(self.smilei_path.COMPILE_ERRORS):
remove(self.smilei_path.COMPILE_ERRORS)
# Compile
self.machine.compile( self.smilei_path.root )
self.sync()
if STAT_SMILEI_R_OLD!=stat(SMILEI_R) or date(SMILEI_W)<date(SMILEI_R): # or date(SMILEI_TOOLS_W)<date(SMILEI_TOOLS_R) :
# if new bin, archive the workdir (if it contains a smilei bin)
# and create a new one with new smilei and compilation_out inside
if exists(SMILEI_W): # and path.exists(SMILEI_TOOLS_W):
workdir_archiv()
copy2(SMILEI_R, SMILEI_W)
#copy2(SMILEI_TOOLS_R,SMILEI_TOOLS_W)
if self.options.verbose:
print(" Smilei compilation succeed.")
else:
if self.options.verbose:
print(" Smilei compilation not needed.")
except CalledProcessError as e:
# if compiling errors, archive the workdir (if it contains a smilei bin),
# create a new one with compilation_errors inside and exit with error code
workdir_archiv()
if self.options.verbose:
print(" Smilei compilation failed. " + str(e.returncode))
exit(3)
if self.options.verbose:
print("")
def run_all(self):
from sys import exit
from os import sep, chdir, getcwd
from os.path import basename, splitext, exists, isabs
from shutil import rmtree
from .tools import mkdir, execfile
from .log import Log
import re, sys
# Load the happi module
sys.path.insert(0, self.smilei_path.root)
import happi
self.sync()
INITIAL_DIRECTORY = getcwd()
global _dataNotMatching
_dataNotMatching = False
for BENCH in self.list_benchmarks():
SMILEI_BENCH = self.smilei_path.benchmarks + BENCH
# Prepare specific resources if requested in a resource file
if BENCH in self.resources:
options = self.options.copy()
for k,v in self.resources[BENCH].items():
setattr(options, k, v)
machine = self.machine_class( self.smilei_path, options )
else:
options = self.options
machine = self.machine
# Create the workdir path
WORKDIR = self.smilei_path.workdirs + 'wd_'+basename(splitext(BENCH)[0]) + sep
mkdir(WORKDIR)
WORKDIR += str(options.mpi) + sep
mkdir(WORKDIR)
WORKDIR += str(options.omp) + sep
mkdir(WORKDIR)
# If there are restarts, prepare a Checkpoints block in the namelist
RESTART_INFO = ""
if options.nb_restarts > 0:
# Load the namelist
namelist = happi.openNamelist(SMILEI_BENCH)
niter = namelist.Main.simulation_time / namelist.Main.timestep
# If the simulation does not have enough timesteps, change the number of restarts
if options.nb_restarts > niter - 4:
options.nb_restarts = max(0, niter - 4)
if options.verbose:
print("Not enough timesteps for restarts. Changed to "+str(options.nb_restarts)+" restarts")
if options.nb_restarts > 0:
# Find out the optimal dump_step
dump_step = int( (niter+3.) / (options.nb_restarts+1) )
# Prepare block
if len(namelist.Checkpoints) > 0:
RESTART_INFO = (" \""
+ "Checkpoints.keep_n_dumps="+str(options.nb_restarts)+";"
+ "Checkpoints.dump_minutes=0.;"
+ "Checkpoints.dump_step="+str(dump_step)+";"
+ "Checkpoints.exit_after_dump=True;"
+ "Checkpoints.restart_dir=%s;"
+ "\""
)
else:
RESTART_INFO = (" \"Checkpoints("
+ " keep_n_dumps="+str(options.nb_restarts)+","
+ " dump_minutes=0.,"
+ " dump_step="+str(dump_step)+","
+ " exit_after_dump=True,"
+ " restart_dir=%s,"
+ ")\""
)
del namelist
# Prepare logging
if options.log:
log_dir = ("" if isabs(options.log) else INITIAL_DIRECTORY + sep) + options.log + sep
log = Log(log_dir, log_dir + BENCH + ".log")
# Loop restarts
for irestart in range(options.nb_restarts+1):
RESTART_WORKDIR = WORKDIR + "restart%03d"%irestart + sep
execution = True
if not exists(RESTART_WORKDIR):
mkdir(RESTART_WORKDIR)
elif options.generate:
execution = False
chdir(RESTART_WORKDIR)
# Copy of the databases
# For the cases that need a database
# if BENCH in [
# "tst1d_09_rad_electron_laser_collision.py",
# "tst1d_10_pair_electron_laser_collision.py",
# "tst2d_08_synchrotron_chi1.py",
# "tst2d_09_synchrotron_chi0.1.py",
# "tst2d_v_09_synchrotron_chi0.1.py",
# "tst2d_v_10_multiphoton_Breit_Wheeler.py",
# "tst2d_10_multiphoton_Breit_Wheeler.py",
# "tst2d_15_qed_cascade_particle_merging.py",
# "tst3d_15_magnetic_shower_particle_merging.py"
# ]:
# try :
# # Copy the database
# check_call(['cp '+SMILEI_DATABASE+'/*.h5 '+RESTART_WORKDIR], shell=True)
# except CalledProcessError:
# if options.verbose :
# print( "Execution failed to copy databases in ",RESTART_WORKDIR)
# sys.exit(2)
# If there are restarts, adds the Checkpoints block
arguments = SMILEI_BENCH
if options.nb_restarts > 0:
if irestart == 0:
RESTART_DIR = "None"
else:
RESTART_DIR = "'"+WORKDIR+("restart%03d"%(irestart-1))+sep+"'"
arguments += RESTART_INFO % RESTART_DIR
# Run smilei
if execution:
if options.verbose:
print("")
display.seperator()
print(" Running " + BENCH + " on " + self.HOSTNAME)
print(" Resources: " + str(options.mpi) + " MPI processes x " + str(options.omp) +" openMP threads on " + str(options.nodes) + " nodes"
+ ( " (overridden by --resource-file)" if BENCH in self.resources else "" ))
if options.nb_restarts > 0:
print(" Restart #" + str(irestart))
display.seperator()
machine.run( arguments, RESTART_WORKDIR )
self.sync()
# Check the output for errors
errors = []
search_error = re.compile('error', re.IGNORECASE)
with open(self.smilei_path.output_file,"r") as fout:
errors = [line for line in fout if search_error.search(line)]
if errors:
if options.verbose:
print("")
display.error(" Errors appeared while running the simulation:")
display.seperator()
for error in errors:
print(error)
exit(2)
# Scan some info for logging
if options.log:
log.scan(self.smilei_path.output_file)
# Append info in log file
if options.log:
log.append(self.git_version)
# Find the validation script for this bench
validation_script = self.smilei_path.analyses + "validate_" + BENCH
if options.verbose:
print("")
if not exists(validation_script):
display.error(" Unable to find the validation script "+validation_script)
exit(1)
chdir(WORKDIR)
# If required, generate the references
if options.generate:
if options.verbose:
display.seperator()
print( ' Generating reference for '+BENCH)
display.seperator()
Validate = self.CreateReference(self.smilei_path.references, BENCH)
execfile(validation_script, {"Validate":Validate})
Validate.write()
# Or plot differences with respect to existing references
elif options.showdiff:
if options.verbose:
display.seperator()
print( ' Viewing differences for '+BENCH)
display.seperator()
Validate = self.ShowDiffWithReference(self.smilei_path.references, BENCH)
execfile(validation_script, {"Validate":Validate})
if _dataNotMatching:
display.error(" Benchmark "+BENCH+" did NOT pass")
# Otherwise, compare to the existing references
else:
if options.verbose:
display.seperator()
print( ' Validating '+BENCH)
display.seperator()
Validate = self.CompareToReference(self.smilei_path.references, BENCH)
execfile(validation_script, {"Validate":Validate})
if _dataNotMatching:
break
# Clean workdirs, goes here only if succeeded
chdir(self.smilei_path.workdirs)
rmtree(WORKDIR, True)
if options.verbose:
print( "")
chdir(INITIAL_DIRECTORY)
if _dataNotMatching:
display.error( "Errors detected")
exit(1)
else:
display.positive( "Everything passed")
def list_benchmarks(self):
from os.path import basename
from glob import glob
# Build the list of the requested input files
list_validation = [basename(b) for b in glob(self.smilei_path.analyses+"validate_tst*py")]
if self.options.bench == "":
benchmarks = [basename(b) for b in glob(self.smilei_path.benchmarks+"tst*py")]
else:
benchmarks = glob( self.smilei_path.benchmarks + self.options.bench )
benchmarks = [b.replace(self.smilei_path.benchmarks,'') for b in benchmarks]
benchmarks = [b for b in benchmarks if "validate_"+b in list_validation]
if not benchmarks:
raise Exception(display.error("Input file(s) "+self.options.bench+" not found, or without validation file"))
if self.options.verbose:
print("")
print(" The list of input files to be validated is:\n\t"+"\n\t".join(benchmarks))
print("")
return benchmarks
# DEFINE A CLASS TO CREATE A REFERENCE
class CreateReference(object):
def __init__(self, references_path, bench_name):
self.reference_file = references_path+bench_name+".txt"
self.data = {}
def __call__(self, data_name, data, precision=None, error_type="absolute_error"):
self.data[data_name] = data
def write(self):
import pickle
from os.path import getsize
from os import remove
with open(self.reference_file, "wb") as f:
pickle.dump(self.data, f)
size = getsize(self.reference_file)
if size > 1000000:
print("Reference file is too large ("+str(size)+"B) - suppressing ...")
remove(self.reference_file)
print("Created reference file "+self.reference_file)
# DEFINE A CLASS TO COMPARE A SIMULATION TO A REFERENCE
class CompareToReference(object):
def __init__(self, references_path, bench_name):
self.ref_data = loadReference(references_path, bench_name)
def __call__(self, data_name, data, precision=None, error_type="absolute_error"):
global _dataNotMatching
from sys import exit
# verify the name is in the reference
if data_name not in self.ref_data.keys():
print(" Reference quantity '"+data_name+"' not found")
_dataNotMatching = True
return
expected_data = self.ref_data[data_name]
if not matchesWithReference(data, expected_data, data_name, precision, error_type):
print(" Reference data:")
print(expected_data)
print(" New data:")
print(data)
print("")
_dataNotMatching = True
# DEFINE A CLASS TO VIEW DIFFERENCES BETWEEN A SIMULATION AND A REFERENCE
class ShowDiffWithReference(object):
def __init__(self, references_path, bench_name):
self.ref_data = loadReference(references_path, bench_name)
def __call__(self, data_name, data, precision=None, error_type="absolute_error"):
global _dataNotMatching
import matplotlib.pyplot as plt
from numpy import array
plt.ion()
print(" Showing differences about '"+data_name+"'")
display.seperator()
# verify the name is in the reference
if data_name not in self.ref_data.keys():
print("\tReference quantity not found")
expected_data = None
else:
expected_data = self.ref_data[data_name]
print_data = False
# First, check whether the data matches
if not matchesWithReference(data, expected_data, data_name, precision, error_type):
_dataNotMatching = True
# try to convert to array
try:
data_float = array(data, dtype=float)
expected_data_float = array(expected_data, dtype=float)
# Otherwise, simply print the result
except:
print("\tQuantity cannot be plotted")
print_data = True
data_float = None
# Manage array plotting
if data_float is not None:
if expected_data is not None and data_float.shape != expected_data_float.shape:
print("\tReference and new data do not have the same shape: "+str(expected_data_float.shape)+" vs. "+str(data_float.shape))
if expected_data is not None and data_float.ndim != expected_data_float.ndim:
print("\tReference and new data do not have the same dimension: "+str(expected_data_float.ndim)+" vs. "+str(data_float.ndim))
print_data = True
elif data_float.size == 0:
print("\t0D quantity cannot be plotted")
print_data = True
elif data_float.ndim == 1:
nplots = 2
if expected_data is None or data_float.shape != expected_data_float.shape:
nplots = 1
fig = plt.figure()
fig.suptitle(data_name)
print("\tPlotting in figure "+str(fig.number))
ax1 = fig.add_subplot(nplots,1,1)
ax1.plot( data_float, label="new data" )
ax1.plot( expected_data_float, label="reference data" )
ax1.legend()
if nplots == 2:
ax2 = fig.add_subplot(nplots,1,2)
ax2.plot( data_float-expected_data_float )
ax2.set_title("difference")
elif data_float.ndim == 2:
nplots = 3
if expected_data is None:
nplots = 1
elif data_float.shape != expected_data_float.shape:
nplots = 2
fig = plt.figure()
fig.suptitle(data_name)
print("\tPlotting in figure "+str(fig.number))
ax1 = fig.add_subplot(1,nplots,1)
im = ax1.imshow( data_float )
ax1.set_title("new data")
plt.colorbar(im)
if nplots > 1:
ax2 = fig.add_subplot(1,nplots,2)
im = ax2.imshow( expected_data_float )
ax2.set_title("reference data")
plt.colorbar( im )
if nplots > 2:
ax3 = fig.add_subplot(1,nplots,nplots)
im = ax3.imshow( data_float-expected_data_float )
ax3.set_title("difference")
plt.colorbar( im )
plt.draw()
plt.show()
else:
print("\t"+str(data_float.ndim)+"D quantity cannot be plotted")
print_data = True
# Print data if necessary
if print_data:
if expected_data is not None:
print("\tReference data:")
print(expected_data)
print("\tNew data:")
print(data)
|
7f85d6114b559165c30c2815f1855f22d8a04593 | ChristopheTeixeira/swinnen | /chapitre6/part51.py | 335 | 3.71875 | 4 | print("Entrez une année.")
nn=input()
an = int(nn)
bissextile = False
if an % 400 == 0:
bissextile = True
if an % 4 == 0:
if an % 100 == 0:
bissextile = False
else:
bissextile = True
if bissextile == True:
print(an, "est une année bissextile.")
else:
print(an,"n'est pas une année bissextile") |
29754a474ef34ef0b15a7eaec781ee3854d1ab95 | agoering/sci_prog | /hw2/hw2_corrected.py | 4,569 | 4.28125 | 4 | #TODO:
# Contents of hw2.csv:
# Column C: Year
# Column D: Temperature in F
# 1. (DONE) Program: Calculate standard deviation of temperature from arbitrary beginning year and ending year input by user.
# 2. (DONE - see calibration.txt) Calibrate: report standard deviations for the years 1930 to 1960 and 1980 to 2010.
# 3. (DONE - see temp_plot.ps) Plot: temperature averaged in 10 year increments and standard deviation in 10 year increments. Temp data = red, stddev data = blue.
import numpy as np
import scipy as sp
data = np.genfromtxt('./data/hw2.csv', delimiter = ',' , usecols = (2,3))
#print data
import matplotlib
matplotlib.use('PS')
import matplotlib.pyplot as plt
# Verbose function to return the standard deviation of the temperature given a range of years
def annual_temp_stdev(data,begin,end):
"""data must be a 2-col array of year and temp, begin and end are years to define averaging"""
#check to make sure begin and end are within range
if begin not in data[:,0]:
print "Beginning year not in range " + str(data[0,0]) + " to " + str(data[len(data)-1,0]) + ", try again."
elif end not in data[:,0]:
print "Ending year not in range " + str(data[0,0]) + " to " + str(data[len(data)-1,0]) + ", try again."
else:
#index the begin and end years
ibegin = begin - data[0,0]
iend = end - data[0,0]
#compute standard deviation of the temperatures in the range indicated by years
stdev = np.std(data[ibegin:iend+1,1])
#round
stdev = round(stdev,3)
return "Standard deviation for temperatures in years " + str(begin) \
+ " to " + str(end) + " is " + str(stdev) + " degrees Fahrenheit."
# return stdev
# Computes the standard deviation of the 2nd col given a range of items in the 1st col
def my_stdev(data,begin,end):
"""data must be a 2-col array, begin and end are endpoints to define averaging"""
#check to make sure begin and end are within range
if begin not in data[:,0]:
print "begin not in range " + str(data[0,0]) + " to " + str(data[len(data)-1,0]) + ", try again."
elif end not in data[:,0]:
print "end not in range " + str(data[0,0]) + " to " + str(data[len(data)-1,0]) + ", try again."
else:
#index the begin and end points
ibegin = begin - data[0,0]
iend = end - data[0,0]
#compute standard deviation of the data in the range indicated by [begin:end+1]
stdev = np.std(data[ibegin:iend+1,1])
return stdev
# Computes the mean of the 2nd col given a range of items in the 1st col
def my_mean(data,begin,end):
"""data must be a 2-col array, begin and end are endpoints to define averaging"""
#check to make sure begin and end are within range
if begin not in data[:,0]:
print "begin not in range " + str(data[0,0]) + " to " + str(data[len(data)-1,0]) + ", try again."
elif end not in data[:,0]:
print "end not in range " + str(data[0,0]) + " to " + str(data[len(data)-1,0]) + ", try again."
else:
#index the begin and end points
ibegin = begin - data[0,0]
iend = end - data[0,0]
#compute standard deviation of the data in the range indicated by [begin:end+1]
datamean = np.mean(data[ibegin:iend+1,1])
return datamean
def bin_plot(data,binsize,begin,end):
#initialize lists to store binned averages and stdevs
years = []
means = []
stdevs = []
#loop in increments of binsize to populate lists, up to the last full decade (doesn't work for 2011,2012 in this vsn)
i = 0
while i < int(round(2012-1850,-1)):
years.append(begin+i)
means.append(my_mean(data,begin+i,begin+i+binsize))
stdevs.append(my_stdev(data,begin+i,begin+i+binsize))
i += binsize
return [years,means,stdevs]
plotdata=bin_plot(data,10,1850,2012)
[years,means,stdevs] = plotdata
#Calibrate: report standard deviations for the years 1930 to 1960 and 1980 to 2010.
thirtyToSixty = annual_temp_stdev(data,1930,1960)
eightyToTen = annual_temp_stdev(data,1980,2010)
#output calibration
with open('./ch/calibration.txt','w') as f:
# printString =
f.write(thirtyToSixty + ' ' + eightyToTen)
#plotting code borrowed from Jordan
plt.plot(years,means,'ro')
plt.errorbar(years,means,yerr=stdevs,linestyle = 'None',color='blue')
plt.xlabel('Decade')
plt.ylabel("Average Temperature")
plt.title("Average Temperature by Decade")
plt.xlim([1840,2012])
plt.ylim([57,60])
plt.savefig('./img/temp_plot') |
76556ea68684ef88d77926efe5a80d5462539fe9 | nathan7798/PostREC | /Documents/pythoncode/Modulated/PostREC3/plotter.py | 9,925 | 3.53125 | 4 | ####Python plotting program for PostREC, takes values from integration and plots their evolution as a function of redhsift for the user. Hydrogen, Deuterium, Lithium and Helium are all plotted
##as well as the evolution of the matter temperature. Each figure is shown in turn with an option for the user to save or dismiss the file.
##Inputs:
##Z_initial : The chosen start point of the Integration (used for the title of the plot)
##Z_final : The chosen end point of the Integration (used for the title of the plot)
## y : the data values obatined from the integration, size is 25 by X, where X is (Z_initial-Z_final)/step_size
def plotting_program(Z_initial,Z_final,y):
from pylab import * #Needed for plotting commands
from matplotlib import rc #Needed for titles of graphs
from numpy import absolute #Needed to calculate absolute values
from matplotlib import pyplot #Needed for plotting commands
##Begin plotting of Hydrogen species
figure()
##Each species is plotted as a fractional abundance of the total number of nuceli. The list of chemical species and thier corresponding array columns are shown for reference purposes.
##The fractional abudnace is plotted as a function of redshift, which is calculated by taking the CMB temperature, dividing it by today's value and subtracting 1 (Becuase T_0 = 2.725 at Z = 0).
##The scale is logarithmic for each axis, for the best visual representation. The limits are also set with this in mind. The lines are color coded and labelled as such.
#species_list = ["[H]","[H+]","[H-]","[H2]","[H2+]","[e-]","[hv]","[D]","[D-]","[D+]","[HD]","[HD+]","[He]","[He+]","[He++]","[HeH+]",[Li], [Li+], [Li-], [LiH], [LiH+], [H2D+], [D2]]
# 0 1 2 3 4 5 6 9 10 11 12 13 14 15 16 17 18 19 20 21 22 , 23 , 24
subplot(221)
plot(((y[:,7]/2.725)-1),absolute(y[:,0]/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'r')
plot(((y[:,7]/2.725)-1),absolute((y[:,1])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'b')
plot(((y[:,7]/2.725)-1),absolute((y[:,2])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'c')
plot(((y[:,7]/2.725)-1),absolute((y[:,3])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'m')
plot(((y[:,7]/2.725)-1),absolute((y[:,4])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'g')
##axes scales and limits
pyplot.xscale('log')
pyplot.yscale('log')
plt.gca().invert_xaxis()
ylim(10**-25,10)
xlim(Z_initial,Z_final+1)
pyplot.yticks([10**-25,10**-20,10**-15,10**-10,10**-5,10**0])
##Font settings for title and labels
rc('font',**{'family':'serif','sans-serif':['Helvetica'] ,'size': 20 })
##create a legend and plot it
labels = [r'$H$', r'$H^+$', r'$H^-$', r'$H_2$', r'$H_2^+$']
legend_location = 'lower left'
colors = ['r','b','c','m','g']
plt.legend(labels, loc=legend_location, prop={'size':10})
##The same is repeated for each chemical species, as shown below.
##Plot Deuterium Species
subplot(222)
plot(((y[:,7]/2.725)-1),absolute((y[:,9])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'r')
plot(((y[:,7]/2.725)-1),absolute((y[:,10])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'b')
plot(((y[:,7]/2.725)-1),absolute((y[:,11])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'c')
plot(((y[:,7]/2.725)-1),absolute((y[:,12])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'k')
plot(((y[:,7]/2.725)-1),absolute((y[:,13])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'g')
pyplot.xscale('log')
pyplot.yscale('log')
plt.gca().invert_xaxis()
ylim(10**-25,10)
xlim(Z_initial,Z_final+1)
pyplot.yticks([10**-25,10**-20,10**-15,10**-10,10**-5,10**0])
rc('font',**{'family':'serif','sans-serif':['Helvetica']})
labels = [r'$D$', r'$D^-$', r'$D^+$', r'$HD$', r'$HD^+$']
legend_location = 'lower left'
colors = ['r','b','c','m','g']
plt.legend(labels, loc=legend_location, prop={'size':10})
##Begin plotting Helium Species
subplot(223)
plot(((y[:,7]/2.725)-1),absolute((y[:,14])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'r')
plot(((y[:,7]/2.725)-1),absolute((y[:,15])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'b')
plot(((y[:,7]/2.725)-1),absolute((y[:,17])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'k')
pyplot.xscale('log')
pyplot.yscale('log')
plt.gca().invert_xaxis()
ylim(10**-25,10**1)
xlim(Z_initial,Z_final+1)
pyplot.yticks([10**-25,10**-20,10**-15,10**-10,10**-5,10**0])
rc('font',**{'family':'serif','sans-serif':['Helvetica'] ,'size': 20 })
labels = [r'$He$', r'$He^+$', r'$HeH^{+}$']
legend_location = 'lower left'
colors = ['r','b','k']
xlabel('Redshift (Z)', fontsize=24)
plt.gca().xaxis.set_label_coords(1.10, -0.105)
ylabel(r' log$_{10}$(Fractional Abundance)', fontsize=24)
plt.gca().yaxis.set_label_coords(-0.15, 1.105)
plt.legend(labels, loc=legend_location, prop={'size':10})
##Begin plotting Lithium Species
subplot(224)
plot(((y[:,7]/2.725)-1),absolute((y[:,18])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'r')
plot(((y[:,7]/2.725)-1),absolute((y[:,19])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'b')
plot(((y[:,7]/2.725)-1),absolute((y[:,20])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'c')
plot(((y[:,7]/2.725)-1),absolute((y[:,21])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'k')
plot(((y[:,7]/2.725)-1),absolute((y[:,22])/(y[:,0]+y[:,1]+y[:,2]+(2*y[:,3])+(2*y[:,4])+y[:,9]+y[:,10]+y[:,11]+(2*y[:,12])+(2*y[:,13])+y[:,15]+y[:,16]+(2*y[:,17])+y[:,18]+y[:,19]+y[:,20]+(2*y[:,21])+(2*y[:,22])+(3*y[:,23])+y[:,14]+(2*y[:,24]))),'g')
pyplot.xscale('log')
pyplot.yscale('log')
plt.gca().invert_xaxis()
ylim(10**-25,10**1)
xlim(Z_initial,Z_final+1)
pyplot.yticks([10**-25,10**-20,10**-15,10**-10,10**-5,10**0])
rc('font',**{'family':'serif','sans-serif':['Helvetica'] ,'size': 12 })
labels = [r'$Li$', r'$Li^+$', r'$Li^-$', r'$LiH$', r'$LiH^+$']
legend_location = 'lower left'
colors = ['r','b','c','k','g']
suptitle(r'Change in Number Density of Chemical Species between ' + str(Z_initial) + '$\leq$ Z $\leq$' + str(Z_final), fontsize=20)
plt.legend(labels, loc=legend_location, prop={'size':10})
show()
##Begin plotting of matter temperature evolution
figure()
plot(((y[:,7]/2.725)-1),absolute(y[:,8]),'r')
pyplot.xscale('log')
pyplot.yscale('log')
plt.gca().invert_xaxis()
xlim(Z_initial,Z_final+1)
pyplot.yticks([10**-25,10**-20,10**-15,10**-10,10**-5,10**0])
rc('font',**{'family':'serif','sans-serif':['Helvetica']})
title(r'The change in gas temperature between ' + str(Z_initial) + ' $\leq$ Z $\leq$ '+ str(Z_final))
xlabel('Redshift (Z)')
ylabel(r'Gas temperature (K)')
#show() ##disabled by default, as this plot is not commonly used apart from checking it has the correct form.
exit = raw_input("\nProcess complete. Press any key to exit...")
raise SystemExit |
04165dfce7e78a294eb3e5fc1485b07709c0fea4 | stream3715/AI_Algorithm | /dfs.py | 990 | 3.703125 | 4 | from myfunc import get_next_positions
def search_dfs(maze, start, end):
checked = {start: None}
solved_maze = [[], checked]
if not dfs_recursive(maze, start, end, checked):
return []
(parent_y, parent_x) = end
while not (parent_y, parent_x) == start:
solved_maze[0].append((parent_y, parent_x))
(parent_y, parent_x) = solved_maze[1][parent_y, parent_x]
return solved_maze
def dfs_recursive(maze, pos, end, checked):
for next_pos in get_next_positions(pos, maze):
(y, x) = next_pos
""" IS_GOAL?"""
if next_pos == end:
checked[end[0], end[1]] = pos
return checked
# 壁でなく、かつゴールに到達していない場合
elif maze[y][x] != "O" and (y, x) not in checked:
checked[y, x] = pos
result = dfs_recursive(maze, (y, x), end, checked)
if result:
return result
checked.pop((y, x))
return {}
|
f4aa442758e372a9bbbbb0f300b2a10486961484 | whleung/project-euler | /problem14.py | 402 | 3.5 | 4 | from collections import Counter
LIMIT = 1000000
steps = Counter()
def collatz(n):
if steps[n] == 0:
if n == 1:
steps[n] = 1
elif n % 2 == 0:
steps[n] = 1 + collatz(n / 2)
else:
steps[n] = 1 + collatz(3 * n + 1)
return steps[n]
for i in xrange(1, LIMIT):
collatz(i)
print max(steps.iterkeys(), key=(lambda key: steps[key]))
|
d5bbe8ee212df785c097a86ebf067fff881485c9 | pemedeiros/python-CeV | /pacote-download/CursoemVideo/ex020.py | 253 | 3.53125 | 4 | import random
n1 = input('Qual o nome do primeiro aluno?')
n2 = input('Qual o nome do segundo aluno?')
n3 = input('Qual o nome do terceiro aluno?')
n4 = input('Qual o nome do quarto aluno?')
lista = [n1, n2, n3, n4]
random.shuffle(lista)
print(lista)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.