blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
060d2128d92384d26461f8edb75267fda0f8fb6b | cxc1357/PythonBasic | /reverseList.py | 745 | 3.953125 | 4 | # day14:反转链表
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
def reverseList(self,head):
preNode = None
curNode = head
while curNode:
next = curNode.next
curNode.next = preNode
preNode = curNode
curNode = next
return preNode
if __name__ == "__main__":
original_list = [1,7,3,6,5,8]
# 哑节点创建链表
head = ListNode(None)
tmp = head
for i in original_list:
newNode = ListNode(i)
# 迭代
tmp.next = newNode
tmp = newNode
head = head.next
so = Solution()
res = so.reverseList(head)
print(res.val)
print(res.next.val) |
80c118641bc514df90cbbfba51c206ac1047f7b1 | NizanHulq/Kuliah-Python | /UTS 2/biner_desimal.py | 1,175 | 3.78125 | 4 | class Node:
def __init__ (self, data=None):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
self.tail = None
def push(self, data):
dataBaru = Node(data)
if self.head == None:
self.head = dataBaru
self.tail = dataBaru
else:
temp = self.head
self.head = dataBaru
self.head.next = temp
def pop(self):
if self.head == None:
self.head = None
self.tail = None
elif self.head == self.tail:
self.head = self.head.next
self.tail = None
else:
self.head = self.head.next
def display(self):
p = self.head
lis = []
while p is not None:
lis.append(p.data)
p = p.next
return lis
def peek(self):
return self.head
biner = Stack()
angkaBiner = input()
for i in angkaBiner:
biner.push(i)
bulat = 0
pangkat = 0
angka = list(map(int,biner.display()))
for j in angka:
bulat += j*2**pangkat
pangkat += 1
print(bulat)
|
4a75da368741182e971315cc91b24d4eb2e8ac35 | JustineRobert/TITech-Africa | /Program to Print Odd Numbers within a Given Range.py | 241 | 4.0625 | 4 | lower = int(input("Enter the lower limit number for the range: "))
upper = int(input("Enter the upper limit number for the range: "))
for i in range (lower, upper+1):
if (i%2!=0):
print(i)
input("Press Enter to Exit!")
|
2c7437beca4873eb066242c79548775677ea815a | semen-ksv/Python_learn | /Learning/lambda.py | 404 | 3.828125 | 4 | import time
start_time = time.time()
def funk(arg, arg1):
result = arg * arg1
return result
def funk1(arg, arg1):
return arg * arg1
c = lambda arg, arg1: arg*arg1
print(c(5, 9))
for i in range(1300):
print(i**i)
# сколько времени прошло при выполнении кода
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time) |
d1bedcf478faf4cd64010d33c4afc5359e3917db | mjs139/PythonPractice | /Lottery Probabilities.py | 4,573 | 3.9375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Logic For Mobile App For Lottery Addiction
#
# I wish to create the underlying logic for an app that helps treat those addicted to played the lottery by showing them the odds. For this version of the app, I will focus on the [6/49 lottery](https://en.wikipedia.org/wiki/Lotto_6/49).
#
# I will also consider [historical data](https://www.kaggle.com/datascienceai/lottery-dataset) coming from the national 6/49 lottery game in Canada.
# ## Core Functions
#
# I will write two functions that will be used frequently: combination and factorial calculators.
# In[5]:
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
def combinations(n, k):
numerator = factorial(n)
denominator = factorial(k) * factorial(n-k)
return numerator / denominator
# ## One Ticket Probability
#
# Below I will build a function that calculates the probability of winning the big prize for any given ticket. For each drawing, six numbers are drawn from a set of 49, and a player wins the big prize if the six numbers on their tickets match all six numbers.
# In[9]:
def one_ticket_probability(user_numbers):
n_outcomes = combinations(49, 6)
probability_one_ticket = 1/n_outcomes
percentage_form = probability_one_ticket * 100
print('''Your chances to win the big prize with the numbers {} are {:.7f}%.
In other words, you have a 1 in {:,} chances to win.'''.format(user_numbers,
percentage_form, int(n_outcomes)))
# I will test the function with a few inputs.
# In[10]:
input1 = [1, 2, 3, 4, 5, 6]
one_ticket_probability(input1)
# ## Historical Data
#
# I also want users to be able to compare their ticket against the historical lottery data in Canada and determine whether they would have ever won by now. First I will view the data
# In[11]:
import pandas as pd
sixfournine = pd.read_csv("649.csv")
print(sixfournine.shape)
# In[13]:
sixfournine.head()
# In[14]:
sixfournine.tail()
# ## Function for Historical Data Check
#
# I will now build the historical data check function described above.
# In[17]:
def extract_number(row):
row = row[4:10]
row = set(row.values)
return row
winning_numbers = sixfournine.apply(extract_number, axis=1)
winning_numbers.head()
# In[27]:
def check_historical_occurence(user_nums, winning_nums):
user_nums_set = set(user_nums)
bools = winning_nums == user_nums_set
total = bools.sum()
if total == 0:
print('''The combination {} has never occured.
This doesn't mean it's more likely to occur now. Your chances to win the big prize in the next drawing using the combination {} are 0.0000072%.
In other words, you have a 1 in 13,983,816 chances to win.'''.format(user_nums, user_nums))
else:
print('''The number of times combination {} has occured in the past is {}.
Your chances to win the big prize in the next drawing using the combination {} are 0.0000072%.
In other words, you have a 1 in 13,983,816 chances to win.'''.format(user_nums, total,
user_nums))
# I will now test the function
# In[28]:
user_numbs = [1, 2, 3, 4, 5, 6]
check_historical_occurence(user_numbs, winning_numbers)
# In[29]:
user_numbs2 = [33, 36, 37, 39, 8, 41]
check_historical_occurence(user_numbs2, winning_numbers)
# ## Multi Ticket Probability
#
# I also want users to put in multiple tickets and view the probability of winning.
#
# The multi_ticket_probability() function below takes in the number of tickets and prints probability information depending on the input.
# In[30]:
def multi_ticket_probability(n_tickets):
#total number of outcomes
outcomes = combinations(49, 6)
prob = n_tickets / outcomes
prob_percent = prob * 100
if n_tickets == 1:
print('''Your chances to win the big prize with one ticket are {:.6f}%.
In other words, you have a 1 in {:,} chances to win.'''.format(prob_percent, int(outcomes)))
else:
combinations_simplified = round(outcomes / n_tickets)
print('''Your chances to win the big prize with {:,} different tickets are {:.6f}%.
In other words, you have a 1 in {:,} chances to win.'''.format(n_tickets, prob_percent,
combinations_simplified))
# I will now test my function
# In[31]:
multi_ticket_probability(1)
# In[32]:
multi_ticket_probability(100)
# In[ ]:
|
c1a96f6675a0682c51df4017915da40d07e1e0a3 | rjimeno/PracticePython | /e13.py | 294 | 4.09375 | 4 | #!/usr/bin/env python3
n = int(input("How many Fibonacci numbers?: "))
def f(n):
if n < 1:
exit(1)
elif n == 1:
return 1
elif n == 2:
return 1
else:
return f(n-2)+f(n-1)
result=[]
for i in range(1, n+1):
result.append(f(i))
print(result)
|
0fdbb01620ccc35615237f69986f7bfe02cff0f5 | Hrishikesh-3459/coders_club | /Day_3/2.py | 175 | 4.34375 | 4 | # Write a program to find factorial of a given number
n = int(input("Please enter a number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print(f"Factorial is: {fact}") |
44dd3947ee1d77b13b833c33bbdb53ebe5464ad2 | globocom/dojo | /2021_03_31/dojo.py | 1,498 | 3.6875 | 4 | def append_string_value(c, value):
if len(value) == 0:
return c
return (int(value)*c)
def main(input_string, max_length):
value = ""
decoded_string = ""
for c in input_string:
if c.isdigit():
value = value + c
else:
decoded_string += append_string_value(c,value)
if len(decoded_string) > max_length:
return "unfeasible"
value = ""
return decoded_string
def encode_value(value, previous_letter):
if value == 1:
return previous_letter
return str(value) + previous_letter
def encode_string(decoded_string):
previous_letter = decoded_string[0]
value = 0
encoded_string = ""
for c in decoded_string:
if c == previous_letter:
value += 1
else:
encoded_string += encode_value(value, previous_letter)
value = 1
previous_letter = c
encoded_string += encode_value(value, previous_letter)
return encoded_string
# if decoded_string == "abcd":
# return "abcd"
# if decoded_string == "aaaaabbc":
# return "5a2bc"
# else:
# return "asdf4x"
# Celso - Ingrid - Lara - Tiago - Juan
#input
#5a2bc 8
#output
#aaaaabbc
#input
#5a2bc 7 => aaaaabbc (length: 8)
#output
#unfeasible
#input
#asdf4x 50
#output
#asdfxxxx
#input
#asjkdf10000000000kz 1000000
#output
#unfeasible
#func com o objetivo de formar o numero |
1b78fc4165b6eae7c6cfb20de64ff32db899d3c2 | danyanos/sandbox | /python/data-crane/tests/test_main.py | 352 | 3.765625 | 4 | from dataclasses import dataclass
from data_crane.main import as_dataclass
@dataclass
class Car():
make: str
model: str
year: int
def test_as_dataclass():
dict_data = {
"make": "chevrolet",
"model": "malibu",
"year": 2014
}
result = as_dataclass(dict_data, Car)
print(result)
assert False
|
f34eabdef9a2bed341661c0d3ba4626e9b8ef8ce | Margarita89/LeetCode | /0022_Generate_Parentheses.py | 1,030 | 3.953125 | 4 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""
General idea: use recursion with left and right as a number of open and closed parentheses
1. Base case: length of s is equal to 2*n - means all parentheses are included -> append to answer
2. If number of left parentheses is less than half (which is n) -> add '(' and start over
3. If number of left parentheses is larger than right - it's possible to close -> add ')' and start over
Thus it will be always <= n opened paranthesis and all combination will be checked
"""
parentheses = []
def recursive_parentesis(s, left, right):
if len(s) == 2 * n:
parentheses.append(s)
return
if left < n:
recursive_parentesis(s + '(', left + 1, right)
if left > right:
recursive_parentesis(s + ')', left, right + 1)
recursive_parentesis('', 0, 0)
return parentheses |
f9b87963355992b5730aa8b3205cec539727a2b1 | jchadwick92/Simple_maths_test | /multiplication questions.py | 1,964 | 3.71875 | 4 | import random, time, csv, datetime
class Multiplication():
def __init__(self, num_of_questions=100):
self.num_of_questions = num_of_questions
self.score = 0
self.wrong_answers = []
self.date = str(datetime.date.today()).replace('-', '.')
def run(self):
input('Type in your name and press enter to begin: ')
time.sleep(0.3)
self.start_time = time.time()
for i in range(self.num_of_questions):
self.gen_que()
self.end_time = time.time()
self.time_taken()
self.final_score = str((self.score / self.num_of_questions)*100) + '%'
print('Score: ' + self.final_score)
if self.wrong_answers != []:
print('Questions that you answered wrong: ')
for i in self.wrong_answers:
print(i)
self.save_results()
def time_taken(self):
self.total_secs = self.end_time - self.start_time
self.secs = self.total_secs % 60
self.mins = int((self.total_secs - self.secs) / 60)
self.time_taken = str(self.mins) + ' minutes, ' + str(round(self.secs)) + ' seconds'
print('Time taken: ' + self.time_taken)
def gen_que(self):
self.a = random.randint(2,12)
self.b = random.randint(2,12)
self.question = str(self.a) + ' x ' + str(self.b)
self.ans = str(self.a * self.b)
self.answer = input(self.question + ' = ')
if self.answer == self.ans:
self.score += 1
if self.answer != self.ans:
self.wrong_answers.append(self.question)
def save_results(self):
csvFile = open('Multiplication_results.csv', 'a', newline='')
writer = csv.writer(csvFile)
writer.writerow([self.date] + [self.final_score] + [self.time_taken])
csvFile.close()
M = Multiplication()
M.run()
|
6302128aff3d33f752b62fa1a66637d03706599b | siddharth-sen/Algorithms | /dynamic_programming/primitive_calculator.py | 1,321 | 3.53125 | 4 | # Uses python3
import sys
def optimal_sequence(n):
sequence = []
while n >= 1:
sequence.append(n)
if n % 3 == 0:
n = n // 3
elif n % 2 == 0:
n = n // 2
else:
n = n - 1
return reversed(sequence)
def get_min_ops(n):
result = [0]*(n+1)
for i in range(2, n+1):
op1 = result[i-1]
op2 = sys.maxsize
op3 = sys.maxsize
if i % 2 == 0:
op2 = result[int(i/2)]
if i % 3 == 0:
op3 = result[int(i/3)]
min_ops = min(op1, op2, op3)
result[i] = min_ops+1
return result
def optimal_sequence_dp(n):
sequence = []
ops = get_min_ops(n)
while n > 0:
sequence.append(n)
if n % 3 != 0 and n % 2 != 0:
n = n - 1
elif n % 2 == 0 and n % 3 == 0:
n = n // 3
elif n % 2 == 0:
if ops[n-1] < ops[n//2]:
n = n - 1
else:
n = n // 2
elif n % 3 == 0:
if ops[n-1] < ops[n//3]:
n = n - 1
else:
n = n // 3
return reversed(sequence)
input = sys.stdin.read()
n = int(input)
sequence = list(optimal_sequence_dp(n))
print(len(sequence) - 1)
for x in sequence:
print(x, end=' ')
|
aba747ca1ef1921a8bcdb087516c5ea98b9a7421 | noppakorn-11417/psit-2019 | /problem/SceneSwitch.py | 624 | 3.796875 | 4 | """psit"""
def switch(time, temp, ans):
"""sad psit"""
while time != "End":
time1 = float(time)
if time == "0":
light, status = "cool", "on"
elif status == "on":
temp = time1+6
status = "off"
elif status == "off" and light == "cool":
if time1 <= temp:
ans += 1
status, light = "on", "warm"
else:
status, light = "on", "cool"
elif status == "off" and light == "warm":
status, light = "on", "cool"
time = input()
print(ans)
switch(input(), 0, 0)
|
7e43c82f1c46cf974eb171ce841d089e22c8af11 | xungeer29/Stanford-CS231n-Convolutional-Neural-Networks-for-Visual-Recognition | /Assignment/Two Layers Neural Network/DataPreprocess.py | 1,747 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/14 20:41
# @Author : GFX
# @Site :
# @File : Train_and_Predict.py
# @Software: PyCharm
# 2 数据处理 图像转化为数组,归一化处理(减去均值)
import numpy as np
from data_utils import load_cifar10
def get_cifar_data(num_training=49000, num_validation=1000, num_test=1000):
cifar10_dir = 'datasets'
X_train, y_train, X_test, y_test = load_cifar10(cifar10_dir)
# 验证集
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]
# 训练集
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
# 测试集
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
# 数据归一化处理
# 处理方法:对每特征值减去平均值来中心化
mean_image = np.mean(X_train, axis=0) # axis:0 求列求平均值;1 按行求平均值
X_train -= mean_image
X_val -= mean_image
X_test -= mean_image
#将图像转化为列向量
X_train = X_train.reshape(num_training, -1)
X_val = X_val.reshape(num_validation, -1)
X_test = X_test.reshape(num_test, -1)
return X_train, y_train, X_val, y_val, X_test, y_test
# 验证结果是否正确
X_train, y_train, X_val, y_val, X_test, y_test = get_cifar_data()
print('\n验证分离验证集结果是否正确')
print('training data shape: ', X_train.shape)
print('training labels shape: ', y_train.shape)
print('validation data shape: ', X_val.shape)
print('validation data shape: ', y_val.shape)
print('test data shape: ', X_test.shape)
print('test labels shape: ', y_test.shape)
|
5b2ca6357b78bbad8c257531ab2219182e3512dc | Chansamnang/Chansamnang.github.io | /Python Bootcamp (Ex & Pro)/Week01/10_str_length.py | 102 | 3.921875 | 4 | k = input("Enter a String: ")
if len(k) == 0:
print('The String is empty')
else:
print(len(k)) |
33f9d705c420fe255068a47b517c374f1d6b98ad | keurfonluu/My-Daily-Dose-of-Python | /Solutions/34-maximum-profit-from-stocks.py | 509 | 3.8125 | 4 | #%% [markdown]
# You are given an array. Each element represents the price of a stock on that particular day.
# Calculate and return the maximum profit you can make from buying and selling that stock only once.
#
# Example
# ```
# Input: [9, 11, 8, 5, 7, 10]
# Output: 5
# ```
#%%
def buy_and_sell(arr):
profit = arr[1] - arr[0]
for i, buy in enumerate(arr[:-1]):
for sell in arr[i:]:
profit = max(profit, sell - buy)
return profit
print(buy_and_sell([9, 11, 8, 5, 7, 10])) |
fda9cc81454a01036819db2a94bff94b1423f20b | benjaminkweku/dev | /reverse.py | 109 | 3.609375 | 4 | def even(x,y):
for i in range(x,y,-1):
if(i%2==0):
print(i)
even(20,12) |
b110b9f35e94d051bdadd3dba96b8ee27cf603ca | renukadeshmukh/Leetcode_Solutions | /2164_SortEvenOddIndicesIndependently.py | 2,032 | 4.40625 | 4 | '''
2164. Sort Even and Odd Indices Independently
You are given a 0-indexed integer array nums. Rearrange the values of nums
according to the following rules:
Sort the values at odd indices of nums in non-increasing order.
For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after.
The values at odd indices 1 and 3 are sorted in non-increasing order.
Sort the values at even indices of nums in non-decreasing order.
For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after.
The values at even indices 0 and 2 are sorted in non-decreasing order.
Return the array formed after rearranging the values of nums.
Example 1:
Input: nums = [4,1,2,3]
Output: [2,3,4,1]
Explanation:
First, we sort the values present at odd indices (1 and 3) in non-increasing order.
So, nums changes from [4,1,2,3] to [4,3,2,1].
Next, we sort the values present at even indices (0 and 2) in non-decreasing order.
So, nums changes from [4,1,2,3] to [2,3,4,1].
Thus, the array formed after rearranging the values is [2,3,4,1].
Example 2:
Input: nums = [2,1]
Output: [2,1]
Explanation:
Since there is exactly one odd index and one even index, no rearrangement of values takes place.
The resultant array formed is [2,1], which is the same as the initial array.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
'''
'''
ALGORITHM:
1. Separate odd and even indices into separate arrays and sort.
2. Merge the arrays alternately and return result.
RUNTIME COMPLEXITY: O(NLOGN)
SPACE COMPLEXITY: O(N)
'''
class Solution(object):
def sortEvenOdd(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
odd_list = sorted(nums[1::2], reverse = True)
even_list = sorted(nums[::2])
result = [0] * len(nums)
for i in range(len(even_list)):
result[2*i] = even_list[i]
for i in range(len(odd_list)):
result[2*i+1] = odd_list[i]
return result |
099a1e21422e08eb8c32087f74bc5a42d6869b6a | StanislavHorod/LV-431-PythonCore | /lec 8.12/CW-7.py | 329 | 3.84375 | 4 | for test_number in range(10, 31):
i = 2
base = int(test_number**0.5)
while i <= base:
if test_number % i == 0:
half = test_number/2
print("Number {} equal 2*{}".format(test_number, half))
break
i += 1
else:
print("Number {} is easy".format(test_number)) |
770aeee854f86ca929b3912503dccb3a4ef091bd | BenSparksCode/serverless-sandbox | /functions/factorial/factorial.py | 235 | 4.21875 | 4 |
def factorial(num):
if(not num or type(num) != int or num < 0):
return -1
if(num == 0 or num == 1):
return 1
return num*factorial(num - 1)
# For testing
if __name__ == "__main__":
print(factorial(10)) |
01b13b0ca4765534f33c18b900fcdad1713eadfa | alessandro-canevaro/ATFMDM | /counting_a_lot.py | 1,555 | 3.546875 | 4 | #count a lot
import random
random.seed(0)
n = 10 #number of distinct elements in the universe
m = 15 #number of elements in the stream
stream = [2, 1, 2, 2, 3, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 3, 1, 1, 1, 1]#[random.randint(0,n) for i in range(m)]
class bin:
def __init__(self, id):
self.bin_no = id
self.element = None
self.counter = 0
def __repr__(self):
return "{'"+str(self.element) + "'->" + str(self.counter)+'}'
k = 2 #number of bins
bins = [bin(i) for i in range(k)]
history = {b.bin_no: [b.element] for b in bins}
def countalot(stream):
for j, a in enumerate(stream):
#print('Processing elem:', a, ' Currrent bins:', bins)
for b in bins:
if b.element == a:
#print("Found a bin")
b.counter += 1
break
else:
minimum = bins[0].counter
min_obj = bins[0]
for b in bins:
if b.counter < minimum:
minimum = b.counter
min_obj = b
#print("Bin not found, incrementing bin:", min_obj)
min_obj.element = a
min_obj.counter += 1
history[min_obj.bin_no].append(min_obj.element)
print("i:", j, "a:", a, [(b.bin_no, b.element, b.counter) for b in bins])
def output(i):
for b in bins:
if b.element == i:
return b.counter
return 0
if __name__ == '__main__':
print(stream)
countalot(stream)
print(bins)
print(history)
print(output(2))
|
5edb67c9cf42802b673f4e40a325cf9fbf734743 | victoriavilasb/Python-Algorithms | /1036.py | 357 | 3.625 | 4 |
# -*- coding: utf-8 -*-
import math
wlinha = input().split(" ")
a, b, c = wlinha
delta = float(b)**2 - (4*float(a)*float(c))
if delta<0 or float(a)==0:
print("Impossivel calcular")
else:
R1=(float(b)*(-1)+math.sqrt(delta))/(2*float(a))
R2=(float(b)*(-1)-math.sqrt(delta))/(2*float(a))
print("R1 = %0.5f"%(R1))
print("R2 = %0.5f"%(R2)) |
3c890fca47501442014493d804708c2d7da52056 | ssanseri/playing-with-python | /datetime_drill.py | 2,060 | 4.375 | 4 | ##Scenario: The company you work for just opened two new branches. One is in New York City,
##the other in London. They need a very simple program to find out if the branches are open or
##closed based on the current time of the Headquarters here in Portland. The hours of both
##branches are 9:00AM - 9:00PM in their own time zone.
##What is asked of you:
##Create code that will use the current time of the Portland HQ to find out the time in the NYC &
##London branches, then compare that time with the branches hours to see if they are open or
##closed.
##Print out if each of the two branches are open or closed.
import datetime
from pytz import timezone
import time
def get_hms_from_datetime (my_datetime):
hms_datetime = my_datetime.strftime(fmt)
hms = hms_datetime.split(':')
return hms
def business_hours (my_datetime):
hms = get_hms_from_datetime (my_datetime)
hrs = int(hms[0])
mins = int(hms[1])
secs = int(hms[2])
if hrs < 9:
return False
elif hrs > 21:
return False
elif hrs == 21 and (mins > 0 or secs > 0):
return False
else:
return True
def show_is_business_hours (my_datetime, city):
if business_hours(my_datetime):
print("Yes, " + city + " branch is open!")
else:
print("No, " + city + "branch is closed!")
#fmt = "%Y-%m-%d %H:%M%:%S %Z%z"
#fmt = "%Y-%m-%d %H:%M%:%S"
fmt = "%H:%M:%S"
# Current time in UTC
now_utc = datetime.datetime.now(timezone('UTC'))
# Convert to US/Pacific time zone
now_pacific = now_utc.astimezone(timezone('US/Pacific'))
print(now_pacific.strftime(fmt))
show_is_business_hours(now_pacific, "Portland")
# Convert to US/Eastern time zone
now_eastern = now_utc.astimezone(timezone('US/Eastern'))
print(now_eastern.strftime(fmt))
show_is_business_hours(now_eastern, "New York")
# Convert to London time zone
now_london = now_pacific.astimezone(timezone('Europe/London'))
print(now_london.strftime(fmt))
show_is_business_hours(now_london, "London")
|
5e11dae5b65224f3d9848011a14c7abc0b3ad5cd | pr0PM/c2py | /22.py | 439 | 3.953125 | 4 | # Write a program that takes 2 arrays as input and prints the sum of the corresponding elements
# in the third arrays
print('Enter the first array : ')
a = [int(x) for x in input().split()]
print('Enter the second array : ')
b = [int(x) for x in input().split()]
print('The sum of corresponding elements of the entered arrays is : ')
c = []
for i in range(len(a)):
c.append(a[i] + b[i])
print('The sum is : ',c)
|
fc4a97c5aa6253ccb2bb92e7c70de882ab056c51 | pranaykhurana/Hackerrank | /Python/lists.py | 2,672 | 4.1875 | 4 | """
I HAVE USED AN ACTION METHODOLOGY WHICH IS OFTEN USED IN HIGH FREQUENCY TRADING PLATFORMS TO EXECUTE ACTIONS, UPDATE VALUES, ETC
IN A PROFESSIONAL ENVIRONMENT, ACTIONS WOULD BE CONVERTED TO A CLASS FOR EFFICIENCY AND PROPER PRACTICE
"""
def insertAction(tempLst, action):
# action receives something like ->
# insert 0 5
action_split = action.split(" ")
pos = int(action_split[1])
item = int(action_split[2])
if pos >= 0:
tempLst.insert(pos, item)
return tempLst
def printAction(tempLst):
if(len(tempLst) > 0):
print(tempLst)
else:
print("Trying to print an empty list")
def removeAction(tempLst, action):
action_split = action.split(" ")
item = int(action_split[1])
if(len(tempLst) > 0 ):
tempLst.remove(item)
else:
print("Trying to remove item from an empty list")
return tempLst
def appendAction(tempLst, action):
action_split = action.split(" ")
item = int(action_split[1])
tempLst.append(item)
return tempLst
def sortAction(tempLst):
if(len(tempLst) > 0):
return sorted(tempLst)
else:
print("Trying to sort an empty list")
return tempLst
def popAction(tempLst):
if(len(tempLst) > 0):
popped_element = tempLst.pop(len(tempLst) - 1)
else:
print("Trying to pop from an empty list")
return tempLst
def reverseAction(tempLst):
return list(reversed(tempLst))
if __name__ == '__main__':
N = int(input())
# number list to which the actions will be performed
number_lst = []
# create a list to store the actions and input them into the list
actions = []
for i in range(N):
actions.append(str(input()))
for action in actions:
action_split = action.lower().split(" ")
action_verb = str(action_split[0])
if action_verb == "insert":
number_lst = insertAction(number_lst, action)
elif action_verb == "print":
printAction(number_lst)
elif action_verb == "remove":
number_lst = removeAction(number_lst, action)
elif action_verb == "append":
number_lst = appendAction(number_lst, action)
elif action_verb == "sort":
number_lst = sortAction(number_lst)
elif action_verb == "pop":
number_lst = popAction(number_lst)
elif action_verb == "reverse":
number_lst = reverseAction(number_lst)
else:
print("---------------------------\n")
print("ACTION NOT FOUND ERROR IN LOOP")
|
588082f7d49f630c03356b2ea1913b212c88a501 | jakobcodes/Algorithms-And-Data-Structures-AGH-Course | /cwiczenia2/quicksort.py | 849 | 3.75 | 4 | import random, time
def quicksort(A,p,r):
if p<r:
q = partition(A,p,r)
quicksort(A,p,q-1)
quicksort(A,q+1,r)
def partition(A,p,r):
x = A[r]
i = p-1
for j in range(p,r):
if A[j] <= x:
i += 1
A[i] , A[j] = A[j] , A[i]
A[i+1] , A[r] = A[r], A[i+1]
return i+1
def quicker_sort(A,p,r):
while p < r:
q = partition(A,p,r)
if q-p <= r-q:
quicker_sort(A,p,q-1)
p = q + 1
else:
quicker_sort(A,q+1,r)
r = q - 1
A = [random.randint(0,9) for _ in range(100000)]
N = A
# print(A)
# t1 = time.time()
# quicksort(A,0,len(A)-1)
# t2 = time.time()
# print(f"quicksort, czas: {t2-t1}")
# print(N)
t1 = time.time()
quicker_sort(N,0,len(N)-1)
t2 = time.time()
print(f"quicker_sort, czas: {t2-t1}")
|
76e20494db7c9d659a379640ba35b008c287e8bd | nalangekrushna/comprinno_test | /9.py | 557 | 3.859375 | 4 | def rec_func(lst,cost) :
# if list contains last element then return it as value.
if len(lst) == 1 :
return lst[0],cost
# find min, max from list, add min to cost and remove max from list.
else :
cost += min(lst[0],lst[1])
lst.remove(max(lst[0],lst[1]))
return lst,cost
def get_min_cost_of_operation(lst) :
cost = 0
# until return type of lst is list call function
while isinstance(lst,list) :
lst,cost = rec_func(lst,cost)
return cost
print(get_min_cost_of_operation([4,2,5]))
|
d96835e4dd38ef2446550ac79ed9a6918204e80c | mlcenzer/PFB2017_problemsets | /pythonfiles/pythonprobs2-2.py | 438 | 4.28125 | 4 | #!/usr/bin/env python3
import sys
num=float(sys.argv[1])
if num>0:
print(num, "is non-zero positive")
if num>50:
print(num, "is greater than 50")
if not num%3:
print(num, "is divisible by 3")
else:
print(num, "is not divisible by 3")
elif num<50:
print(num, "is less than 50")
if not num%2:
print(num, "is even")
else:
print(num, "is odd")
elif num<0:
print(num, "is negative")
else:
print(num, "is zero")
|
0735c5f0c7465cb39dd90c525ecaa258d0239b9d | samuel871211/My-python-code | /Additional/897.Increasing Order Search Tree.py | 802 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
if root == None or (root.left == None and root.right == None):
return root
else:
arr = self.traversal(root,[])
new = TreeNode(arr[0])
cur = new
for i in range(1,len(arr)):
cur.right = TreeNode(arr[i])
cur = cur.right
return new
def traversal(self,root,arr):
if root.left:
self.traversal(root.left,arr)
arr.append(root.val)
if root.right:
self.traversal(root.right,arr)
return arr
|
e1c52bc7e773a242013f6cf22e56034414a3337a | patrickschu/tgdp | /summer16/gilberttools/adding_IPA_0627.py | 4,813 | 3.65625 | 4 | # -*- coding: utf-8 -*-
#getting transcripts for gilbert table
from bs4 import BeautifulSoup
import urllib
import codecs
import pandas as pd
import requests
import json
header="\n\n---\n"
##note the encoding nightmare in here
def transcriber(inputfile, outputfile, column, json_file=None):
"""
The transcriber adds a column of IPA transcriptions and entry lengths to a spreadsheet.
Inputfile is a csv file; outputfile a new csv file; column is the column name of the column to be transcribed.
The optional json_file takes a dictionary of format {word1:IPA_transcription, word2:...}.
Words not found in the dictionary are looked up online and added to the dictionary.
The transcriber outputs the csv file with columns 'transcription' and 'items' (# of words) added.
It also writes the final version of the word:IPA dictionary into a JSON file called outputfile + '_dict.txt'.
"""
print "Transcriber started"
my_dicti={}
if json_file:
print header, "Reading JSON file from ", json_file
json_input=codecs.open(json_file, "r", "utf-8")
my_dicti=json.load(json_input)
print "Dictionary entries: ", len(my_dicti)
inputfile=pd.read_csv(inputfile, encoding="utf-8")
print header, inputfile[column], header
transcriptions=[]
length=[]
for line in inputfile[column]:
entry=line.split(" ")
entry_transcription=[]
for word in entry:
print header, word
if my_dicti.get(word, None) == None:
transcription=wiktionaryfinder(word)
print "Looking {} up online".format(word)
entry_transcription.append(transcription)
my_dicti[word]=transcription
else:
print "Found {} in my_dicti".format(word)
transcription=my_dicti[word]
entry_transcription.append(transcription)
print entry_transcription
print [type(i) for i in entry_transcription]
transcriptions.append(" ".join(entry_transcription))
length.append(len(entry_transcription))
with open(outputfile+"_dicti.txt", "w") as dictiwriter:
json.dump(my_dicti, dictiwriter)
inputfile['transcription']=transcriptions
inputfile['items']=length
with open(outputfile, "w") as outputfile:
inputfile.to_csv(outputfile, encoding="utf-8")
print header, inputfile, header
print header, "Transcriber exited, files written to ", outputfile, "+ _dicti"
#helper functions
def wiktionaryfinder(inputword):
"""
The wiktionaryfinder looks up the input word on Wiktionary and returns a IPA transcription of the word.
It then extracts all IPA transcriptions on the relevant page.
If there is more than one, it asks for user input.
If there is not Wiktionary page for the input word, it asks the user to input a transcription.
"""
inputword=umlautchecker(inputword)
inputword=capschecker(inputword)
link="https://de.wiktionary.org/wiki/"+inputword
link=link.encode('utf-8')
inputi=urllib.urlopen(link).read()
inputisoup=BeautifulSoup(inputi, 'html.parser')
results= [r.string for r in inputisoup.find_all('span', 'ipa') if r.string and not r.string.startswith("-")]
if len(results) == 0:
print "No options found. Please enter transcription for", inputword
final_form=raw_input("Which form do you want?\n")
if len(results) ==1 :
final_form=results[0]
if len(results) > 1:
print "Several options found for word", inputword
for result in results:
print result
final_form=raw_input("Which form do you want?\n")
return final_form
def capschecker(inputword):
"""
The capschecker tests whether a lowercase word exists on Wiktionary.
If not, it capitalizes the word and re-tests.
Returns whatever is working, and inputword if nothing does.
"""
link="https://de.wiktionary.org/wiki/"+inputword
link=link.encode('utf-8')
originalstatus=requests.get(link)
if originalstatus.status_code in [404]:
newlink="https://de.wiktionary.org/wiki/"+inputword.capitalize()
newlink=newlink.encode('utf-8')
newstatus=requests.get(newlink)
if newstatus.status_code not in [404]:
print inputword, "has been changed to", inputword.capitalize(), "by the capschecker"
return inputword.capitalize()
else:
return inputword
else:
print "Capschecker didn't change a thing"
return inputword
def umlautchecker(inputword):
"""
The umlautchecker replaces all ae, oe and ue strings with the respective umlaut characters.
Note that the dictionary can be expanded quite easily.
"""
umlautdict={
'ae': 'ä',
'ue': 'ü',
'oe': 'ö'
}
for item in umlautdict.keys():
inputword=inputword.replace(item, umlautdict[item].decode('utf-8'))
return inputword
transcriber('/Users/ps22344/Downloads/tgdp-master/summer16/gilbert_questions.csv', '/Users/ps22344/Downloads/tgdp-master/summer16/gilbert_questions_withtrans_2ndtry.csv', 'target_form', '/Users/ps22344/Downloads/tgdp-master/summer16/gilbert_questions_withtrans_2ndtry.csv_dicti.txt')
|
0af1b153d9263dda47f2ed98ad382e2acb077172 | lvah/201901python | /day13/07_property属性.py | 2,418 | 4.1875 | 4 | """
总结:
1). Python内置的@property装饰器就是负责把一个方法变成属性调用的;
2). @property本身又创建了另一个装饰器@state.setter,负责把一个
setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作.
3). @property广泛应用在类的定义中,可以让调用者写出简短的代码,
同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。
源代码应用范例: 让属性只读:
from datetime import date
# Read-only field accessors
@property
def year(self):
# year (1-9999)
return self._year
@property
def month(self):
# month (1-12)
return self._month
@property
def day(self):
# day (1-31)
return self._day
/home/kiosk/anaconda2/envs/2048/lib/python3.6/datetime.py
"""
from datetime import date
from datetime import time
import time
from colorFont import *
class Book(object):
def __init__(self, name, kind, state):
self.name = name
self.kind = kind
# 0: 借出 1: "未借出"
# 书的状态只能是0或者1, 如果是其他, 应该报错;
# 查看书状态, 希望是汉字形式, 有实际意义的;
self.__state = 0
@property # 将这个方法转换为类的属性; print(book.state)
def state(self):
if self.__state == 0:
return ERRRED + "借出"
elif self.__state == 1:
return OKGREEN + "未借出"
@state.setter # book.state = 0
def state(self, value):
if value in (0,1):
# 更新书状态
self.__state = value
else:
print(ERRRED + "更新错误, 必须是0或者1")
@state.deleter # del book.state
def state(self):
del self.__state
print(OKGREEN + "删除书状态成功!")
if __name__ == "__main__":
# book = Book("python核心编程", 'python', 1)
# # book.set_state(3) # book.state = 3
# # print(book.get_state()) # print(book.state)
# book.state = 0
# print(book.state)
# del book.state
d = date(2019, 10, 10)
print(d.year)
print(d.month)
print(d.day)
# d.year = 2020 # 此处不成功, year是只读的
# del d.year # 此处不成功, year是只读的
print(d.year)
|
c967cdb333379e3d9d2d459a399c1753a56ef80e | arpiagar/HackerEarth | /flood-fill/solution.py | 1,402 | 3.65625 | 4 | i#https://leetcode.com/problems/flood-fill/
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
if not image or not image[0]:
return image
n_rows = len(image)
n_cols = len(image[0])
current_color = image[sr][sc]
if current_color == newColor:
return image
visited = set([])
self.fill(sr, sc, image, current_color, newColor, n_rows, n_cols, visited)
return image
def fill(self, curr_x, curr_y, image, current_color, color, n_rows, n_cols, visited):
if (curr_x,curr_y) not in visited :
visited.add((curr_x,curr_y))
print(visited)
if image[curr_x][curr_y] == current_color:
image[curr_x][curr_y] = color
if curr_x + 1 < n_rows:
self.fill(curr_x+1, curr_y, image, current_color,color, n_rows, n_cols, visited)
if curr_y + 1 < n_cols:
self.fill(curr_x, curr_y+1, image, current_color,color, n_rows, n_cols, visited)
if curr_x -1 >= 0:
self.fill(curr_x-1, curr_y, image, current_color, color, n_rows, n_cols, visited)
if curr_y -1 >=0 :
self.fill(curr_x, curr_y-1, image, current_color, color, n_rows, n_cols, visited)
return image
|
1a1f1b9dc741f99c83d4f45fbc3a4bbe7c74a2b0 | MartinThoma/LaTeX-examples | /source-code/Pseudocode/SolveLinearCongruences/solveLinearCongruences.py | 1,215 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def extended_euclidean_algorithm(a, b):
"""
Calculates gcd(a,b) and a linear combination such that
gcd(a,b) = a*x + b*y
As a side effect:
If gcd(a,b) = 1 = a*x + b*y
Then x is multiplicative inverse of a modulo b.
"""
aO, bO = a, b
x = lasty = 0
y = lastx = 1
while (b != 0):
q = a/b
a, b = b, a % b
x, lastx = lastx-q*x, x
y, lasty = lasty-q*y, y
return {
"x": lastx,
"y": lasty,
"gcd": aO * lastx + bO * lasty
}
def solve_linear_congruence_equations(rests, modulos):
"""
Solve a system of linear congruences.
Examples
--------
>>> solve_linear_congruence_equations([4, 12, 14], [19, 37, 43])
{'congruence class': 22804, 'modulo': 30229}
"""
assert len(rests) == len(modulos)
x = 0
M = reduce(lambda x, y: x*y, modulos)
for mi, resti in zip(modulos, rests):
Mi = M / mi
s = extended_euclidean_algorithm(Mi, mi)["x"]
e = s * Mi
x += resti * e
return {"congruence class": ((x % M) + M) % M, "modulo": M}
if __name__ == "__main__":
import doctest
doctest.testmod()
|
f4a3b9794a598b16372d00d7f6b49ba6da773b26 | souravbiswas1/PCA | /pca.py | 624 | 3.578125 | 4 | # PCA
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('sample.csv')
data = dataset.iloc[:, 2:12]
data_corr = data.corr()
print(data_corr)
X = dataset.iloc[:, 2:12].values
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X = sc.fit_transform(X)
# Applying PCA
from sklearn.decomposition import PCA
pca = PCA(n_components = 5)
X_pca = pca.fit_transform(X)
explained_variance = pca.explained_variance_ratio_
print('List of variance : ',explained_variance)
print('Reduced data : ',X_pca) |
bfeadf306fc8dde2da7daea954d4ad58ce5d1b81 | k906506/2020-Algorithm | /5주차_연습 (정렬1)/1. 문자 정렬.py | 180 | 3.765625 | 4 | def multiple_sort(input_list):
result = sorted(input_list, key = lambda x : (len(x), x))
return result
input_list = list(input().split())
print(multiple_sort(input_list))
|
482a33ffbf97e9c275eae9035de33c369ce782e6 | omedalus/IntrospectivePlanner | /python/ipl/nnplanner/estimate.py | 5,277 | 3.546875 | 4 |
import math
import random
from .action import Action
from .outcome import Outcome
class OutcomeLikelihoodEstimatorParams:
"""Configuration for an estimator.
"""
def __init__(self, n_sensors, n_actuators, **kwargs):
self.n_sensors = n_sensors
self.n_actuators = n_actuators
self.forget_delta_threshold = kwargs.get('forget_delta_threshold')
if self.forget_delta_threshold is None:
self.forget_delta_threshold = 0.005
#self.n_registers = 0
class OutcomeLikelihoodEstimator:
"""An object that can be given a set of vectors representing both
a current state and a subsequent state, and tries to estimate the
likelihood of seeing that subsequent state given the current one."""
def __init__(self, organism, params):
"""Create the estimator.
Arguments:
params {OutcomeLikelihoodEstimatorParams} -- Configuration info.
"""
self.organism = organism
self.params = params
def __relative_similarity(self, s1, s2):
"""Compute the proximity of two sensor vectors.
Arguments:
s1 {Outcome|list} -- A sensor vector to compare against.
s2 {Outcome|list} -- A sensor vector to compare against.
Returns:
{float} -- A float between 0 and 1, where 1 means the two vectors are identical
and 0 means the two vectors differ by at least .5 in every element.
"""
if isinstance(s1, Outcome):
s1 = s1.sensors
if isinstance(s2, Outcome):
s2 = s2.sensors
if len(s1) != len(s2):
raise ValueError('Sensor vectors need to be the same length.')
# This is just a const that tells us how different we permit two different
# sensor values to be before we give no reward at all for the counterfactual
# one. By setting it to <=.5, we can ensure that the trainee can't "cheat" by
# always outputting exactly .5 and always getting partial credit regardless of
# if the desired value is 0 or 1.
max_piecewise_diff = .5
# I could do something cleverly Pythonic here, but I'd really rather make
# the math explicit and obvious to make coding and debugging easier.
total_prox = 0
for se1, se2 in zip(s1, s2):
abs_diff = abs(se1 - se2)
magnified_diff = abs_diff / max_piecewise_diff
truncated_magnified_diff = min(magnified_diff, 1)
prox = 1 - truncated_magnified_diff
total_prox += prox
normalized_prox = total_prox / len(s1)
return normalized_prox
def learn(self, experience_repo):
"""Tell the estimator that certain combinations of sensors, actions, etc.,
led to certain observed outcome, and not any of the other outcomes that the estimator
might have previously believed had high likelihoods.
Arguments:
experience_repo {ExperienceRepo} -- Repository of all experiences the organism has ever had.
"""
pass
def estimate(self, sensors_prev, action, sensors_next):
"""Compute the likelihood that, after performing action action in the context of sensor state
sensors_prev, that the next sensor state encountered will be sensors_next.
Returns:
{float} -- The estimated relative likelihood of seeing the outcome.
"""
if self.organism is None or self.organism.experience_repo is None:
raise ValueError('Experience repo must be specified.')
p, ci = self.organism.experience_repo.get_outcome_probability(sensors_prev, action, sensors_next)
return p, ci
def get_known_outcomes(self, sensors_prev, action, prob_threshold=0):
if self.organism is None or self.organism.experience_repo is None:
raise ValueError('Experience repo must be specified.')
sensorsprobs = self.organism.experience_repo.lookup_outcomes(sensors_prev, action, prob_threshold=0)
outcomes = []
for sensorsprob in sensorsprobs:
sensors = sensorsprob[0]
prob = sensorsprob[1]
ci = sensorsprob[2]
c = Outcome()
c.sensors = sensors
c.probability = prob
c.probability_95ci = ci
outcomes.append(c)
return outcomes
def get_known_actions(self, sensors_prev):
if self.organism is None or self.organism.experience_repo is None:
raise ValueError('Experience repo must be specified.')
actuatorses = self.organism.experience_repo.lookup_actions(sensors_prev)
actions = []
for actuators in actuatorses:
a = Action()
a.actuators = actuators
actions.append(a)
return actions
def consolidate_experiences(self, max_experience_repo_size, verbosity=0):
"""Tries to determine which experiences can be removed from the repo, that will have a negligible effect
on the estimate results.
Arguments:
max_experience_repo_size {int} -- The biggest we want to let the experience repo get. We'll
stop consolidating if it's smaller than this.
Returns:
{list} -- A list of Experience objects that can be removed from the repo with no significant change
to the output of the estimator.
"""
raise NotImplementedError('Not implemented anymore.')
if verbosity > 0:
print('Repo size before consolidation: {}'.format(
len(experience_repo)))
pass
if verbosity > 0:
print('Repo size after consolidation: {}'.format(
len(experience_repo)))
|
39b3c278e8a424bd993002dcad0234862d7e72bf | leetuckert10/CrashCourse | /chapter_6/exercise_6-5.py | 1,032 | 4.65625 | 5 | # Rivers
# Make a dictionary containing three major rivers and the country each river
# runs through.
major_rivers = {
'sepik': 'new guinea',
'mississippi': 'united states',
'volga': 'russia',
'zambezi': 'africa',
'mekong': 'cambodia',
'ganges': 'india',
'danube': 'europe',
'yangtze': 'china',
'nile': 'egypt',
'amazon': 'brazil',
}
# print a sentence regarding the river and country
for river, country in major_rivers.items():
if country.lower() == 'united states':
print(f"The {river.title()} river runs through the {country.title()}.")
else:
print(f"The {river.title()} river runs through {country.title()}.")
# print just the river names
print("\nThe ten major rivers of the world are:")
for river in major_rivers:
print(f"\t{river.title()}")
# print just the names of the countries through which these rivers flow
print("\n These major rivers flow through these countries:")
for country in major_rivers.values():
print(f"\t{country.title()}")
|
01f2a1c634ff0e45a8b0760bf584931b77ca8282 | ankitshu/Python | /list.py | 928 | 3.96875 | 4 | #list data type
squares = [1, 4, 9, 16, 25]
print(squares)
#indexing
print(squares[0])
print(squares[-1])
#slicing
print(squares[2:])
print(squares[-2:])
list_copy=squares[:]
print(type(list_copy))
#concatination
new_list=squares + [36, 49, 64, 81, 100]
print(type(new_list),new_list)
#mutablity
cubes = [1, 8, 27, 65, 125]
print(id(cubes))
cubes[3]=64
print(id(cubes),cubes)
cubes.append(6**3)
print(cubes)
cubes[2:5]=[12,13,14]
print(cubes)
cubes[2:5]=[]
print(cubes)
cubes[:]=[]
print(cubes)
print(len(cubes))
#nested List
alpha=['a','b','c','d']
num=[5,30,10,5]
new_list=[alpha,num]
print(new_list)
print(new_list[0])
print(new_list[1])
print(new_list[0][2],(new_list[1][3]))
alpha.append('e')
print(new_list)
#in and not in
if('c' in alpha):
print("it gives true")
if('e' in alpha):
print("it gives true")
if('c' not in num):
print("it gives true")
if(10 not in num):
print("it gives true")
|
98cd2981cced419a2eaac440d7ff32cd22ff17fc | MahZin/Python-Automation- | /Section 12_Debugging/35_assert.py | 817 | 3.90625 | 4 | # Assertion
# at a street, northsouth stoplight is grn, eastwest is red
market_2nd = {'ns': 'green', 'ew': 'red'}
# Let's define a function that can switch the lights
def switchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 'red':
intersection[key] = 'green'
# assert something that must be true
assert 'red' in intersection.values(), 'Neither light is red!' + str(intersection)
print(market_2nd)
switchLights(market_2nd)
print(market_2nd)
# AssertionErrors are for detecting programmer errors meant to be recovered from
# UserErrors should raise Exceptions
|
5bfafc967afb422930873b3bf3a6700aadb9e9fc | FazalJarral/TicTacToe | /main.py | 3,259 | 3.984375 | 4 | import random
board = {
"1": '_', "2": '_', "3": '_',
"4": '_', "5": '_', "6": '_',
"7": '_', "8": '_', "9": '_',
}
def print_board():
print(' | |')
print(' ' + board["1"] + ' | ' + board["2"] + ' | ' + board["3"])
print(' | |')
print(' ' + board["4"] + ' | ' + board["5"] + ' | ' + board["6"])
print(' | |')
print(' ' + board["7"] + ' | ' + board["8"] + ' | ' + board["9"])
def first_turn():
if random.randint(0, 2) == 0:
# X is for human
return "Human"
else:
return "Computer"
def get_available_slots():
return [pos for pos, value in board.items() if value == "_"]
def board_has_space():
if [item for pos,item in board.items() if item == "_"]:
return True
else:
return False
moves_made = []
def is_winning_move(marker):
return ((board["7"] == marker and board["8"] == marker and board["9"] == marker) or # across the bottom
(board["4"] == marker and board["5"] == marker and board["6"] == marker) or
(board["1"] == marker and board["2"] == marker and board["3"] == marker) or
(board["1"] == marker and board["4"] == marker and board["7"] == marker) or
(board["2"] == marker and board["5"] == marker and board["8"] == marker) or
(board["3"] == marker and board["6"] == marker and board["9"] == marker) or
(board["1"] == marker and board["5"] == marker and board["9"] == marker) or
(board["3"] == marker and board["5"] == marker and board["7"] == marker))
def main():
found_winner = False
current_player = first_turn()
continue_game = True
while continue_game:
if current_player == 'Human':
print("You Will Make the Move")
board_piece = input("Where Would You Place Your Marker: ")
if board_has_space():
if board_piece.isnumeric() and board_piece != 0:
if board_piece in moves_made:
print("The Block Is Not Empty, Select Another One")
else:
board[board_piece] = "X"
moves_made.append(board_piece)
print_board()
if is_winning_move("X"):
found_winner = True
continue_game = False
else:
current_player = 'Computer'
else:
print("Please Select From 1-10")
else:
# Computer will make a move
print("Computer Will Make the Move")
if board_has_space():
empty_space = get_available_slots()
move = random.choice(empty_space)
board[move] = "O"
moves_made.append(move)
print_board()
if is_winning_move("O"):
found_winner = True
continue_game = False
else:
current_player = 'Human'
else:
if found_winner:
print(f'{current_player} has WON!!!')
else:
print("Its a draw")
if __name__ == "__main__":
main()
|
399e0ea7155c26a6769e4725bbe992c67cbc8599 | MarcusQuigley/MIT_Python | /IronPythonApplication1/Lecture4/ContainsVowel.py | 293 | 3.875 | 4 | def isVowel(char):
return char.lower() in ('a', 'e', 'i', 'o', 'u')
def isVowel2(char):
chr = char.lower()
if chr == 'a' or chr == 'e' or chr == 'i' or chr == 'o' or chr == 'u':
return True
return False
print isVowel('a')
print isVowel('d')
print isVowel('A') |
40345cc1ffd6361b7c40e73cf2b752d054869a23 | sahiljain2497/fill-ups-python | /Project1.py | 3,789 | 3.90625 | 4 | print "Welcome to my first quiz"
print
#this fucntion helps the user to select the data required for the selected input
def selection(level):
paragraph = game_data[level]['paragraph']
answers = game_data[level]['answers']
return paragraph,answers
#finds words that match in the paragraph
def word_in_pos(word, parts_changed):
for pos in parts_changed:
if pos in word:
return pos
return None
#asks users to enter the answer and makes replacement accordingly
#split function returns the list of all the words used in the string
#replace function used replaced the string we need to change
#append function stored the new word in the string
def game(paragraph, parts_changed,answers):
print
print paragraph
print
i=0
edited = paragraph
count=0
limit=5
replaced = []
paragraph = paragraph.split()
for word in paragraph:
replacement = word_in_pos(word, parts_changed)
if replacement != None:
while i<limit:
user_input = raw_input("Type in: " + replacement + " ")
if user_input!=answers[count]:
i=i+1
print "try again"
else:
paragraph = str(paragraph)
edited = edited.replace(replacement, user_input)
print edited
break
count+=1
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
if i==limit:
print "You failed"
else:
replaced = " ".join(replaced)
print
print "Ok, lets see your results."
print
print replaced
while True:
#List of words to be replaced
parts_changed = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
#DATA FOR THE QUESTIONS AND THEIR ANSWERS
game_data={
'easy':{
'paragraph':"HTML is short for _Word1_ Markup Language. HTML is used to create electronic documents called _Word2_ that are displayed on the World Wide Web. Each page contains a series of connections to other pages called _Word3_.HTML provides a structure of the page, upon which _Word4_ Style Sheets are used to change its appearance.",
'answers':['hypertext','webpages','hyperlinks','cascading']
},
'medium':{
'paragraph':"Java is a general purpose, high-level programming language developed by _Word1_ Java was originally called _Word2_ and was designed for handheld devices .Java is an _Word3_ language similar to C++. Java source code files are compiled into a format called _Word4_ (.class extension).",
'answers':['sun microsystems','OAK','object-oriented','bytecodes']
},
'hard':{
'paragraph':" This type of loop will continue to run as long as it is true: _Word1_. When using a comparison this is used to say not equal to : _Word2_ .Creating a _Word3_ also creates certain methods inside it. When creating a function you may have to pass : _Word4_",
'answers':['while','!','class','argument']
}
}
level= raw_input("Which difficulty level would you like? Type EASY, MEDIUM or HARD to continue? ")
while level.lower()!="easy" and level.lower()!="medium" and level.lower()!="hard":
print "Sorry wrong choice!try again."
level= raw_input("Which difficulty level would you like? Type EASY, MEDIUM or HARD to continue? ")
paragraph,answers = selection(level.lower())
game(paragraph, parts_changed,answers)
print
choice=raw_input("If you don't want to play again press N else press Enter")
if choice.upper()=="N":
break
|
a47580cf89f2db523a9f38f372875aeb0fb57e48 | tarungoyal1/practice-100 | /11- binary conversion divisible.py | 961 | 4 | 4 | # Question 11
# Level 2
#
# Question:
# Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
# Example:
# 0100,0011,1010,1001
# Then the output should be:
# 1010
# Notes: Assume the data is input by console.
def main(binlist):
divisiblelist = [num for num in binlist if convertBinToInt(num)%5==0]
if divisiblelist:print(", ".join(divisiblelist))
else:print("No such number")
def convertBinToInt(binNum):
i = 1
integer = 0
for digit in binNum[::-1]:
if int(digit) == 1:
integer += i
i *= 2
return integer
if __name__=='__main__':
binarylist = [num.strip(' ') for num in input("Enter comma-seperated binary numbers:").split(',') if all((int(char) in [1, 0]) for char in num.strip(' '))==True]
main(binarylist) |
6b5f78271f6f2ae4817ef6342b3f86a5ae8de077 | FourSwordKirby/NLP-Final-Project | /Question Generating/inc/Questions.py | 864 | 3.578125 | 4 | """
author:
etctec
desc:
"""
import rules
# Takes in a dict of {heading : paragraph} and returns a list of questions.
def articleToQuestion(article):
questions = [];
for heading in article.keys() :
paragraph = article[heading];
for sentence in paragraph:
new_question = rules.who_rule(sentence)
if not (new_question == ""):
questions.append(new_question)
new_question = rules.has_rule(sentence)
if not (new_question == ""):
questions.append(new_question)
new_question = rules.can_rule(sentence)
if not (new_question == ""):
questions.append(new_question)
return questions
# Returns the top num questions in questions.
def determineBestQuestions(questions, num):
# NYI
return []
|
434eaf812315caba0ae78c9c91b88565df925fa8 | Hogusong/CodeFight-Python3 | /Trees/deleteFromBST.py | 3,907 | 3.84375 | 4 | # A tree is considered a binary search tree (BST) if for each of its nodes the following is true:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and the right subtrees must also be binary search trees.
# Removing a value x from a BST t is done in the following way:
#
# If there is no x in t, nothing happens;
# Otherwise, let t' be a subtree of t such that t'.value = x.
# If t' has a left subtree, remove the rightmost node from it and put it at the root of t';
# Otherwise, remove the root of t' and its right subtree becomes the new t's root.
# For example, removing 4 from the following tree has no effect because there is no such value in the tree:
#
# 5
# / \
# 2 6
# / \ \
# 1 3 8
# /
# 7
# Removing 5 causes 3 (the rightmost node in left subtree) to move to the root:
#
# 3
# / \
# 2 6
# / \
# 1 8
# /
# 7
# And removing 6 after that creates the following tree:
#
# 3
# / \
# 2 8
# / /
# 1 7
# You're given a binary search tree t and an array of numbers queries. Your task is to remove
# queries[0], queries[1], etc., from t, step by step, following the algorithm above. Return the resulting BST.
#
# Example
#
# For
#
# t = {
# "value": 5,
# "left": {
# "value": 2,
# "left": {
# "value": 1,
# "left": null,
# "right": null
# },
# "right": {
# "value": 3,
# "left": null,
# "right": null
# }
# },
# "right": {
# "value": 6,
# "left": null,
# "right": {
# "value": 8,
# "left": {
# "value": 7,
# "left": null,
# "right": null
# },
# "right": null
# }
# }
# }
# and queries = [4, 5, 6], the output should be
#
# deleteFromBST(t, queries) = {
# "value": 3,
# "left": {
# "value": 2,
# "left": {
# "value": 1,
# "left": null,
# "right": null
# },
# "right": null
# },
# "right": {
# "value": 8,
# "left": {
# "value": 7,
# "left": null,
# "right": null
# },
# "right": null
# }
# }
# Input/Output
#
# [execution time limit] 4 seconds (py3)
#
# [input] tree.integer t
#
# A tree of integers.
#
# Guaranteed constraints:
# 0 ≤ t size ≤ 1000,
# -109 ≤ node value ≤ 109.
#
# [input] array.integer queries
#
# An array that contains the numbers to be deleted from t.
#
# Guaranteed constraints:
# 1 ≤ queries.length ≤ 1000,
# -109 ≤ queries[i] ≤ 109.
#
# [output] tree.integer
#
# The tree after removing all the numbers in queries, following the algorithm above.
def deleteNode(t):
left = t.left
right = t.right
if left == None and right == None:
return None
elif left == None:
return right
else:
if left.right == None:
left.right = right
return t.left
previous = t
t = t.left
while t.right != None:
previous = t
t = t.right
previous.right = t.left
t.left = left
t.right = right
return t
def deleteOneFromBST(t, value):
if t == None: return None
if t.value == value: return deleteNode(t)
if value < t.value:
if t.left == None:
return t
else:
t.left = deleteOneFromBST(t.left, value)
else:
if t.right == None:
return t
else:
t.right = deleteOneFromBST(t.right, value)
return t
def deleteFromBST(t, queries):
for value in queries:
t = deleteOneFromBST(t, value)
return t
|
5377e978e6830c0e9264d732ba01b8bd7781a0be | juvelop17/problem_solving | /programmers/code challenge 3-2/2.py | 292 | 3.625 | 4 |
def solution(n, left, right):
answer = []
for a in range(left, right + 1):
i = a // n
j = a - i * n
answer.append(max(i + 1, j + 1))
return answer
if __name__ == '__main__':
n = 3
left = 2
right = 5
print(solution(n, left, right))
|
f535ae9ad828cbf5cf6c18bf623ee4bbff862750 | john-karlen/COMPSCI590S | /projects/project1/wordcount.py | 1,103 | 4.21875 | 4 | # Wordcount
# Prints words and frequencies in decreasing order of frequency.
# To invoke:
# python wordcount.py file1 file2 file3...
# Author: Emery Berger, www.emeryberger.com
import sys
import operator
# The map of words -> counts.
wordcount={}
# Read filenames off the argument list.
for filename in sys.argv[1:]:
file=open(filename,"r+")
# Process all words.
for word in file.read().split():
# Get the previous count (possibly 0 if new).
count = wordcount.get(word, 0)
# Increment it.
wordcount[word] = count + 1
file.close()
# Build a list of words for each count.
revwordcount = {} # revwordcount: count -> [word]
for pair in wordcount.iteritems():
if not pair[1] in revwordcount:
revwordcount[pair[1]] = []
revwordcount[pair[1]].append(pair[0])
# Sort the counts in reverse order.
for pair in sorted(revwordcount.iteritems(), key=lambda s: s[0], reverse = True):
# Print word and count, with words sorted in alphabetical order.
for v in sorted(pair[1]):
print ("%s : %s" %(pair[0] , v))
|
7c47fa8f558ec682f00a53aef08b26b85c61dc1b | TaoKeC/sc-projects | /stanCode_Projects/my_photoshop/blur.py | 7,469 | 3.921875 | 4 | """
File: blur.py
Name: TaoKe Chorng
-------------------------------
This file shows the original image first,
smiley-face.png, and then compare to its
blurred image. The blur algorithm uses the
average RGB values of a pixel's nearest neighbors
"""
from simpleimage import SimpleImage
def blur(img):
"""
:param img: (SimpleImage) the original image
:return: The updated image with blur result
"""
new_image = SimpleImage.blank(img.width, img.height) # create a new blank canvas
for y in range(new_image.height):
for x in range(new_image.width):
new_pixel = new_image.get_pixel(x, y) # (comment for TaoKe Chorng) get the 8 bit*3 info 0000000*3
# blur four corner's pixels
if x == 0 and y == 0:
pixel = img.get_pixel(x, y)
pixel6 = img.get_pixel(x + 1, y)
pixel8 = img.get_pixel(x, y + 1)
pixel9 = img.get_pixel(x + 1, y + 1)
# (comment for TaoKe Chorng) adjust the 00000000 info
new_pixel.red = (pixel.red + pixel6.red + pixel8.red + pixel9.red) / 4
new_pixel.blue = (pixel.blue + pixel6.blue + pixel8.blue + pixel9.blue) / 4
new_pixel.green = (pixel.green + pixel6.green + pixel8.green + pixel9.green) / 4
elif x == img.width - 1 and y == 0:
pixel4 = img.get_pixel(x - 1, y)
pixel = img.get_pixel(x, y)
pixel7 = img.get_pixel(x - 1, y + 1)
pixel8 = img.get_pixel(x, y + 1)
new_pixel.red = (pixel.red + pixel4.red + pixel8.red + pixel7.red) / 4
new_pixel.blue = (pixel.blue + pixel4.blue + pixel8.blue + pixel7.blue) / 4
new_pixel.green = (pixel.green + pixel4.green + pixel8.green + pixel7.green) / 4
elif x == 0 and y == img.height - 1:
pixel2 = img.get_pixel(x, y - 1)
pixel3 = img.get_pixel(x + 1, y - 1)
pixel = img.get_pixel(x, y)
pixel6 = img.get_pixel(x + 1, y)
new_pixel.red = (pixel2.red + pixel3.red + pixel.red + pixel6.red) / 4
new_pixel.blue = (pixel.blue + pixel2.blue + pixel3.blue + pixel6.blue) / 4
new_pixel.green = (pixel.green + pixel2.green + pixel3.green + pixel6.green) / 4
elif x == img.width-1 and y == img.height-1:
pixel1 = img.get_pixel(x - 1, y - 1)
pixel2 = img.get_pixel(x, y - 1)
pixel4 = img.get_pixel(x - 1, y)
pixel = img.get_pixel(x, y)
new_pixel.red = (pixel1.red + pixel2.red + pixel.red + pixel4.red) / 4
new_pixel.blue = (pixel.blue + pixel2.blue + pixel1.blue + pixel4.blue) / 4
new_pixel.green = (pixel.green + pixel2.green + pixel1.green + pixel4.green) / 4
# blur the upper side
elif y == 0 and img.width - 1 > x > 0:
pixel4 = img.get_pixel(x - 1, y)
pixel = img.get_pixel(x, y)
pixel6 = img.get_pixel(x + 1, y)
pixel7 = img.get_pixel(x - 1, y + 1)
pixel8 = img.get_pixel(x, y + 1)
pixel9 = img.get_pixel(x + 1, y + 1)
new_pixel.red = (pixel4.red + pixel.red + pixel6.red + pixel7.red + pixel8.red + pixel9.red) / 6
new_pixel.blue = (pixel4.blue + pixel.blue + pixel6.blue + pixel7.blue + pixel8.blue + pixel9.blue) / 6
new_pixel.green = (pixel4.green + pixel.green + pixel6.green + pixel7.green + pixel8.green +
pixel9.green) / 6
# blur the right side pixels
elif x == 0 and img.height - 1 > y > 0:
pixel2 = img.get_pixel(x, y - 1)
pixel3 = img.get_pixel(x + 1, y - 1)
pixel = img.get_pixel(x, y)
pixel6 = img.get_pixel(x + 1, y)
pixel8 = img.get_pixel(x, y + 1)
pixel9 = img.get_pixel(x + 1, y + 1)
new_pixel.red = (pixel2.red + pixel3.red + pixel.red + pixel6.red + pixel8.red + pixel9.red) / 6
new_pixel.blue = (pixel2.blue + pixel3.blue + pixel.blue + pixel6.blue + pixel8.blue + pixel9.blue) / 6
new_pixel.green = (pixel2.green + pixel3.green + pixel.green + pixel6.green + pixel8.green +
pixel9.green) / 6
# blur the left side pixels
elif x == img.width - 1 and img.height - 1 > y > 0:
pixel1 = img.get_pixel(x - 1, y - 1)
pixel2 = img.get_pixel(x, y - 1)
pixel4 = img.get_pixel(x - 1, y)
pixel = img.get_pixel(x, y)
pixel7 = img.get_pixel(x - 1, y + 1)
pixel8 = img.get_pixel(x, y + 1)
new_pixel.red = (pixel1.red + pixel2.red + pixel4.red + pixel.red + pixel7.red + pixel8.red) / 6
new_pixel.blue = (pixel1.blue + pixel2.blue + pixel4.blue + pixel.blue + pixel7.blue + pixel8.blue) / 6
new_pixel.green = (pixel1.green + pixel2.green + pixel4.green + pixel.green + pixel7.green +
pixel8.green) / 6
# blur the bottom side pixels
elif img.width - 1 > x > 0 and y == img.height - 1:
pixel1 = img.get_pixel(x - 1, y - 1)
pixel2 = img.get_pixel(x, y - 1)
pixel3 = img.get_pixel(x + 1, y - 1)
pixel4 = img.get_pixel(x - 1, y)
pixel = img.get_pixel(x, y)
pixel6 = img.get_pixel(x + 1, y)
new_pixel.red = (pixel1.red + pixel2.red + pixel3.red + pixel4.red + pixel.red + pixel6.red) / 6
new_pixel.blue = (pixel1.blue + pixel2.blue + pixel3.blue + pixel4.blue + pixel.blue + pixel6.blue) / 6
new_pixel.green = (pixel1.green + pixel2.green + pixel3.green + pixel4.green + pixel.green +
pixel6.green) / 6
# blur the rest pixels
else:
pixel1 = img.get_pixel(x - 1, y - 1)
pixel2 = img.get_pixel(x, y - 1)
pixel3 = img.get_pixel(x + 1, y - 1)
pixel4 = img.get_pixel(x - 1, y)
pixel = img.get_pixel(x, y)
pixel6 = img.get_pixel(x + 1, y)
pixel7 = img.get_pixel(x - 1, y + 1)
pixel8 = img.get_pixel(x, y + 1)
pixel9 = img.get_pixel(x + 1, y + 1)
new_pixel.red = (pixel1.red + pixel2.red + pixel3.red + pixel4.red + pixel.red + pixel6.red +
pixel7.red + pixel8.red + pixel9.red) / 9
new_pixel.blue = (pixel1.blue + pixel2.blue + pixel3.blue + pixel4.blue + pixel.blue + pixel6.blue +
pixel7.blue + pixel8.blue + pixel9.blue) / 9
new_pixel.green = (pixel1.green + pixel2.green + pixel3.green + pixel4.green + pixel.green + pixel6.green +
pixel7.green + pixel8.green + pixel9.green) / 9
return new_image
def main():
"""
This program blur the original image with the blur function and
"""
old_img = SimpleImage("images/smiley-face.png")
old_img.show()
blurred_img = blur(old_img)
for i in range(10):
blurred_img = blur(blurred_img)
blurred_img.show()
if __name__ == '__main__':
main()
|
326132bf341ab4c7e4d8f5d00880ef40195e8b8c | sanjayait/core-python | /10-Chapter 10/dict_if_else.py | 139 | 3.84375 | 4 | odd_even={i : ('even' if i%2==0 else 'odd') for i in range(1,11)}
# print(odd_even)
for j,k in odd_even.items():
print(f"{j} : {k}") |
a19496f05f17639c0f464f595ad674cb65da1c38 | chu1070y/algorithm | /matrix.py | 922 | 3.90625 | 4 | # 3x3행렬 중 합이 최소가 되는 항목 선택허긔
# 각 행과 열이 중복되지 않도록 숫자를 선택하고, 선택한 숫자들의 최소값을 구하는 알고리즘
class MatrixMinimum:
def __init__(self, data):
self.idx = [False] * len(data[0])
self.data = data
self.count = len(data[0])
self.sum = 0
self.min = 100000
def find(self, row = 0):
if row == 3:
if self.sum < self.min:
self.min = self.sum
return self.min
for i in range(self.count):
if self.idx[i] == False:
self.sum += self.data[row][i]
self.idx[i] = True
self.find(row+1)
self.idx[i] = False
self.sum = 0
return self.min
matrix = [[1, 5, 3], [2, 5, 7], [5, 3, 5]]
result = MatrixMinimum(matrix)
result.find()
print(result.min)
|
7fdf21d68603254c8f112001fbe0f8a83ee03323 | judong93/TIL | /algorithm/0824~/반복문자 지우기.py | 345 | 3.59375 | 4 | def dele(text):
if len(text) >= 2:
for i in range(len(text)-1):
if text[i] == text[i+1]:
text.pop(i)
text.pop(i)
return dele(text)
return len(text)
T = int(input())
for tc in range(1, T+1):
text = list(input())
result = dele(text)
print(f'#{tc} {result}')
|
20a5ecd5ba704cc590126ba8bb8751decba25242 | bkestelman/python_algorithms_and_data_structures | /search.py | 1,484 | 4.28125 | 4 | def binary_search_simple_recursive(arr, e):
"""
Simple recursive implementation of binary search that does not
need to keep track of left and right bounds.
@param arr list
@param e element
@return index of e, or its insertion point if not found
"""
if len(arr) == 0:
return 0
mid = len(arr) // 2 # exact middle for odd len, just right of middle for even len
if arr[mid] == e:
return mid
if arr[mid] > e:
return binary_search_simple_recursive(arr[:mid], e)
else:
return mid+1 + binary_search_simple_recursive(arr[mid+1:], e)
def binary_search_recursive(arr, e, l=0, r=None):
"""
Recursive implementation of binary search
@param arr list
@param e element
@param l left bound
@param r right bound
@return index of e, or -1 if not found
"""
if r is None:
r = len(arr)
if r <= l:
return -1
mid = (l + r) // 2
if arr[mid] == e:
return mid
if arr[mid] > e:
return binary_search_recursive(arr, e, l=l, r=mid)
else:
return binary_search_recursive(arr, e, l=mid+1, r=r)
def binary_search_iterative(arr, e, l=0, r=None):
"""
"""
if r is None:
r = len(arr)
while l < r:
mid = (l + r) // 2
if arr[mid] == e:
return mid
if arr[mid] > e:
r = mid
else:
l = mid + 1
return -1
|
3495066851fc5780f948f97565a683ba28acbea5 | essneider0707/andres | /ejercicio_41.py | 302 | 3.875 | 4 | n1=int(input("ingresa un numero por favor: "))
n2=int(input("ingresa un numero por favor: "))
n3=int(input("ingresa un numero por favor: "))
#
if n1 == n2 :
print(f"{n1} y {n2} son iguales")
elif n1 == n3 :
print(f"{n1} y {n3} son iguales")
elif n2 == n3 :
print(f"{n2} y {n3} son iguales") |
bbae601856130252d0035f0be2fe7c137e712316 | abijr/master-python101 | /101/guess_game.py | 313 | 3.75 | 4 | secret_word = "hydrogen"
guess_count = 0
guess_limit = 4
while guess_count < guess_limit:
guess_input = str(input(f"Guess the Element right: "))
guess_count += 1
if guess_input.lower() == secret_word:
print(f"You WON! Your guess is Right.")
break
else:
print(f"Sorry, you lost!")
|
3cf234ab165d8f97d19807ee645f127dcbf9f123 | sdrdis/parking_occupancy_planetscope | /convert_datetime.py | 554 | 3.5625 | 4 | from datetime import datetime
import pytz
# METHOD 1: Hardcode zones:
from_zone = pytz.timezone('UTC')
to_zone = pytz.timezone('US/Eastern')
# utc = datetime.utcnow()
utc = datetime.strptime('2019-07-10T16:02:43Z', '%Y-%m-%dT%H:%M:%SZ')
dateutc = from_zone.localize(utc)
dateeastern = dateutc.astimezone(to_zone)
'''
# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
'''
print (dateutc)
print (dateeastern) |
e648cb879b9c378ae4f07040b4cff3dfaf597b80 | lizhou828/python_hello_world | /helloWorld/calcCenterPointByLand/calc_length_by_langitude_latitude.py | 1,259 | 3.890625 | 4 | # -*- coding:utf-8 -*-
# python利用地图两个点的经纬度计算两点间距离
# https://blog.csdn.net/u013401853/article/details/73368850
# 参考文章:
# LBS 球面距离公式 http://oracle-abc.wikidot.com/zh-blog:20
from math import sin, asin, cos, radians, fabs, sqrt
EARTH_RADIUS=6371 # 地球平均半径,6371km
def hav(theta):
s = sin(theta / 2)
return s * s
def get_distance_hav(lat0, lng0, lat1, lng1):
"用haversine公式计算球面两点间的距离。"
# 经纬度转换成弧度
lat0 = radians(lat0)
lat1 = radians(lat1)
lng0 = radians(lng0)
lng1 = radians(lng1)
dlng = fabs(lng0 - lng1)
dlat = fabs(lat0 - lat1)
h = hav(dlat) + cos(lat0) * cos(lat1) * hav(dlng)
distance = 2 * EARTH_RADIUS * asin(sqrt(h))
return distance
lon1,lat1 = (22.599578, 113.973129) #深圳野生动物园(起点)
lon2,lat2 = (22.6986848, 114.3311032) #深圳坪山站 (百度地图测距:38.3km)
d2 = get_distance_hav(lon1,lat1,lon2,lat2)
print(d2)
lon2,lat2 = (39.9087202, 116.3974799) #北京天安门(1938.4KM)
d2 = get_distance_hav(lon1,lat1,lon2,lat2)
print(d2)
lon2,lat2 =(34.0522342, -118.2436849) #洛杉矶(11625.7KM)
d2 = get_distance_hav(lon1,lat1,lon2,lat2)
print(d2) |
60fa65f498f724876052bf3f71ed477e7b9b6011 | ChristianBalazs/DFESW3 | /abstraction_tutorial.py | 1,105 | 4.5625 | 5 |
# We are going to create some classes. The superclass is going to be Bird.
from abc import ABC, abstractmethod
class Bird(ABC):
fly = True
babies = 0
def noise(self):
return "Squawk"
def reproduce(self):
self.babies += 1
@abstractmethod
def eat(self):
pass
extinct = False
# Now we are going to create the first subclass.
class Owl(Bird):
def reproduce(self):
self.babies += 6
def eat(self):
return "Peck peck"
# So we have used Polymorphism to override the reproduce method, Abstraction with the eat method and Inheritance in this child class.
# Now we will add another subclass.
class Dodo(Bird):
Fly = False
extinct = True
def eat(self):
return "Nom nom"
def reproduce(self):
if not self.extinct:
self.babies += 1
# For this subclass we have used Polymorphism to override the reproduce method and Fly and extinct variables, Encapsulation to keep the babies variable from being directly accessed as well as Inheritance again to create a child class of Bird.
|
f95c7868d25d661168035cfe7306a092e1b7d473 | tata-LY/python | /study_oldboy/python_work/进度条.py | 657 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021-2-22 11:14
# @Author : liuyang
# @File : 进度条.py
# @Software: PyCharm
import math
import sys
import time
def progressbar(cur, total):
percent = '{:.2%}'.format(cur / total)
sys.stdout.write('\r')
sys.stdout.write('[%-50s] %s' % ('=' * int(math.floor(cur * 50 / total)), percent))
sys.stdout.flush()
if cur == total:
sys.stdout.write('\n')
if __name__ == '__main__':
file_size = 102400
size = 0
while size <= file_size:
progressbar(size, file_size)
size += 1024
time.sleep(0.5) # 增加sleep,可以看出效果 |
108878c6985a1eec9b546d4f71f7e8411ed9c432 | shoroogAlghamdi/test | /Unit4/unit4-activity6.py | 111 | 3.53125 | 4 | # Slide 108
count = 0
while(count<10):
print("I have made a mistake and I am sorry!")
count = count + 1 |
f2b6a25d84fe3299ce1891249e09c947712e08d4 | Python-Programming-Boot-Camp/TimGrogan | /lab_2.6.1.9py.py | 468 | 4.1875 | 4 | a = float(input("input value for a ")) # input a float value for variable a here
b = float(input("input value for b ")) # input a float value for variable b here
print(" a+b=", a+b) # output the result of addition here
print(" a-b=", a-b) # output the result of subtraction here
print(" a*b=", a*b) # output the result of multiplication here
print(" a/b=", a/b) # output the result of division here
print("\nThat's all, folks!") |
51af537e155885599267898393abb1bea1cf8aeb | grantmartin161096/Grant-Martin-b00340010-trimester-1 | /Creating module for sentiment analysis.py | 6,108 | 3.71875 | 4 | import nltk
import random
import pickle
from nltk.classify import ClassifierI
from statistics import mode
from nltk.tokenize import word_tokenize
# import nltk gives me access to the nltk libraries of data and programs for data analysis
# import random will be used to shuffle my training and testing dataset of short movie reviews
# to make the classifier accurate and reliable when processing live tweets
# My dataset has already been labelled as positive and negative, making it possible to train and test with
# import pickle will insert my previously saved and serialised file of my naive bayes classifier and most common 5000 words
# word_tokenize will tokenizes the dataset, separating each word from the body of text as tokens
# I imported mode, this will choose the most popular classifier vote (this code was used when I had more classifiers in the code)
# Line classifierI is the classifier being used on the data
# The class below is for my classifier
# The classifier is called VoteClassifier and is inherting ClassifierI
# The classifiers well in this case the naive bayes classifier is programmed to pass through the class to self.classifier
# In the second function 'def classify' I define my classify process, so I can call on it later on.
# The functions below are passing through the classifier and classifying by features
# The classification is being processed as a vote (was more effective when I had more classifiers)
# Finally the class returns the the mode(vote), the most popular classifier (again better when you have more classifiers)
class VoteClassifier(ClassifierI):
def __init__(self, *classifiers):
self._classifiers = classifiers
def classify(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
return mode(votes)
def confidence(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
choice_votes = votes.count(mode(votes))
conf = choice_votes / len(votes)
return conf
# confidence function is simply counting up the votes for each classifiers (again working better when you use more classifiers)
# See the user guide for instructions on how to download the positive and negative.txt files for training and testing classifier.
# 2 two lines below open the text files and reads the text data contained within.
short_pos = open("positive.txt", "r").read()
short_neg = open("negative.txt", "r").read()
all_words = []
documents = []
# all_words equals empty list
# documents equals empty list
# j is adjective, r is adverb, and v is verb
# allowed_word_types = ["J","R","V"]
allowed_word_types = ["J"]
# I am only looking for adjectives in the dataset
for p in short_pos.split('\n'):
documents.append((p, "pos"))
words = word_tokenize(p)
pos = nltk.pos_tag(words)
for w in pos:
if w[1][0] in allowed_word_types:
all_words.append(w[0].lower())
# The above if statement is saying if the word is an adjective I want to append that word
for p in short_neg.split('\n'):
documents.append((p, "neg"))
words = word_tokenize(p)
pos = nltk.pos_tag(words)
for w in pos:
if w[1][0] in allowed_word_types:
all_words.append(w[0].lower())
# The above if statement is saying if the word is an adjective I want to append that word
# Below I am saving the words in a pickle file
save_documents = open("documents.pickle", "wb")
pickle.dump(documents, save_documents)
save_documents.close()
# The above 3 lines of code saved and stored the results of my code in a pickle file, to be accessed at any point in the future.
all_words = nltk.FreqDist(all_words)
# The line of code above will form a list of the most common words in the text files.
word_features = list(all_words.keys())[:5000]
# The above line of code records the most common 5000 words from both text files.
save_word_features = open("word_features5k.pickle", "wb")
pickle.dump(word_features, save_word_features)
save_word_features.close()
# The above 3 lines of code saved and stored the results of my code in a pickle file, to be accessed at any point in the future.
def find_features(document):
words = word_tokenize(document)
features = {}
for w in word_features:
features[w] = (w in words)
return features
# The line of code below does this to all documents, saving the feature existence booleans and the positive or negative categories
featuresets = [(find_features(rev), category) for (rev, category) in documents]
random.shuffle(featuresets)
#This mixes up the positive and negative featuresets
print(len(featuresets))
# The line of code above prints the length of the dataset (total number of positive and negative datasets)
# dataset I will test classifier against
testing_set = featuresets[10000:]
# dataset I will train classifier with
training_set = featuresets[:10000]
classifier = nltk.NaiveBayesClassifier.train(training_set)
print("Original Naive Bayes Algo accuracy percent:", (nltk.classify.accuracy(classifier, testing_set)) * 100)
classifier.show_most_informative_features(15)
# The above lines of code will print the percentage accuracy of the naive bayes classifier and the 15 most common words
save_classifier = open("originalnaivebayes5k.pickle", "wb")
pickle.dump(classifier, save_classifier)
save_classifier.close()
# The above 3 lines of code saved and stored the results of my code in a pickle file, to be accessed at any point in the future.
# 'open' create a new pickle file
# 'wb' means write in bytes
# I used pickle.dump() to dump the data.
# The first parameter to pickle.dump() is what are you dumping.
# The second parameter is where are you dumping it.
# Close the file and now I have a pickle file saved.
# Reference for code used: https://pythonprogramming.net/sentiment-analysis-module-nltk-tutorial/ |
baa5976184e112e1c2339e134105eac2aad432eb | arnabs542/onebroccoli | /leetcode_journey/Q270_Closest_Binary_Search_Tree_Value.py | 1,519 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Given a non-empty binary search tree and a target value,
find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
Example:
Input: root = [4,2,5,1,3], target = 3.714286
4
/ \
2 5
/ \
1 3
Output: 4
"""
class Solution(object):
def cloesetValue(self, root, target):
"""
:param root: TreeNode
:param target: float
:return: int
"""
lst = []
def inorder(root):
if root:
inorder(root.left)
lst.append(root.val)
inorder(root.right)
inorder(root)
close = lst[0]
diff = abs(target - lst[0])
for i in lst:
if abs(target - i) < diff:
close = i
diff = abs(target - i)
return close
class newnode:
# Constructor to create a new node
def __init__(self, data):
self.val = data
self.left = None
self.right = None
# Driver Code
if __name__ == '__main__':
root = newnode(9)
root.left = newnode(4)
root.right = newnode(17)
root.left.left = newnode(3)
root.left.right = newnode(6)
root.left.right.left = newnode(5)
root.left.right.right = newnode(7)
root.right.right = newnode(22)
root.right.right.left = newnode(20)
k = 18
print(Solution().cloesetValue(root,k)) |
c021ffd66a8fb60f57b42f837bbe7281418b2cfd | monty8800/PythonDemo | /base/06.循环.py | 1,195 | 3.65625 | 4 | # 循环
# 1.for x in ... 遍历list
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
# 累加
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum) # 55
# range() - 可以生成一个整数序列,再通过list()函数可以转换为list
print(list(range(6))) # [0, 1, 2, 3, 4, 5]
print(list(range(2, 6))) # [2, 3, 4, 5] 包前不包后
sum = 0
for x in range(101): # 0~101之间所有整数累加
sum = sum + x
print(sum) # 5050
sum = 0
for x in range(50, 101): # 50~101之间所有整数累加
sum = sum + x
print(sum) # 3825
# 2.while - 只要满足条件,就一直循环
sum = 0
n = 99
while n > 0:
sum = sum + n
# 在循环内部变量n不断自减2,直到变为-1时,不再满足while条件,循环退出。
n = n - 2
print(sum) # 2500
# break 退出当前循环
n = 1
while n <= 100:
if n > 10: # 当n = 11时,条件满足,执行break语句
break # break语句会结束当前循环
print(n)
n = n + 1
print('END')
# continue 退出当次循环,进入下一次循环
n = 0
while n < 10:
n = n + 1
if n % 2 == 0:
continue
print(n) # 1,3,5,7,9
|
557a05dd00aa9a14cadb3f0dfe5a24a4e210fadd | chea-young/IP-assignment | /practice visual studio/Ex-2_loop_and_function.py | 5,690 | 3.59375 | 4 | import sys
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
#Q1. 절대값을def absolute_value(n): # Buggy version
def absolute_value(n): # Buggy version
if n < 0:
return n*(-1)
elif n > 0:
return n
elif n == 0:
return 0
test(absolute_value(17) == 17)
test(absolute_value(-17) == 17)
test(absolute_value(0) == 0)
test(absolute_value(3.14) == 3.14)
test(absolute_value(-3.14) == 3.14)
#Q2. 정수를 매개 변수로 받아 각 자리를 제곱한 뒤 모두 더하는 sum_of_digit_square function을 작성하라.
#Parameter: 789 -> Output: 49+64+81=194
def sum_of_digit_square(n):
str_n = str(absolute_value(n))
sum = 0
for i in range(len(str_n)):
sum += int(str_n[i])**2
return sum
test(sum_of_digit_square(789) == 7**2 + 8**2 + 9**2)
test(sum_of_digit_square(-123) == 1**2 + 2**2 + 3**2 )
#Q3. 2이상의 자연수를 매개 변수로 받아 소수인지 검사하는 is_prime function을 작성하라.
def is_prime(n):
for i in range (2,n):
if(n%i == 0):
return False
return True
test(is_prime(2) == True)
test(is_prime(5) == True)
test(is_prime(12) == False)
test(is_prime(13) == True)
test(is_prime(1033) == True)
#Q4. 2이상의 자연수를 인자로 받아, 아래와 같은 문양을 출력하는 star_pattern void function을 작성하라.
#void function이란 결과를 return하지 않는 함수다.
def star_pattern(n):
for i in range(1,n):
print('*'*(i))
for i in range(n,0,-1):
print('*'*(i))
star_pattern(5)
star_pattern(6)
#Q5. 자연수를 매개 변수로 받아 가장 가까운 완전 제곱수를 출력하는 perfect_square function을 작성하라.
def perfect_square(n):
n_extra = n**(1/2)
num = int(n_extra)
num_plus = num+1
if(absolute_value(num**2-n) > absolute_value(num_plus**2 - n)):
return num_plus
else:
return num
test(perfect_square(15) == 4)
test(perfect_square(31) == 6)
test(perfect_square(41) == 6)
test(perfect_square(99) == 10)
#Q6. 자연수를 매개 변수로 받아 각 자리의 수를 더하여 새로운 수를 구하고, 이를 반복하여 한 자리 수를 만들어 출력하는 unit_place_value function을 작성하라.
#(e.g., 75 -> 7+5=12 -> 1+2=3).
def unit_place_value(n):
str_n = str(n)
if(len(str_n) == 1 ):
return n
else :
sum = 0
for i in range(len(str_n)):
sum += int(str_n[i])
return unit_place_value(sum)
test(unit_place_value(75) == 3)
test(unit_place_value(3942) == 9)
test(unit_place_value(32) == 5)
test(unit_place_value(9) == 9)
#Q7. 자연수를 매개 변수로 받아 해당 숫자까지의 팩토리얼을 계산하는 recursive_factorial recursive function을 작성하라.
def recursive_factorial(n):
if(n<=0):
return 1
else:
return n*recursive_factorial(n-1)
import math
test(recursive_factorial(5) == math.factorial(5))
test(recursive_factorial(8) == math.factorial(8))
test(recursive_factorial(2) == math.factorial(2))
test(recursive_factorial(10) == math.factorial(10))
#Q8. 자연수를 매개 변수로 받아 해당 숫자까지의 팩토리얼을 계산하는 non_recursive_factorial non recursive function을 작성하라.
def non_recursive_factorial(n):
sum = 1
for i in range(1,n+1):
sum *= i
return sum
import math
test(non_recursive_factorial(5) == math.factorial(5))
test(non_recursive_factorial(8) == math.factorial(8))
test(non_recursive_factorial(2) == math.factorial(2))
test(non_recursive_factorial(10) == math.factorial(10))
#Q9. 두 자연수를 매개 변수로 받아 최대공약수를 구하는 my_gcd function을 작성하라.
def my_gcd(a, b):
a = absolute_value(a)
b = absolute_value(b)
min_num = min(a,b)
for i in range(min_num,0,-1):
if(a %i ==0 and b%i ==0):
return i
import math
test(my_gcd(12, 16) == math.gcd(12,16))
test(my_gcd(16, 12) == math.gcd(16, 12))
test(my_gcd(9, 6) == math.gcd(9, 6))
test(my_gcd(-12, -38) == math.gcd(-12, -38))
#Q10. 임의의 정수가 들어있는 set을 input으로 입력받아, 가장 큰 세 숫자만을 가지고 있는 set을 반환하는 max_of_three function을 작성하라.
def max_of_three(l):
count = len(l)-3
list_l = list(l)
for i in range(count):
list_l.remove(min(list_l))
return set(list_l)
test(max_of_three({1, 2, 3, 4, 5}) == {3, 4, 5})
test(max_of_three({-100, 42, 32, -4, -1}) == {42, 32, -1})
#Q11. 임의의 정수가 들어있는 리스트를 input으로 입력받아, 전부 곱한 결과를 반환하는 mult_of_list function을 작성하라.
def mult_of_list(l):
mul_num = 1
for i in l:
mul_num *= i
return mul_num
test(mult_of_list([1, 2, 3, 4]) == 24)
test(mult_of_list([1, 20, -3, 4]) == -240)
test(mult_of_list([1, 0, -33, 9999]) == 0)
#Q12. 임의의 정수가 들어있는 리스트를 input으로 입력받아, 그 중 짝수만을 가진 리스트를 반환하는 even_filter function을 작성하라.
def even_filter(l):
even = []
for i in l:
if(i%2 == 0):
even.append(i)
return even
test(even_filter([1, 2, 3, 4, 5, 6, 7, 8, 9]) == [2, 4, 6, 8])
test(even_filter([1, 3, 5, 7, 9]) == []) |
72b3807cd83a811e9ffa8fc1a99aed7d32900bb5 | Asuper-code/NTM-DMIE | /Data_Process.py | 3,429 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
#English wordPreprocessing
from nltk import word_tokenize
from nltk import pos_tag
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
def wordProcess(sentence):
"""
1.tokenize
2.words_lower
3.pos_tag
4.stemming
5.remove stopwords
input: sentence string ; output: cleaned tokens
"""
token_words = word_tokenize(sentence) #word_tokenize
token_words = [x.lower() for x in token_words] #lowercase
token_tag = pos_tag(token_words) #pos_tag
words_lematizer = [] #stemming
wordnet_lematizer = WordNetLemmatizer()
for word, tag in token_tag:
if tag.startswith('NN'):
word_lematizer = wordnet_lematizer.lemmatize(word, pos='n')
elif tag.startswith('VB'):
word_lematizer = wordnet_lematizer.lemmatize(word, pos='v')
elif tag.startswith('JJ'):
word_lematizer = wordnet_lematizer.lemmatize(word, pos='a')
elif tag.startswith('R'):
word_lematizer = wordnet_lematizer.lemmatize(word, pos='r')
else:
word_lematizer = wordnet_lematizer.lemmatize(word)
words_lematizer.append(word_lematizer)
cleaned_words = [word for word in words_lematizer if word not in stopwords.words('english')] #stopwords
characters = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%','-','...','^','{','}']
words_list = [word for word in cleaned_words if word not in characters]
return words_list
#####laelTransExample
def labelTrans(label):
for i in range(len(label)):
if label[i] =="1":
label[i] = 0
if label[i] =="0":
label[i] = 1
if label[i]=="-1":
label[i]=2
batch_size = 128
class_num=3
label = np.array(label)
label = torch.from_numpy(label)
label = label.view(128,1)
one_hot = torch.zeros(batch_size, class_num).scatter_(1, label, 1)
return one_hot
########tokenize
import re
def tokenize(text):
try:
text = text.decode('utf-8').lower()
except:
text = text.encode('utf-8').decode('utf-8').lower()
text = re.sub(u"\u2019|\u2018", "\'", text)
text = re.sub(u"\u201c|\u201d", "\"", text)
text = re.sub(r"http[s]?:[^\ ]+", " ", text)
text = re.sub(r">", " ", text)
text = re.sub(r"<", " ", text)
text = re.sub(r""", " ", text)
text = re.sub(r" ", " ", text)
text = re.sub(r"\"", " ", text)
text = re.sub(r"#\ ", "#", text)
text = re.sub(r"\\n", " ", text)
text = re.sub(r"\\", " ", text)
text = re.sub(r"[\(\)\[\]\{\}]", r" ", text)
text = re.sub(r"#", " #", text)
text = re.sub(r"\@", " \@", text)
text = re.sub(r"[\!\?\.\,\+\-\$\%\^\>\<\=\:\;\*\(\)\{\}\[\]\/\~\&\'\|]", " ", text)
words = text.split()
return words
#####clean for space
import re
def clean_space(text):
match_regex = re.compile(u'[\u4e00-\u9fa5。\.,,::《》、\(\)()]{1} +(?<![a-zA-Z])|\d+ +| +\d+|[a-z A-Z]+')
should_replace_list = match_regex.findall(text)
order_replace_list = sorted(should_replace_list,key=lambda i:len(i),reverse=True)
for i in order_replace_list:
if i == u' ':
continue
new_i = i.strip()
text = text.replace(i,new_i)
return text
|
ace05c3c834d8768cf4b363fc0fd6de4af6a66a1 | yosef8234/test | /python3_book/tasks.py | 2,538 | 3.6875 | 4 | # Нам необходимо найти позицию наименьшего элемента в следующем
# Наборе данных: 809, 834, 477, 478, 307, 122, 96, 102, 324, 476.
counts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
counts.index(min(counts)) #6
# Усложним задачу и попытаемся найти позицию двух наименьших элементов в не отсортированном списке.
# Какие возможны алгоритмы решения?
# 1. Поиск, удаление, поиск. Поиск индекса минимального элемента в списке, удаление его, снова поиск минимального, возвращаем удаленный элемент в список.
def find_two_smallest(L):
smallest = min(L)
min1 = L.index(smallest)
L.remove(smallest) # удаляем первый минимальный элемент
next_smallest = min(L)
min2 = L.index(next_smallest)
L.insert(min1, smallest) # возвращаем первый минимальный обратно
if min1 <= min2: # проверяем индекс второго минимального из-за смещения
min2 += 1 # min2 = min2 + 1
return(min1, min2) # возвращаем кортеж
find_two_smallest(counts) # (6, 7)
# 2. Сортировка, поиск минимальных, определение индексов.
def find_two_smallest2(L):
temp_list = sorted(L) # возвращаем КОПИЮ отсортированного списка
smallest = temp_list[0]
next_smallest = temp_list[1]
min1 = L.index(smallest)
min2 = L.index(next_smallest)
return(min1, min2)
find_two_smallest2(counts) # (6, 7)
# 3. Перебор всего списка. Сравниваем каждый элемент по порядку, получаем два наименьших значения, обновляем значения, если найдены наименьшие.
def find_two_smallest3(L):
if L[0] < L[1]:
min1, min2 = 0, 1 # устанавливаем начальные значения
else:
min1, min2 = 1, 0
for i in range(2, len(L)):
if L[i] < L[min1]: # «первый вариант»
min2 = min1
min1 = i
elif L[i] < L[min2]: # «второй вариант»
min2 = i
return(min1, min2)
find_two_smallest3(counts) # (6, 7) |
3de125aebdf116df8489f8293db88990a300979f | raiyan1102006/leetcode-solutions | /0953_verifying_an_alien_dictionary.py | 1,029 | 3.6875 | 4 | # 953. Verifying an Alien Dictionary
# https://leetcode.com/problems/verifying-an-alien-dictionary/
# Runtime: 24 ms, faster than 98.89% of Python3 online submissions for Verifying an Alien Dictionary.
# Memory Usage: 14.4 MB, less than 5.77% of Python3 online submissions for Verifying an Alien Dictionary.
class Solution:
def ordered(self, word1, word2):
for chars in zip(*[word1,word2]):
if self.strDict[chars[0]]>self.strDict[chars[1]]: return False
if self.strDict[chars[0]]<self.strDict[chars[1]]: return True
# by this time, the zip(*) chars are same. So the first str must be smaller
if word1>word2: return False
else: return True
def isAlienSorted(self, words: List[str], order: str) -> bool:
self.strDict = {order[i]:i for i in range(len(order))}
for word_ind in range(1,len(words)):
if not self.ordered(words[word_ind-1],words[word_ind]):
return False
return True
|
9e7b2f84063c8aa5de058a7df0361559cccc8c32 | jdmarti2/python-interview-practice | /arrays_strings/expressive_wrods.py | 1,635 | 4.28125 | 4 | """Given a list of query words, return the number of words that are stretchy.
Task: For some given string s, a query word is stretchy if it can be made to be
equal to s by any number of applications of the following extension operation:
choose a group consisting of characters c, and add some number of characters c
to the group so that the size of the group is 3 or more.
If s = "helllllooo", then the query word "hello" would be stretchy because of
these two extension operations:
query = "hello" -> "hellooo" -> "helllllooo" = s.
"""
def check(s, word):
"""Check if word can be elongated to match s."""
si, w, s_len, w_len = 0, 0, len(s), len(word)
if w_len > s_len:
return False
# Use two pointers to match characters
while w < w_len and si < s_len:
# If char in word and s match, move both pointers right
if s[si] == word[w]:
si += 1
w += 1
# If char in s is streched, move s char right
elif s[si] * 3 in (s[si - 2:si + 1], s[si - 1: si + 2]):
si += 1
else:
return False
if w == w_len and si == s_len:
return True
# check if last char in word matches rest of s
if (word[w_len - 1] * len(s[si:]) == s[si:])\
and (s[si - 1] * 3 in (s[si - 3:si],
s[si - 2: si + 1],
s[si - 1: si + 2])):
return True
return False
def expressive_words(s, words):
"""Return number of words that can be stretched."""
num = 0
for word in words:
if check(s, word) is True:
num += 1
return num
|
473f48a5279d8418f5456c5fc6857c2cb4e1f253 | DakshMeghawat/Python-Programs | /Replace.py | 80 | 3.59375 | 4 | a="He is principal of the school"
a.replace('a','e')
print(a.replace('al','le')) |
b10cecb4c81ad3eee6e5053f7bed02edefdedb41 | HaykSahakyan11/Machine_Learning | /Practical3/Lucky Numbers.py | 616 | 3.78125 | 4 | # Lucky Numbers
def is_lucky_num(num):
odd = 0
even = 0
for i in range(-1, -len(num), -2):
odd += int(num[i])
even += int(num[i - 1])
if len(num) % 2 == 1:
odd += int(num[0])
return odd == even
# version 1 (my)
# print("Yes" if is_lucky_num(input("Num ")) else "No")
def is_lucky_num_2(n):
odd = 0
even = 0
parity = 1
while n > 0:
if parity:
odd += n % 10
else:
even += n % 10
parity = 1 - parity
n //= 10
return even == odd
# print("Yes" if is_lucky_num_2(int(input("Num "))) else "No")
|
9bff6a7e8e9e58356589b88d9d1cc200ccbceb31 | naray89k/Python | /DeepDive_1/6_First-Class_Functions/Lambdas_and_Sorting.py | 1,944 | 4.78125 | 5 | #!/usr/bin/env python
# coding: utf-8
# ### Lambdas and Sorting
# Python has a built-in **sorted** method that can be used to sort any iterable. It will use the default ordering of the particular items, but sometimes you may want to (or need to) specify a different criteria for sorting.
# Let's start with a simple list:
l = ['a', 'B', 'c', 'D']
sorted(l)
# As you can see there is a difference between upper and lower-case characters when sorting strings.
# What if we wanted to make a case-insensitive sort?
# Python's **sorted** function kas a keyword-only argument that allows us to modify the values that are used to sort the list.
sorted(l, key=str.upper)
# We could have used a lambda here (but you should not, this is just to illustrate using a lambda in this case):
sorted(l, key = lambda s: s.upper())
# Let's look at how we might create a sorted list from a dictionary:
d = {'def': 300, 'abc': 200, 'ghi': 100}
d
sorted(d)
# What happened here?
# Remember that iterating dictionaries actually iterates the keys - so we ended up with tyhe keys sorted alphabetically.
# What if we want to return the keys sorted by their associated value instead?
sorted(d, key=lambda k: d[k])
# Maybe we want to sort complex numbers based on their distance from the origin:
def dist(x):
return (x.real)**2 + (x.imag)**2
l = [3+3j, 1+1j, 0]
# Trying to sort this list directly won't work since Python does not have an ordering defined for complex numbers:
sorted(l)
# Instead, let's try to specify the key using the distance:
sorted(l, key=dist)
# Of course, if we're only going to use the **dist** function once, we can just do the same thing this way:
sorted(l, key=lambda x: (x.real)**2 + (x.imag)**2)
# And here's another example where we want to sort a list of strings based on the **last character** of the string:
l = ['Cleese', 'Idle', 'Palin', 'Chapman', 'Gilliam', 'Jones']
sorted(l)
sorted(l, key=lambda s: s[-1])
|
063cd077de63d53e4fd968a0d5a61a028ab17d81 | fabiofigueredo/python | /curso/desafio04.py | 827 | 4.28125 | 4 | # Faça um programa receba um valor e print detalhes sobre o valor inserido e a que tipo primitivo ele pertence
valor = input('Digite algo aqui e te direi o que ele é (na linguagem das máquinas, claro: ')
print('O tipo primitivo desse valor é: ',type(valor))
print('Este conteúdo é um título? ',valor.istitle())
print('Este conteúdo é um espaço? ',valor.isspace())
print('Este conteúdo está em maiúsculo? ',valor.isupper())
print('Este conteúdo está em minúsculo? ',valor.islower())
print('Este conteúdo é printável? ',valor.isprintable())
print('Este conteúdo é um dígito? ',valor.isdigit())
print('Este valor é decimal? ',valor.isdecimal())
print('Este valor é um texto? ',valor.isalpha())
print('Este valor é um número? ',valor.isnumeric())
print('Este valor é alphanumérico? ',valor. isalnum())
|
6d6f243222bfa13a421d5f067d31e1ff23f7f5b4 | abdelrhman-adel-ahmed/Functional-Programming | /python implementation/lesson_7.py | 1,748 | 4.5625 | 5 | """
i recommend to read those articles in order to gain more deep understanding of closures
1-https://en.wikipedia.org/wiki/Closure_(computer_programming)
2-https://en.wikipedia.org/wiki/Funarg_problem
3-https://medium.com/@5066aman/lexical-environment-the-hidden-part-to-understand-closures-71d60efac0e0
4-https://www.youtube.com/watch?v=HcW5-P2SNec
5-You Don't Know JS: Scope & Closures Book by Kyle Simpson
"""
# note:The example of the lecture has already been written by MuhammadMotawe
# link : https://github.com/MuhammadMotawe/FunctionalProgramming/blob/main/Closures/Python/Closures.py
# note: its not recomended to use OrderedDict with large data due to overhead complexity of using doubly linked list
def outer(x):
x1 = x + 10
def inner(a):
return a + x1
return inner
out1 = outer(10)
print(out1(4))
# --------------------------------------------------------------------------
# use the clouser to decorate another function
def decorator_fun(original_fn):
def wrapper_fun():
print(f"decorated the function {original_fn}")
return original_fn()
return wrapper_fun
def display():
print("decorated fucntion is hereee ")
out2 = decorator_fun(display)()
# --------------------------------------------------------------------------
# using @ to directly calling the decorated function
def decorator_fun1(original_fn):
def wrapper_fun(*args, **kwargs):
print(f"decorated the function value get passed to wrapper is {args[0]}")
return original_fn(*args, **kwargs)
return wrapper_fun
@decorator_fun1
def display1(x):
print("decorated fucntion is hereee ")
out3 = display1
out3(12)
# --------------------------------------------------------------------------
|
b7fe43503bcc87fdc8261016538b89660b666ddd | cgi0911/LeetCodePractice | /lc0049_GroupAnagrams/lc0049.py | 884 | 3.84375 | 4 | class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
myMap = {} # Map for grouping anagrams
for s in strs:
k = ''.join(sorted(s)) # k means 'key'
if (k in myMap):
myMap[k].append(s)
else:
myMap[k] = [s]
ret = []
for k in myMap.keys():
ret.append(sorted(myMap[k]))
ret = sorted(ret, key=lambda x: x[0])
return ret
if __name__ == "__main__":
sol = Solution()
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print ("Grouping anagrams for %s" %(str(strs)))
res = sol.groupAnagrams(strs)
print ("Result:")
for a in res:
print (a) |
adf5307b5909d6107ad6186185bce1c1cd0544e4 | WaterPhoenix8/Cellphone-Index | /CP prefix numbers (as of Nov 2016).py | 1,080 | 3.59375 | 4 | globe = ['0817', '0905', '0906', '0915', '0916', '0917', '09173', '09175', '09176', '09178', '09253', '09256', '09257', '0926', '0927', '0935', '0936', '0937', '0945', '0975', '0976', '0977', '0978', '0979', '0994', '0995', '0996', '0997']
smart = ['0813', '0900', '0907', '0908', '0909', '0910', '0911', '0912', '0913', '0914', '0918', '0919', '0920', '0921', '0928', '0929', '0930', '0938', '0939', '0946', '0947', '0948', '0949', '0950', '0951', '0981', '0989', '0998', '0999'] #, '0956']
sun = ['0922', '0923', '0924', '0925', '09255', '09258', '0931', '0932', '0933', '0934', '0942', '0943', '0944']
extelcom = ['0973', '0974']
prefix = input('Enter Cellphone Prefix No. Please: ')
#if prefix == '0925':
#print('The number is both GLOBE and SUN!')
if prefix in globe:
print('The number is a GLOBE number!')
elif prefix in smart:
print('The number is a SMART number!')
elif prefix in sun:
print('The number is a SUN number!')
elif prefix in extelcom:
print('The number is an EXTELCOM number!')
else:
print('NOT a PREFIX NUMBER as of November 2016!')
|
07246cccf69c96668022822d7da28ae978c6d0b8 | sidneyalex/Desafios-do-Curso | /Desafio093.py | 880 | 3.828125 | 4 | #Crie um pgm q gerencie o aproveitamento de um jogador de futebol. O pgm vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionario, incluindo o total de gols feitos durante o campeonato
cad = {'Nome': str(input('Nome do jogador: '))}
partidas = int(input(f'Quantas partidas {cad["Nome"]} jogou? '))
gols = list()
for g in range(0, partidas):
gols.append(int(input(f'Gols na partida {g + 1}: ')))
cad['Gols'] = gols[:]
cad['Total'] = sum(gols)
print('-=' * 30)
print(cad)
print('-=' * 30)
for k, v in cad.items():
print(f'O campo {k} tem valor {v}')
print('-=' * 30)
print(f'O jogador {cad["Nome"]} jogou {len(cad["Gols"])} partidas.')
for i, g in enumerate(cad['Gols']):
print(f' => Partida {i+1} - {g} gols.')
print(f'Foi um total de {cad["Total"]} gols.')
|
8a292a7e1612685038e8ab619985aace32e1ce40 | skinan/Competative-Programming-Problems-Solutions-Using-Python | /FindingThePercentage.py | 423 | 3.875 | 4 | # Hackerrank
# Practice > Python > Basic Data Types > Finding the percentage
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
temp = student_marks.get(query_name)
ans = sum(temp)/len(temp)
print("{0:.2f}".format(ans))
|
51f3ab1f7e0a5269c8304c8e3eb4914dd6f82717 | rahultiwari56/weekday2019_08_06 | /Assignments/Ashok/AssignmentPython7Dict- If-else.py | 1,135 | 3.8125 | 4 | #1. WAP to create a dictionary of numbers mapped to their negative value for numbers from 1-5.
#The dictionary should contain something like this:
#Do with both with and without range based for loop.
f = {}
for i in range(1,6):
f[i] = -i
print(f)
#2. Check which of the following declarations will work
#1
d ={1=2,3=4} #wrong
#2
d ={1:2,3:4} #correct
#3
d = {1,2;3,4} #wrong
d = {'a':'A','b':1,c:[1234]} #wrong
d = {'a':'A','b':1,'c':[1234]} #correct
d = dict([(1,2), (2,3)]) #correct
d = dict(((1,2), (2,3))) #correct
### 3
l1 = [1,2,3,4]
l2 = [10,11,12,13]
print(dict(zip(l1,l2)))
### 4
asc = 65
d = {}
while asc:
d[chr(asc)] = asc
asc+=1
if chr(asc) == 'Z':
break
print(d)
### 5
val = {0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
lo = {}
for x in 'aeiou':
count = 1
for y in 'Beautiful day':
if x==y:
lo[x]=count
count+=1
print(lo)
#### 6
doc = {}
count = 1
gg='Beautiful day'
for y in gg:
if y.isalpha():
doc[y]= gg.count(y)
print(doc)
### 7
d = 'count the words in the sentence in'
dp = d.split()
ee = {}
for x in dp:
ee[x] = dp.count(x)
print(ee)
|
229bd7a9cd4782ef76912f63a80704661df36c98 | Snehabisht/LIVE-STREAMING-NEWS | /twitter_analysis.py | 12,616 | 3.5 | 4 | import platform
platform.platform()
import nltk
#nltk.__version__
#nltk.download_shell()
from nltk.tokenize import sent_tokenize, word_tokenize
EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard."
print(sent_tokenize(EXAMPLE_TEXT))
print(word_tokenize(EXAMPLE_TEXT))
#stop words like ourselves ,a an the --useless words
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sent = "USA is in talks with India for nuclear deals."
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(example_sent)
#filtered_sentence = [w for w in word_tokens if not w in stop_words]
filtered_sentence = []
for w in word_tokens:
if w not in stop_words:
filtered_sentence.append(w)
#filtered_sentence = []
print(filtered_sentence)
for w in word_tokens:
if w not in stop_words:
filtered_sentence.append(w)
print(word_tokens)
print(filtered_sentence)
#stemming
from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize, word_tokenize
ps = PorterStemmer()
example_words = ["python","pythoner","pythoning","pythoned","pythonly"]
new_text = "It is important to by very pythonly while you are pythoning with python. All pythoners have pythoned poorly at least once."
words = word_tokenize(new_text)
for w in words:
print(ps.stem(w))
#part of speech
#import nltk
#POS tag list:
#
#CC coordinating conjunction
#CD cardinal digit
#DT determiner
#EX existential there (like: "there is" ... think of it like "there exists")
#FW foreign word
#IN preposition/subordinating conjunction
#JJ adjective 'big'
#JJR adjective, comparative 'bigger'
#JJS adjective, superlative 'biggest'
#LS list marker 1)
#MD modal could, will
#NN noun, singular 'desk'
#NNS noun plural 'desks'
#NNP proper noun, singular 'Harrison'
#NNPS proper noun, plural 'Americans'
#PDT predeterminer 'all the kids'
#POS possessive ending parent\'s
#PRP personal pronoun I, he, she
#PRP$ possessive pronoun my, his, hers
#RB adverb very, silently,
#RBR adverb, comparative better
#RBS adverb, superlative best
#RP particle give up
#TO to go 'to' the store.
#UH interjection errrrrrrrm
#VB verb, base form take
#VBD verb, past tense took
#VBG verb, gerund/present participle taking
#VBN verb, past participle taken
#VBP verb, sing. present, non-3d take
#VBZ verb, 3rd person sing. present takes
#WDT wh-determiner which
#WP wh-pronoun who, what
#WP$ possessive wh-pronoun whose
#WRB wh-abverb where, when
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer #this tokeniser comes in trained it itself but we can also train it (unsupervise ml model)
train_text = state_union.raw("2005-GWBush.txt")
sample_text = state_union.raw("2006-GWBush.txt")
custom_sent_tokenizer = PunktSentenceTokenizer(train_text)
tokenized = custom_sent_tokenizer.tokenize(sample_text)
def process_content():
try:
for i in tokenized[:5]:
words = nltk.word_tokenize(i)
tagged = nltk.pos_tag(words)
print(tagged)
except Exception as e:
print(str(e))
process_content()
#chunking --group words into hopefully meaningful chunks
#The idea is to group nouns with the words that are in relation to them.
#import nltk
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
train_text = state_union.raw("2005-GWBush.txt")
sample_text = state_union.raw("2006-GWBush.txt")
custom_sent_tokenizer = PunktSentenceTokenizer(train_text)
tokenized = custom_sent_tokenizer.tokenize(sample_text)
def process_content():
try:
for i in tokenized:
words = nltk.word_tokenize(i)
tagged = nltk.pos_tag(words)
chunkGram = r"""Chunk: {<.*>+}
}<VB.?|IN|DT|TO>+{""" #chinking }{ --chunk except thse mentioned in these braces
chunkParser = nltk.RegexpParser(chunkGram)
chunked = chunkParser.parse(tagged)
#print(Chunk)
print(chunked)
#for subtree in chunked.subtrees(filter=lambda t: t.label() == 'Chunk'):
# print(subtree)
chunked.draw()
except Exception as e:
print(str(e))
process_content()
#named entity recognition
import nltk
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
train_text = state_union.raw("2005-GWBush.txt")
sample_text = state_union.raw("2006-GWBush.txt")
custom_sent_tokenizer = PunktSentenceTokenizer(train_text)
tokenized = custom_sent_tokenizer.tokenize(sample_text)
def process_content():
try:
for t in range(4):
for i in tokenized[5:]:
words = nltk.word_tokenize(i)
tagged = nltk.pos_tag(words)
namedEnt = nltk.ne_chunk(tagged, binary=True)
namedEnt.draw()
except Exception as e:
print(str(e))
#namedEnt.draw()
process_content()
#lematizing-- same as stemming but a meaningful word
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print(lemmatizer.lemmatize("cats"))
print(lemmatizer.lemmatize("cacti"))
print(lemmatizer.lemmatize("geese"))
print(lemmatizer.lemmatize("rocks"))
print(lemmatizer.lemmatize("python"))
print(lemmatizer.lemmatize("better", pos="a")) # a is for adjective
print(lemmatizer.lemmatize("best", pos="a"))
print(lemmatizer.lemmatize("running",'v'))
print(lemmatizer.lemmatize("run",'v'))
#corpora
#import nltk
#print(nltk.__file__)
#file for fining nltk data
from nltk.tokenize import sent_tokenize, PunktSentenceTokenizer
from nltk.corpus import gutenberg
# sample text
sample = gutenberg.raw("bible-kjv.txt")
tok = sent_tokenize(sample)
for x in range(5):
print(tok[x])
#wordnet
from nltk.corpus import wordnet
syns = wordnet.synsets("achievement") #synsets for synonym
print(syns[0].name())
print(syns[0].lemmas()[0].name())
print(syns[0].definition())
print(syns[0].examples())
synonyms = []
antonyms = []
for syn in wordnet.synsets("good"): #synonyms and antonyms of the word good
for l in syn.lemmas():
synonyms.append(l.name())
#print("l:",l)
if l.antonyms():
antonyms.append(l.antonyms()[0].name())
print(set(synonyms))
print(set(antonyms))
w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('boat.n.01')
print(w1.wup_similarity(w2))
w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('car.n.01')
print(w1.wup_similarity(w2))
w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('cat.n.01')
print(w1.wup_similarity(w2))
#
#import nltk
import random
from nltk.corpus import movie_reviews
short_pos = open("positive.txt","r").read()
short_neg = open("negative.txt","r").read()
documents = []
for r in short_pos.split('\n'):
documents.append( (r, "pos") )
for r in short_neg.split('\n'):
documents.append( (r, "neg") )
all_words = []
short_pos_words = word_tokenize(short_pos)
short_neg_words = word_tokenize(short_neg)
for w in short_pos_words:
all_words.append(w.lower())
for w in short_neg_words:
all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)
word_features = list(all_words.keys())[:5000]
def find_features(document):
words = set(document) #all the words of that document
features = {}
for w in word_features:
features[w] = (w in words)
return features
#print((find_features(movie_reviews.words('neg/cv000_29416.txt'))))
featuresets = [(find_features(rev), category) for (rev, category) in documents]
random.shuffle(featuresets)
#print(featuresets[0])
# set that we'll train our classifier with
training_set = featuresets[:10000]
# set that we'll test against.
testing_set = featuresets[10000:]
#posterior=prior occarance * likelihood /evidence
classifier = nltk.NaiveBayesClassifier.train(training_set)
print("Classifier accuracy percent:",(nltk.classify.accuracy(classifier, testing_set))*100)
classifier.show_most_informative_features(15)
#pickle -to store python objects, here classfier
import pickle
save_classifier = open("naivebayes.pickle","wb")
pickle.dump(classifier, save_classifier)
save_classifier.close()
classifier_f = open("naivebayes.pickle", "rb")
classifier = pickle.load(classifier_f)
classifier_f.close()
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB,BernoulliNB
MNB_classifier = SklearnClassifier(MultinomialNB())
MNB_classifier.train(training_set)
print("MultinomialNB accuracy percent:",nltk.classify.accuracy(MNB_classifier, testing_set))
BNB_classifier = SklearnClassifier(BernoulliNB())
BNB_classifier.train(training_set)
print("BernoulliNB accuracy percent:",nltk.classify.accuracy(BNB_classifier, testing_set))
from sklearn.linear_model import LogisticRegression,SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
from nltk.classify import ClassifierI
from statistics import mode
class VoteClassifier(ClassifierI):
def __init__(self, *classifiers):
self._classifiers = classifiers
def classify(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
return mode(votes)
def confidence(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
choice_votes = votes.count(mode(votes))
conf = choice_votes / len(votes)
return conf
print("Original Naive Bayes Algo accuracy percent:", (nltk.classify.accuracy(classifier, testing_set))*100)
classifier.show_most_informative_features(15)
MNB_classifier = SklearnClassifier(MultinomialNB())
MNB_classifier.train(training_set)
print("MNB_classifier accuracy percent:", (nltk.classify.accuracy(MNB_classifier, testing_set))*100)
BernoulliNB_classifier = SklearnClassifier(BernoulliNB())
BernoulliNB_classifier.train(training_set)
print("BernoulliNB_classifier accuracy percent:", (nltk.classify.accuracy(BernoulliNB_classifier, testing_set))*100)
LogisticRegression_classifier = SklearnClassifier(LogisticRegression())
LogisticRegression_classifier.train(training_set)
print("LogisticRegression_classifier accuracy percent:", (nltk.classify.accuracy(LogisticRegression_classifier, testing_set))*100)
SGDClassifier_classifier = SklearnClassifier(SGDClassifier())
SGDClassifier_classifier.train(training_set)
print("SGDClassifier_classifier accuracy percent:", (nltk.classify.accuracy(SGDClassifier_classifier, testing_set))*100)
SVC_classifier = SklearnClassifier(SVC())
SVC_classifier.train(training_set)
print("SVC_classifier accuracy percent:", (nltk.classify.accuracy(SVC_classifier, testing_set))*100)
#LinearSVC_classifier = SklearnClassifier(LinearSVC())
#LinearSVC_classifier.train(training_set)
#print("LinearSVC_classifier accuracy percent:", (nltk.classify.accuracy(LinearSVC_classifier, testing_set))*100)
NuSVC_classifier = SklearnClassifier(NuSVC())
NuSVC_classifier.train(training_set)
print("NuSVC_classifier accuracy percent:", (nltk.classify.accuracy(NuSVC_classifier, testing_set))*100)
voted_classifier = VoteClassifier(classifier,
NuSVC_classifier,
#LinearSVC_classifier,
SGDClassifier_classifier,
MNB_classifier,
BernoulliNB_classifier,
LogisticRegression_classifier)
print("voted_classifier accuracy percent:", (nltk.classify.accuracy(voted_classifier, testing_set))*100)
print("Classification:", voted_classifier.classify(testing_set[0][0]), "Confidence %:",voted_classifier.confidence(testing_set[0][0])*100)
print("Classification:", voted_classifier.classify(testing_set[1][0]), "Confidence %:",voted_classifier.confidence(testing_set[1][0])*100)
print("Classification:", voted_classifier.classify(testing_set[2][0]), "Confidence %:",voted_classifier.confidence(testing_set[2][0])*100)
print("Classification:", voted_classifier.classify(testing_set[3][0]), "Confidence %:",voted_classifier.confidence(testing_set[3][0])*100)
print("Classification:", voted_classifier.classify(testing_set[4][0]), "Confidence %:",voted_classifier.confidence(testing_set[4][0])*100)
print("Classification:", voted_classifier.classify(testing_set[5][0]), "Confidence %:",voted_classifier.confidence(testing_set[5][0])*100) |
6da5183c1cb5186b6ce3e3d69dc51f4e8aaadb7d | AmalRamakrishnan/ML-DNN.github.in | /DNN.py | 2,863 | 3.5 | 4 | from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import RandomizedSearchCV
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
import numpy
# Function to create model, required for KerasClassifier
def create_model(optimizer='rmsprop', init='glorot_uniform', dropout_rate=0.0):
# create model
#we designed a DNN model with two hidden layers.
#The first hidden layer constituted the number of
#neurons amounting to 50% of attributes of the
#input feature space. Subsequently, the second layer
#contained 50% of the neurons that were present in the previous layer.
#For example, if the feature set contains 1000 attributes,
#then the first layer will be created with 500 neurons and
#the second layer is formed using 250 neurons.
model = Sequential()
model.add(Dense(4, input_dim=8, kernel_initializer=init, activation='relu'))
model.add(Dropout(dropout_rate))
model.add(Dense(2, kernel_initializer=init, activation='relu'))
model.add(Dropout(dropout_rate))
model.add(Dense(1, kernel_initializer=init, activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians diabetes dataset
dataset = numpy.loadtxt("pima-indians-diabetes.data.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
y = dataset[:,8]
#Data Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
RescaledX = sc.fit_transform(X)
#Spliting Data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(RescaledX, y, test_size =0.4, random_state=4)
# create model
model = KerasClassifier(build_fn=create_model, verbose=0)
#Parameters
# grid search init, epochs, batch size,optimizer and dropout rate
dropout_rate = [0.0]
optimizers = ['rmsprop', 'adam']
init = ['glorot_uniform', 'normal', 'uniform']
epochs = [50, 100, 150]
batches = [2,3]
param_grid = dict(optimizer=optimizers, epochs=epochs, batch_size=batches, init=init, dropout_rate=dropout_rate)
rcv = RandomizedSearchCV(estimator=model, param_distributions=param_grid)
rcv_result = rcv.fit(X_train, y_train)
#rcv.best_estimator_.fit(X_train, y_train)
y_pred = rcv.best_estimator_.predict(X_test)
print('Accuracy :',accuracy_score(y_test, y_pred), rcv_result.best_params_)
print('Precision :',precision_score(y_test,y_pred))
print('Recall :',recall_score(y_test,y_pred))
print('F1_Score :',f1_score(y_test,y_pred)) |
5e5ad24fe3730647ff55713ba2527924d14d99a6 | ATUL786pandey/python_prac_codewithharry | /loop_break_statement.py | 120 | 4.03125 | 4 | for i in range (1,50):
print(i)
if i == 3:
break #it will break the loop when i is reached to 3
|
62848616120848a7cbee215b04bbc924c8aa583f | ha5aan/Algorithms-applicaction | /codes/Levenshtein Distance (edit-distance).py | 1,273 | 3.515625 | 4 |
def editDistDP(str1, str2, m, n):
# Create a table to store results of subproblems
dp = [[0 for x in range(n + 1)] for x in range(m + 1)]
# Fill d[][] in bottom up manner
for i in range(m + 1):
for j in range(n + 1):
# If first string is empty, only option is to
# insert all characters of second string
if i == 0:
dp[i][j] = j # Min. operations = j
# If second string is empty, only option is to
# remove all characters of second string
elif j == 0:
dp[i][j] = i # Min. operations = i
# If last characters are same, ignore last char
# and recur for remaining string
elif str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1]
# If last character are different, consider all
# possibilities and find minimum
else:
dp[i][j] = 1 + min(dp[i][j-1], # Insert
dp[i-1][j], # Remove
dp[i-1][j-1]) # Replace
return dp[m][n]
# Driver code
for i in range(10):
tt=i+1
var3="QabcINPUTa"+str(tt)+".txt"
f=open(var3,"r+")
m=int(f.readline())
X=f.readline()
f.close()
var3="QabcINPUTb"+str(tt)+".txt"
f=open(var3,"r+")
n=int(f.readline())
Y=f.readline()
f.close()
print("The Levenshtein Distance (edit-distance) is ",end = "")
print(editDistDP(X, Y, m, n))
|
f3f8b8efe7a86c5ac3d084e104a6534c48c8cb43 | AlekhyaMupparaju/pyothon | /42.py | 98 | 3.53125 | 4 | a,b = map(str,raw_input().split())
if(a==b):
print b
elif(a>b):
print a
else:
print b
|
f42bb476d9f38f3e6524c26af04e7b26b407a7fc | projeto-de-algoritmos/Grafos1_WarFGA | /sources/classes/Graph.py | 546 | 3.515625 | 4 | from classes import Node, Connection
class Graph:
def __init__(self):
self.graph = {}
def add_node(self, text):
empty_node = Node.Node(text)
def print_node (self):
return empty_node
"""def add_edge(self, src, dest, srcPos, destPos):
if (dest in self.graph[src]):
return
self.graph[src].append(dest)
self.graph[dest].append(src)
self.createGameEdge(srcPos, destPos)
def createGameEdge(self, src, dest):
edge = Connection.Connection(src, dest)"""
|
afcca3f2465a77bd789621344aa17afddb94e1dc | samuil-ganev/games | /TicTacToe/tictactoe.py | 3,555 | 3.671875 | 4 | from itertools import permutations
from textwrap import wrap
from random import randint
def pc_can_win(x):
for i in range(3):
for j in range(3):
if x[i][j] == 0:
x[i][j] = 'x'
if win(x, 'x'):
return [True, [i, j]]
else:
x[i][j] = 0
return [False]
def win(x, e):
for i in range(3):
if x[i][0] == x[i][1] == x[i][2] == e:
return True
for j in range(3):
if x[0][j] == x[1][j] == x[2][j] == e:
return True
if x[0][0] == x[1][1] == x[2][2] == e:
return True
elif x[0][2] == x[1][1] == x[2][0] == e:
return True
return False
board = [[0 for i in range(3)] for j in range(3)]
# print(board)
player = {1: "Your turn", 2: "Computer's turn"}
game_over = False
turn = randint(1, 2)
variants = [wrap(''.join(el), 3) for el in list(set(permutations(['x'] * (turn + 3) + ['o'] * (6 - turn))))]
variants = [el for el in variants if win(el, 'x') and not win(el, 'o')]
# print(len(variants))
# print(variants)
points = 0
while not game_over:
if points == 9:
break
print(player[turn])
if turn == 1:
# TODO:
x, y = [int(num) for num in input().split()]
board[x-1][y-1] = 'o'
#for pc:
variants = [el for el in variants if el[x-1][y-1] == 'o']
if win(board, 'o'):
game_over = True
print_board = ''.join([str(i) for i in board[0]]) + '\n' + ''.join([str(i) for i in board[1]]) + '\n' + ''.join([str(i) for i in board[2]])
print(print_board)
print('You win.')
break
turn = 2
else:
# TODO:
oponent_win = False
select = False
if pc_can_win(board)[0]:
select = True
x, y = pc_can_win(board)[1]
board[x][y] = 'x'
for i in range(3):
if select == True:
break
for j in range(3):
if board[i][j] == 0:
board[i][j] = 'o'
if win(board, 'o'):
board[i][j] = 'x'
oponent_win = True
select = True
break
else:
board[i][j] = 0
if not select:
for i in range(3):
if select == True:
break
for j in range(3):
if board[i][j] == 0:
try:
if variants[0][i][j] == 'x':
board[i][j] = 'x'
select = True
break
except:
select = True
board[i][j] = 'x'
break
if win(board, 'x'):
game_over = True
print_board = ''.join([str(i) for i in board[0]]) + '\n' + ''.join([str(i) for i in board[1]]) + '\n' + ''.join([str(i) for i in board[2]])
print(print_board)
print('Computer wins.')
break
turn = 1
print_board = ''.join([str(i) for i in board[0]]) + '\n' + ''.join([str(i) for i in board[1]]) + '\n' + ''.join([str(i) for i in board[2]])
print(print_board)
points += 1
input('Press any key to exit.')
|
e7e05039a10f84c1fd19718e2c6f9807cd662622 | EdsonRodrigues1994/Mundo-2-Python | /desafio056.py | 1,011 | 3.859375 | 4 | #Faça um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa mostre:
#A média de idade do grupo
#Qual é o nome do homem mais velho
#Quantas mulheres tem menos de 20 anos
somaIdade = 0
maioridadehomem = 0
count = 0
maior = 0
menor = 0
nomevelho = ""
for pessoas in range(1,5):
print("Informe os seguintes dados da {}ª pessoa: ".format(pessoas))
nome = str(input("Nome: "))
idade = int(input("Idade: "))
sexo = str(input("Sexo ( M / F): ").upper())
somaIdade = somaIdade + idade
media = somaIdade / pessoas
if pessoas == 1 and sexo == "M":
maioridadehomem = idade
nomevelho = nome
if sexo == "M"and idade > maioridadehomem:
maioridadehomem = idade
nomevelho = nome
if idade < 20 and sexo == "F":
count = count + 1
print("A média de idade do grupo é {} anos, o homem mais velho se chama {} e tem {} anos de idade. Temos {} mulher(es) com menos de 20 anos.".format(media,nomevelho, maioridadehomem, count))
|
53290a70274c23ba4714678a2486741d21f263ae | imjoseangel/100-days-of-code | /python/mltraining/supervised/linear_svm/linear_svm.py | 2,601 | 3.578125 | 4 | # All the libraries we need for linear SVM
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
# This is used for our dataset
from sklearn.datasets import load_breast_cancer
# =============================================================================
# We are using sklearn datasets to create the set of data points about breast
# cancer
# Data is the set data points
# target is the classification of those data points.
# More information can be found at
# https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html#sklearn.datasets.load_breast_cancer
# =============================================================================
dataCancer = load_breast_cancer()
# The data[:, x:n] gets two features for the data given.
# The : part gets all the rows in the matrix. And 0:2 gets the first 2 columns
# If you want to get a different two features you can replace 0:2 with 1:3,
# 2:4,... 28:30,
# there are 30 features in the set so it can only go up to 30.
# If we wanted to plot a 3 dimensional plot then the difference between
# x and n needs to be 3 instead of two
data = dataCancer.data[:, 0:2]
target = dataCancer.target
# =============================================================================
# Creates the linear svm model and fits it to our data points
# The optional parameter will be default other than these two,
# You can find the other parameters at
# https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html
# =============================================================================
model = svm.SVC(kernel='rbf', C=10000)
model.fit(data, target)
# plots the points
plt.scatter(data[:, 0], data[:, 1], c=target, s=30, cmap=plt.cm.prism)
# Creates the axis bounds for the grid
axis = plt.gca()
x_limit = axis.get_xlim()
y_limit = axis.get_ylim()
# Creates a grid to evaluate model
x = np.linspace(x_limit[0], x_limit[1], 50)
y = np.linspace(y_limit[0], y_limit[1], 50)
X, Y = np.meshgrid(x, y)
xy = np.c_[X.ravel(), Y.ravel()]
# Creates the decision line for the data points, use model.predict if you are
# classifying more than two
decision_line = model.decision_function(xy).reshape(Y.shape)
# Plot the decision line and the margins
axis.contour(X, Y, decision_line, colors='k', levels=[0], linestyles=['-'])
# Shows the support vectors that determine the desision line
axis.scatter(model.support_vectors_[:, 0],
model.support_vectors_[:, 1],
s=100,
linewidth=1,
facecolors='none',
edgecolors='k')
# Shows the graph
plt.show()
|
17663d8e257d7c71700afd1be61831180e190181 | 2kwattz/Snake-Water-Gun-Python | /snakewatergun.py | 3,146 | 3.6875 | 4 | import random
import pyfiglet
import os
gameoptions = ['s','w','g']
banner = pyfiglet.figlet_format("Snake Water Gun")
print(banner)
print("Code by 2kwattz")
username = input("Enter your name : ")
rounds = 0
userpoints = 0
compoints = 0
print(f"\nWelcome {username}... Let's Play \n\nTotal rounds : 10\nEnter s for Snake\nEnter w for Water\nEnter g for Gun\n")
while (rounds<10):
comp = random.choice(gameoptions)
rounds = rounds+1
uservalue = input(":")
if uservalue == 's' and comp == 's':
print(f"{rounds} Round : {username} chose Snake.Computer chose snake\nIts a Draw")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
elif uservalue == 's' and comp == 'w':
userpoints = userpoints +1
print(f"Round {rounds}. \n{username} chose Snake.Computer chose Water\n{username} Won this round")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
elif uservalue == 's' and comp == 'g':
compoints = compoints + 1
print(f"Round : {rounds}. {username} chose Snake,Computer chose gun.\nComputer won this round")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
elif uservalue == 'w' and comp == 'w':
print(f"Round : {rounds}. {username} chose Water , Computer chose water\nIts a Draw")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
elif uservalue == 'w' and comp == 's':
compoints = compoints + 1
print(f"Round : {rounds}. {username} chose Water , Computer chose Snake\nComputer won this round")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
elif uservalue == 'w' and comp == 'g':
userpoints = userpoints +1
print(f"Round : {rounds}. {username} chose Water , Computer chose gun\n{username} won this round")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
elif uservalue == 'g' and comp == 'g':
print(f"Round : {rounds}. {username} chose Gun , Computer chose gun\nIts a draw")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
elif uservalue == 'g' and comp == 'w':
compoints = compoints + 1
print(f"Round : {rounds}. {username} chose Gun, Computer chose Water\nComputer won this round")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
elif uservalue == 'g' and comp == 's':
userpoints = userpoints +1
print(f"Round : {rounds}. {username} chose gun , Computer chose snake\n{username} won this round")
print(f"{username} Points : {userpoints} \t\t Computer points : {compoints}\n")
else:
print("Incorrect parameters . You have to insert either 's' for Snake , 'w' for Water,'g' for Gun\n")
break
if rounds == 10:
if userpoints > compoints:
print("Congratulations ! You Won the game !")
elif compoints > userpoints:
print("Sorry . You Lose")
|
ab291af1b987718b4142ffb88af833e82a3790f1 | leovasone/curso_python | /Work001/file007_tipo_float.py | 731 | 3.84375 | 4 |
#errado
valor = 1, 44
print(f'valor é {valor} e seu tipo é {type(valor)}')
#certo
valor = 1.44
print(f'valor é {valor} e seu tipo é {type(valor)}')
#É possível
valor1, valor2 = 2, 3
print(f'valor1 é {valor1} e valor2 é {valor2}')
print(f'tipo de valor1 é {type(valor1)} e tipo de valor2 é {type(valor2)}')
#Converter float para int
valor3 = 2.6
print(f'valor3 convertido é {int(valor3)} e o novo tipo fica {type(int(valor3))}')
#Podemos trabalhar com números complexos
numcomplex = 3j
print(f'numcomplex é {numcomplex} e seu tipo é {type(numcomplex)}')
numcomplex1 = 5j
print(f'numcomplex1 ao quadrado é {numcomplex1**2}')
#Converter int para float
valor4 = 500
print(f'valor4 em float é {float(valor4)}')
|
2ac2de3fb316d65dfae70becd8927d70451437fe | 981377660LMT/algorithm-study | /11_动态规划/背包问题/完全背包/6011. 完成比赛的最少时间-预处理.py | 2,085 | 3.671875 | 4 | from typing import List, Tuple
# 1 <= numLaps <= 1000
# 1 <= tires.length <= 105
# 总结:
# 这道题一开始想贪心的解法(贪心ptsd),sortedList弄了好久,
# 最后才意识到是dp 状态由圈数唯一决定 但是怎么求每个圈的最小时间花费呢?
# 总结:很明显贪心不对的(举反例),就不要贪心了,考虑别的解法,一般是dp,找dfs的自变量是什么,怎么转移,初始值是什么
# 实际上是20个完全背包,凑成numLaps的容量,看最少花费
# 1 <= tires.length <= 105
# 1 <= numLaps <= 1000
# 2 <= ri <= 105
INF = int(1e20)
class Solution:
def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:
"""tires[i] = [fi, ri] 表示第 i 种轮胎如果连续使用,第 x 圈需要耗时 fi * ri(x-1) 秒"""
"""每一圈后,你可以选择耗费 changeTime 秒 换成 任意一种轮胎(也可以换成当前种类的新轮胎)。"""
# 预处理出不换轮胎,连续使用同一个轮胎跑 xx 圈的最小耗时 即每个物品的价格
# 状态转移 每个圈为状态 转移为下一次连续用多少个轮胎
prices = [INF] * 20
for a0, q in tires:
curSum, curItem = 0, a0
for j in range(20):
curSum += curItem
if curSum > int(1e5):
break
prices[j] = min(prices[j], curSum)
curItem *= q
# dp[i]表示第i圈的最小耗时 (容量)
dp = [INF] * (numLaps + 1)
dp[0] = 0
for i in range(len(prices)):
for j in range(numLaps + 1):
if j - (i + 1) >= 0:
dp[j] = min(dp[j], dp[j - (i + 1)] + prices[i] + changeTime)
# 减去最后一次的换轮胎耗时
return dp[-1] - changeTime
# 21 25
print(Solution().minimumFinishTime(tires=[[2, 3], [3, 4]], changeTime=5, numLaps=4))
print(Solution().minimumFinishTime(tires=[[1, 10], [2, 2], [3, 4]], changeTime=6, numLaps=5))
|
106144303d16a97664d52a67e6846e84ac94a20f | a1928375/Tokens | /Expanding Exp.py | 1,065 | 3.5625 | 4 | grammar = [
("exp", ["exp", "+", "exp"]),
("exp", ["exp", "-", "exp"]),
("exp", ["(", "exp", ")"]),
("exp", ["num"]),
]
def expand(tokens, grammar):
for pos in range(len(tokens)): # this tokens means sentence => sentence is element of utterances => Ex: ["exp"]
# len(tokens) => len(sentence) => len("exp") (because sentence will be longer
# in different depth, Ex: len(['exp', '+', 'exp'])) => so every "exp" should be
# replaced
for rule in grammar: # Ex: rule = ("exp", ["exp", "+", "exp"])
if tokens[pos] == rule[0]:
yield tokens[0:pos]+rule[1]+tokens[pos+1:]
depth = 1
utterances = [["exp"]]
for x in range(depth):
for sentence in utterances:
utterances = utterances + [ i for i in expand(sentence, grammar)]
for sentence in utterances:
print (sentence)
|
ff08a4e971c5a25f32d5b2607236d2eca989f2e0 | bl00p1ng/ejercicios-basicos-python | /imprimiendo_datos/ejercicio02.py | 742 | 3.875 | 4 | def run():
# Ejercicio 2
# Escribe un programa que muestre tu horario de clase. Puedes usar espacios o
# tabuladores para alinear el texto
schedule = [
['🕐 Hora ', '👨🏫 Clase '],
['08:30 am', 'Fundamentos de Python'],
['10:30 am', 'Matemáticas '],
['12:30 pm', 'Almorzar '],
['01:30 pm', 'Estadística '],
['03:30 pm', 'Estructuras de datos '],
['04:30 pm', 'Bases de datos ']
]
for i in range(len(schedule)):
for j in range(len(schedule[i])):
print("| {0} ".format(schedule[i][j]), sep=',', end='')
print('|')
if __name__ == '__main__':
run()
|
4e821c1486177a2ef8e3027fa2caca94a0943350 | piku-kaanu/chess_simulation | /src/piece.py | 5,385 | 3.546875 | 4 | """This module contains the Piece class which represents a piece in a chessboard and simulates it's move."""
from src import common
class Piece:
pieces = {'King': {'move': common.ONE_MOVE},
'Queen': {'move': common.FULL_MOVE},
'Bishop': {'move': common.FULL_MOVE, 'direction': [common.CROSS]},
'Horse': {'move': common.HORSE_MOVE, 'direction': [common.VERTICAL, common.HORIZONTAL]},
'Rook': {'move': common.FULL_MOVE, 'direction': [common.VERTICAL, common.HORIZONTAL]},
'Pawn': {'move': common.ONE_MOVE, 'direction': [common.VERTICAL]}}
def __init__(self, type_, x_position, y_position):
if type_ not in self.pieces:
raise common.UnsupportedChessPiece(
f'Error: Unsupported chess piece type: {type_}\n'
'Supported types are any one of King, Queen, Bishop, Horse, Rook or Pawn.\n')
if x_position not in range(common.MIN_X, common.MAX_X + 1) or \
y_position not in range(common.MIN_Y, common.MAX_Y + 1):
raise common.UnsupportedChessCell(
f'Error: Unsupported chess cell position: {chr(x_position)}{y_position}\n'
'Supported positions are any one from A1 to A8, B1 to B8 ... H1 to H8')
self.type_ = type_
self.x_position = x_position
self.y_position = y_position
self.step_move = self.pieces.get(type_).get('move')
self.direction = self.pieces.get(type_).get('direction', common.ALL_DIRECTIONS)
def get_possible_moves(self):
possible_moves = []
min_y = max(self.y_position - self.step_move, common.MIN_Y)
max_y = min(self.y_position + self.step_move, common.MAX_Y)
min_x = max(self.x_position - self.step_move, common.MIN_X)
max_x = min(self.x_position + self.step_move, common.MAX_X)
for direction in self.direction:
if direction == common.VERTICAL:
if common.IS_DEBUG:
print('Moves vertical')
possible_moves.extend(self.__get_range(self.x_position, self.x_position, min_y, max_y))
elif direction == common.HORIZONTAL:
if common.IS_DEBUG:
print('Moves horizontal')
possible_moves.extend(self.__get_range(min_x, max_x, self.y_position, self.y_position))
elif direction == common.CROSS:
if common.IS_DEBUG:
print('Moves cross ways')
possible_moves.extend(self.__get_range(min_x, max_x, min_y, max_y, is_cross=True))
return possible_moves
def __get_range(self, min_x, max_x, min_y, max_y, is_cross=False):
if not is_cross:
return [chr(i) + str(j) for i in range(min_x, max_x + 1) for j in range(min_y, max_y + 1) if
self.x_position != i or self.y_position != j]
else:
pass
ret_list = []
i = 1
while True:
count = 0
if self.x_position - i >= min_x:
if self.y_position - i >= min_y:
ret_list.append(chr(self.x_position - i) + str(self.y_position - i))
count += 1
if self.y_position + i <= max_y:
ret_list.append(chr(self.x_position - i) + str(self.y_position + i))
count += 1
if self.x_position + i <= max_x:
if self.y_position - i >= min_y:
ret_list.append(chr(self.x_position + i) + str(self.y_position - i))
count += 1
if self.y_position + i <= max_y:
ret_list.append(chr(self.x_position + i) + str(self.y_position + i))
count += 1
if count == 0:
break
i += 1
return ret_list
def get_horse_moves(self):
possible_moves = []
if self.x_position + 2 <= common.MAX_X:
if self.y_position - 1 >= common.MIN_Y:
possible_moves.append(chr(self.x_position + 2) + str(self.y_position - 1))
if self.y_position + 1 <= common.MAX_Y:
possible_moves.append(chr(self.x_position + 2) + str(self.y_position + 1))
if self.x_position - 2 >= common.MIN_X:
if self.y_position - 1 >= common.MIN_Y:
possible_moves.append(chr(self.x_position - 2) + str(self.y_position - 1))
if self.y_position + 1 <= common.MAX_Y:
possible_moves.append(chr(self.x_position - 2) + str(self.y_position + 1))
if self.y_position + 2 <= common.MAX_Y:
if self.x_position - 1 >= common.MIN_X:
possible_moves.append(chr(self.x_position - 1) + str(self.y_position + 2))
if self.x_position + 1 <= common.MAX_X:
possible_moves.append(chr(self.x_position + 1) + str(self.y_position + 2))
if self.y_position - 2 >= common.MIN_Y:
if self.x_position - 1 >= common.MIN_X:
possible_moves.append(chr(self.x_position - 1) + str(self.y_position - 2))
if self.x_position + 1 <= common.MAX_X:
possible_moves.append(chr(self.x_position + 1) + str(self.y_position - 2))
return possible_moves
|
3fe4fdb08536624b46d65d442da3cdaecdc7a047 | cassianasb/python_studies | /fiap-on/2-10 - ForLoop.py | 113 | 3.96875 | 4 | for number in range(1, int(input("Digite um número para determinar o fim: ")), 1):
print(" " + str(number))
|
dd5ffc56e0b3114652ceaa076d2d72ff2581057d | MacHu-GWU/Data-Science-in-Python | /Developer_version/Lesson3_polyfit_and_interpolation/polyfit.py | 1,485 | 3.59375 | 4 | ##encoding=utf8
##version =py27, py33
##author =sanhe
##date =2014-10-15
"""
[标题]如何用Python做曲线拟合,多项式分析
"""
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
def example1():
""" 1. 根据多项式系数求 f(x) 的值
np.poly1d(a) 根据系数a 生成一个多项式计算器
np.poly1d(a)(x) = f(x) 其中 f(x)是以a为系数的多项式
"""
a = [1,0,0] ## y = 1*x^2 + 0*x + 0
p = np.poly1d(a) ## 建立 poly1d 对象
print(p(0.1), p(0.2), p(0.3) ) ## 对单个x值求值
xp = [1,2,3] ## 对多个x值向量求多项式值
print(p(xp) )
example1()
def example2():
""" 2. 根据样本值拟合多项式系数
np.polyfit(x_data, y_data, p) 根据 x, y数据和阶数p返回拟合的多项式系数列表
"""
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
a3 = np.polyfit(x, y, 3) ## 3阶拟合,即x最高次方系数是3
a10 = np.polyfit(x, y, 10) ## 10阶拟合,即x最高次方系数是10
p3 = np.poly1d(a3)
p10 = np.poly1d(a10)
## 画图验证
xp = np.linspace(0,5,10)
plt.plot(x, y, ".", markersize = 10) # 点是原数据
plt.plot(xp, p3(xp), "r--") # 红线是3阶拟合
plt.plot(xp, p10(xp), "b--") # 蓝线是10阶拟合
plt.show()
example2()
# 更多信息请参考官方文档: http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html |
098baf1224bd768c20efca915664aa3d3b7cf39d | mornhuang/study | /python/P3_bk01/ch01/sum1.py | 662 | 3.859375 | 4 | #!/usr/bin/env python
#-*- coding:UTF-8 -*-
"""
Created on 2011-10-5
@author: IBM
A simple add input value demo
"""
import sys
if __name__ == '__main__':
print("Type integers, each followed by Enter; or just Enter to finish")
total = 0
count = 0
while True:
line = input("integer:")
if line:
try:
number = int(line)
except ValueError as err:
print(err)
continue
total += number
count += 1
else:
break
if count:
print("总共=", count, "total=", total, "mean=", total / count)
sys.exit(0)
|
83d90978091e7a93722a44ad04bbcac54ccfcd8f | mzhuang1/lintcode-by-python | /中等/83. 落单的数 II.py | 578 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字。
样例
给出 [1,1,2,3,3,3,2,2,4,1] ,返回 4
挑战
一次遍历,常数级的额外空间复杂度
"""
class Solution:
"""
@param A: An integer array
@return: An integer
"""
def singleNumberII(self, A):
# write your code here
A.sort()
i = 2
while i < len(A):
if A[i-2] != A[i]:
return A[i-2]
i += 3
return A[-1]
|
0de62620f09003613f05ce55895e7c2cb6662980 | yunakim2/Algorithm_Python | /프로그래머스/level2/JadenCase 문자열 만들기.py | 528 | 3.90625 | 4 | import re
def solution(s):
s = s.replace(' ', '-')
s = list(s.split('-'))
for idx, item in enumerate(s):
upper_str = ''
if item == '':
continue
if item[0].isnumeric():
upper_str = item[0]+ item[1:].lower()
s[idx] = upper_str
continue
upper_str = item[0].upper() + item[1:].lower()
s[idx] = upper_str
return ' '.join(s)
if __name__ == "__main__":
print(solution("tomato"))
print(solution(' adgagd 3eagdag '))
|
35b20155d7cd275312efcab54d27d39dfeb7644c | yizow/robot-synthesis | /Beam.py | 2,273 | 4.0625 | 4 | from robot import Link
from operator import *
from math import *
class Beam(Link):
"""Represents a beam, a specific type of link that is a rigid, straight, and has no twist.
Calculates positions of endpoints for calculating pin connections
Position of beam is defined as the startPin
Travel the length of the Beam to get to the endPin
The point of interest is the point that we use to trace out a curve. This is measured the perpendicular distnace from the point to the beam, and how far away from the start that intersection is from start.
PoIOffset = distance along the beam, as a ratio of the beam length. Positive offset means traveling towards the endEffector, negative means travelling away.
PoIDistance = Perpendicular distance the the PoI. Positive means a clockwise motion, negative means counterclockwise.
"""
zeroThreshold = .00001
def __init__(self, length, PoIOffset = 0.0, PoIDistance = 0.0):
Link.__init__(self, 0,length,0,0)
self.position = [0.0,0.0,0.0]
# rotation about Z axis, X axis, Z axis
self.rotation = [0.0,0.0,0.0]
# a unit vector describing the direction of the axis that this beam rotates around
self.axis = [0.0, 0.0, 1.0]
self.PoIOffset = PoIOffset
self.PoIDistance = PoIDistance
def __setattr__(self, name, value):
if name in Link.fields:
Link.__setattr__(self, name, value)
else:
self.__dict__[name] = value
def start(self):
return self.position
def end(self):
return travel(self.position, self.rotation[0], self.A)
def where(self):
array = [a for a in self.position]
for i in range(len(array)):
if abs(array[i]) < self.zeroThreshold:
array[i] = 0.0
return array
def PoI(self):
intersect = travel(self.position, self.rotation[0], self.PoIOffset*self.A)
PoI = travel(intersect, self.rotation[0]+pi/2, self.PoIDistance)
return PoI
def offsetBeam(self):
intersect = travel(self.position, self.rotation[0], self.PoIOffset*self.A)
end = self.PoI()
return [[list(self.position), list(intersect)], [list(intersect), list(end)]]
def travel(startPos, angle, distance):
"""Utility function to find relative positions
Angle is measured from horizontal pointing right."""
ret = map(add, startPos, [distance*x for x in (cos(angle), sin(angle), 0.0)])
return ret
|
a18576aba4bd4c18ea6faa99aaf978604e752f96 | SuchismitaDhal/Solutions-dailyInterviewPro | /2020/04-April/04.17.py | 355 | 4.0625 | 4 | # UBER
"""
Given a string s and a character c,
find the distance for all characters
in the string to the character c in the string s.
You can assume that the character c will appear at least once in the string.
"""
def shortest_dist(s, c):
# Fill this in.
print(shortest_dist('helloworld', 'l'))
# [2, 1, 0, 0, 1, 2, 2, 1, 0, 1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.