blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f8b01b3e9b6e2a3979cde4b563ba06c274f11e45 | janvirighthere/projecteuler | /01_mult_three_five.py | 240 | 4.5 | 4 |
def multiples(number):
"""Takes in a number and returns the sum
of all numbers that are multiples of 3 or five"""
sum = 0
for i in range(1, number):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
|
292c478494f5324435a68edf7230fff9b5d9ff2e | Sudheer-Movva/Python_Assignment01 | /Assignment-1/Chap5/ChapFive30.py | 2,882 | 4.3125 | 4 |
year,first_day =eval(input("Enter the year and the first day of the year: "))
if first_day%7 == 1:
day_name = "Monday"
elif first_day%7 == 2:
day_name = "Tuesday"
elif first_day%7 == 3:
day_name = "Wednesday"
elif first_day%7 == 4:
day_name = "Thursday"
elif first_day%7 == 5:
day_name = "Friday"
elif first_day%7 == 6:
day_name = "Saturday"
else:
day_name = "Sunday"
print("January 1 ",year," is ",day_name)
days_sum = 1 + 32
for month in range(2,13):
if month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
if days_sum%7 == 1:
day_name = "Monday"
elif days_sum%7 == 2:
day_name = "Tuesday"
elif days_sum%7 == 3:
day_name = "Wednesday"
elif days_sum%7 == 4:
day_name = "Thursday"
elif days_sum%7 == 5:
day_name = "Friday"
elif days_sum%7 == 6:
day_name = "Saturday"
else:
day_name = "Sunday"
if month == 3:
month_name = "March"
elif month == 5:
month_name = "May"
elif month == 7:
month_name = "July"
elif month == 8:
month_name = "August"
elif month == 10:
month_name = "October"
elif month == 12:
month_name = "December"
days_sum += 31
if month == 4 or month == 6 or month == 9 or month == 11:
if days_sum%7 == 1:
day_name = "Monday"
elif days_sum%7 == 2:
day_name = "Tuesday"
elif days_sum%7 == 3:
day_name = "Wednesday"
elif days_sum%7 == 4:
day_name = "Thursday"
elif days_sum%7 == 5:
day_name = "Friday"
elif days_sum%7 == 6:
day_name = "Saturday"
else:
day_name = "Sunday"
if month == 4:
month_name = "April"
elif month == 6:
month_name = "June"
elif month == 9:
month_name = "September"
elif month == 11:
month_name = "November"
days_sum += 30
if month == 2:
if days_sum%7 == 1:
day_name = "Monday"
elif days_sum%7 == 2:
day_name = "Tuesday"
elif days_sum%7 == 3:
day_name = "Wednesday"
elif days_sum%7 == 4:
day_name = "Thursday"
elif days_sum%7 == 5:
day_name = "Friday"
elif days_sum%7 == 6:
day_name = "Saturday"
else:
day_name = "Sunday"
if month == 2:
month_name = "Febraury"
if year%4 == 0:
days_sum += 29
else:
days_sum += 28
print(month_name," 1 ",year," is ",day_name)
|
479aebdde27dc2f13403abedb4f51efab1f14274 | acanida0623/week2day1 | /program.py | 679 | 3.765625 | 4 | import fibo
print (fibo.fib(2000))
#enumerate returns each item as a tupell
for i, n in enumerate(fibo.fib2(1000)):
print("{0}: {1}".format(i,n,))
#The {0} and {1} are indexes of the enumerate values that i had place in the format method. {2} is going to print i
#take ninthe fibo number and divide it by the eigth
"""def nth_quot(n):
fibos = []
for i, x in enumerate(fibo.fib2(1000000000)):
fibos.append(x)
answer = fibos[n-1] / fibos[n-2]
return answer
print (nth_quot(9))"""
def nth_quot2(n):
answer = fibo.fib3(n) / fibo.fib3(n-1)
return answer
print (fibo.fib3(2000))
print (fibo.fib3(1999))
print (nth_quot2(2000))
|
7ee8328a9a33b47d50eb82b2aceb45e217068917 | manjesh41/project_4 | /9.py | 293 | 4.28125 | 4 | '''
. Write a program to find the factorial of a number
'''
num=int(input('Enter the number:'))
factorial=1
if num<0:
print('error')
elif num==0:
print('the factoral of 0 s 1')
else:
for i in range(1,num+1):
factorial*=i
print(f'The factorial of {num} is {factorial}') |
6ce360d523aeba59e55618e05eb046308406ff1b | LichiSaez/mi_primer_programa | /comer_helado.py | 912 | 4.25 | 4 |
apetece_helado_input = input("¿Te apetece un helado? (Si/No):").upper()
if apetece_helado_input == "SI":
apetece_helado = True
elif apetece_helado_input == "NO":
apetece_helado = False
else:
print("Te he dicho que me digas si o no, no se que has dicho pero lo tomo como que no")
apetece_helado = False
tienes_dinero_input = input("¿Tienes dinero para un helado? (Si/No):").upper()
esta_el_senor_de_los_helado_input= input("¿Esta el señor de los helados? (Si/No)").upper()
esta_tu_tia_input = input ("¿Estas con tu tía? (Si/No)").upper()
apetece_helado = apetece_helado_input == "SI"
puede_permitirselo = tienes_dinero_input == "Si" or esta_tu_tia_input == "SI"
esta_el_señor_de_los_helados = esta_el_senor_de_los_helado_input == "SI"
if apetece_helado and puede_permitirselo and esta_el_señor_de_los_helados:
print("Pues comete un helado")
else:
print("Pues nada")
|
5406e10e7b398bf24a544490a0ba588e0ce2c621 | sgarg87/sahilgarg.github.io | /code_bases/python_coding_practice/reverse_linked_list.py | 1,960 | 4.0625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class ReverseLinkedList:
def __init__(self):
pass
def input_number_as_list(self, numbers_list):
assert len(numbers_list) >= 1
previous_node = None
start_node = None
for curr_idx, curr_number in enumerate(numbers_list):
curr_node = ListNode(x=curr_number)
if curr_idx == 0:
start_node = curr_node
else:
assert previous_node is not None
previous_node.next = curr_node
previous_node = curr_node
del curr_node
return start_node
def print_digits(self, l1):
assert l1 is not None
curr_node = l1
while curr_node is not None:
print(curr_node.val),
curr_node = curr_node.next
print('')
def reverseList(self, head, is_head_node=True):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
next_node = head.next
if is_head_node:
head.next = None
if next_node is None:
return head
else:
assert next_node is not None
if next_node.next is None:
# print(head.val)
next_node.next = head
return next_node
else:
# print((head.val, next_node.val))
reverse_head = self.reverseList(next_node, is_head_node=False)
next_node.next = head
return reverse_head
if __name__ == '__main__':
inputs = [1, 2, 3, 4, 5]
obj = ReverseLinkedList()
head_inputs_as_list = obj.input_number_as_list(numbers_list=inputs)
obj.print_digits(head_inputs_as_list)
reverse_list_head = obj.reverseList(head=head_inputs_as_list)
obj.print_digits(reverse_list_head)
|
0afb28b346345116100fe18b25a67b86ff5e50d6 | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_77.py | 706 | 4.40625 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 10: OOP (Python Object-Oriented Programming) - Aula: 77 """
# 77. Criando a sua primeira classe
# classes
# utilizamos para criar objetos (instances)
# objetos sao partes dentro de uma class (instancias)
# classes sao utilizadas para agrupas dados e funções, podendo reutilizar
# class: frutas
# objects: abacate, banana, ...
# criando uma classe
class Funcionarios:
nome = 'Elena'
sobrenome = 'Cabral'
data_nascimento = '12/01/1999'
# criando um objeto
usuario1 = Funcionarios()
print(usuario1.nome)
print(usuario1.sobrenome)
print(usuario1.data_nascimento)
|
72374a38bdb9ec39143bbe586a0a3e92e10a1c5e | alvinlee90/TensorFlow-Tutorials | /04 Batch Normalisation/mnist_model.py | 6,292 | 3.5625 | 4 | """ CNN model based from the TensorFlow tutorial for the MNIST dataset
(https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/mnist_saved_model.py)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def conv2d(x, weight, bias):
""" Function for the convolutional layers.
CNN layers with 1 x 1 stride and zero padding
Args:
x: input tensor for the CNN layer
weight: tensor for the filter of the CNN
bias: tensor for the bias of the CNN
Returns:
Tensor of the output of the layer
"""
return tf.nn.conv2d(x, filter=weight, strides=[1,1,1,1], padding='SAME') + bias
def max_pool_2x2(x):
""" Function for the max pool layer
Max pool layer with 2 x 2 kernel size, 2 x 2 stride and zero padding.
Args:
x: input tensor for the max pool layer
Returns:
Tensor of the output of the layer
"""
return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
def variable_summaries(var):
""" Function for the TensorBoard summaries
Adds the mean, standard deviation and histogram to the TensorBoard summaries
Args:
var: tensor of variable to add to summaries
"""
mean = tf.reduce_mean(var)
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('mean', mean)
tf.summary.scalar('stddev', stddev)
tf.summary.histogram('histogram', var)
def inference(image, img_size, num_classes, keep_prob, train_phase):
# Create graph
with tf.variable_scope('conv1') as scope:
image = tf.reshape(image, shape=[-1, img_size, img_size, 1])
# Placeholder for weights and bias
with tf.variable_scope('weight'):
w = tf.get_variable('weights',
shape=[5, 5, 1, 32],
initializer=tf.truncated_normal_initializer())
variable_summaries(w)
with tf.variable_scope('bias'):
b = tf.get_variable('bias',
shape=[32],
initializer=tf.truncated_normal_initializer())
variable_summaries(b)
conv1a = tf.nn.relu(conv2d(image, w, b), name=scope.name)
conv1b = tf.contrib.layers.batch_norm(conv1a,
center=True,
scale=True,
is_training=train_phase)
with tf.variable_scope('pool1'):
pool1 = max_pool_2x2(conv1b)
# output dimension = 14 x 14 x 32
with tf.variable_scope('conv2'):
# Placeholder for weights and bias
with tf.variable_scope('weight'):
w = tf.get_variable('weights',
shape=[5, 5, 32, 64],
initializer=tf.truncated_normal_initializer())
variable_summaries(w)
with tf.variable_scope('bias'):
b = tf.get_variable('bias',
shape=[64],
initializer=tf.truncated_normal_initializer())
variable_summaries(b)
conv2a = tf.nn.relu(conv2d(pool1, w, b), name=scope.name)
conv2b = tf.contrib.layers.batch_norm(conv2a,
center=True,
scale=True,
is_training=train_phase)
with tf.variable_scope('pool2'):
pool2 = max_pool_2x2(conv2b)
# output dimension = 7 x 7 x 64
# Flatten layer (for fully_connected layer)
with tf.name_scope('flatten'):
flat_dim = pool2.get_shape()[1].value * pool2.get_shape()[2].value * pool2.get_shape()[3].value
flat = tf.reshape(pool2, [-1, flat_dim])
with tf.variable_scope('fc1') as scope:
# Placeholder for weights and bias
with tf.variable_scope('weight'):
w = tf.get_variable('weights', shape=[flat_dim, 1024],
initializer=tf.truncated_normal_initializer())
variable_summaries(w)
with tf.variable_scope('bias'):
b = tf.get_variable('bias', shape=[1024],
initializer=tf.random_normal_initializer())
variable_summaries(b)
fc1a = tf.nn.relu(tf.matmul(flat, w) + b, name=scope.name)
fc1b = tf.contrib.layers.batch_norm(fc1a,
center=True,
scale=True,
is_training=train_phase)
# Apply dropout
fc1_drop = tf.nn.dropout(fc1b, keep_prob)
with tf.variable_scope('softmax'):
# Placeholder for weights and bias
with tf.variable_scope('weight'):
w = tf.get_variable('weights', shape=[1024, num_classes],
initializer=tf.truncated_normal_initializer())
variable_summaries(w)
with tf.variable_scope('bias'):
b = tf.get_variable('bias', shape=[num_classes],
initializer=tf.random_normal_initializer())
variable_summaries(b)
y_conv = tf.add(tf.matmul(fc1_drop, w), b)
return y_conv
def loss(labels, logits):
with tf.name_scope('loss'):
# Define loss
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits), name='loss')
tf.summary.scalar('loss', loss)
return loss
def train(loss):
# Define training method
with tf.name_scope('train'):
optimizer = tf.train.RMSPropOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(loss)
return train_op
def evaluate(logits, labels):
# Evaluate the model
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
with tf.name_scope('evaluate'):
# Evaluate accuracy
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return accuracy
|
e7e8e0c7f9cc16870d0320726367a2f4e5d85b9d | daniel-reich/turbo-robot | /CszujsGawysQPJoyZ_0.py | 1,600 | 4.0625 | 4 | """
You're working for Jaffar in the newest game of Prince of Persia. The prince
is coming to get the princess and you have to stop him. He's entering the
castle on a horse, don't ask me why he's riding a horse... he just is!
You're standing next to the cannon and you have to check if the aim / velocity
/ height is ok for hitting the prince on his horse.
Your function will get four values / circumstances:
1. Velocity
2. Angle
3. Height
4. Distance to the prince
With the formula of **Ballistic Trajectory** you'll be able to calculate the
distance the cannonball is gonna travel for impact. You don't need to apply
rounding.
The complete formula is found in the **Resources** section. Computations are
based on the acceleration of gravity on the earth's surface (9.81 m/s/s),
atmospheric drag is neglected. The chance of hitting the prince / his horse is
plus or minus 0.5m.
### Examples
hit_prince(10, 10, 10, 16) ➞ True
hit_prince(20, 45, 0, 45) ➞ False
hit_prince(5, 45, 10, 6) ➞ True

### Notes
* No actual princes / horses are harmed during the making of this challenge.
* All the inputs are correct. 0 > Angle < 90, and so on.
* Values will be in meters per second / degrees / meters.
"""
import math
g = 9.81
pi = math.pi
def hit_prince(vo, th, yo, ds):
h = yo
a = th * pi / 180
w = vo**2 * math.sin(2*a) / (2 * g) + vo * math.cos(a) * \
math.sqrt(vo**2 * math.sin(a)**2 + 2 * g * h) / g
return abs(w - ds) < .5
|
34ac2345aa4da35db46609f3e2c990f7692c20b2 | jcshott/interview_prep | /cracking_code_interview/ch1_arrays-strings/ispermutation.py | 400 | 4.0625 | 4 | def is_permutation(str1, str2):
""" check if one string is a permutation of another """
char_a = {}
char_b = {}
for a in str1:
char_a[a] = char_a.get(a, 0) + 1
for b in str2:
char_b[b] = char_b.get(b, 0) + 1
return char_a == char_b
assert is_permutation("aabbcda", "cdababa") == True
assert is_permutation("xyz", "aabbcda") == False
assert is_permutation("abbc", "aabbcda") == False
|
4d4d08aff07b671e154e427c8dd897e0e9674bdf | mariahmm/class-work | /8.1.2Answer.py | 124 | 3.859375 | 4 | def middle(m):
return m[1:len(m)-1]
numbers = ['1', '2', '3', '4' '5']
rest = middle(numbers)
print(rest)
print(numbers) |
00ac58a6d615f9b876083903298c332bf120b059 | davidbriddock/rpi | /learn-python/MicroMartSeries/turtle-shapes.py | 269 | 4.0625 | 4 | from turtle import *
# set a shape and colour
shape("circle")
shapesize(5,1,2)
fillcolor("red")
pencolor("darkred")
# move to the start
penup()
goto(0, -100)
# stamp out some shapes
for i in range(72):
forward(10)
left(5)
tilt(7.5)
stamp()
exitonclick() |
924f6dd747d81204ed0d4e14a2a2e1ff7dc7ef80 | SANOOPKV/PythonLessons | /dictionary.py | 259 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#Disctionary
# In[2]:
dict = {1:"Python",2:{"Cpp"}}
print(dict[1])
# In[4]:
print(1 in dict)
# In[6]:
print("Python" in dict)
# In[9]:
print(str(dict))
# In[10]:
print(dict)
# In[ ]:
|
b8f7d165c7bd6c6752df47c1bcd6a3a0210ba5ba | MIS407/ClassWork | /pandas_work.py | 692 | 4.0625 | 4 | """
we have read in our excel file using pd.read_excel(io, sheetname='somename', index_col='colname')
import pandas as pd
Read excel file name d SuperstoreSales.xlsx
create a logical file name
fn = 'C:/myPy/SuperstoreSales.xlsx'
Read into a data frame
df = pd.read_excel(fn, sheetname='Orders', index_col='Order Date')
print(df)
print(df.head(5))
print(df.tail(10))
Create a group (cluster by) on Ship Mode and compute the Shipping Cost statistics for each mode
ShipCostByMode = df['Shipping Cost'].groupby(df['Ship Mode'])
ShipCostByMode.describe()
ShipCostByMode.mean()
Find those customers having sales greater than $5,000
print(df['Customer Name'].where(df['Sales'] > 5000))
|
cc72eb178bdc51fd2beaa7350d7a2cc8f2fbcb1d | techgymjp/techgym_python | /U2gr.py | 153 | 3.9375 | 4 | number = 3
if number == 1:
print('1です')
elif number == 2 or number == 3:
print('2か3です')
else:
print('条件に当てはまりません') |
4a31adb0f713309db63fd4771bf4935a5e38c52e | fuckdinfar/project-hehehehhehe | /Stats_project1.py | 1,785 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 1 13:27:24 2018
@author: Thomas, Frederik
"""
import numpy as np
def dataStatistics(data, statistic):
#Calculates mean Temperature
if statistic == 'Mean temperature':
result = np.mean(data[:,0])
#Calculates mean Growth rate
elif statistic == 'Mean growth rate':
result = np.mean(data[:,1])
#Calculates standard deviation of Temperature
elif statistic == 'Std temperature':
result = np.std(data[:,0])
#Calculates standard deviation of Growth rate
elif statistic == 'Std growth rate':
result = np.std(data[:,1])
#Calculates the total number of rows in the data
elif statistic == 'Rows':
result = np.size(data[:,0])
#Calculates mean Growth rate when temp < 20 degrees
elif statistic == 'Mean cold growth rate':
GRsum = 0
GRamount = 0
for i in range(len(data[:,0])):
if data[i,0] < 20:
GRsum = GRsum + data[i,1]
GRamount = GRamount + 1
if GRamount > 0:
result = GRsum/GRamount
else :
result = 'No temperature below 20 degrees'
#Calculates mean Growth rate when temp > 50 degrees
elif statistic == 'Mean hot growth rate':
GRHsum = 0
GRHamount = 0
for i in range(len(data[:,0])):
if data[i,0] > 50:
GRHsum = GRHsum + data[i,1]
GRHamount = GRHamount + 1
if GRHamount > 0:
result = GRHsum/GRHamount
else :
result = 'No temperature above 50 degrees'
else:
result = 'Invalid input, try again'
return result
|
7a7370bec2a2fe6c22d55fd23a499e5ff0df9306 | hquanitute/unit_test | /testFile.py | 1,082 | 3.75 | 4 | import unittest
execfile('D:/KLTN/UnitTest/Python/basic/reverse-a-string.py')
class TestReverseString(unittest.TestCase):
def test_should_return_string(self):
self.assertEqual(type(reverseString("hello")) is str, True, "{{%<code>hello<code> should be return String%}}")
print("{{<code>hello<code> should be return String}}")
def test_case1(self):
self.assertEqual(reverseString("hello"), "olleh","{{%<code>hello<code> should be return olleh%}}")
print("{{<code>hello<code> should be return olleh}}")
def test_case2(self):
self.assertEqual(reverseString("Howdy"), "ydwoH", "{{%<code>Howdy<code> should be return ydwoH%}}")
print("{{<code>Howdy<code> should be return ydwoH}}")
def test_case3(self):
self.assertEqual(reverseString("Greetings from Earth"), "htraE morf sgniteerG", "{{%<code>Greetings from Earth<code> should be return htraE morf sgniteerG%}}")
print("{{<code>Greetings from Earth<code> should be return htraE morf sgniteerG}}")
if __name__ == '__main__':
unittest.main() |
6b6e9b8f3553ece126889f27055c48dc5fb3bc7e | Aakancha/Python-Workshop | /Jan19/Assignment/List/Q2.py | 241 | 3.75 | 4 | n = int(input("Enter number of items: "))
listn = []
for each in range(n):
i = input("Enter item: ")
listn.append(i)
cnt = 0
for each in listn:
if len(each) >= 2 and each[0] == each[len(each)-1]:
cnt += 1
print(f"{cnt}")
|
89e07aa21f7d6744ef0d6ecfbc70422c4c12cb38 | gnikolaropoulos/AdventOfCode2020 | /day01/main.py | 1,646 | 3.984375 | 4 | from itertools import combinations
def solve_part_1(puzzle_input):
for a, b in combinations(puzzle_input, 2):
if a + b == 2020:
return a * b
return ""
def solve_part_2(puzzle_input):
for a, b, c in combinations(puzzle_input, 3):
if a + b + c == 2020:
return a * b * c
return ""
def find_sum_of_two(sum_to_find, array_of_values):
checked_numbers = {}
for number in array_of_values:
if sum_to_find - number in checked_numbers:
return number, sum_to_find - number
else:
checked_numbers[number] = True
def elegantly_solve_part_1(puzzle_input):
x, y = find_sum_of_two(2020, puzzle_input)
return x * y
def elegantly_solve_part_2(puzzle_input):
for i in range(0, len(puzzle_input) - 2):
diff = 2020 - puzzle_input[i]
results = find_sum_of_two(diff, puzzle_input[: i + 1])
if results:
return results[0] * results[1] * puzzle_input[i]
def get_puzzle_input():
puzzle_input = []
with open("input.txt") as input_txt:
for line in input_txt:
puzzle_input.append(int(line))
return puzzle_input
if __name__ == "__main__":
puzzle_input = get_puzzle_input()
answer_1 = solve_part_1(puzzle_input)
print(f"Part 1: {answer_1}")
answer_2 = solve_part_2(puzzle_input)
print(f"Part 2: {answer_2}")
# more elegant solutions
elegant_answer_1 = elegantly_solve_part_1(puzzle_input)
print(f"Part 1 (elegant): {elegant_answer_1}")
elegant_answer_2 = elegantly_solve_part_2(puzzle_input)
print(f"Part 1 (elegant): {elegant_answer_2}")
|
9327604254218d96fd33ce44ded5e7f50d6f7416 | liuchangling/leetcode | /竞赛题/第 190 场周赛/5418. 二叉树中的伪回文路径 .py | 1,426 | 3.71875 | 4 | # 5418. 二叉树中的伪回文路径
# 题目难度Medium
# 给你一棵二叉树,每个节点的值为 1 到 9 。我们称二叉树中的一条路径是 「伪回文」的,当它满足:路径经过的所有节点值的排列中,存在一个回文序列。
# 请你返回从根到叶子节点的所有路径中 伪回文 路径的数目。
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# dfs全排列,当路径上每个字符出现次数均为奇数时,就说明有回文路径。
import collections
class Solution:
def pseudoPalindromicPaths (self, root: TreeNode) -> int:
return self.dfs(root, [])
def dfs(self, root: TreeNode, parentVals):
vals = parentVals + [root.val]
if root.left == None and root.right == None:
c = collections.Counter(vals)
firstOdd = False
for value in c.values():
if value % 2 == 1:
if not firstOdd:
firstOdd = True
else :
return 0
return 1
else :
left = 0 if root.left == None else self.dfs(root.left, vals)
right = 0 if root.right == None else self.dfs(root.right, vals)
return left + right |
39c4648f52aae00000f239e9f86ed17617b2e2e6 | Surya0705/Pythagoras_Theorem_in_Python | /Main.py | 588 | 4.5625 | 5 | import math # Importing the math module for Square Root.
a = float(input("Enter the Measure of First Side: ")) # Taking the Measure of the First Side as Input from the User.
b = float(input("Enter the Measure of Second Side: ")) # Taking the Measure of the Second Side as Input from the User.
c = (a ** 2) + (b ** 2) # Adding the Squares of Both Sides as stated in the Pythagoras Theorem.
d = math.sqrt(c) # Finding the Square Root of 'c' to find the Measure of the Hypoteneuse.
print(f"Using the Pythagoras Theorem the Hypoteneuse[Third Side] will measure {d}.") # Printing the Result. |
810876bfb394350d84319e3d6f5f05e9db55d5fa | jiayaozhang/taichi | /lsys.py | 2,528 | 3.53125 | 4 | from math import sin, cos, radians
class Lsystem:
def __init__(self):
self.axiom = "F"
self.angle = 22.5
self.length = .05
self.rules = {
"F": "FF+[+F-F-F]-[-F+F+F]"
}
def custom(self, ax, ang, rules, length=.05):
self.axiom = ax
self.angle = ang
self.length = length
self.rules = rules
def build_string(self, depth):
count = depth
lsys_string = self.axiom
while count > 0:
chars = [lsys_string[i:i+1] for i in range(0, len(lsys_string), 1)]
temp = "";
for char in chars:
if char in self.rules:
temp = temp + self.rules[char]
else:
temp = temp + char
lsys_string = temp
count = count - 1
return lsys_string[:-1]
def construct_points(self, lsys):
# chars = lsys.split()
chars = [lsys[i:i+1] for i in range(0, len(lsys), 1)]
angle = self.angle
length = self.length
stack = []
bone = []
factor = 1
curr = (0,0,90, 1)
for char in chars:
if char == 'F':
# push (curr_loc, changed_loc) to list of lines
bone.append(curr)
yrun = sin(radians(curr[2]))
xrun = cos(radians(curr[2]))
curr = (curr[0]+xrun*length, curr[1]+yrun*length, curr[2], 1/factor)
elif char == '+':
# rotate direction positively
if curr[2] + angle < 360:
curr = (curr[0], curr[1], curr[2] + angle, curr[3])
else:
curr = (curr[0], curr[1], curr[2] + angle - 360, curr[3])
elif char == '-':
# rotate direction negatively
if curr[2] - angle >= 0:
curr = (curr[0], curr[1], curr[2] - angle, curr[3])
else:
curr = (curr[0], curr[1], curr[2] - angle + 360, curr[3])
elif char == '[':
# push curr_loc to stack
if factor+1 > 5:
factor = 5
else:
factor += 1
stack.append(curr)
elif char == ']':
# set curr_loc to popped stack
if factor-1 < 0:
factor = 0
else:
factor -= 1
curr = stack.pop()
return bone |
d3c387b052af624f65eeb0f6fc47a4c3a074e1ca | marcingorecki/crazy-pigeon-studios | /pigeon_school/pigeon school.py | 141 | 3.640625 | 4 | print "Welcome to pigeon school"
print
for a in range (1,6):
for b in range (1,6):
print "%s + %s = %s" % (a, b, a+b)
print
|
13fdaede655fe32092ae2e0a30cbce205f040e5a | SimpleLogic96/cs_problem_sets | /a04_string_processing/a04_strings_puzzles.py | 1,205 | 3.96875 | 4 | #PtI: String Processing Puzzles
#Reveres Function
def reverse(s):
reverse_text = s[len(s):: -1]
return reverse_text
#Test
print(reverse('blackbird'))
#Every Other Function
def every_other(s):
every_other_text = s[:len(s):2]
return every_other_text
#Test
print(every_other('blackbird'))
#Outside Characters Function
def outside_chars(s,n):
outside_chars_text = s[0:n]
return outside_chars_texttouc
#Test
print(outside_chars('blackbird',3))
#Tripple Outside Function
def tripple_outsides(s):
tripple_outside_text = s[0:2] * 3 + s[3:]
return tripple_outside_text
#Test
print(tripple_outsides('blackbird'))
#Swap Halves Functino
def swap_halves(s):
if len(s) % 2 == 0:
swap_halves_text = s[len(s)/2:] + s[: len(s)/2-1]
return swap_halves_text
else:
swap_halves_text = s[int(round(len(s)/2)):] + s[:int(round(len(s)/2-1)):]
return swap_halves_text
#Test
print(swap_halves('Good day sunshine '))
#Slice Middle Function
def slice_middle(s):
quarter = int(round(len(s)/4))
minus_one = quarter - 1
slice_middle_text = s[quarter: len(s)-quarter]
return slice_middle_text
#Test
print(slice_middle("she came in through the bathroom window!"))
|
e61e4af53563e2a8b3f62e69797e1a2a9d1c1f8f | Aasthaengg/IBMdataset | /Python_codes/p02846/s267827015.py | 991 | 3.71875 | 4 | #!/usr/bin/env python3
import sys
INF = float("inf")
def solve(T: "List[int]", A: "List[int]", B: "List[int]"):
if A[0] < B[0]:
A, B = B, A
if A[1] > B[1]:
print(0)
return
elif A[0]*T[0]+A[1]*T[1] > B[0]*T[0]+B[1]*T[1]:
print(0)
return
elif A[0]*T[0]+A[1]*T[1] == B[0]*T[0]+B[1]*T[1]:
print("infinity")
return
K = (B[0]*T[0]+B[1]*T[1])-(A[0]*T[0]+A[1]*T[1])
L = (A[0]-B[0])*T[0] // K
if (B[0]-A[0])*T[0] % K == 0:
print(2*L)
else:
print(2*L+1)
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
T = [int(next(tokens)) for _ in range(2)] # type: "List[int]"
A = [int(next(tokens)) for _ in range(2)] # type: "List[int]"
B = [int(next(tokens)) for _ in range(2)] # type: "List[int]"
solve(T, A, B)
if __name__ == '__main__':
main()
|
5f292a4f5a4eac811e94b51c9e6a7ddd4f303ccf | yuchanmo/python1_class | /ch4/palindrome.py | 754 | 3.953125 | 4 | def pallindrome():
p_candidate = input("type your pallindrome candidate : ")
print('here is your pallindrome',p_candidate)
p_candidate = p_candidate.lower()
print('after lowering characters ==>',p_candidate)
isp_candidate = True
p1 = 0
p2 = len(p_candidate)-1
while isp_candidate and p1<p2:
if p_candidate[p1].isalpha():
if p_candidate[p2].isalpha():
if p_candidate[p1]==p_candidate[p2]:
p1 = p1 + 1
p2 = p2 - 1
else:
isp_candidate = False
return isp_candidate
else:
p2 = p2-1
else :
p1 = p1+1
return isp_candidate
pallindrome() |
bc79cfdc032c72dbaa0d5ec12eff996326930c8f | AtharvaTiwari56/ATM | /atm.py | 1,539 | 4.03125 | 4 | class Atm:
def __init__(self, cardnum, pinnum, balance):
self.pinnum = pinnum
self.cardnum = cardnum
self.balance = balance
def cashWithdrawal(self):
amount = int(input("Enter the amount you want to withdraw:"))
pin = int(input('Verify PIN number'))
if(amount>self.balance):
print('Not enough money!')
elif(amount <= self.balance and pin == self.pinnum):
self.balance = self.balance - amount
print('Withdrawal successful. New balance is ' + str(self.balance))
elif(pin != self.pinnum):
print('Incorrect PIN!')
def checkBalance(self):
print(self.balance)
def cashDeposit(self):
deposition = int(input("Enter the deposition amount:"))
pinn = int(input('Verify PIN number'))
if(pinn == self.pinnum):
self.balance = self.balance + deposition
print('Deposit succesful! New balance is ' + str(self.balance))
elif(pinn != self.pinnum):
print('Incorrect PIN!')
cardnum = int(input('Enter card number:'))
pinnum = int(input('Enter your PIN number:'))
balance = int(input('Enter your current bank balance:'))
atm = Atm(cardnum, pinnum, balance)
choice = input('What would you like to do today (withdraw, deposit, check balance):')
if(choice == 'withdraw'):
atm.cashWithdrawal()
elif(choice == 'deposit'):
atm.cashDeposit()
elif(choice == 'check balance'):
atm.checkBalance()
|
c31f4ad74a3bdf4bb368d67664e5a22144b9d3c6 | act5924/MomLookImCoding | /plots_cli.py | 3,250 | 3.90625 | 4 | '''
Arthur Tonoyan
Assignment 5.2
'''
import plots
def student_average():
while True:
lst = input('Enter the... File FirstName LastName (Enter to go back): ')
bst = lst.split()
if lst == '':
return True
try:
if len(bst) > 3:
raise IndexError
if plots.plot_grades(bst[0], bst[1], bst[2]) == True:
print ('Plot finished (window may be hidden)')
return True
else:
print ('Plot failed (no such student)')
True
except FileNotFoundError:
print ('No such file: ' + str(bst[0]))
True
except IndexError:
print ('Usage for stu: <filename> (space) <first name> (space) <last name>')
True
def print_average():
while True:
lst = input('Enter the... File GradeItem(#) (Enter to go back): ')
bst = lst.split()
if lst == '':
return True
try:
if len(bst) > 2:
raise IndexError
col = int(bst[1])
print ('Average: ' + str(plots.get_average_new(bst[0], col)))
return True
except FileNotFoundError:
print ('No such file: ' + str(bst[0]))
True
except IndexError:
print ('Usage for avg: <filename> (space) <Grade Item (#)>')
True
except ValueError:
print ('GradeItem must be a number')
def class_average():
while True:
lst = input('Enter the... File (Enter to go bacK): ')
if lst == '':
return True
try:
if len(lst.split()) > 1:
raise IndexError
plots.plot_class_averages(lst)
print ('Plot is finished (window may be hidden)')
return True
except FileNotFoundError:
print ('No such file: ' + str(lst))
True
except IndexError:
print ('Usage for avg: <filename> (space) <Grade Item (#)>')
True
def help():
print ('stu --> <filename> (space) <first name> (space) <last name> - plot student grades')
print ('cavg --> <filename> - plot class average')
print ('avg --> <filename> <GradeItem(#)> - prints average of Grade Item')
print ('quit - quits')
print ('help - displays this message')
return True
def quit():
quit_quit = input('Are you sure (y/n) : ')
if quit_quit == 'y' or quit_quit == 'Y':
return True
else:
return False
def main():
print ('>> ')
while True:
print ('Enter a command(\'help\') or \'quit\' to quit')
command = input('>> ')
command_split = command.split()
try:
if command_split[0] == 'quit':
if quit() == True:
print ('Goodbye!')
break
if command == 'stu':
student_average()
if command == 'avg':
print_average()
if command == 'cavg':
class_average()
if command == 'help':
help()
except IndexError:
True
if __name__ == '__main__':
main()
#print_average() |
52c2029295f2f49244a37d8ee02716a9cd56e4c9 | Lwk1071373366/zdh | /S20/day02/03作业.py | 3,721 | 3.734375 | 4 | # print(bool('1>1or3<4or4>5and2>1and9>8or7<6'))
# print(bool('not2>1and3<4or4>5and2>1and9>8or7<6'))
# TRUE
# 利⽤while语句写出猜⼤⼩的游戏:
# 设定⼀个理想数字⽐如:66,让⽤户输⼊数字,如果⽐66⼤,则显示猜测的结果⼤
# 了;如果⽐66⼩,则显示猜测的结果⼩了;只有等于66,显示猜测结果正确,然后退出
# 循环
# num = 66
# while True:
# num = int(input('请输入一个数字:'))
# if num > 66:
# print('大了')
#
# elif num < 66:
# print('小了')
#
# elif num == 66:
# print('结果正确')
# 在5题的基础上进⾏升级:
# 给⽤户三次猜测机会,如果三次之内猜测对了,则显示猜测正确,退出循环,如果
# 三次之内没有猜测正确,则⾃动退出循环,并显示‘太笨了你....’。
# num = 66
# count = 1
# while count <=3:
# num = int(input('请输入一个数字:'))
# count += 1
# if num > 66:
# if count == 4 :
# print('太笨了')
# break
# if num < 66:
# if count == 4:
# print('太笨了')
# break
# if num == 66:
# if count <=3:
# print('聪明')
# break
# 使⽤while循环输出 1 2 3 4 5 6 8 9 10
#
# count = 1
#
# while count<11:
# if count == 7:
# pass
# else:print(count)
# count=count+1
# 求1-100的所有数的和
# count = 1
# s = 0
# while True :
# s = s + count
# count =count + 1
# if count > 100 :
# break
# print(s)
#
#
# count = 1
# s = 0
#
# while count <101:
# s = s +count
# count =count + 1
# print(s)
# 输出 1-100 内的所有奇数
# count = 1
#
# while count < 100:
# print(count)
# count % 2 == 1
# count = count + 2
# if count == 101:
# break
# 输出 1-100 内的所有偶数
# count = 2
# while True:
# print(count)
# count = count+2
# if count ==102:
# break
# 求1-2+3-4+5 ... 99的所有数的和
# 思路!!! ???
# a = 1
# b = 0
# while a<100:
# c= a % 2
# if c == 1 :
# b= b +a
# else:b = b -a
# a += 1
# print(b)
# ⽤户登陆(三次输错机会)且每次输错误时显示剩余错误次数(提示:使⽤字符串格
# 式化)
username = 'kai'
password = '666'
count = 1
while count < 4:
username = input('请输入姓名:')
password = input('请输入密码:')
if username =='kai'and password == '666':
print('登录成功了')
break
else:
print('登录失败,剩余%s次,请重新登录' % (3-count))
count = count +1
# name = input('请输入你的姓名:')
# age = input('请输入你的年龄:')
# job = input('请输入你的工作:')
# hobby = input('请输入你的爱好:')
# msg = '''-----userinfo of %s----
# name = %s
# age = %d
# job = %s
# hobby = %s
# -----end-----'''% (name,name,int(age),job,hobby)
# print(msg)
# count = 1
#
# while count<11:
# if count== 9:
# pass
# else:
# print(count)
# count = count +1
#
#
#
# count = 1
#
# while count < 100:
# if count % 10 == 0:
# pass
# else:print(count)
# count=count +1
# age_of_0ldboy = 66
# count = 0
# while count < 3:
# guess=int(input('>>>'))
# if guess == age_of_0ldboy:
# print("ni zhen bang")
# break
# count=count+1
username = 'kai'
password = '111'
count =1
while count < 4:
username =input('请输入你的名字')
password = input('请输入你的密码:')
if username == 'kai'and password=='111':
print('正确')
break
else:print('请重新输入,还剩%s次' % (3-count))
count=count+1
|
7858582492fadaf24fedaad03a02f326cdc6c021 | ZordoC/How-to-Think-Like-a-ComputerScientist-Learning-with-Pytho3-and-Data-Structures | /5.4.6.1_without_col_5.py | 439 | 3.625 | 4 |
strin = "ThiS is String with Upper and lower case Letters"
def cunt_letters(s):
s= string.lower()
s = s.split()
s = "".join(s1)
pint(s2)
0
1
2 ltter_counts = {}
3
4 fr l in s2:
5 letter_counts[l] = letter_counts.get(l ,0)+1
6
7
8 _ist = list(letter_counts.items())
9 _ist.sort()
0 dc = dict(_list)
1
2
3 fr key,value in dic.items():
4 print(key," ",value)
5
6
7countletters(string) |
b5cedd51003cb2531c11325249d90cf5ebcd0a73 | KATO-Hiro/AtCoder | /ABC/abc001-abc050/abc031/c.py | 1,173 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def main():
n = int(input())
a = list(map(int, input().split()))
ans = -float('inf')
# See:
# https://www.slideshare.net/chokudai/abc031
for first in range(n):
# aに負の値があるため,0で初期化するとマズい
# See:
# https://atcoder.jp/contests/abc031/submissions/2336454
t_score = -float('inf')
a_score = -float('inf')
for second in range(n):
if first == second:
continue
if first < second:
small = first
large = second
else:
small = second
large = first
b = a[small:large + 1]
takahashi_score = sum(b[::2])
aoki_score = sum(b[1::2])
# 青木君が選択する要素:丸を付けられ中で,最も得点が得られる要素を選択
if aoki_score > a_score:
a_score = aoki_score
t_score = takahashi_score
ans = max(ans, t_score)
print(ans)
if __name__ == '__main__':
main()
|
4e6e1358db5cc44ad7de58508df1d60109c3e4c9 | 666syh/python_cookbook | /python_cookbook/2_string_and_text/2.5_字符串搜索和替换.py | 692 | 4.03125 | 4 | """
问题
你想在字符串中搜索和替换指定的文本模式
"""
# 简单的替换
text = 'yeah, but no, but yeah, but no, but yeah'
print(text.replace('yeah', 'yep'))
# yep, but no, but yep, but no, but yep
# 复杂的替换
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
import re
print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text))
# Today is 2012-11-27. PyCon starts 2013-3-13.
from calendar import month_abbr
def change_date(m):
mon_name = month_abbr[int(m.group(1))]
return '{} {} {}'.format(m.group(2), mon_name, m.group(3))
datepad = re.compile(r'(\d+)/(\d+)/(\d+)')
print(datepad.sub(change_date, text))
# Today is 27 Nov 2012. PyCon starts 13 Mar 2013.
|
45c9008852a14be6d6244e59886bd4667bb9fb32 | Giby666566/programacioncursos | /programa1.py | 117 | 3.875 | 4 | print("Dame un numero")
a=input()
b=input("Dame otro numero")
print(int(a)+int(b))
print(a-b)
print(a*b)
print(a/b)
|
4553542e1122be8eb1ac7ce6730c37acf1df6703 | judDickey1/Codewars | /findMissingLetter.py | 238 | 3.875 | 4 | from string import ascii_letters
def find_missing_letter(chars):
start = ascii_letters.index(chars[0])
for char, match_char in zip(chars,ascii_letters[start:]):
if char != match_char:
return match_char |
c85ce19c20cccf2abcbb5ea3b9ef301b8656525e | n-apier/CC-CS-PRACT | /Misc_Functions/dna.py | 740 | 3.75 | 4 | dna_1 = "ACCGTT"
dna_2 = "CCAGCA"
def longest_common_subsequence(string_1, string_2):
print("Finding longest common subsequence of {0} and {1}".format(string_1, string_2))
grid = [[0 for col in range(len(string_1) + 1)] for row in range(len(string_2) + 1)]
for row in range(1, len(string_2) + 1):
print("Comparing: {0}".format(string_2[row - 1]))
for col in range(1, len(string_1) + 1):
print("Against: {0}".format(string_1[col - 1]))
if string_1[col - 1] == string_2[row - 1]:
grid[row][col] = grid[row - 1][col - 1] + 1
else:
grid[row][col] = max(grid[row - 1][col], grid[row][col - 1])
for row_line in grid:
print(row_line)
longest_common_subsequence(dna_1, dna_2) |
b87ef074a7d143c3006bad66ab57fae2c6409cc8 | raal7102/raghad | /week9_exercise3.py | 275 | 3.671875 | 4 |
import sys
#print "Number of arguments: ", len(sys.argv), 'arguments'
#print "Argument List:", str(sys.argv)
userNumber1 = int(sys.argv[1])
userNumber2 = int(sys.argv[2])
sum = userNumber1+userNumber2
print "The sum of the two numbers you entered is: ", sum
|
ee732f92e1574a35409a575e238488710456bb28 | SmatMan/password-cracking | /random-with-no-confirmation.py | 390 | 3.671875 | 4 | import random
import string
alpha = dict(enumerate(string.ascii_lowercase))
password = input("Password: ").lower()
maxLength = len(password)
while True:
temp = ""
for i in range(maxLength):
tempCharGen = random.choice(alpha)
temp = temp + tempCharGen
print("testing: " + temp)
if temp == password:
break
else:
continue
print(temp)
|
72cd6bc57927b9dd01498b2fd77a4a403a38e0ae | nptravis/python-studies | /try_except.py | 735 | 3.609375 | 4 |
# f = open('testfile.txt')
try:
# f = open('test_file.txt')
# var = bar_var
f = open('corrupt_file.txt')
if f.name == 'corrupt_file.txt':
raise Exception
# pass
# except Exception: # will catch many other exception errors
# print("Sorry, this file does not exist")
# # pass
# except FileNotFoundError: # make sure this one is on top
# print("Sorry, this file does not exist")
# except Exception:
# print("Sorry, something went wrong")
except FileNotFoundError as e:
print(e)
except Exception as e:
# print(e)
print("Error!")
else: # only runs if we don't throw an exception
print(f.read())
f.close()
finally: # always runs even if there is an exception, like shutting down a database
print("Executing Finally...")
|
c55a72a9c6b892371d328ac47264f018eeca0778 | JoeyCipher/Kattis-Solutions | /Python/shiritori/shiritory.py | 550 | 3.515625 | 4 | list = set()
cases = int(input())
fair = True
for i in range(cases):
curr = input()
if curr in list:
if i % 2 == 0:
print("Player 1 lost")
else:
print("Player 2 lost")
break
list.add(curr)
if i != 0:
if lLetter != curr[0]:
fair = False
index = len(curr) - 1
lLetter = curr[index]
if i == (cases - 1):
if fair:
print("Fair Game")
elif i % 2 == 0:
print("Player 1 lost")
else:
print("Player 2 lost") |
ea0c94b0987d9e4ad39bbd72d6fad1b293670bea | amit5570/python | /label_tk.py | 308 | 3.734375 | 4 | from tkinter import *
root=Tk()
root.title("LABEL")
def disply():
print('Name '+ent1.get())
l1=Label(root,text="Enter Name: ")
ent1=Entry(root)
b1=Button(root,text="Submit",command=disply,bg="black",fg="white")
l1.grid(row=0,column=0)
ent1.grid(row=0,column=1)
b1.grid(row=1,columnspan=2)
|
e43dec94279a2fe46fa7efc67d8b1095059fd179 | svnavytka/lv-485.2.PythonCore | /CW_4.py | 1,631 | 4.1875 | 4 | #Task 1 Which value is bigger
a=int(input("Enter first number "))
b=int(input("Enter second number "))
if a>b:
print('First value is more then Second')
else:
print('Second value is more then First')
#Task 2 Even or Odd value
z=int(input("Enter any number "))
if z%2==0:
print ("Even number")
else:
print ("Odd number")
#Task 3 Factorial
n=int(input("Enter number that you need to find factorial for "))
factorial = 1
while n > 1:
factorial *= n
n -= 1
print(factorial)
#Task 4.1 Print all even values less than 100
start=0
finish=100
while start<finish:
if start % 2 == 0:
print(start)
start+=1
else:
print ('The end')
#Task 4.2 Print all even values less than 100
for a in range(0, 101, 2):
print(a, end=" ")
#Task 5.1 Print all odd values less than 100
for a in range(1, 101, 2):
print(a, end=" ")
#Task 5.2 Print all odd values less than 100
for a in range(0, 101):
if a % 2 == 0:
continue
print(a, end=" ")
#Task 6 Check list for odd values NEED HELP TO FIX IT!!!
ccc=[10, 4, 2]
for a in ccc:
if a % 2 != 0:
break
else:
print("List contains even values only")
print("List contains odd values, such as", a)
#Task 7 Change values in list to float
a = [9, 34, 26, 55, 65, 13]
pos = 0
for x in a:
a[pos] = float(a[pos])
pos += 1
print(a)
#Task 8
fib1 = fib2 = 1
n = int(input("Enter number of positions Fibo list: ")) - 2
while n > 0:
print(fib1, end=" ")
fib1, fib2 = fib2, fib1 + fib2
n -= 1
print(': It is your Fibo list') |
88c7ded1d2ecff45526b0abebfd3523631df8503 | Fliv/my-leetcode | /roman-to-integer.py | 633 | 3.578125 | 4 | class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
strTable = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
romanSum = 0
for i in range(len(s)):
if i == len(s) - 1:
romanSum += strTable[s[i]]
else:
if strTable[s[i]] < strTable[s[i+1]]:
romanSum -= strTable[s[i]]
else:
romanSum += strTable[s[i]]
return romanSum
if __name__=='__main__':
solution = Solution()
print solution.romanToInt('MCMXC') |
ad786ec83d96250508b1af575e7167a6ad75e87c | Souravvk18/DSA-nd-ALGO | /Data Structures/array_rotation.py | 892 | 3.8125 | 4 | # import sys
# def leftRotation(a, d):
# out = list(a)
# a_len = len(a)
# for ind, el in enumerate(a):
# out[(ind + a_len - d) % a_len] = el
# return out
# if __name__ == "__main__":
# n, d = input().strip().split(' ')
# n, d = [int(n), int(d)]
# a = list(map(int, input().strip().split(' ')))
# result = leftRotation(a, d)
# print (" ".join(map(str, result)))
"""
i/p-
5 4
1 2 3 4 5
o/p-
5 1 2 3 4
"""
def rotate(arr, n , d):
temp= []
i=0
while (i<d):
temp.append(arr[i])
i= i+1
i= 0
while (d<n):
arr[i] = arr[d]
i= i+1
d= d+1
arr[ : ] = arr[ 0 : i] + temp
return arr
n=int(input())
arr = [int(array) for array in input().split(' ')]
print("array after the rotation is:")
print(rotate(arr,n, 4))
"""
5
1 2 3 4 5
array after the rotation is:
[5, 1, 2, 3, 4]"""
|
89593271b035f5a0d0facde0f31850033d08efa8 | alinenecchi/AULAS_ALGORITIMOS_III | /aula03/main.py | 3,045 | 4.0625 | 4 | from data import Data
if __name__ == '__main__':
def verificaData():
print("Digite uma data")
dia, mes, ano = input('Data (dd/mm/aaaa): ').split('/')
dataP= int(dia),int(mes),int(ano)
data = Data._valida(dataP)
print("{}/{}/{}".format(dia,mes,ano))
if data == True:
print("Data valida")
else:
print("Data invalida")
def verificaBisexto():
print("Digite um ano")
ano = int(input("Ano:"))
data = Data._bisexto(ano)
print(ano)
print(data)
if data == True:
print("Este ano é bisexto")
else:
print("Este ano não é bisexto")
def verificarPasca():# fonte de pesquisa utilisada https://pipeless.blogspot.com/2008/10/calculando-data-da-pscoa-em-python.html
ano = int(input('Digite o ano desejado para calcularmos o dia da páscoa: '))
a = int(ano % 19)
b = int(ano / 100)
c = int(ano % 100)
d = int(b / 4)
e = int(b % 4)
f = int((b + 8) / 25)
g = int((b - f + 1) / 3)
h = ((19 * a + b - d - g + 15) % 30)
i = int(c / 4)
k = int(c % 4)
L = ((32 + 2 * e + 2 * i - h - k) % 7)
m = int((a + 11 * h + 22 * L) / 451)
mes = int((h + L - 7 * m + 114) / 31)
if mes == 1:
mes = 'Janeiro'
elif mes == 2:
mes = 'Fevereiro'
elif mes == 3:
mes = 'Março'
elif mes == 4:
mes = 'Abril'
elif mes == 5:
mes = 'Maio'
elif mes == 6:
mes = 'Junho'
elif mes == 7:
mes = 'Julho'
elif mes == 8:
mes = 'Agosto'
elif mes == 9:
mes = 'Setembro'
elif mes == 10:
mes = 'Outubro'
elif mes == 11:
mes = 'Novembro'
else:
mes = 'Dezembro'
mes1 = mes
dia = (((h + L - 7 * m + 114) % 31) + 1)
print(" A pascoa do ano de {} foi dia {} de {}.".format(ano, dia, mes1))
def escreverExtenso():
dia, mes, ano = input('Data (dd/mm/aaaa): ').split('/')
meses = ['janeiro', 'fevereiro', 'março', 'abril',
'maio', 'junho', 'julho', 'agosto', 'setembro',
'outubro', 'novembro', 'dezembro']
print('Data:')
print('%s de %s de %s' % (dia, meses[int(mes) - 1], ano))
def imprimeMenu ():
print ("(1) Teste data valida.")
print ("(2) Teste ano bisexto.")
print ("(3) Teste data por extenso.")
print ("(4) Teste data Pascoa.")
print ("(0) Sair.")
imprimeMenu()
opcao = input("Escolha uma das opcoes acima: ")
while opcao != '0':
if opcao == '1':
verificaData()
elif opcao == '2':
verificaBisexto()
elif opcao == '3':
escreverExtenso()
elif opcao == '4':
verificarPasca()
else:
print("Opção Invalida")
imprimeMenu()
opcao = input("Escolha uma das opcoes acima: ")
|
3867b67cd796ee73ade0f756ec132326d38c41e0 | rohinikavitake/pa | /char_range.py | 114 | 3.734375 | 4 | pharse="This is an example sentance. Lets see if we can find letters"
print(re.findall('[a-z]+',pharse))
print()
|
cd03b7b76bfb8c217c0a82b3d48321f8326cc017 | jnassula/calculator | /calculator.py | 1,555 | 4.3125 | 4 | def welcome():
print('Welcome to Python Calculator')
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for substraction
* for multiplication
/ for division
** for power
% for modulo
''')
number_1 = int(input("Enter your first number: "))
number_2 = int(input("Enter your second number: "))
#Addition
if operation == '+':
print(f'{number_1} + {number_2} = ')
print(number_1 + number_2)
#Subtraction
elif operation == '-':
print(f'{number_1} - {number_2} = ')
print(number_1 - number_2)
#Multiplication
elif operation == '*':
print(f'{number_1} * {number_2} = ')
print(number_1 * number_2)
#Division
elif operation == '/':
print(f'{number_1} / {number_2} = ')
print(number_1 / number_2)
#Power
elif operation == '**':
print(f'{number_1} ** {number_2} = ')
print(number_1 ** number_2)
#Modulo
elif operation == '%':
print(f'{number_1 % number_2} = ')
print(number_1 % number_2)
else:
print('You have not typed a valid operator, please run the program again.')
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
welcome()
calculate()
|
74ed32084e927932f5e2ad7d0007294225ade577 | JumiHsu/HeadFirst_python | /Simon_discuss_01/Simon_discuss_01_rewrite01.py | 9,130 | 3.796875 | 4 | import random
import math
import time
# =============================================================================
# 生成一個隨機向量 (input= 長度上限,元素值上限)
# =============================================================================
def generateList(lengthMax,elementMax):
A=[]
length=random.sample(range(1,lengthMax+1),1) # 取出物=字串,range有頭無尾
length=int(length[0])
fn ,index = 0 ,0 # 不知道怎麼宣告一個空的int變數,先令他=0
while index < length:
element=random.sample(range(0,elementMax+1),1)
element=int(element[0]) # random.sample取出物= list
A.append(element)
# fn += 2**A[index]
index += 1
fn ,length = calculate_fn(A)
return A,fn,length
# =============================================================================
# 生成題目向量、題目fn
# =============================================================================
def generateExampleList():
A = [1,0,2,0,0,2]
# length = len(A)
# fn ,index = 0 ,0
# while index < length:
# fn += 2**A[index]
# index += 1
fn ,length = calculate_fn(A)
return A ,fn ,length
# =============================================================================
# 計算fn (input= 任意向量)
# =============================================================================
def calculate_fn(anyList):
length = len(anyList)
fn ,index = 0 ,0
while index < length:
fn += 2**anyList[index]
index += 1
return fn ,length
# =============================================================================
# (一) 對 fn 連續取log (input= fn)
# =============================================================================
def methodLog(fn):
t21=time.time()
print("========== (一) LOG轉換 ==========")
B=[]
fnb,bCount = 0,0
fna = fn
fnaList = []
while fna != 0: # fna 扣到0就結束
fnaList.append(fna) # 為了觀察fna的變化
B.append( int(math.log(fna,2)) ) # 對fn取log2,取完的值取整,放入B[]
# fnb += 2**B[bCount] # 再順手計算 fnb,此時 bCount=0
fna += -2**B[bCount] # fna 扣掉 2**B[0],剩下來的成為新的fna
bCount += 1 # 計數+1,雖不是用 bCount 來限制迴圈次數,
# 但要用他來安排向量填入的順序
# print("fna的變化 =",fnaList)
fnb ,length = calculate_fn(B)
t22=time.time()
print("取 log 花費秒數= {:>9.16f}".format(t22-t21) )
return B ,fnb ,length ,(t22-t21)
# =============================================================================
# (二) 用二進位轉換來處理 (input= fn)
# =============================================================================
def methodBin(fn):
t31=time.time()
print("========== (二) 二進位轉換 ==========")
C=[]
fnBin = bin(fn)[2:]
# 轉成二進位,前面一定會被加上 0b,取 fnBin[2:] 或取 b 後的數字,即可取得實際數字
# 最高位數 = len(fnBin)-1
j=0
for power in range(len(fnBin)-1,-1,-1): # fnBin=1101 power =[3 2 1 0] 表 2進位之次方list
if int(fnBin[j]) != 0: # 從 fnBin 的第0位開始找,若 不等於0(即=1),
C.append(power) # 就把 次方向量power 放入 C
j += 1 # 找完就找下一位
else:
j += 1 # =0,沒事,下一位
fnc ,length = calculate_fn(C)
t32=time.time()
print("二進位轉換 花費秒數= {:>9.16f}".format(t32-t31) )
return C ,fnc ,length ,(t32-t31)
# =============================================================================
# 主程式
# =============================================================================
# 記得補寫錯誤信息
lengthMax=int(input("向量長度上限:")) # 特別注意input進去的是字串!!! 老是錯這邊
elementMax=int(input("元素值上限:"))
# A, fn, length = generateExampleList() #生成題目
A, fn, length = generateList(lengthMax,elementMax) #生成隨機向量
print("\n目標向量 A =",A,",向量長度 =",length,"fn =",fn,"\n")
# ----- 取 LOG 處理
logList ,fn_Log ,lengthLog ,tLog = methodLog(fn)
print("logList = ",logList)
# 檢查答案是否 = fn
if fn_Log == fn :
print( "fn =" ,fn ,",fn_Log =" ,fn_Log ,",LOG算法,答案正確\n" )
else:
print( "fn =" ,fn ,",fn_Log =" ,fn_Log ,",答案有誤,請確認\n" )
# 別忘了回答問題
print( "所求B向量長度 =",lengthLog )
# ----- 取 二進位 處理
binList ,fn_Bin ,lengthBin ,tBin = methodBin(fn)
print("binList = ",binList)
# 檢查答案是否 = fn
if fn_Bin == fn :
print( "fn =" ,fn ,",fn_Bin =" ,fn_Bin ,",二進位算法,答案正確\n" )
else:
print( "fn =" ,fn ,",fn_Bin =" ,fn_Bin ,",答案有誤,請確認\n" )
# 別忘了回答問題
print( "所求B向量長度 =",lengthBin )
print( "使用函式 =" , )
# ----- 檢查程式執行時間
if min( tLog ,tBin ) == tLog :
print( "LOG算法 較快!!\n\n較 二進位算法 快了:" )
print( 'percent: {:.2%}'.format( abs(tLog-tBin)/max(tLog ,tBin) ) )
elif min( tLog ,tBin ) == tBin :
print( "二進位算法 較快!!\n\n較 LOG算法 快了:" )
print( 'percent: {:.2%}'.format( abs(tLog-tBin)/max(tLog ,tBin) ) )
else :
print( "答案有誤,請確認" ,"\ntLog =" ,tLog ,"\ntBin =" ,tBin )
print("\n")
'''
# =============================================================================
# 檢查:「取log結果 與 2進位轉換」,結果是否相同
# =============================================================================
print("========== 檢查:「取log結果 與 2進位轉換」,結果是否相同 ==========")
if B == C:
print("檢查結果 = OK!! 相同")
elif B != C:
print("檢查結果 = Error!! 不同")
else:
print("Check! 其他問題!")
print("\n")
# =============================================================================
# 比較:「取log結果(t22-t21) 與 2進位轉換(t32-t31)」,程式需時
# (計算程式執行時間而非CPU時間)
# =============================================================================
print("========== 比較:「取log結果 與 2進位轉換」,程式需時 ==========")
if (t32-t31) - (t22-t21) > 0:
print("取 log 較快,較2進位快了")
h1=((t32-t31) - (t22-t21))/(t22-t21)
print( 'percent: {:.2%}'.format(h1) )
elif (t32-t31) - (t22-t21) < 0:
# print("做 二進位轉換 較快,較log快了", ((t22-t21) - (t32-t31))/(t32-t31))
print("做 二進位轉換 較快,較log快了")
h2=((t22-t21) - (t32-t31))/(t32-t31)
print( 'percent: {:.2%}'.format(h2) )
else:
print("Check! 其他問題!")
print("\n")
# rate = .1234
# print('%.2f%%' % (rate * 100))
'''
# =============================================================================
# =============================================================================
# (二) 用二進位轉換來處理
# =============================================================================
'''
print("========== (二) 用二進位轉換來處理 ==========")
t31=time.time()
# bin轉二進位、oct轉八進位、hex轉十六進位
# fn=50
C=[]
fnBin=bin(fn)
print("fn=",fn,",其二進位=",fnBin)
# 轉成二進位,前面一定會被加上 0b,取 fnBin[2:] 或取 b 後的數字,即可取得實際數字
fnBin=fnBin[2:]
print("fnBin的向量長度=",len(fnBin)) #最高位數 = len(fnBin)-1
j=0
for i in range(len(fnBin)-1,-1,-1):
if int(fnBin[j]) != 0:
C.append(i)
# print("C向量=",C,",i=",i,",j=",j)
j += 1
else:
# print("C向量=",C,",i=",i,",j=",j)
j += 1
print("\n")
print("最終C向量=",C)
t32=time.time()
print("(三) 二進位轉換 花費秒數= {:>9.16f}".format(t32-t31) )
print("\n")
'''
'''
import time
start = time.monotonic()
time.sleep(0.1)
end = time.monotonic()
print('start : {:>9.2f}'.format(start))
print('end : {:>9.2f}'.format(end))
print('span : {:>9.2f}'.format(end - start))
$ python3 time_monotonic.py
start : 716028.72
end : 716028.82
span : 0.10
'''
'''
# 留意!! 這樣只會print出8~1,0是不會print的
for i in range(8,0,-1):
print(i)
'''
# =============================================================================
# 測試 B[0] 是不是都等於 fn取平方根 的整數
# =============================================================================
'''
print("========== 測試 B[0] 是不是都等於 fn取平方根 的整數 ==========")
fn1=abs(math.sqrt(fn))
if B[0] == int( fn1 ) :
print("B[0] 等於 fn取平方根 的整數")
else:
print("不等於哦~")
''' |
dcdb4f3cb8d8363d5d2f6e86ec4fa5fdabb60b4f | Buremoh/fibonacci-ageFind-timeZone | /time-zone.py | 1,011 | 3.546875 | 4 | from datetime import datetime
from pytz import timezone
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
# get the current time in UTC
now_utc = datetime.now(timezone('UTC'))
print('UTC :', now_utc)
# Convert this to EST
now_est = now_utc.astimezone(timezone('US/Eastern'))
print('EST :', now_est)
# Convert this to Berlin
now_berlin = now_utc.astimezone(timezone('Europe/Berlin'))
print('Berlin:', now_berlin)
# Convert this to London
now_london = now_utc.astimezone(timezone('Europe/London'))
print('London:', now_london)
# Convert this to Kolkata
now_Kolkata = now_utc.astimezone(timezone('Asia/Kolkata'))
print('Kolkata:', now_Kolkata)
# Convert this to Shanghai
now_Shanghai = now_utc.astimezone(timezone('Asia/Shanghai'))
print('Shanghai:', now_Shanghai)
# Convert this to Sydney
now_Sydney = now_utc.astimezone(timezone('Australia/Sydney'))
print('Sydney:', now_Sydney)
# Convert this to Johannesburg
now_Johannesburg = now_utc.astimezone(timezone('Africa/Johannesburg'))
print('Johannesburg:', now_Johannesburg)
|
9bd98561d0dba03bbac528643bcd44c6ec87a495 | millerg09/python_lesson | /dict_sandbox.py | 343 | 4.03125 | 4 | # create a mapping of people to numbers
phone_numbers = {
'Gabe': '607.437.4130',
'Amy': '321.662.8623',
'Dad': '607.435.0122',
'Mom': '607.435.0537'
}
print "This is the original dict of numbers: \n\n", phone_numbers
phone_numbers['New'] = "number not available"
print "This is the new dict of numbers: \n\n", phone_numbers |
5c66634ab29b8d9303fefaa936169edd96663fdb | MichaelCoding25/Programming-School | /High_School/Python/24.09.17/name.py | 116 | 3.75 | 4 | name = ""
while name!= 'your name':
print 'Please type your name:'
name= raw_input()
print 'Well done!'
|
a0cb5530904823e33f54cf394f11408db0ab61e2 | ISEexchange/Python-Bootcamp | /pythonbc_winners/view_extract_from_file.py | 5,891 | 4.375 | 4 | '''
Function searches through a file and checks for the presence of a specified string.
If there are any occurrences of this string, the function return True, otherwise False.
The function also takes an optional parameter to provide an extract of x lines before and after
the occurrence of the search string in the file.
Additionally the user can also chose to get a paged output to get extract in batches
The function also provides an option to highlight the search string in the extracted text for better readability
Author: Girish Ganeshan
'''
import os
def view_extract_from_file(file_name, search_string, case_sensitive=True, extract_lines=0,isuserinput=False,color_output=False):
# Implement Function Below
file_open = open(file_name, 'r')
# Contains the line number at which the search string was found
line_num = 0
# Contains the count of occurrence of the search string
num_of_lines = 0
# clear the screen for an enhanced understanding of the output
# os.system('cls' if os.name == 'nt' else 'clear')
if (case_sensitive == True):
print '\nPerforming case sensitive search for the string \'%s\' in file %s' % (search_string,file_name)
else :
print '\nPerforming case insensitive search for the string \'%s\' in file %s' % (search_string,file_name)
for file_line in file_open:
# Remove trailing blank spaces
file_line = file_line.rstrip()
# If case insensitive convert the file and search string to upper case
if (case_sensitive == False):
file_line_cs = file_line.upper()
search_string_cs = search_string.upper()
string_found = file_line_cs.find(search_string_cs)
else :
string_found = file_line.find(search_string)
# Irrespective of whether search string is found increase the line number counter
line_num = line_num + 1
if (string_found != -1):
# If search string is found increment the number of lines counter
num_of_lines = num_of_lines + 1
# a new string to contain the start of extract value
start_of_extract = line_num - extract_lines
# if start of extract is negative the program will break.
if (start_of_extract < 0):
start_of_extract = 0
# a variable to contain the end of extract value.
end_of_extract = line_num + extract_lines
# counter to determine which lines are printed
file_extract_counter = 1
print '\nFound the search string \'%s\' in file %s' % (search_string,file_name)
if (extract_lines > 0):
# print file_extract_counter
print '\n------ You chose to get an extract of %d line before and after the search string --------' % (extract_lines)
print '\n------------------- Start of Extracted File content #%d -----------------' % (num_of_lines)
# open the file again to go through specific lines only.
file_extract = open(file_name, 'r')
# Loop through a specific set of lines in the file to print the extract
for file_line_extract in file_extract:
file_line_extract = file_line_extract.rstrip()
if ((file_extract_counter >= start_of_extract) and (file_extract_counter <= end_of_extract)):
# If color_output is true check if the line is where the match was found, if so highlight it
if (color_output == True):
# This is where the match was found so highlight it
if (file_extract_counter == line_num):
print '\033[0;32m%s\033[m' % (file_line_extract)
else:
print '%s' % (file_line_extract)
# For no colored output print as is
else:
print '%s' % (file_line_extract)
file_extract_counter = file_extract_counter + 1
print '\nFile: %s \ncontains: %s \nat line number: %d ' % (file_name,search_string,line_num)
if (extract_lines > 0):
# print file_extract_counter
print '\n------------------- End of Extracted File content #%d -----------------' % (num_of_lines)
# If user choses to get a page by page ouput then wait for the input before looping further
if (isuserinput == True):
print '\nYou chose to fetch paged output, kindly hit enter to get the next extract !!!'
userinput = raw_input()
continue
if (num_of_lines != 0):
print '\nFound \'%s\' %d time(s) in the file %s \n' % (search_string,num_of_lines,file_name)
return True
else:
print '\nDid not find \'%s\' in the file %s' % (search_string,file_name)
return False
# clear the screen for an enhanced viewing experience of the output
os.system('cls' if os.name == 'nt' else 'clear')
view_extract_from_file('/home/python_bootcamp/file_manipulation/ISE.BusinessServiceInterface.exe.config','LogLevel',True,0,False)
#view_extract_from_file('/home/python_bootcamp/file_manipulation/ISE.BusinessServiceInterface.exe.config','loglevel',False)
#view_extract_from_file('/home/python_bootcamp/file_manipulation/ISE.BusinessServiceInterface.exe.config','ISE.Library',True,5)
view_extract_from_file('/home/python_bootcamp/file_manipulation/ISE.BusinessServiceInterface.exe.config','add key',False,5,True,True)
#view_extract_from_file('/home/python_bootcamp/file_manipulation/ISE.BusinessServiceInterface.exe.config','Girish')
# Execute Function below
# File Path: '/home/python_bootcamp/file_manipulation/ISE.BusinessServiceInterface.exe.config'
# Ex. Search Strings : 'LogLevel'
# : 'ISE.Library'
# : 'add key'
|
ef1581c47e02e4124bf66090c87b3f841c2ad722 | Hoon94/Algorithm | /Leetcode/257. Binary Tree Paths.py | 652 | 3.75 | 4 | from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
stack, ret = [(root, "")], []
while stack:
node, path = stack.pop()
if node:
if not node.left and not node.right:
ret.append(path+str(node.val))
s = path + str(node.val) + "->"
stack.append((node.right, s))
stack.append((node.left, s))
return ret
|
79f77de5dd47044ce54baef757330b24c7cf90de | MichaelShaneSmith/Code2040 | /code2040_partII.py | 582 | 3.515625 | 4 | import requests
urls = {
'reverse' : 'http://challenge.code2040.org/api/reverse',
'validate' : 'http://challenge.code2040.org/api/reverse/validate'
}
# Setup
params1 = {
'token' : '<token>'
}
response1 = requests.post(urls['reverse'], data=params1)
# Reverse word
word = response1.text
ans = word[::-1]
# ^^ This is like saying, 'give me the letters of the string in steps of one
# but backwards from the end to the beginning'
# Return Answer
params2 = {
'token' : '<token>',
'string' : ans
}
response2 = requests.post(urls['validate'], data=params2)
print response2.text |
0b92ca1f61c3219a8c1e5a3ab19e76fc4900da40 | sdbaronc/LaboratorioRepeticionRemoto | /Mayor.py | 203 | 3.875 | 4 | a= int(input("ingrese un numero entero"))
if a >0:
print ("el numero" + str(a) + "es mayor que 0")
elif a == 0:
print ("el numeroes igual a 0")
else:
print ("el numero" + str(a) + "es menor que 0")
|
f8b95e5f2931dec5a2cd4d8f3c20875b4a8b8290 | gspillman/fun_with_python | /funwithcsv.py | 2,435 | 4.25 | 4 | #Hacking on CSV files!
import csv
import shutil
from tempfile import NamedTemporaryFile
#write a very basic CSV file
#+w means read/or/write and overwrite an existing file or create a new one
with open("templates/data.csv", "w+") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Title", "Description"])
writer.writerow(["Row 1", "Some descriptionm"])
writer.writerow(["Row 2", "Some other kind of description"])
# Now to read our file we created in the code block above:
with open("templates/data.csv", "r") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
#Using DictReader to open an existing csv file as a dictionary
with open("templates/books.csv", "r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
#Using append and DictWriter to add to an existing CSV file w/o overwriting things
with open("templates/books.csv", "a") as csvfile:
#You have to provide a list of field names to properly map how the CSV will be read/written
fieldnames = ["title", "author"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({"title": "1984", "author": "George Orwell"})
#as a challenge - try to abscract the last 2 code blocks into their own functions we can call repeatedly to inject data into a csv file.
def get_lenght(file_path):
return 1
def append_books(file_path, title, author):
return []
#Here's how to edit an existing csv file using temp files so
#you don't accidentally clobber your existing file contents
filename = "templates/books.csv"
tempfile = NamedTemporaryFile(delete=False)
#rb is used for writing/create new
with open(filename, "rb") as tempcsv, tempfile:
reader = csv.DictReader(tempcsv)
fieldnames = ["title", "author"]
#Yes - you need to reference tempfile as your argument here
writer = csv.DictWriter(tempfile, fieldnames=fieldnames)
writer.writeheader()
for row in reader:
print(row)
if (row["author"] == ""):
row["author"] = "Unknown"
writer.writerow(row)
#This next line copies our temp file to the exiting real file of books.csv
shutil.move(tempfile.name, filename)
def get_author(author=None):
filename = 'templates/books.csv'
with open(filename, "r") as csvfile:
reader = csv.DictReader(csvfile)
items = []
for row in reader:
if author is not None:
if author == row.get("author"):
items.append(row)
print("Boo yaaaa grandma!")
print(items)
get_author("George Orwell") |
74ab5f2e1b930965b34902b376ce8393f70fa2a2 | karunaswamy1/Dictionary | /qu5.py | 115 | 3.625 | 4 | # list1=["one","two","three","four","five"]
# list2=[1,2,3,4,5,]
# for i in list1:
# print(list1.keys())
#
|
213bd2740f3af9c22d6dcf6dec14ae23702f1076 | clylau/E206_Labs | /Lab0/traj_tracker.py | 2,212 | 3.609375 | 4 | import time
import math
import random
from traj_planner_utils import *
TIME_STEP_SIZE = 0.01 #s
LOOK_AHEAD_TIME = 1.0 #s
MIN_DIST_TO_POINT = 0.1 #m
MIN_ANG_TO_POINT = 0.10 #rad
class TrajectoryTracker():
""" A class to hold the functionality for tracking trajectories.
Arguments:
traj (list of lists): A list of traj points Time, X, Y, Theta (s, m, m, rad).
"""
current_point_to_track = 0
traj_tracked = False
traj = []
def __init__(self, traj):
self.current_point_to_track = 0
self.traj = traj
self.traj_tracked = False
def get_traj_point_to_track(self, current_state):
""" Determine which point of the traj should be tracked at the current time.
Arguments:
current_state (list of floats): The current Time, X, Y, Theta (s, m, m, rad).
Returns:
desired_state (list of floats: The desired state to track - Time, X, Y, Theta (s, m, m, rad).
"""
self.current_point_to_track = 0
return self.traj[self.current_point_to_track]
def print_traj(self):
""" Print the trajectory points.
"""
print("Traj:")
for i in range(len(self.traj)):
print(i,self.traj[i])
def is_traj_tracked(self):
""" Return true if the traj is tracked.
Returns:
traj_tracked (boolean): True if traj has been tracked.
"""
return self.traj_tracked
class PointTracker():
""" A class to determine actions (motor control signals) for driving a robot to a position.
"""
def __init__(self):
pass
def get_dummy_action(self, x_des, x):
""" Return a dummy action for now
"""
action = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ]
return action
def point_tracking_control(self, desired_state, current_state):
""" Return the motor control signals as actions to drive a robot to a desired configuration
Arguments:
desired_state (list of floats): The desired Time, X, Y, Theta (s, m, m, rad).
current_state (list of floats): The current Time, X, Y, Theta (s, m, m, rad).
"""
# zero all of action
action = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ]
return action
|
f775baa553afd29868bf6fd81ad767507ac31ae5 | MattHill94/Python-hangman-game | /phrasehunter/game.py | 2,200 | 3.734375 | 4 | import random
from .phrase import Phrase
import string
class Game(list):
def __init__(self, *args):
super().__init__()
for phrs in args:
self.append(Phrase(phrs))
self.active = random.choice(self)
self.life = 5
self.choices_made = set()
def reset(self):
self.life = 5
self.active.reset()
self.active = random.choice(self)
self.choices_made = set()
def main_loop(self):
while self.life:
print(self.active)
choice = input("Choose a letter for the phrase: ")
if choice.upper() not in string.ascii_uppercase:
print("The choice must be a letter (a-z)")
elif len(choice) > 1:
print("The choice must be a single letter")
else:
if choice not in self.choices_made:
self.choices_made.add(choice)
if self.active.guess(choice):
print("You guessed right!")
if self.active.all_guessed:
print(self.active)
again = input("You win!, do you want to play again? (y) yes / (n) no : ")
if again.lower() == "y":
self.reset()
if again.lower() == "n":
print("Thanks for playing!")
break
else:
self.life -= 1
print("You chose wrong. You have {} out of 5 lives remaining!".format(self.life))
if 0 == self.life:
again = input("You lose!, want to play again? (y) yes / (n) no : ")
if again.lower() == "y":
self.reset()
if again.lower() == "n":
print("Thanks for playing!")
break
else:
print("You can't repeat your choice.")
|
3d4a321bd71155c4a7fd746a7da5f28785cf6b1b | kxu12348760/ProgrammingInterviewExercises | /misc.py | 1,119 | 3.65625 | 4 | #!/usr/bin/python
def expansions(original, relatedWords):
results = []
strippedSentence = original.strip()
words = strippedSentence.split(" ")
if strippedSentence != "":
firstWord = words[0]
restOfSentence = " ".join(words[1:])
subExpansions = expansions(restOfSentence, relatedWords)
if len(subExpansions) > 0:
for subExpansion in subExpansions:
results.append(firstWord + " " + subExpansion)
if firstWord in relatedWords:
for relatedWord in relatedWords[firstWord]:
results.append(relatedWord + " " + subExpansion)
else:
results.append(firstWord)
if firstWord in relatedWords:
for relatedWord in relatedWords[firstWord]:
results.append(relatedWord)
return results
def main():
original = "pictures of puppies"
relatedWords = {"pictures": ["photos"], "puppies": ["dogs", "pets"]}
for expansion in expansions(original, relatedWords):
print expansion
if __name__ == '__main__':
main()
|
17ca9ef1eac45553ea260f145c3f34055ce573f5 | zhuyanzhe98/evaptransmission | /weather.py | 1,360 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[116]:
import csv
import numpy as np
import matplotlib.pyplot as plt
# Weather data source:
# https://www.ncdc.noaa.gov/cdo-web/datatools/lcd
# In[119]:
# Here consider Feb 1 as Day 1, different for a new data file
def weatherdataprocess(filename):
weatherdata = []
with open(filename) as weather_data_file:
metadata = csv.reader(weather_data_file, delimiter=',')
for item in metadata:
weatherdata.append(item)
num_records = len(weatherdata)
columnhead = weatherdata[0]
recorddata = weatherdata[1:num_records]
tempdata = []
RHdata = []
for num in range(850): # modified here to use only febuary part of the data
pull_a_record = recorddata[num]
if pull_a_record[2] == 'SOD ':#to read 'summary of the day' data only for daily average temp and RH
tempdata.append(pull_a_record[19])
RHdata.append(pull_a_record[20])
temp = np.array(tempdata)
temp = temp.astype(np.float)
tempC = (temp-32)*5/9
RH = np.array(RHdata)
RH = RH.astype(np.float)
return [tempC,RH]
# In[113]:
def weatherdatapplot(tempC,RH):
plt.plot(tempC)
plt.ylabel('Daily Temperature in C')
plt.show()
plt.plot(RH)
plt.ylabel('Daily Relative Humidity in %')
plt.show()
# In[ ]:
|
54b7739c9327c9360c3b491b2ecbac5881e3a8f3 | ramenkup/Madlib | /madlib.py | 3,498 | 3.96875 | 4 | vowl_list='aeiou'
consinant_list='bcdfghjklmnpqrstvwxyz'
'''
#def print_report(txt file)
this method runs through a text file line by line and sums the number of vowls, consinants, punctuation,
and white space. it then outputs them along with their percentages in a text box formatted by the
homework outline
'''
def print_report(file_name):
vowls=0
consinants=0
white=0
punc=0
char_num=0
counter=0
#counter counts the characters by +1 with each char iteration of the for loop.
#char_num does it by adding up the results of all the boolean comparisons.
input_file= open(file_name,"r")
for line in input_file:
for char in line:
counter+=1
if char in vowl_list:
vowls+=1
elif char in consinant_list:
consinants+=1
elif char == ' ' or char == '\t' or char == '\n':
white+=1
else:
punc+=1
char_num= vowls+consinants+white+punc
print('----------------'+ file_name + '----------------')
print(str('Vowls:').ljust(20)+str(vowls).rjust(5))
print(str('Consinants:').ljust(20)+str(consinants).rjust(5))
print(str('Whitespace:').ljust(20)+str(white).rjust(5))
print(str('Punctuation:').ljust(20)+str(punc).rjust(5))
print('-------------------------------------------')
print(str('Total:').ljust(20)+str(counter).rjust(5))
print(str('Percent vowls:').ljust(20)+ str(round((vowls / char_num)*100,1)).rjust(5))
print(str('Percent consinants:').ljust(20) + str(round((consinants / counter)*100,1)).rjust(5))
print(str('Percent spaces:').ljust(20) + str(round((white/counter)*100,1)).rjust(5))
print(str('Percent punctuation:').ljust(20) + str(round((punc/ counter)*100,1)).rjust(5))
print('=========================')
'''
def replace_parts_of_speech(string, string):
This method is the brains of the mad lib game. given a un libbed string and the part of speech,
The method searchs the string to find every occourance of the part of speech, and replace it with
the word input by the user
'''
def replace_parts_of_speech(phrase, label):
label_length= len(label)
phrase_index=phrase.find(label)
while phrase_index !=-1:
phrase=phrase.replace(label, input('Enter '+label+':'), 1)
phrase_index=phrase.find(label)#will this work, iterate to next phrase
return phrase
'''
def complete_mad_lib(file)
this method is the outline of the madlib game, referencing a local madlib file template, it
writes and reads line by line each type of speech the user would need to input for the particular
peice. It takes care to close the writer file
'''
def complete_mad_lib(lib_name):
reader= open(lib_name)
writer= open('Mad_'+lib_name, 'w')
for line in reader:
temp_line=''
temp_line=replace_parts_of_speech(line, 'PLURAL NOUN')
temp_line=replace_parts_of_speech(temp_line,'VERB PAST')
temp_line=replace_parts_of_speech(temp_line,'VERB')
temp_line=replace_parts_of_speech(temp_line,'NOUN')
temp_line=replace_parts_of_speech(temp_line,'ADJECTIVE')
writer.write(temp_line+'\n')
writer.close()
'''
main prompts the user for an original file, runs the report, then completes the mad lib game.
'''
def main():
mad_lib_file= input('please enter local file name:')
print_report(mad_lib_file)
complete_mad_lib(mad_lib_file)
if __name__ == '__main__':
main() |
fefabae50f638d4ac8d00622f98dd5f125a4de12 | Krishan00007/Python_practicals | /AI_ML_visulizations/string_nullfilling.py | 517 | 3.921875 | 4 | import pandas as pd
import numpy as np
data=pd.read_csv('employees_with_missing_data.csv')
#printing the first 10 to 24 rows of the data frame form visualization
print( data[10:25] )
#Analyse the value of gender in RowIndex no 20 and 22
#Now we are going to fill all the null values in Gender column with "NO GENDER"
#filling a null values using fillna()
df2=data["Gender"].fillna("No Gender")
df3=data[10:25]["Gender"].fillna("No Gender")
print("\n\n\n", data)
print("\n\n\n", df2)
print("\n\n\n", df3) |
68b5a1c517c55ed324331051a1c7b5fe6a3accad | ZemiosLemon/HillelPythonBasic | /homework_05/task_2.py | 267 | 3.59375 | 4 | user_text = input()
def main(text: str) -> (int, int):
words = len(text.split())
symbols = len(text)
return words, symbols
print('Количество слов:', main(user_text)[0])
print('Количество символов:', main(user_text)[1])
|
a8a82701b2270f5eba020dd843f2998c9149e7bf | paulgryllz/DONE | /lab3ahsan.py | 591 | 3.609375 | 4 | def is_long(srz):
return 'very long' if (len(srz) > 10) else 'kinda short'
def longer(str1, str2):
if len(str1) > len(str2):
return len(str1)
else:
return len(str2)
def earlier(str1, str2):
if str1 < str2:
return str1
else:
return str2
def where(str1, str2):
return str1.find(str2)
def is_vowel(str1):
return True if str1 in 'aeiou' else False
def count_letter(str1, str2):
return str1.count(str2)
def remove_digits(str1):
ret = ''
for i in str1:
if i.isalpha():
ret += i
return ret
|
a7eed180c94bfcc06bcad6fa498f0316df153fad | liusska/Python-Fundamentals-Jan-2021 | /Final Exam Solutions/04.04.2020_2/emoji_detector_02.py | 659 | 3.90625 | 4 | import re
pattern = r"([:]{2}|[*]{2})([A-Z]{1}[a-z]{2,})(\1)"
data = input()
matches = re.findall(pattern, data)
cool_threshold = 1
for word in data:
for ch in word:
if ch.isdigit():
cool_threshold *= int(ch)
emoji_count = len(matches)
coolness_emoji = []
for match in matches:
current_coolness = 0
for ch in match[1]:
current_coolness += ord(ch)
if current_coolness >= cool_threshold:
coolness_emoji.append(''.join(match))
print(f"Cool threshold: {cool_threshold}")
print(f"{emoji_count} emojis found in the text. The cool ones are:")
for em in coolness_emoji:
print(em) |
ed9726dde5c3e88eea0e495cd880a10d0848e4ac | Jaden5672/Python_Coding | /list.py | 779 | 4.375 | 4 | fruits=["Apple","Apple","Bananas","Blueberry"]
print(fruits)
#duplicates are allowed in a list
mixed=["Car",56,789,"cat",True,"bus"]
print(mixed)
#A list allows multiple data types
print(type(fruits))
print(mixed[0:4])
print(mixed[:2])
mixed[0]= "Jeep"
print(mixed)
#you can change the values of a list, these types of varibles are called mutable
print(mixed[-4:-1])
print(mixed[-5:-1])
if "truck" in mixed:
print("Cat is present in this list!")
else:
print("This value is not present in this list.")
mixed[1:3]= ["Sheep",200]
print(mixed)
mixed[0:4]=["Milk","Apple",66,"pizza"]
print(mixed)
mixed[0:1]=["Forest","Farm",101]
print(mixed)
print(len(mixed))
mixed[0:2]=["Earth"]
print(mixed)
print(len(mixed))
mixed.insert(1,False)
print(mixed) |
e4b1591177816b550add00586b1c55fd3addbcff | Pittor052/SoftUni-Courses | /Python/Fundamentals/0.8-Text-Processing/More-Exercises/treasure_finder.py | 749 | 3.53125 | 4 | keys = [int(n) for n in input().split()]
text= input()
while text != "find":
keys_i = 0
for i in range(len(text)):
text = text[:i] + chr(ord(text[i]) - keys[keys_i]) + text[i + 1:]
keys_i += 1
if keys_i == len(keys):
keys_i = 0
treasure, coordinates = "", ""
ind = 0
while ind < len(text):
if text[ind] == "&":
ind += 1
while text[ind] != "&":
treasure += text[ind]
ind += 1
elif text[ind] == "<":
ind += 1
while text[ind] != ">":
coordinates += text[ind]
ind += 1
ind += 1
print(f"Found {treasure} at {coordinates}")
text = input()
|
2b986a453bcdb614b7bbf834becfc9a1c010c17c | percevalw/treeprinter | /treeprinter/tests/test_default_printer.py | 1,639 | 3.5 | 4 | from unittest import TestCase
from treeprinter.printers.default_printer import TreePrinter
class Tree(object):
def __init__(self, tag, children=None):
self.children = children or []
self.tag = tag
class TestDefaultPrinter(TestCase):
def setUp(self):
self.tree = \
Tree("animal", [
Tree("cat"),
Tree("dog", [Tree("Doge"), Tree("Dalmatian")]),
Tree("wolf")])
def test_format(self):
printer = TreePrinter(children_attr="children", text_attr="tag")
self.assertEqual(printer.pformat(self.tree), (
" animal " '\n'
" | " '\n'
" ---------------------- " '\n'
" | | | " '\n'
" cat dog wolf " '\n'
" | " '\n'
" ------- " '\n'
" | | " '\n'
" Doge Dalmatian "))
def test_decorator(self):
@TreePrinter('children', 'tag')
class DecoratedTree(object):
def __init__(self, tag, children):
self.children = children
self.tag = tag
self.assertTrue(hasattr(DecoratedTree, '__str__'))
tree = DecoratedTree("house", [DecoratedTree("roof", []), DecoratedTree("walls", [])])
self.assertEqual(str(tree), (
' house ' '\n'
' | ' '\n'
' ----- ' '\n'
' | | ' '\n'
' roof walls ')
)
|
3828dacb61ea45e62f75a183beb4d8c677fe1cba | mohanraj1311/leetcode-2 | /evaluatReversePolish/main.py | 773 | 3.5625 | 4 | class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
stack = []
for t in tokens:
if t in ["+", "-", "*", "/"]:
a = stack.pop()
b = stack.pop()
s = b + '.0' + t + '(' + a + '.0' + ')'
res = eval(s)
res = int(res)
stack.append(str(res))
else:
stack.append(t)
return int(stack[0])
if __name__ == '__main__':
s = Solution()
arr = ["2", "1", "+", "3", "*"]
print s.evalRPN(arr)
arr = ["4", "13", "5", "/", "+"]
# arr = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
print s.evalRPN(arr)
|
2687229bdc1950715af798d282ad4b70b1a75248 | gflorianom/Programacion | /Practica4/Ejercicio6.py | 266 | 3.921875 | 4 | """Biel Floriano Morey - 1 DAW - PRACTICA4 - EJERCICIO 6
Escriu un programa que demani l'alada d'un triangle i ho dibuixi de la segent manera:"""
print "Dime la altura del triangulo"
a=input()
for i in range(1, a+1):
for j in range(i):
print "*",
print " "
|
4a5bb679a7fe9362ba4c4af787b4779880f7dc89 | andreodendaal/coursera_algo_toolkit | /week3_greedy_algorithms/4_collecting_signatures/covering_segments2.py | 2,624 | 3.6875 | 4 | # Uses python3
import sys
from collections import namedtuple
import operator
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
points = []
common_points = []
#write your code here
segments.sort(key=operator.itemgetter(0))
intersected = set()
for s in segments:
sets = []
process = True
while process:
sub_segment = []
value = s.start
while value <= s.end:
sub_segment.append(value)
value += 1
sets.append(set(sub_segment))
points.append(intersected)
intersected = set.intersection(*sets)
process = intersected
points.append(intersected)
points = list(intersected)
points.sort()
return points
if __name__ == '__main__':
input = sys.stdin.read()
n, *data = map(int, input.split())
segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))
points = optimal_points(segments)
print(len(points))
for p in points:
print(p, end=' ')
# 3 1 3 2 5 3 6 = 1 3
# 4 4 7 1 3 2 5 5 6 = 2 3 6
# 100 41 42 52 52 63 63 80 82 78 79 35 35 22 23 31 32 44 45 81 82 36 38 10 12 1 1 23 23 32 33 87 88 55 56 69 71 89 91 93 93 38 40 33 34 14 16 57 59 70 72 36 36 29 29 73 74 66 68 36 38 1 3 49 50 68 70 26 28 30 30 1 2 64 65 57 58 58 58 51 53 41 41 17 18 45 46 4 4 0 1 65 67 92 93 84 85 75 77 39 41 15 15 29 31 83 84 12 14 91 93 83 84 81 81 3 4 66 67 8 8 17 19 86 87 44 44 34 34 74 74 94 95 79 81 29 29 60 61 58 59 62 62 54 56 58 58 79 79 89 91 40 42 2 4 12 14 5 5 28 28 35 36 7 8 82 84 49 51 2 4 57 59 25 27 52 53 48 49 9 9 10 10 78 78 26 26 83 84 22 24 86 87 52 54 49 51 63 64 54 54
# = 43
# 1 4 5 8 9 10 14 15 18 23 26 28 29 30 32 34 35 36 40 41 44 46 49 52 54 56 58 61 62 63 65 67 70 74 77 78 79 81 84 87 91 93 95
# 1 4 5 8 9 10 14 15 17 22 23 27 26 28 29 30 32 34 35 36 40 41 42 41 44 46 49 53 52 54 56 57 58 61 62 63 65 66 70 71 72 74 77 78 79 82 81 84 87 91 93 95
# 1 4 5 8 9 10 14 15 18 23 26 28 29 30 32 34 35 36 40 41 44 46 49 52 54 56 58 61 62 63 65 67 70 74 77 78 79 81 84 87 91 93
# 1 4 8 10 14 18 23 26 29 32 34 35 36 40 41 44 49 52 54 58 63 65 67 70 74 78 79 81 84 87 91 93
# M
# 1 4 5 8 9 10 14 15 18 23 26 28 29 30 32 34 35 36 40 41 44 46 49 52 54 56 58 61 62 63 65 67 70 74 77 78 79 81 84 87 91 93 95
#M
# 1 2 4 8 10 14 15 18 23 26 27 29 32 33 34 35 36 38 40 41 42 44 49 51 52 54 58 63 64 65 67 70 74 78 79 81 82 84 87 91 93
#https://rosettacode.org/wiki/Largest_int_from_concatenated_ints#Python:_Sort_on_comparison_of_concatenated_ints_method |
84a936413a2b79d8ce2f41a6642dae7034421c3d | stefanocovino/SRPAstro | /SRP/TimeAstro.py | 11,111 | 3.90625 | 4 | """Adapted from Practical Astronomy with your Calculator.
By Peter Duffett-Smith"""
# Bugs in version 1.6
# Modified by stefano Covino (covino@mi.astro.it), 10 Aug 2003
from .TimeAstro_algs import *
Error='astro.Error'
class Time:
""" Class to handle time requirements.
Initialize with 3 arguments: longitude, latitude and daylight
savings time if applicable. Longitude can range from 0-360 or -180
to 180. Latitude -90 to 90.
Example:
>>> now=Time(-72,38,0)
Class Time defines the following methods:
>>> now.set_now()
Sets the time to the current time
>>> now.local()
With a tuple of six as argument sets the local time. With no
argument it returns the local time:
>>> now.local((1997,11,13,23,12,5))
The tuple has the form (year,month,date,hour,minute,second)
Similarly for Greenwitch Sidereal Time (gst), Local Sidereal Time
>>> (lst) and Universal Coordinated Time (utc).
>>> now.gst()
>>> now.utc()
>>> now.lst()
>>> now.julian() returns the julian day corresponding to 0hours
of the given date.
>>> now.day() returns the day
The class defines the following (useful) attributes:
x.lon longitude
x.lat latitude
x.savings daylight savings time
x.utchour utc hour in decimal notation
x.gsthour gst hour in decimal notation
x.lsthour lst hour in decimal notation
x.localhour local hour in decimal notation
x.localtime a list of the local time (year,month,day,hour,min,sec)
x.utctime a list of the utc time (year,month,day,hour,min,sec)
x.gsttime a list of the gst time (year,month,day,hour,min,sec)
x.lsttime a list of the lst time (year,month,day,hour,min,sec)
"""
def __init__(self,lon=0,lat=0,savings=0):
if lon>180:
self.lon=lon-360
else:
self.lon=lon
self.lat=lat
self.savings=savings
self.localtime=[0,0,0,0.0,0.0,0.0]
def local(self,time=None):
if time==None:
return tuple(self.localtime)
elif len(time)!=6:
raise Error("Requires a tuple of 6")
self.localtime[0:len(time)]=list(time[:])
self.localhour=to_decimal(time[-3:])
def set_now(self):
import time
now=time.localtime(time.time())[0:6]
self.local(now)
def gst(self,time=None):
if time==None:
T=self.utc()
self.gsthour=to_gst(to_julian(T[0:3]+(0.0,0.0,0.0)),
self.utchour)
return to_hms(self.gsthour)
elif len(time)!=6:
raise Error("Requires a tuple of 6")
self.date=list(time[0:3])
self.gsthour=to_decimal(time[-3:])
self.julianday=to_julian(time[0:3]+(0.0,0.0,0.0))
self.utchour=gst_to_utc(self.julianday,self.gsthour)
self.localday,self.localhour=utc_to_local(self.utchour,
self.lon,self.savings)
self.localtime=self.date+list(to_hms(self.localhour))
self.localtime[2]=self.localtime[2]+self.localday
def utc(self,time=None):
if time==None:
if 'localhour' not in self.__dict__:
self.set_now()
utcday,self.utchour=to_utc(self.localhour,self.lon,self.savings)
hour=to_hms(self.utchour)
self.utctime=self.localtime[:]
self.utctime[-3:]=list(hour)
self.utctime[2]=self.utctime[2]+utcday
return tuple(self.utctime)
elif len(time)!=6:
raise Error("Requires a tuple of 6")
self.date=list(time[0:3])
self.utchour=to_decimal(time[-3:])
self.julianday=to_julian(time[0:3]+(0.0,0.0,0.0))
self.localday,self.localhour=utc_to_local(self.utchour,
self.lon,self.savings)
self.localtime=self.date+list(to_hms(self.localhour))
self.localtime[2]=self.localtime[2]+self.localday
def lst(self,time=None):
if time==None:
self.gst()
self.lsthour=divmod(self.gsthour+self.lon/float(15),24)[1]
return to_hms(self.lsthour)
elif len(time)!=6:
raise Error("Requires a tuple of 6")
self.date=list(time[0:3])
self.lsthour=to_decimal(time[-3:])
self.gsthour=lst_to_gst(self.lsthour,self.lon)
self.gst(time[0:3]+to_hms(self.gsthour))
def julian(self):
if 'localhour' not in self.__dict__:
self.set_now()
return to_julian(tuple(self.localtime[0:3])+(0.0,0.0,0.0))
def day(self):
return day_of_week(self.julian())
class Coordinates:
""" Fixes the coordinates of a heavenly body. provides methods to
convert from one coordinate system to the other. Requires a Time
object as an argument upon initialization."""
def __init__(self,Time):
import copy
self.Time=copy.deepcopy(Time)
def ecliptic(self,ecl_lon=None,beta=None):
if ecl_lon==None and beta==None:
if not ('Declination' in self.__dict__ and \
'right_ascension' in self.__dict__):
raise Error("No location has been specified")
ecl_lon,beta=eq_to_ecl(self.right_ascension,self.Declination,
self.Time.julian())
self.ecliptic_longitude,self.beta=ecl_lon,beta
return to_hms(self.ecliptic_longitude),to_hms(self.beta)
elif ecl_lon==None or beta==None:
raise Error("Requires 0 or 2 arguments")
[ecl_lon,beta]=list(map(to_decimal,[ecl_lon,beta]))
self.ecliptic_longitude=ecl_lon
self.beta=beta
ascens,self.Declination=ecl_to_eq(ecl_lon,beta,self.Time.julian())
self.ascension(to_hms(ascens))
def horizon(self,azi=None,alt=None):
if azi==None and alt==None:
if not ('Declination' in self.__dict__ and \
'right_ascension' in self.__dict__):
raise Error("No location has been specified")
azi,alt=eq_to_hor(self.hour_angle,
self.Declination,self.Time.lat)
self.azimuth,self.altitude=azi,alt
return to_hms(self.azimuth),to_hms(self.altitude)
elif azi==None or alt==None:
raise Error("Requires 0 or 2 arguments")
[azi,alt]=list(map(to_decimal,[azi,alt]))
self.azimuth=azi
self.altitude=alt
h_angle,self.Declination=hor_to_eq(azi,alt,self.Time.lat)
self.hourangle(to_hms(h_angle))
def hourangle(self,h_angle=None):
if h_angle==None:
try:
return to_hms(self.hour_angle)
except AttributeError:
raise Error("No location has been specified")
h_angle=to_decimal(h_angle)
self.hour_angle=h_angle
ascens=to_decimal(self.Time.lst())-h_angle
if ascens<0:ascens=ascens+24
self.right_ascension=ascens
def ascension(self,ascens=None):
if ascens==None:
try:
return to_hms(self.right_ascension)
except AttributeError:
raise Error("No location has been specified")
ascens=to_decimal(ascens)
self.right_ascension=ascens
h_angle=to_decimal(self.Time.lst())-ascens
if h_angle<0:h_angle=h_angle+24
self.hour_angle=h_angle
def declination(self,decl=None):
if decl==None:
try:
return to_hms(self.Declination)
except AttributeError:
raise Error("No location has been specified")
self.Declination=to_decimal(decl)
def equatorial(self,ascens=None,decl=None):
if ascens==None and decl==None:
if not ('Declination' in self.__dict__ and \
'right_ascension' in self.__dict__):
raise Error("No location has been specified")
return to_hms(self.hour_angle),to_hms(self.Declination)
elif ascens==None or decl==None:
raise Error("Requires 0 or 2 arguments")
self.ascension(ascens)
self.declination(decl)
def __sub__(self,other):
[a1,a2,d1,d2]=list(map(deg_to_rad,[self.right_ascension*15,
other.right_ascension*15,
self.Declination,other.Declination]))
d=acos(sin(d1)*sin(d2)+cos(d1)*cos(d2)*cos(a1-a2))
return to_hms(rad_to_deg(d))
def rising(self):
cosAr=sin(deg_to_rad(self.Declination))/cos(deg_to_rad(self.Time.lat))
if cosAr<-1:
raise Error("Body is never rising")
elif cosAr>1:
raise Error("Body is circumpolar")
Ar=rad_to_deg(acos(cosAr))
As=360-Ar
h=acos(-tan(deg_to_rad(self.Declination))*
tan(deg_to_rad(self.Time.lat)))
LSTr=(24+self.right_ascension-rad_to_deg(h)/15.0)%24
LSTs=(self.right_ascension+rad_to_deg(h)/15.0)%24
Trising=Time(self.Time.lon,self.Time.lat,self.Time.savings)
Tsetting=Time(self.Time.lon,self.Time.lat,self.Time.savings)
Trising.lst(tuple(self.Time.localtime[0:3])+to_hms(LSTr))
Tsetting.lst(tuple(self.Time.localtime[0:3])+to_hms(LSTs))
Brising=Coordinates(Trising)
Bsetting=Coordinates(Tsetting)
Brising.horizon(to_hms(Ar),(0,0,0))
Bsetting.horizon(to_hms(As),(0,0,0))
return Brising,Bsetting
def test():
time=Time(40,-80,0)
print("LST",time.lst())
print("Julian",time.julian())
print("UTC",time.utc())
print("GST",time.gst())
print("Local",time.local())
print("Day",time.day())
t=(1997,1,1,5,0,0)
time.lst(t)
print(time.local())
time.gst(t)
print(time.local())
time.local(t)
print(time.gst())
time.utc(t)
print(time.day())
star=Coordinates(time)
try:
star.ecliptic()
except Error:
print("need to specify location")
try:
star.ascension()
except Error:
print("need to specify location")
a=(120,40,0)
b=(-5,40,10)
star.ecliptic(a,b)
print("Horizon",star.horizon())
star.horizon(a,b)
print("Equatorial",star.equatorial())
print("Hour Angle",star.hourangle())
print("Right Ascension",star.ascension())
star.ascension(b)
star.declination(a)
print("Right Ascension",star.ascension())
print("Ecliptic",star.ecliptic())
print("-----------------------------------")
print("-----------------------------------")
print("Test for Class Time")
t=Time(-70,40,0)
t.set_now()
print("Local ",t.local())
print("UTC ",t.utc())
print("GST ",t.gst())
print("LST ",t.lst())
print("Set LST to ",t.lst())
t.lst(t.local()[0:3]+t.lst())
print("Local ",t.local())
print("UTC ",t.utc())
print("GST ",t.gst())
print("LST ",t.lst())
print("Set UTC to ",t.utc())
t.utc(t.utc())
print("Local ",t.local())
print("UTC ",t.utc())
print("GST ",t.gst())
print("LST ",t.lst())
|
205839f94fed14c48c703d2120aeef40de935f92 | wuhaochen/kutils | /examples/grader.py | 2,562 | 3.734375 | 4 | import kutils
import random
# Implement your own question class following instructions in
# each function.
class SumQuestion(kutils.KQuestion):
# Used to identify your class.
# DO NOT CHANGE
_name = 'Sum Question'
# Initializer. The specification of the problem should
# be initilized here.
def __init__(self, data=None):
self.first, self.second = data
self.parser = kutils.IntegerParser()
# Factory static method.
# Generate a random object of this class with the parameters.
@staticmethod
def generate_question(**gen_args):
first = random.randrange(10)
second = random.randrange(10)
return SumQuestion((first, second))
# Specify how to format your question in Kodethon.
# Return a string that will be used to show your question.
@property
def description(self):
return ('What is the anwser of %d + %d ?' %
(self.first, self.second))
# Solve the question of this object.
@property
def solution(self):
return self.first + self.second
# Grade student's submission.
# The submission is a raw string if your class doesn't have
# a parser or the format from the parser's output.
# It should return a kutils.score_map including score,
# maximum score and comments for the submission.
def score_submission(self, submission, max_score=10):
if submission == self.solution:
return kutils.score_map(10, comment='Correct!')
else:
return kutils.score_map(0, comment='Wrong!')
### ADDITIONAL EXTRA CHOICE. ###
# Parse the raw submission from student submission to data
# format match the solution.
# kutils provides a few common ones that can be chosen from.
# if you want to use those, set self.parser = KParser()
# in the __init__ function.
# of you can define your own parser below.
# @staticmethod
# def parser(raw_submission):
# The dumps and loads are a pair of function to serialize
# your object.
# The Default option implemented in the base class uses pickle,
# but it may not work with complicated class.
# dumps function should return a portable string that can
# be safely stored in json.
# def dumps(self):
# return pickle.loads(codecs.decode(data.encode(), "base64"))
# loads function should reconstrct the object from a string
# generated by dumps function.
# @staticmethod
# def loads(data):
# return FunctionQuestion(mapping)
|
4d58d61a87a6b51265ebd821ede8897de3441db0 | MissSheyni/HackerRank | /Python/Sets/py-set-intersection-operation.py | 218 | 3.65625 | 4 | # https://www.hackerrank.com/challenges/py-set-intersection-operation
_ = raw_input()
M = set(map(int, raw_input().split(" ")))
_ = raw_input()
N = set(map(int, raw_input().split(" ")))
print(len(M.intersection(N)))
|
7f07ec309d8360ab094042ec6152c8e3c0c87ec1 | PrangeGabriel/python-exercises | /ex070.py | 891 | 3.640625 | 4 | nome = fim = nomebarato = ''
preco = ptotal = contprodk = maisbarato = contcomp = 0
print('.:|:.' * 3, 'Supermercado BIG BALDE', '.:|:.' * 3)
while True:
nome = str(input('QUal o nome do produto?'))
preco = float(input(f'Qual o preço do {nome}?'))
ptotal += preco
contcomp += 1
if preco > 1000:
contprodk += 1
if contcomp == 1:
maisbarato = preco
nomebarato = nome
elif contcomp > 1:
if preco < maisbarato:
maisbarato = preco
nomebarato = nome
fim = str(input('Deseja continuar adicionando produtos? [Sim ou Não]'))
if fim.strip().upper()[0] in 'Nn':
break
print(f'O total gasto em compras foi de R$ {ptotal:.2f}'
f'\n Foram um total de {contprodk} produtos acima de R$1000,00'
f'\n o nome do produt mais barato é {nomebarato} custando R${maisbarato}')
|
f419d2356d38610375261a81f24fc47873070644 | tedye/leetcode | /tools/leetcode.002.Add Two Numbers/leetcode.002.Add Two Numbers.submission15.py | 826 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
s = (l1.val + l2.val) % 10
carry = (l1.val + l2.val) // 10
head = ListNode(s)
temp = head
while l1.next or l2.next:
val1 = val2 = 0
if l1.next:
l1 = l1.next
val1 = l1.val
if l2.next:
l2 = l2.next
val2 = l2.val
s = (val1 + val2 + carry) % 10
carry = (val1 + val2 + carry) // 10
temp.next = ListNode(s)
temp = temp.next
if carry:
temp.next = ListNode(carry)
return head
|
2d1bc79931cee4b40665af15e09f337a8de8ecd9 | amit19-meet/meet2017y1lab4 | /turtle_party.py | 264 | 4 | 4 | strawberries = 39
is_weekend = True
if is_weekend:
if strawberries > 39:
print("Fun")
else:
print("Not fun")
else: # weekday
if strawberries > 39 and strawberries < 61:
print("Fun")
else:
print("Not fun")
|
9f78ca9755c70655b8b74df2def537fa0d44efd9 | anjalilajna/Bestenlist | /day10.py | 1,157 | 3.8125 | 4 | #1.
import re
def check(string):
charRe = re.compile(r'[^a-zA-Z0-9.]')
string = charRe.search(string)
return not bool(string)
str=input() #gdg27ASF
print(check(str)) #true
#2.
import re
def match(text):
if re.search('\w*ab.\w*', text):
return 'matched'
else:
return('Not matched!')
str1=input()#jfoioje234
print(match(str1)) #Not matched!
#3.
def num_check(string):
if re.search(r'\d+$', string):
return 'yes'
else:
return'NO!'
str2=input()
print(num_check(str2))
#4.
import re
str3=input() #print 1,2,45,645,334 and 45
results = re.finditer(r"([0-9]{1,3})", str3)
for n in results:
print(n.group(0)) #1
# 2
# 345
# 3
# 56
# 5
#5.
import re
def text_match(text):
patterns = '^[A-Z]*$'
if re.search(patterns, text):
return 'matched!'
else:
return('Not matched!')
str4=input() #ASDFGDG
print(text_match(str4)) #matched!
|
75eb5916dd140f40e30fa3872ee18b79fa0732f2 | fredy-glz/Fundamentos_de_Programacion_en_Python_Curso | /Modulo_04/34_ProyectoTICTACTOE.py | 1,927 | 3.828125 | 4 | from random import randrange
def DisplayBoard(board):
print("+-------+-------+-------+")
for col in board:
print("|\t|\t|\t|")
print("| ", end=" ")
for fil in col:
print(fil, " | ", end=" ")
print("\n|\t|\t|\t|")
print("+-------+-------+-------+")
def EnterMove(board):
mov = input("Ingresa tu moviento: ")
if int(mov) > 0 and int(mov) < 10:
for col in range(len(board)):
for fil in range(len(board[col])):
if board[col][fil] == mov:
board[col][fil] = 'O'
return
return
def VictoryFor(board, sign):
if sign:
sign = 'X'
else:
sign = 'O'
ganarD1 = 0
ganarD2 = 0
for col in range(len(board)):
ganarF = 0
ganarC = 0
for fil in range(len(board[col])):
if board[col][fil] == sign:
ganarF += 1
if board[fil][col] == sign:
ganarC += 1
if ganarC == 3 or ganarF == 3:
print("Gana", sign)
return True
if board[col][col] == sign:
ganarD1 += 1
if board[2-col][col] == sign:
ganarD2 += 1
if ganarD1 == 3 or ganarD2 == 3:
print("Gana", sign)
return True
return False
def DrawMove(board):
while True:
mov = str(randrange(1,10))
for col in range(len(board)):
for fil in range(len(board[col])):
if board[col][fil] == mov:
board[col][fil] = 'X'
DisplayBoard(board)
return
return
board = [['1', '2', '3'], ['4', 'X', '6'], ['7', '8', '9']]
DisplayBoard(board)
sign = True
while not VictoryFor(board, sign):
sign = not sign
EnterMove(board)
DisplayBoard(board)
if VictoryFor(board, sign):
break
sign = not sign
DrawMove(board) |
b1e73571def58d26120d767bab52ca0d5822878f | MiroVatov/Algorithms-and-Data-Structures | /Algorithms and Data Structures Tutorial - Full Course for Beginners/Sorting and Searching/quick_sort_search_names.py | 288 | 3.5 | 4 | from quick_sort import quicksort
from load import load_strings
unsorted_names = load_strings('names/unsorted.txt')
sorted_names = quicksort(unsorted_names)
file = open('names/sorted.txt', 'w')
for n in sorted_names:
file.write(n + '\n')
print(n)
file.close()
|
9fad8ae6dc61908027124d8b05aee77409111e8a | CyberSecurityUP/Python-Introduction | /exercicio função.py | 1,180 | 4.03125 | 4 | #Problema: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer
# como parâmetro e mostre uma mensagem com o tamanho adaptável.
# Função para imprimir mensagens dentro de cabeçalho com bordas
def escreva(mensagem):
print('-' * (len(mensagem) + 4))
print(f' {mensagem} ')
print('-' * (len(mensagem) + 4))
# Cases de chamada da função
escreva('Olá, mundo')
escreva('Python é a melhor linguagem do mundo')
escreva('Python é maior que Java')
#Problema: Faça um programa que tenha uma função chamada area(), que receba as dimeções
# de um terreno retangular(largura e comprimento) e mostre a área do terreno.
#Função para impressão de cabeçalho
def header(mensagem):
print('-' * 30)
print(f'{mensagem:^30}')
print('-' * 30)
# Função para calcular area do terreno
def area(largura, comprimento):
area = largura * comprimento
print(f'A área de um terreno de {largura}x{comprimento} é de {area}m²')
header('Área de Terreno')
larg = float(input('Largura em (m): '))
compri = float(input('Comprimento em (m): '))
area(larg, compri)
|
76537c8170559803e53c7956e22bea6373c0e05d | aoruize/Machine-Learning | /regression/regression.py | 1,065 | 3.578125 | 4 | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def best_fit_slope_and_intercept(xs, ys):
m = (((mean(xs) * mean(ys)) - mean(xs * ys)) /
(mean(xs)**2 - mean(xs**2)))
b = mean(ys) - m*mean(xs)
return m,b
def squared_error(ys_orig, ys_line):
return sum((ys_line-ys_orig)**2)
def coefficient_of_determination(ys_orig, ys_line):
y_mean_line = [mean(ys_orig) for y in ys_orig]
squared_error_regr = squared_error(ys_orig, ys_line)
squared_error_y_mean = squared_error(ys_orig, y_mean_line)
return 1 - (squared_error_regr / squared_error_y_mean)
m,b = best_fit_slope_and_intercept(xs, ys)
regression_line = [(m*x) + b for x in xs]
predict_x = 8
predict_y = (m * predict_x) + b
r_squared = coefficient_of_determination(ys, regression_line)
print(r_squared)
plt.scatter(xs, ys)
plt.scatter(predict_x, predict_y, color='g')
plt.plot(regression_line)
plt.show() |
8ce457e3d773ade5db9353d9a3e063e7b5e012ec | LiFulian/LearnPython | /01.网络编程/tcp-client.py | 670 | 3.546875 | 4 | import socket
def main():
# 1. 创建tcp的套接字
tcp_scoket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2.链接服务器
server_ip = input("请输入要连接的服务器的ip:")
server_port = int(input("请输入要链接的服务器的port:"))
server_addr = (server_ip, server_port)
tcp_scoket.connect(server_addr)
while True:
# 3. 发送数据/接收数据
send_data = input("请输入要发送的数据:")
tcp_scoket.send(send_data.encode("utf-8"))
print(tcp_scoket.recv(1024).decode("utf-8"))
# 4. 关闭套接字
tcp_scoket.close()
if __name__ == "__main__":
main()
|
cb21b4ab6885aff5693517342e185f1a730a737f | bhupendpatil/Practice | /Python/Program based on loop for prime numbers.py | 179 | 4 | 4 | # Program based on loop for prime numbers
prime1 = int(input(("How many outputs you want: ")))
i = 1
while i <= prime1:
if i%2 != 0 and i>2:
print(i)
i = i + 1
|
979f45ff9a1d46849ad0016cc6bec930b5cb78ce | pf1990623/py-gs-lean | /student_day3/oldboy_4.py | 844 | 3.625 | 4 | # 4、 写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# dic = {"k1": "v1v1", "k2": [11,22,33,44]}
# PS:字典中的value只能是字符串或列表
dic = {"k1": "v1v1", "k2": [11, 22, 33, 44]}
def fun4(dict_data):
for k in dict_data.keys():
print(k, dict_data.get(k))
if len(dict_data.get(k)) > 2:
dict_data[k] = dict_data.get(k)[0:2]
print(dict_data.get(k))
return dict_data
x = fun4(dic)
print(x)
def func1(seq):
if len(seq) > 2:
seq=seq[0:2]
return seq
print(func1([1, 2, 3, 4]))
def func3(dic):
d={}
for k,v in dic.items():
if len(v) > 2:
d[k]=v[0:2]
return d
print(func3({'k1':'abcdef','k2':[1,2,3,4],'k3':('a','b','c')})) |
0917db04d4d77b9c408039f7761c8dcf7f189d78 | RenegaDe1288/pythonProject | /lesson21/mission1.py | 215 | 3.921875 | 4 | def count(start, end):
if end != start:
print(start, end=' ')
return count(start+1, end)
else:
print(start)
num = int(input('Введите число: '))
count(start=1, end=num)
|
d9ec6a708c1efee6e02179894f15160ab993a33c | Leopbrito/Curso_em_Video | /Python/Exercicios/012.py | 150 | 3.6875 | 4 | p = float(input('Digite o preço do produto: R$'))
print('Valor do produto: R${:.2f}\nValor do produto com 5% de desconto: R${:.2f}'.format(p,p*0.95)) |
5a083633fede80a18656aa75b08f8d328c5b7446 | worklifesg/Computer-Vision-Algorithms-and-Projects | /2-Image Enhancement using Histogram Equalization/1-histogram-equalization-and-CLAHE-opencv.py | 1,235 | 3.53125 | 4 | '''
Program to apply histogram equalization and CLAHE algorithm using OpenCV
Credits: PyImageSearch
'''
import cv2
image1 = '1_Chest_XRay.jpg'
image2 = '2_BrainTumor.jpg'
image3 = '3_HandSkeleton.jpg'
imagePaths = [image1,image2,image3]
### text on images
text1 = 'HISTOGRAM EQUALIZATION'
text2 = 'CLAHE'
color = (0,0,255)
#function for histogram equalization
def hist_eq(gray):
hist_eq_out = cv2.equalizeHist(gray)
return hist_eq_out
def hist_clahe(gray):
clahe= cv2.createCLAHE(clipLimit=40,tileGridSize=(8,8))
hist_clahe_out = clahe.apply(gray)
return hist_clahe_out
for (i,imagePath) in enumerate(imagePaths):
print('processing image {}/{}'.format(i+1,len(imagePaths)))
image = cv2.imread(imagePath) #read the image
image = cv2.resize(image,(400,300))
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
hist_eq1 = hist_eq(gray)
clahe_eq = hist_clahe(gray)
cv2.putText(hist_eq1,text1,(5,25),cv2.FONT_HERSHEY_SIMPLEX,0.8,color,thickness=2)
cv2.putText(clahe_eq,text2,(5,25),cv2.FONT_HERSHEY_SIMPLEX,0.8,color,thickness=2)
cv2.imshow('Input',gray)
cv2.imshow('Enhanced_image_histogram',hist_eq1)
cv2.imshow('Enhanced_image_CLAHE',clahe_eq)
cv2.waitKey(0)
|
7837688649e4cdc954a8592ffa99c0c3277cda59 | sudhanvalalit/Koonin-Problems | /Koonin/Chapter2/Exercises/Ex4.py | 3,732 | 3.65625 | 4 | """
Exercise 4: Try out the second-, third- and fourth-order Runge-Kutta methods discussed above
on the problem defined by Eq. (2.7). Compare the computational effort for a given accuracy
with that of other methods.
"""
import numpy as np
def f(x, y):
return -x*y
def RK2(f, x0, xe, y0, h):
times = np.arange(x0, xe + h, h)
solutionx, solutiony = [], []
y = y0
nstep = 0
for x in times:
solutionx.append(x)
solutiony.append(y)
k = h * f(x, y)
y += h * f(x + 0.5 * h, y + 0.5 * k)
if x == 3.0 or x == 1.0:
exact = np.exp(-x**2/2)
diff = exact - solutiony[nstep]
print("step \t x \t\t y \t\t exact \t\t diff")
print("{:3} \t {:.5f} \t {:.5E} \t {:.5E} \t {:.5E}".format(
nstep, solutionx[nstep], solutiony[nstep], exact, diff))
nstep += 1
return times, np.array([solutionx, solutiony], float)
def RK3(f, x0, xe, y0, h):
times = np.arange(x0, xe + h, h)
solutionx, solutiony = [], []
y = y0
x = x0
nstep = 0
for x in times:
solutionx.append(x)
solutiony.append(y)
k1 = h * f(x, y)
k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
k4 = h * f(x + h, y + k3)
y += (k1 + 2 * (k2 + k3) + k4) / 6
if x == 3.0 or x == 1.0:
exact = np.exp(-x**2/2)
diff = exact - solutiony[nstep]
print("step \t x \t\t y \t\t exact \t\t diff")
print("{:3} \t {:.5f} \t {:.5E} \t {:.5E} \t {:.5E}".format(
nstep, solutionx[nstep], solutiony[nstep], exact, diff))
nstep += 1
return times, np.array([solutionx, solutiony], float)
def RK4(f, x0, xe, y0, h):
times = np.arange(x0, xe + h, h)
solutionx, solutiony = [], []
x = x0
y = y0
nstep = 0
for x in times:
solutionx.append(x)
solutiony.append(y)
k1 = h * f(x, y)
k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
k4 = h * f(x + h, y + k3)
y += (k1 + 2 * (k2 + k3) + k4) / 6
if x == 3.0 or x == 1.0:
exact = np.exp(-x**2/2)
diff = exact - solutiony[nstep]
print("step \t x \t\t y \t\t exact \t\t diff")
print("{:3} \t {:.5f} \t {:.5E} \t {:.5E} \t {:.5E}".format(
nstep, solutionx[nstep], solutiony[nstep], exact, diff))
nstep += 1
return times, np.array([solutionx, solutiony], float)
def main():
h = 0.01
x0 = 0.0
y0 = 1.0
xe = 3.0
xed = 3.0
while h > 0.0:
h = float(
input(f"\n Enter step size [h= {h:.2E}] (.le. 0 to stop): ") or h)
if h <= 0.0:
break
print("Using Runge-Kutta Second order method:")
times, soly = RK2(f, x0, xe, y0, h)
print()
print("Using Runge-Kutta Third order method:")
times, sol1y = RK3(f, x0, xe, y0, h)
print()
print("Using Runge-Kutta Fourth order method:")
times, sol2y = RK4(f, x0, xe, y0, h)
if xe > 3.0:
x = np.arange(x0, xe+h, h)
exact = np.exp(-x**2/2)
diff = exact - sol2y[1]
print(f"\n The table for the values upto {xe:.4F} using RK4: ")
print("\t x \t\t y \t\t exact \t\t diff")
for i in range(len(x)):
print("\t {:.5f} \t {:.5E} \t {:.5E} \t {:.5E}".format(
sol2y[0][i], sol2y[1][i], exact[i], diff[i]))
print()
xe = float(
input("If you want to check higher values of x, enter here: \n ") or xed)
if __name__ == "__main__":
main()
|
e4268599c81c1f461b2a9d0f9c42f55ab6bf63f1 | yanky2000/ud_course_backend | /test.py | 220 | 3.90625 | 4 | import encrypt
s = "some text"
s1 = "abc"
z = enumerate(s)
t = [t for t in enumerate(s)]
l = list(s)
print s1[-1]
# dic = encrypt.Rot13().encrypted_dic()
# for char in s:
# print char, chr(ord(char)+13)
# print dic
|
3a1ce12cd7d388aa994fcb27a00888339bd56807 | frankieliu/problems | /leetcode/python/1021/sol.py | 1,976 | 3.609375 | 4 |
[Java/C++/Python] One Pass
https://leetcode.com/problems/best-sightseeing-pair/discuss/260850
* Lang: python
* Author: lee215
* Votes: 49
Hope some explanation in this [video](https://www.youtube.com/watch?v=AxVUCzee-XI) (chinese) can help.
The link is good, preview is somehow broken on the Leetcode.
## **Intuition**:
Count the current best score in all previous sightseeing spot.
Note that, as we go further, the score of previous spot decrement.
## **Explanation**
`cur` will record the best score that we have met.
We iterate each value `a` in the array `A`,
update `res` by `max(res, cur + a)`
Also we can update `cur` by `max(cur, a)`.
Note that when we move forward,
all sightseeing spot we have seen will be 1 distance further.
So for the next sightseeing spot `cur = Math.max(cur, a) **- 1**`
It\'s kinds of like, "A near neighbor is better than a distant cousin."
## **Time Complexity**:
One pass, `O(N)` time, `O(1)` space
<br>
**Java:**
```
public int maxScoreSightseeingPair(int[] A) {
int res = 0, cur = 0;
for (int a: A) {
res = Math.max(res, cur + a);
cur = Math.max(cur, a) - 1;
}
return res;
}
```
**C++:**
```
int maxScoreSightseeingPair(vector<int>& A) {
int res = 0, cur = 0;
for (int a: A) {
res = max(res, cur + a);
cur = max(cur, a) - 1;
}
return res;
}
```
**Python:**
```
def maxScoreSightseeingPair(self, A):
cur = res = 0
for a in A:
res = max(res, cur + a)
cur = max(cur, a) - 1
return res
```
**Python:**
```
def maxScoreSightseeingPair(self, A):
cur = res = 0
for a in A:
res = max(res, cur + a)
cur = max(cur, a) - 1
return res
```
**Python 1-line:**
```
def maxScoreSightseeingPair(self, A):
return reduce(lambda (r, c), a: [max(r, c + a), max(c, a) - 1], A, [0, 0])[0]
```
|
4d8aa8c36171bb6d7180593fdd437dc77e5498fd | hanking356/python_practice | /day1/pack01/multi_data.py | 1,079 | 3.53125 | 4 | food = ['아이스크림','아이스아메리카노','생수'] #목록(list)
# hobby = []
print(food[0])
print(food[1])
print(food[2])
#food의 요소 3개를 변수 i로 순서대로 print 함
for i in range (0,3):
print(food[i], end='')
print()
#food에 있는 요소를 차례대로 하나씩 뽑아서 print 함
for x in food: #for-each
print(x, end='')
######
#오늘 끝나고 나서, 할 일 5가지를 목록으로 만들어보세요.
#2가지 방식으로 프린트!
print()
print()
activity=['운동하기','밥먹기','샤워하기','유튜브보기','잠 자기']
#activity의 요소 5개를 변수 i로 순서대로 print 함
for i in range(0,5):
print(activity[i], end=' ')
print()
#food에 있는 요소를 차례대로 하나씩 뽑아서 print 함
for x in activity:
print(x, end=' ')
#activity의 요소 5개를 변수 i로 순서대로 print 함. 다만, len()는 activity lsit의 갯수를 뽑아내는 함수 이므로 마지막 값 대신 사용 가능
print()
for i in range(0,len(activity)):
print(activity[i], end=' ')
|
559298441349290383d7d6d1cf28655d3d8c4c2f | Tatz18/Web-Crawler | /json-url.py | 554 | 3.859375 | 4 | import urllib.request as ur
import urllib.parse as up
import json
# for manually input the url json_url = input("Enter the url >>> ")
json_url = "https://python-data.dr-chuk.net/comments_22962.json" # url for the data(in json)
print('Retrieving ', json_url)
data = ur.urlopen(json_url).read().decode("utf-8")
print("Retrieved ", len(data),'characters')
json_obj = json.loads(data)
sum = 0
total_number = 0
for comment in json_obj["comments"]:
sum += int(comment["count"])
total_number += 1
print("Count ", total_number)
print("Sum : ", sum)
|
c9ebce1600c9f8c38eb0a413c38dcb1f4e9990ce | Damianpon/damianpondel96-gmail.com | /zjazd 2/sklep_spozywczy.py | 1,993 | 3.984375 | 4 |
produkty = {"pomidory": 4, "malina": 8, "banan": 2, "jabłko": 4.4}
magazyn = {"pomidory": 10, "malina": 10, "banan": 10, "jabłko": 10}
def sklep_spozywczy():
lista_zakupow = dict()
koszt = list()
print("Dzień dobry! W czym możemy pomóc?")
while True:
print("Jeśli chcesz kupować to naciśnik- k, zapłacić- p, zakończyć- z")
komenda = input("Chce: ")
if komenda == "k":
print("Nasz sklep oferuje: ")
for item in produkty.items():
a, b = item
print(f"{a} za {b} zł/kg.")
print("Co chcesz kupić")
produkt = input("Kupuję: ")
if produkt in produkty:
print("Ile potrzebujesz? ")
ile = float(input("Potrzebuję: "))
if ile < magazyn[produkt]:
lista_zakupow[produkt] = (ile * b)
koszt.append(ile * b)
magazyn[produkt] = magazyn[produkt] - ile
print(f"Za {ile} kg {produkt} zapłacisz {ile * b:.2f} złotych.")
else:
print("Niestety nie mamy wystarczająco. Ile podać?")
ile = float(input("Podaj: "))
lista_zakupow[produkt] = (ile * b)
magazyn[produkt] = magazyn[produkt] - ile
koszt.append(ile * b)
print(f"Za {ile} kg {produkt} zapłacisz {ile * b:.2f} złotych.")
elif komenda == "p":
suma = sum(koszt)
print(f"Za wszystkie produkty zapłacisz {suma:.2f} złotych.")
print("Tu masz paragon:")
for itemy in lista_zakupow.items():
c, d = itemy
print(f"{c}, {d:.2f} zł")
print(f"Suma {suma:.2f} zł.")
elif komenda == "z":
return "Dziękujemy za zakupy, zapraszamy ponownie!"
else:
print("Wpisz poprawną komendę!")
print(sklep_spozywczy())
|
a37c385c45a17c7b2d70204519a3c4a8d20f5515 | Drishtant-Shri/seglearn | /examples/plot_imblearn.py | 2,720 | 3.5625 | 4 | """
===============================
Simple imbalanced-learn example
===============================
This example demonstrates how to use imbalanced-learn resample transforms inside a seglearn Pype.
"""
# Author: Matthias Gazzari
# License: BSD
import numpy as np
from sklearn.dummy import DummyClassifier
from seglearn.pipe import Pype
from seglearn.transform import Segment, patch_sampler, FeatureRep
from seglearn.feature_functions import minimum
from seglearn.split import temporal_split
from imblearn.under_sampling import RandomUnderSampler
# Single univariate time series with 10 samples
X = [np.array([[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5,6], [6, 7], [7, 8], [8, 9], [9, 10]])]
# Time series target (imbalanced towards False)
y = [np.array([True, False, False, False, False, False, True, False, False, False])]
print("Implementation details: transform and fit_transform methods:")
pipe = Pype([
('segment', Segment(width=1, overlap=0)),
('resample', patch_sampler(RandomUnderSampler)()),
])
print("Pipeline:", pipe)
print("Calling a transform on the data does not change it ...")
Xf, yf = pipe.transform(X, y)
print("X (flattened):", Xf.flatten())
print("y", yf)
print("... but calling fit_transform resamples the data.")
Xf, yf = pipe.fit_transform(X, y)
print("X (flattened):", Xf.flatten())
print("y", yf)
print()
print("VerboseDummyClassifier example:")
print()
class VerboseDummyClassifier(DummyClassifier):
def fit(self, X, y, sample_weight=None):
print("Fitting X (flattened):", X.flatten(), "on y:", y)
return super(VerboseDummyClassifier, self).fit(X, y, sample_weight)
def predict(self, X):
print("Predicting X (flattened):", X.flatten())
return super(VerboseDummyClassifier, self).predict(X)
def score(self, X, y, sample_weight=None):
print("Scoring X (flattened):", X.flatten(), "on y:", y)
return super(VerboseDummyClassifier, self).score(X, y, sample_weight)
pipe = Pype([
('segment', Segment(width=1, overlap=0)),
('resample', patch_sampler(RandomUnderSampler)(shuffle=True)),
('feature', FeatureRep(features={"min":minimum})),
('estimator', VerboseDummyClassifier(strategy="constant", constant=True)),
])
print("Pipeline:", pipe)
print("Split the data into half training and half test data:")
X_train, X_test, y_train, y_test = temporal_split(X, y, 0.5)
print("X_train:", X_train)
print("y_train:", y_train)
print("X_test:", X_test)
print("y_test:", y_test)
print()
print("Fit on the training data (this includes resampling):")
pipe.fit(X_train, y_train)
print()
print("Score the fitted estimator on test data (this excludes resampling):")
score = pipe.score(X_test, y_test)
print("Score: ", score)
|
43e75644a2d81551e4c45f0b40078bf96356e49d | minininja/crap-fibonacci | /src/python/fib.py | 102 | 3.5625 | 4 | def fib(n):
if n == 0: return 0
if n <= 2: return 1
return fib(n-1) + fib(n-2)
print(fib(45))
|
f04d32cb757a50fe7ad0ccacf74c8b5354317d99 | pogostick29dev/LL-Python | /CInput.py | 206 | 4.03125 | 4 | name = input("What is your name?\n")
print("Hello, " + name + "!")
age = int(input("What is your age?\n"))
age2 = int(input("What is your friend's age?\n"))
print("Your combined age is " + str(age + age2)) |
c2cd3898acefc79a9059e223c6afd5cc604cc251 | jasonwbw/jason_putils | /putils/tools/words_length.py | 3,185 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# count how much word in one line, get the statistics result
#
# @Author : Jasonwbw@yahoo.com
import sys
des = '<input file name> [-p parts] [-c threshold]' + \
'\n\tcompute average word count for each line, default will print out int average length, standard variance, max and min value, total line. ' + \
'\n\tAnd divide the line into [parts] by word count, parts must large than 1 and odd, default is 2.' + \
'\n\tAnd you can give threshold to count how much line\'s word count less than it.'
def check_params(argv):
if len(argv) < 1:
print 'leak params, please use like:', des
return False
return True
def handle(argv, opts):
# check the params is right or not
if not check_params(argv):
return
# params
filename = argv[0]
parts = 2
threshold = -1
if opts != None:
for opt, arg in opts:
if opt == '-p':
parts = int(arg)
if parts % 2 != 0:
print '[Error] parts should be odd.'
return
elif opt == '-c':
threshold = int(arg)
# var for count
total_words, min_words, max_words = 0, sys.float_info.max, 0.0
min_s, max_s = '', ''
with open(argv[0], 'r') as fp:
line_num = 0
for line in fp:
sentence = line.strip()
count = sentence.count(' ') + 1
if count < min_words:
min_words, min_s = count, sentence
if count > max_words:
max_words, max_s = count, sentence
total_words += count
line_num += 1
# statistics var
avg, variance = float(total_words) / line_num, 0
small_one_part, large_one_part = int((avg - min_words) / (parts / 2)) + 1, int((max_words - avg) / (parts / 2)) + 1,
part_count = [0] * parts
threshold_count = 0
with open(argv[0], 'r') as fp:
for line in fp:
count = line.strip().count(' ') + 1
variance += (count - avg) ** 2
if count > avg:
part_count[parts / 2 + int(count - avg) / large_one_part] += 1
else:
part_count[int(avg - count) / small_one_part] += 1
if threshold != -1 and count < threshold:
threshold_count += 1
# print out result
print 'The file is total', line_num, 'line.'
print 'average word count for one line is' , avg
print 'min word count', min_words
print 'max word count', max_words
print 'standard variance is', (variance / float(line_num)) ** 0.5
print '\ntake the line into', parts, 'parts'
print_table(min_words, small_one_part, max_words, large_one_part, part_count)
if threshold != -1:
print '\nthere are', threshold_count, 'line\'s word count less than', threshold
def print_table(min_words, small_one_part, max_words, large_one_part, part_count):
for i in xrange(len(part_count) / 2):
print 'smaller ' + str(min_words + small_one_part * i) + '-' + str(min_words + small_one_part * (i + 1)) + '\t' + str(part_count[i])
for i in xrange(len(part_count) / 2, 0, -1):
print 'larger ' + str(max_words - large_one_part * i) + '-' + str(max_words - large_one_part * (i - 1)) + '\t' + str(part_count[len(part_count) - i])
if __name__ == '__main__':
import getopt
reload(sys)
sys.setdefaultencoding('utf-8')
try:
opts, args = getopt.getopt(sys.argv[1:], 'c:p:', [])
handle(args, opts)
except getopt.GetoptError:
sys.exit(2) |
889e7a85a3df22fac5730d1de9a2d00a39dab40e | rafaelnunes44/pythonGuanaba | /Desafio 08 Conversor medidas.py | 280 | 4.09375 | 4 | """
08. Escreva um programa que leia um valor em metros eo exiba convertido em centimetros e milimetros
"""
n1 = int(input('Digite um valor em metros , para ser convertido em cm e mm: '))
cm = n1 * 100
mm = n1 * 1000
print('{}m, equivale a {}cm e {}mm '.format(n1, cm, mm))
|
0d81de91db63d3b09e947662aaab6e2153bf1dbe | DimaRubio/Python3_SeleniumWD | /python_basic/sec3_variables/string.py | 1,270 | 3.8125 | 4 | class StringWrapper:
def convert_case(self, s, case ="lower"):
res = s.lower() if case=="lower" else s.upper()
print("*"*10,
"\nPrevious value is: {0}\n"
"Current value is: {1}".format(s,res))
def get_word(self, s, n = 0):
wordList = s.split()
return wordList[n-1] if wordList.__len__() >= n and n is not 0 else "out off range"
def get_char_from_word(self, s, n = 0):
return s[n-1] if s.__len__() >= n and n is not 0 else "out off range"
def count_words_in_string(self, s):
return s.split().__len__()
def change_sub_string(self, s, old, new, count=0):
return s.replace(old, new, count) if count is not 0 else s.replace(old, new)
def get_sub_string(self, s, start, end):
return s[start : end]
str_example = "SCRUM is a subset of Agile."
sw = StringWrapper()
sw.convert_case(str_example)
sw.convert_case(str_example, "upper")
print("Second char in sixth word of string \"{0}\" is = \"{1}\"".format(str_example, sw.get_char_from_word(sw.get_word(str_example, 6), 2)))
print("String contains of {0} words".format(sw.count_words_in_string(str_example)))
print(sw.change_sub_string(str_example, "is", "$"))
print(sw.get_sub_string(str_example, 0, 5)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.