blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
db1038711e74224bd995b447adfda2efe09a8759 | lgzh1215/codewars | /Solutions/6_kyu/Valid Braces/valid.py | 484 | 4.03125 | 4 | def validBraces(string):
stack=[]
for c in string:
if c=='(' or c=='[' or c=='{':
stack+=[c]
elif c==')':
if stack==[] or stack[-1]!='(': return False
else: stack.pop()
elif c==']':
if stack==[] or stack[-1]!='[': return False
else: stack.pop()
elif c=='}':
if stack==[] or stack[-1]!='{': return False
else: stack.pop()
return True if stack==[] else False |
30398ebd111127f90bc659a6df53e11f8d909d4a | prasanth-ashokan/My-Programs | /HR/BASIC PROGRAMMING/roy.py | 252 | 3.671875 | 4 | n=int(input())
for _ in range(int(input())):
a,b=map(int,input().split())
if a<n or b<n:
print("UPLOAD ANOTHER")
else:
if a==n and b==n or a==b:
print("ACCEPTED")
else:
print("CROP IT")
|
15bf2971363f45288ec147cb10684792c5555e30 | lvbaoxin/learnpython | /day7.py | 836 | 3.921875 | 4 | # for else 适用于for执行完或者没有循环数据时,需要做的事情。
# num = int(input("请输入数量"))
# name = "张三"
# for i in range(num):
# print("{}很饿,正在吃第{}馒头".format(name,i))
# else:
# print("还没有给我馒头,{}饿哭了".format(name))
# #pass 空语句 只要有缩进而缩进的内容还不确定的时候,此是为了保证语法的正确性,就可以使用pass点位。不会报语法错误。
# if 10 > 6:
# print("10是大的")
# else:
# pass
for i in range(3):
username = input("请输入用户名")
password = input("请输入密码")
if username == "admin" and password == "123456":
print("欢迎您:{}登录成功".format(username))
break
else:
print("用户名或密码错误,请重新输入。")
|
366611874216a8b8a7eda7b0810b436643dc28ea | sadpanda123/temp | /app1.py | 1,886 | 4.5625 | 5 | '''
An explanation of the argument 'self' in classes
-------------------------------------------------
Many instances can be created from the same class (instantiation)
eg instance = class()
to identify the different instances when calling a method on an instance the instance itself is passed as an argument
to the method... as follows:
class ex_class():
def ex_method(self):
pass
my_instance = ex_class()
my_instance.ex_method(instance) <--- we dont need to use instance.. this is what python does
instance is effectively passed to self. However we dont need to specify "instance". it is implied by python.
However if we dont specify "self" as a parameter in method in a class an error will be produced as follows:
TypeError: ex_method() takes 0 positional arguments but 1 was given
what follows is a program that demonstrates that "self" = object instance
'''
class Arith():
w = 100
def __init__(self, x, y):
self.x = x
self.y = y
def addition():
print(self, " <------- prints 'self' which is the same as instance above [so self = instance]")
return self.x + self.y
def subtraction(self):
return self.x - self.y
a = Arith(10, 5)
print(a, " <------- Instance comprising <class_module>.<class_name> + memory")
print(a.w)
print(a.addition())
print(a.subtraction())
b = Arith(10, 5)
print(b, " <------- Instance comprising <class_module>.<class_name> + memory")
print(b.w)
print(b.addition())
print(b.subtraction())
'''
if class is defined in the __main__ module then <class_module> = __main__
eg <__main__.Arith object at 0x00716850>
if class is defined in an imported module then <class_module> = module name
eg from app1 import Arith
<app1.Arith object at 0x030AEBB0>
'''
|
2444a15f0e2fd438025da3290bc1ffc7bf638b5b | larrycai/costa-ci | /copy_ssh_id.py | 2,452 | 3.578125 | 4 | #!/usr/bin/env python
"""This runs 'ls -l' on a remote host using SSH. At the prompts enter hostname,
user, and password.
$Id: sshls.py 489 2007-11-28 23:40:34Z noah $
"""
import sys
import os
def ssh_command (host, user, password):
"""This runs a command on the remote host. This could also be done with the
pxssh class, but this demonstrates what that class does at a simpler level.
This returns a pexpect.spawn object. This handles the case when you try to
connect to a new host and ssh asks you if you want to accept the public key
fingerprint and continue connecting. """
ssh_newkey = 'Are you sure you want to continue connecting'
command = 'ssh-copy-id %s@%s'%(user, host)
print "$",command
child = pexpect.spawn(command)
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'assword: ',pexpect.EOF])
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
print child.before, child.after
return None
elif i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
#child.expect ('password: ')
i = child.expect([pexpect.TIMEOUT, 'assword: ',pexpect.EOF])
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
print child.before, child.after
return None
elif i == 1:
child.sendline(password)
else: # EOF
pass
#print child.before
elif i==2: # ask for passwd
child.sendline(password)
elif i==3: # eof
pass
return child
def main (host,user,password):
#host = raw_input('Hostname: ')
#user = raw_input('User: ')
#password = getpass.getpass('Password: ')
child = ssh_command (host,user,password)
child.expect(pexpect.EOF)
print child.before
# ./copy_ssh_id.py <ip> <username> <password> <port>
if __name__ == '__main__':
try:
import pexpect
except ImportError as error:
print "You don't have module {0} installed, please install first".format(error.message[16:])
exit(1)
try:
argc = len(sys.argv)
print argc, sys.argv
if argc < 4:
print " Usage: %s <ip> <username> <password>" % sys.argv[0]
exit (1)
main(sys.argv[1],sys.argv[2],sys.argv[3])
except Exception, e:
print str(e)
os._exit(1)
|
0301e57bac6d46b4c07dc92526f473ec77eaa9dc | fhfhfhd26/PyCharm | /ch07data/ch07-03reverse.py | 520 | 4.09375 | 4 | aa = [10, 20, 30, 40, 50]
print(aa)
# 리스트 aa의 값의 순서를 거꾸로 정렬하여 출력하시오
aa = aa[::-1]
print(aa)
aa.reverse()
print(aa)
# 일부 데이터의 변경
# aa 리스트 데이터 중 3번째 30을 300으로 변경
aa[2] = 300
print(aa)
# 1번째 100으로 2번째는 200으로 변경
aa[0:2] = [100, 200]
print(aa)
aa[1:3] = [700]
print(aa)
aa[1] = [1000, 2000]
print(aa)
print(aa[0], type(aa[0]))
print(aa[1], type(aa[1]))
# 리스트의 데이터 삭제
aa[2:] = []
print(aa)
|
a744a534d0b33a736ce6c2766cdca2a4c030135d | spconger/ITC110-python-Programs | /prime.py | 251 | 3.875 | 4 | #Does a simple calculation
#Steve 9/16/2017
def main():
#number=eval(input("Enter a number from 1 to 41: "))
for number in range(40):
prime=number * number - number + 41
print(prime)
main()
|
a1ecbdf8556e2dbb8b873c6e527677f60bfdc417 | nimishbongale/5th-Sem-ISE | /Sem5SLLPYTHON/demo/NewDictionary.py | 570 | 3.59375 | 4 | dict1 = {
'Name1': 'Archie',
'Age1': 17,
'Identity1': 'Student';
}
dict2 = {
'Name2': 'Weatherbee',
'Age2': 52,
'Identity2': 'Principal';
}
dict3 = {
'Name3': 'Grundy',
'Age3': 51,
'Identity3': 'Teacher';
}
dict4 = dict(list(dict1.items()) + list(dict2.items()) + list(dict3.items()))
print (dict4)
dict1['name1']="Veronica"
dict4 = dict(list(dict1.items()) + list(dict2.items()) + list(dict3.items()))
print (dict4)
dict5 = {
'Reverable' = 'no clue ' ,
'comic' = 'old one'
}
dict6 = dict(list(dict4.items()) + list(dict5.items()))
|
493a08012fbf6267ee4c641755e093db4caf7f98 | JinghongM/Everlasting_Web | /Back_End/data_clean/method_test.py | 950 | 3.53125 | 4 | import logging
from method import calculator
logging.basicConfig()
logger = logging.getLogger("Calculator function test")
logger.setLevel(logging.DEBUG)
try:
logger.debug("This is the test of create a calculator object")
cal = calculator()
logger.debug('Successfully create calculator object')
except exception as e:
logger.error(e.message)
try:
logger.info("This is a basic test for checkUnit function")
logger.debug("cal.checkUnit('345678lbs','w')")
result = cal.checkUnit('345678lbs','w')
logger.debug(result)
logger.debug("cal.checkUnit('3876597inches','h')")
result = cal.checkUnit('3876597inches','h')
logger.debug(result)
logger.debug("cal.checkUnit('3876597inches','w')")
result = cal.checkUnit('3876597inches','w')
logger.debug(result)
logger.info("This is the end of test for checkUnitFunction")
except exception as e:
logger.error(e.message)
|
6973572fac3d3942b286f5abcff196f25d0ee7aa | superbeom97/jumpjump | /02_Coding_Skill/CodingDojang/No4_Printing OXs.py | 715 | 3.59375 | 4 | # input은 int n을 입력 받아
# 첫번째 row는 (n-1)의 O와 X
# 두번째 row는 (n-2)의 O와 XX
# 세번째 row는 (n-3)의 0와 XXX
# ...
# n번째 row는 n의 X을 출력하시오
#
# 입력 예시: 6
#
# 출력 예시:
# OOOOOX
# OOOOXX
# OOOXXX
# OOXXXX
# OXXXXX
# XXXXXX
# Ver.1
def Num_OX():
number_ox = int(input("프린트 할 OX의 총 개수 입력하시오: "))
for i in range(1, number_ox+1):
print((number_ox-i)*'O'+i*'X')
Num_OX()
# Ver.2
def Num_OX():
number_ox = int(input("프린트 할 OX의 총 개수 입력하시오: "))
for i in range(1, number_ox+1):
number_o = (number_ox-i)*'O'
number_x = i*'X'
print(number_o+number_x)
Num_OX() |
9f1861c314321eaf73b0d501d4620f96609146e8 | deathlyhallows010/Interview-Bit-Python | /Binary Search/Rotated Sorted Array Search.py | 1,368 | 3.921875 | 4 | # https://www.interviewbit.com/problems/rotated-sorted-array-search/
# Rotated Sorted Array Search
# Given an array of integers A of size N and an integer B.
# array A is rotated at some pivot unknown to you beforehand.
# You are given a target value B to search. If found in the array, return its index, otherwise return -1.
# You may assume no duplicate exists in the array.
def BinarySearch(A,target):
start = 0
end = len(A) - 1
while(start<=end):
mid = (start + end)//2
if A[mid] == target:
return mid
elif A[mid]>target:
end = mid -1
else:
start = mid + 1
return -1
def findMin(A):
start = 0
end = len(A)-1
N = len(A)
while(start<=end):
if A[start]<=A[end]:
return start
mid = (start + end)//2
nxt = (mid+1)%N
prev = (mid-1+N)%N
if A[mid]<=A[nxt] and A[mid]<=A[prev]:
return mid
elif A[mid]<=A[end]:
end = mid -1
elif A[mid]>=A[end]:
start = mid +1
return -1
class Solution:
# @param A : tuple of integers
# @return an integer
def search(self,A,B):
A = list(A)
n = findMin(A)
if n == -1:
return -1
d
A.sort()
return (BinarySearch(A,B)+n)%len(A) |
234225ca2fe95665434726c1685b61d3b057b5bb | jacklyQinqin/trainning | /pythonTest/PythonSyntax/迭代器.py | 603 | 4.53125 | 5 | """
迭代器
迭代是Python最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
字符串,列表或元组对象都可用于创建迭代器:
"""
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
"""
for i in range(len(list)):
print (next(it)) # 输出迭代器的下一个元素
"""
#for i in it:
# print(i)
|
3bed01063ae1070e6aec5c6bf0cb2845d8a48ecc | abdullahsumbal/Interview | /Companies/Ormuco/QuestionC/Cache.py | 3,099 | 3.953125 | 4 | import time
import random
from threading import Lock, Thread
class Cache():
"""
This is implements the least recently used cache with time expiry
"""
def __init__(self, size=5):
self.cacheList = []
self.cacheKV = {}
self.Maxsize = size
self.currSize = 0
def put(self, item, validTime=2):
"""
This method is responsible for removing items before adding into the queue. It also removes the item if it is expired
"""
#check if item already exist
if item in self.cacheKV:
#check if it has expired
insertTime, duration = self.cacheKV[item]
seconds = int(round(time.time()))
if insertTime + duration > seconds:
print("Item {} already in cache".format(item))
return
else:
print("Item {} expired".format(item))
self.remove(self.cacheList.index(item))
# remove least recently used item.
if len(self.cacheKV) >= self.Maxsize:#self.currSize == self.Maxsize:
self.remove()
# add item to list/queue
self.add(item, validTime)
def add(self, item, validTime):
"""
Add item into the list and update the (key,value) map
"""
self.cacheList.append(item)
seconds = int(round(time.time()))
self.cacheKV[item] = [seconds, validTime]
print("Item {} added in cache".format(item))
def removeItem(self, item):
"""
Remove desired item form the queue. Also remove item from map.
"""
index = self.cacheList.index(item)
self.cacheList.pop(index)
del self.cacheKV[item]
print("Item {} removed from cache".format(item))
def remove(self, index=0):
"""
Remove item at desired index form the queue( or start of the list by default). Also update map
"""
item = self.cacheList.pop(index)
del self.cacheKV[item]
print("Item {} removed from cache".format(item))
def print(self):
"""
For printing queue and Map
"""
print("Items in the Cache")
print("Items", self.cacheList)
print("Key Value of items: ", self.cacheKV)
lock = Lock()
def traffic(cache):
# create traffic
while True:
# create random item and valid times
item = random.randint(1,9)
validTime = random.randint(1,3)
lock.acquire()
try:
cache.put(item, validTime)
cache.print()
finally:
lock.release()
# delay to obersve the output
time.sleep(1)
if __name__ == '__main__':
sources = 1
cacheSize = 5
# initize Cache with size
cache = Cache(cacheSize)
# thread pool
threads = []
for i in range(sources):
t = Thread(target=traffic, args=(cache,))
threads.append(t)
# start threads
for thread in threads:
thread.start()
# wait until all threads are executed
for thread in threads:
thread.join()
|
ea911d2084f132983509924413df96d895207696 | JanhaviMhatre01/pythonprojects | /anagram.py | 506 | 4.25 | 4 | '''
/**********************************************************************************
* Purpose: One string is an anagram of another if the second is simply a
* rearrangement of the first.
*
* @author : Janhavi Mhatre
* @python version 3.7
* @platform : PyCharm
* @since 26-12-2018
*
***********************************************************************************/
'''
from utilities import utility
str1 = input("enter string 1: ")
str2 = input("enter string 2: ")
utility.anagram_check(str1, str2)
|
8c0f3ad6f14bc5330cb1cc8e1fb3a1cbdfb05e98 | dbuscaglia/leetcode_practice | /longest_palindrime_substring.py | 671 | 3.9375 | 4 | '''
5. Longest Palindromic Substring
Medium
4336
396
Favorite
Share
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
'''
import math
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
current_longest = ""
# idea: start in middle and go both ways
floor_middle = math.floor(len(s) / 2)
breakpoint()
return "bab"
assert Solution().longestPalindrome("babada") == "bab" |
1a927cbc66bd9f1c3265c49895e4c0c4fd5d10e0 | aya0221/CNN_image_classification | /cnn_image_recognition_practice.py | 3,214 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#img recognition (binary classification problem)-CNN(Convolutional neural network)
#1st-full_connection: relu
#output layer: sigmoid
# In[2]:
#import the libraries
# In[3]:
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
# In[4]:
#----------data processing
# In[5]:
#processing the TRAINING set
#1. generaete the traing_data
train_data_generator = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
#2. import the training img_set(target_size, batch...)
training_set = train_data_generator.flow_from_directory('dataset/training_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
# In[6]:
#processing the TEST set
#1. generaete the test_data
test_data_generator = ImageDataGenerator(rescale = 1./255)
#2. import the test img_set(target_size, batch...)
test_set = test_data_generator.flow_from_directory('dataset/test_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
# In[7]:
#----------building the model(CNN)
# In[8]:
#initializing CNN
cnn = tf.keras.models.Sequential()
# In[9]:
#1st layer
#1.convolution
cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=[64, 64, 3]))
#2.pooling
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
# In[10]:
#2nd layer
#1.convolution
cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'))
#2.pooling
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
# In[11]:
#flattening (make the data colum)
cnn.add(tf.keras.layers.Flatten())
# In[12]:
#---neural network starts---
# In[13]:
#full connection(dense)
cnn.add(tf.keras.layers.Dense(units=128, activation='relu'))
# In[14]:
#output layer(dense)
cnn.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))
# In[15]:
#----------training the model(CNN)
# In[16]:
#compiling CNN(optimizer, loss, metrics)
cnn.compile(optimizer= 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# In[17]:
#fit the model(CNN) on training_set and evaluate the test_set
cnn.fit(x = training_set, validation_data = test_set, epochs = 25)
# In[18]:
#----------making a single prediction
#(img size=target_size always haves to be the same!)
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = cnn.predict(test_image)
#make 1 or 0
training_set.class_indices
if result[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
print(prediction)
|
5aa370683df3346084e92481d9a8b24cd6805548 | Steph99rod/Metrics-Dashboard | /Issues/Code/Issues.py | 6,455 | 3.71875 | 4 | from datetime import datetime
from githubAPI import GitHubAPI
from sqlite3 import Cursor, Connection
class Logic:
'''
This is logic to analyze the data from the githubAPI Issues Request API and store the data in a database.
'''
def __init__(self, gha: GitHubAPI= None, data: dict = None, responseHeaders: tuple = None, cursor: Cursor = None, connection: Connection = None):
'''
Initializes the class and sets class variables that are to be used only in this class instance.\n
:param gha: An instance of the githubAPI class.\n
:param data: The dictionary of data that is returned from the API call.\n
:param responseHeaders: The dictionary of data that is returned with the API call.\n
:param cursor: The database cursor.\n
:param connection: The database connection.
'''
self.gha = gha
self.data = data
self.responseHeaders = responseHeaders
self.dbCursor = cursor
self.dbConnection = connection
def parser(self) -> None:
'''
Actually scrapes, sanitizes, and stores the data returned from the API call.
'''
def tryParam(getData):
''' Handles try and except while parsing data '''
try:
return getData
except (KeyError,AttributeError):
return None
def callTryParam(data):
''' sets data to 'NA' if parsing fails '''
return tryParam(data) if tryParam(data) is not None else "NA"
while True:
if len(self.data) == 0:
break
for x in self.data:
# Values below are the values that are to be returned/set if parsing FAILS
user = "NA"
user_id = "NA"
issue_id = "NA"
comments_url = "NA"
node_id = "NA"
number = "NA"
title = "NA"
labels = "NA"
state = "NA"
locked = "NA"
assignee = "NA"
assignees = "NA"
comments = "NA"
created_at = "NA"
updated_at = "NA"
closed_at = "NA"
body = "NA"
comment_user = "NA"
comment_user_id = "NA"
comment_id = "NA"
issue_url = "NA"
comment_node_id = "NA"
comment_created_at = "NA"
comment_updated_at = "NA"
comment_body = "NA"
user = callTryParam(x["user"]["login"])
user_id = callTryParam(x["user"]["id"])
issue_id = callTryParam(x["id"])
comments_url = callTryParam(x["comments_url"])
node_id = callTryParam(x["node_id"])
number = callTryParam(x["number"])
title = callTryParam(x["title"])
labels = callTryParam(x["labels"])
state = callTryParam(x["state"])
locked = callTryParam(x["locked"])
assignee = callTryParam(x["assignee"])
assignees = callTryParam(x["assignees"])
comments = callTryParam(x["comments"])
body = callTryParam(x["body"])
# Scrapes and sanitizes the time related data
# closed_at = callTryParam(x["closed_at"].replace("T", " ").replace("Z", " "))
closed_at = callTryParam(x["closed_at"])
closed_at = closed_at.replace("T", " ").replace("Z"," ") if closed_at != "NA" else closed_at
closed_at = datetime.strptime(closed_at, "%Y-%m-%d %H:%M:%S ") if closed_at != "NA" else closed_at
# created_at = callTryParam(x["created_at"].replace("T", " ").replace("Z", " "))
created_at = callTryParam(x["created_at"])
created_at = created_at.replace("T", " ").replace("Z", " ") if created_at != "NA" else created_at
created_at = datetime.strptime(created_at, "%Y-%m-%d %H:%M:%S ") if created_at != "NA" else created_at
updated_at = callTryParam(x["updated_at"])
updated_at = updated_at.replace("T", " ").replace("Z", " ") if updated_at != "NA" else updated_at
updated_at = datetime.strptime(updated_at, "%Y-%m-%d %H:%M:%S ") if updated_at != "NA" else updated_at
# Stores the data into a SQL database
sql = "INSERT INTO ISSUES (user, user_id, issue_id, comments_url, node_id, number, title, labels, state, locked, assignee, assignees, comments, created_at, updated_at, closed_at, body, comment_user, comment_user_id, comment_id, issue_url, comment_node_id, comment_created_at, comment_updated_at, comment_body) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
self.dbCursor.execute(sql, (str(user), str(user_id), str(issue_id), str(comments_url), str(node_id), str(number), str(title), str(labels), str(state), str(locked), str(assignee), str(assignees), str(comments), str(created_at), str(updated_at), str(
closed_at), str(body), str(comment_user), str(comment_user_id), str(comment_id), str(issue_url), str(comment_node_id), str(comment_created_at), str(comment_updated_at), str(comment_body))) # Str data type wrapper called in order to assure type
self.dbConnection.commit()
# Below checks to see if there are any links related to the data returned
try:
foo = self.responseHeaders["Link"]
if 'rel="next"' not in foo: # Breaks if there is no rel="next" text in key Link
break
else:
bar = foo.split(",")
for x in bar:
if 'rel="next"' in x: # Recursive logic to open a supported link, download the data, and reparse the data
url = x[x.find("<")+1:x.find(">")]
self.data = self.gha.access_GitHubAPISpecificURL(url=url)
self.responseHeaders = self.gha.get_ResponseHeaders()
self.parser() # Recursive
except KeyError: # Raises if there is no key Link
break
break
|
f605f6aab7f468492f18bd9fd141ca9367b60985 | anhnh23/PythonLearning | /src/theory/control_flow/condition.py | 742 | 3.703125 | 4 | '''
Created on Dec 8, 2016
@author: ToOro
'''
# can be chained
a = 3
b = 2
c = 1
d = 10
e = 9
if a < b == c < d >= e:
pass
# assign the result of comparison
str1, str2, str3 = '', 'To', 'Tooo'
non_null = str1 or str2 or str3 # if the first one0 is empty, find the not next empty one
print non_null # result: To
# comparing sequences and other types
'''
use lexicographical ordering (thứ tự từ điển), if they differ this determines the outcome
of the comparison (must have the same number of items)
'''
print (1,2,3) < (1,2,4)
print [1,2,3] < [1,2,4]
print 'ABC' < 'C' < 'Pascal' < 'Python'
print (1,2,3,4) < (1,2,4)
print (1,2) < (1,2,-1)
print (1,2,3) == (1.0, 2.0, 3.0)
print (1,2, ('aa', 'ab')) < (1,2,('abc', 'a'), 4) |
0a7f4ece98b30d06ac0771d2f576be66569b39d7 | caiosainvallio/estudos_programacao | /curso_em_video/exe041.py | 776 | 4 | 4 | """Exercício criado por : https://www.cursoemvideo.com/
041 A Confederação Nacional de Natação precisa se um programa que leia o ano de nascimento
de um atleta e mostre sua categoria, de acordo com a idade:
* Até 9 anos: MIRIM
* Até 14 anos: INFANTIL
* Até 19 anos: JUNIOR
* Até 20 anos:SÊNIOR
* Acima: MASTER"""
from datetime import date
ano = int(input('Informe o ano de nascimento: '))
idade = date.today().year - ano
if idade <= 9:
print('Idade: {}\nStatus: MIRIM.'.format(idade))
elif idade <= 14:
print('Idade: {}\nStatus: INFANTIL'.format(idade))
elif idade <= 19:
print('Idade: {}\nStatus: JUNIOR'.format(idade))
elif idade <=20:
print('Idade: {}\nStautus: SÊNIOR'.format(idade))
else:
print('Idade: {}\nStatus: MASTER'.format(idade))
|
e9eaa840d49350497eb188f3ceada36939b6b97c | aleksvetushko/C-l-P-ly | /cpe101/lab1/vehicle/vehicle_tests.py | 458 | 3.546875 | 4 | import vehicle
import unittest
class VehicleTests(unittest.TestCase):
def test_vehicle(self):
def __init__(self, wheels, fuel, doors, roof):
self.wheels = 4
self.fuel = 10
self.doors = 2
self.roof = 1
self.assertEqual(wheels, 4)
self.assertEqual(fuel, 10)
self.assertEqual(doors, 2)
self.assertEqual(roof, 1)
# Add code here.
# Run the unit tests.
if __name__ == '__main__':
unittest.main()
|
969bd0daa250c4c4ffd5ff8f6db3a59a5547f980 | Aniket-d-d/Sudoku_solver | /backtracksudoku.py | 1,051 | 3.796875 | 4 | def solve(board):
find = find_null_place(board)
if not find:
return True
else:
row, col = find
for num in range(1, 10):
if validate(board, num, row, col):
board[row][col] = num
if solve(board):
return True
board[row][col] = 0
return False
def validate(board, num, row, col):
for i in range(9):
if board[row][i] == num:
return False
for j in range(9):
if board[j][col] == num:
return False
ro = col // 3
co = row // 3
for i in range(co * 3, co * 3 + 3):
for j in range(ro * 3, ro * 3 + 3):
if board[i][j] == num:
return False
return True
def find_null_place(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return i, j
return None
"""
for _ in matrix:
print(_)
solve(matrix)
print()
for _ in matrix:
print(_)
"""
|
c0c5edd464f1ccf6b8f56338ca0b424406108076 | summer-vacation/AlgoExec | /tencent/reverseBits.py | 645 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
File Name: reverseBits
Author : jing
Date: 2020/3/24
https://leetcode-cn.com/problems/reverse-bits/
颠倒二进制位
"""
class Solution:
# bin(n):将十进制数转换为二进制字符串,不过字符串首段有“0b”字符;
# s.rjust(32, '0'):将字符串s补全为长度为32的字符串,s右对齐,不够的地方用字符“0”补全;
# int(x, base=2):将二进制字符串转换为十进制数
def reverseBits(self, n: int) -> int:
return int(bin(n)[2:].rjust(32, '0')[::-1], base=2)
print(Solution().reverseBits(43261596))
|
ad3eb841c4cd1e0fa4bad4dc7beb7d7e4209c319 | andresnsn/TestsLogicPythonSolo | /Soma ímpares múltiplos de 3.py | 562 | 3.6875 | 4 | s = 0
cont = 0
for c in range(1, 501):
if c % 2 != 0:
if c % 3 == 0:
cont = cont + 1
s = s + c
print('A soma de todos os valores ímpares e múltiplos de 3, que são um total de {}, números até 500, é {}'.format(cont, s))
#Nós adicionamos "cont" depois de ver a resolução do Guanabara, como um adicional.
# Neste caso, nós acertamos o exercício, mas o Guanabara propôs que o programa também contasse
# a quantidade de números que o programa encontrou, que atendem as condições, e que foram somados.
|
0d68b2c7eedab501e194de4270cc7780b9480411 | ratthaphong02/Learn_Python_Summer2021 | /KR_Python_Day11_ Function Call Function.py | 376 | 3.6875 | 4 | # ฟังก์ชั่นเรียกฟังก์ชั่น
def equal(x,y,z):
# a = compare(x,y) # ฟังก์ชั่นเรียกฟังก์ชั่น
# b = compare(a,z)
# return b
return compare(compare(x,y),z)
def compare(x,y):
if x > y:
return x
else:
return y
print(equal(10,5,20))
|
7f38864b7f349b70509f6a8b588cbaba9bde5877 | varishtyagi786/My-Projects-Using-Python | /forloop.py | 756 | 3.734375 | 4 | """i=0
while i<=10:
print(i)
i+=1
print('OUT OF THE CODE')
print('**********************************************************************')
i=0
while i<10:
print(i)
i+=1
print('OUT OF THE CODE')
print('**********************************************************************')"""
"""i=1
while i<=10:
print(i*2)
i+=1
print('Rest of the code ')
print('**********************************************************************')
i=2
while i<=20:
print(i)
i+=2
print('Rest of the code')"""
"""
i=2
while i<=2:
print(i)
i+=1
else:
print('Rest of the code ')"""
a=int(input("Enter the value : "))
for i in range(1,11):
print(a,'X',i,'=',a*i)
print('Have a nice day')
print('Have a nice day') |
458488502fddcfadeae26f7b305f5557bd2322f5 | liushaoye/PyWorkSpace | /PythonProJ/2018week1/day004/005_Print_Even.py | 175 | 3.515625 | 4 | # coding=utf-8
print('\n')
print('**********输出100内所有偶数************* \n')
number = 1
while number <= 100:
if number % 2 == 0:
print(number)
number += 1
|
85a42c8b0a40f1e361f37240be71e4b1c5c75371 | raquelmcoelho/python | /Files/questão4.py | 359 | 4.09375 | 4 | """
4.Defina uma variável inteira, um float e um decimal atribuindo valores a cada um deles. Qual a
quantidade de memória utilizada por cada um deles?
"""
from decimal import Decimal
i = 1
f = 1.0
d = Decimal(1)
print("espaço ocupado na memória por um:")
print("int:", i.__sizeof__(), "\nfloat:", f.__sizeof__(), "\ndecimal:", d.__sizeof__())
|
aae0b069de21a27822ce0f9ea0af65ca8b1be391 | Mallikarjunkb/MY-PYTHON-FILES | /test3.py | 122 | 3.515625 | 4 | while temperature,20
print(temperature)
#print temperature
temperature=temperature
print("need coffe")
#prints need coffe
|
3aefb6051c5cbecfa6d0c76f5121214c8e4a3682 | marythought/sea-c34-python | /students/RichardGreen/weekthree/session05/comprehensions.py | 1,142 | 4.5625 | 5 | '''Comprehension functions
Richard Green
Foundations 2 Python'''
# comprehensions
# list comprehension
import string
z = range(0, 10)
y = range(0, 25, 2)
x = range(0, 25)
a = string.lowercase[:26]
def comp_list(z):
'''Question: Using Comprehensions what are the results when the equation
below is applied to a sequence of numbers. Arguments a string with a
range of numbers'''
return [2 * x + 50 for x in z]
# nested list comprehension
def comp_nested_list(x, z):
'''Question: Using Comprehensions and nested loops what are the results of
the equation that uses numbers divisible by 2 in one sequnece are applied
to two sequences of numbers. Arguments two numerical sequences'''
return [i % 2 == 0 for i in x for var in z]
# set comprehension
# Turn a sequence into a set
def set_comp(a):
'''Question: How do we use comprehensions to convert a (string) sequence of
characters to a set? Arguments a sequences of characters'''
new_set = {item for item in a}
return new_set
if __name__ == "__main__":
print comp_list(z)
print comp_nested_list(y, x)
print set_comp(a)
|
3273366e1fccedb4d86f2927ffa39806e8537fc3 | dictator-x/practise_as | /algorithm/leetCode/0301_remove_invalid_parentheses.py | 2,313 | 3.65625 | 4 | """
301. Remove Invalid Parentheses
"""
from typing import List
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
patterns = [["(", ")"], [")", "("]]
ret = []
# remove extra ")"
# then reverse remaining string
# remove extra "("
# if current string is invalid, it will return after remove a char and
# test subString in dfs again.
def dfs(pattern, s, start, lastRemovePosition):
count = 0
n = len(s)
# We garantee that before start is valid in one pattern
for i in range(start, n):
if s[i] == pattern[0]:
count += 1
if s[i] == pattern[1]:
count -= 1
# If count is not >= 0, means current s is not a valid Parentheses
# remove one extra char from string.
# Then sub dfs method will check if remaining string is valid.
if count < 0:
# Can j start from "start" instead of "lastRemovePosition"?
for j in range(lastRemovePosition, i+1):
char = s[j]
print(s)
# Only consider invalid char.
# sequence duplicate string are same, so do not need
# to consider. like "((((" or "))"
if char == pattern[1] and ( j == lastRemovePosition or char != s[j-1] ):
# i will be >=j
dfs(pattern, s[:j] + s[j+1:], i, j)
# We iterate the entire string until we find first unmatch position.
# It is safe to return at the position when we find first unmatch
return
# The code can reach here
# meaning that we have a valid string in one pattern
# We do need to check another pattern.
s = s[::-1]
if pattern == patterns[0]:
dfs(patterns[1], s, 0, 0)
else:
ret.append(s)
dfs(patterns[0], s, 0, 0)
return ret
if __name__ == "__main__":
test_arg1 = "()))"
solution = Solution()
print(solution.removeInvalidParentheses(test_arg1))
|
003c0fb8ad48ff6fb1431938ac78ecea5592bc44 | Gravitar64/Advent-of-Code-2020 | /Tag_23.py | 1,187 | 3.625 | 4 | import time
def read_puzzle(file):
with open(file) as f:
return [int(x) for zeile in f for x in zeile]
def get_three(cups, current):
three_cups = [cups[current]]
for _ in range(2):
three_cups.append(cups[three_cups[-1]])
return three_cups
def solve(puzzle, moves):
maxC, minC = max(puzzle), min(puzzle)
current = puzzle[0]
cups = {a: b for a, b in zip(puzzle, puzzle[1:])}
cups[puzzle[-1]] = puzzle[0]
for _ in range(moves):
three_cups = get_three(cups, current)
label = current-1
while label < minC or label in three_cups:
label -= 1
if label < minC:
label = maxC
cups[current] = cups[three_cups[-1]]
cups[three_cups[-1]] = cups[label]
cups[label] = three_cups[0]
current = cups[current]
if moves == 100:
part1 = str(cups[1])
while part1[-1] != '1':
part1 += str(cups[int(part1[-1])])
return part1[:-1]
else:
return cups[1] * cups[cups[1]]
puzzle = read_puzzle('Tag_23.txt')
start = time.perf_counter()
print(solve(puzzle, 100), time.perf_counter()-start)
start = time.perf_counter()
print(solve(puzzle + list(range(10,1_000_001)), 10_000_000), time.perf_counter()-start)
|
4ccfc06b6b19ad8bb4f560c779de44d770206a93 | OrangeB0lt/holbertonschool-higher_level_programming | /0x03-python-data_structures/9-max_integer.py | 242 | 3.6875 | 4 | #!/usr/bin/python3
def max_integer(my_list=[]):
if len(my_list) is 0:
return None
else:
number = my_list[0]
for index in my_list:
if index > number:
number = index
return number
|
d15d4cde15262b548d5014cc055ac2ede5454693 | roshan13ghimire/Competitive_Programming | /CodeChef/CodeChef_Solution_In_Python/From_heaven_to_earth.py | 223 | 3.671875 | 4 | #From_heaven_to_earth
import math
for _ in range(int(input())):
s = math.sqrt(2)
n , v1 , v2 = map(int,input().split())
if s * v1 * n > v2 * n:
print("Stairs")
else:
print("Elevator") |
3ce40298acda2b9330877f41d182997f37ab0f2b | dioonata/cryPython | /tiposBasicos/VerificandoSeETriangulo.py | 485 | 4 | 4 | a = float(input('Informe o primeiro lado do triângulo: '))
b = float(input('Informe o segundo lado do triângulo : '))
c = float(input('Informe o terceito lado do triângulo: '))
if a < b + c or b < a + c or c < a + b:
if a == b == c:
print('Equilátero')
elif a == b or b == c or a == c:
print('Isósceles')
else:
print('Escaleno')
else:
print('Isso nâo pode ser um triângulo!')
print('Um dos lados e maior que a soma do outro!')
|
2569595cfc3fa16f864038b8ac672a7f504bcbde | NosevichOleksandr/firstrepository | /homework 2.1.py | 118 | 3.6875 | 4 | print('hello world')
a = int(input('enter any number'))
b = int(input('enter zero'))
a2 = 0
c = a and 0 or b
print(c)
|
3f86f9174d044c10a0b2a58d4bbd667978dc19b0 | Trietptm-on-Awesome-Lists/cybersecurity-warplan | /problem_solving/496nextgreater.py | 494 | 3.71875 | 4 | def next_greater(nums1,nums2)
sorted_num2 = nums2
num2_dic = {}
for i in range(0,len(sorted_num2)):
has_greater = -1
for j in range(i,len(sorted_num2)):
if sorted_num2[j] > sorted_num2[i]:
has_greater = sorted_num2[j]
break
num2_dic[sorted_num2[i]] = has_greater
new_arr = []
for num in nums1:
new_arr.append(num2_dic[num])
return new_arr
|
4a20d63ede40372385515a1cdb9af1376073c24f | lucasjurado/Curso-em-Video | /Mundo 3/ex087.py | 556 | 4 | 4 | num = ('zero','um','dois','três','quarto','cinco','seis','sete','oito','nove','dez')
while True:
n = -1
while n <0 or n>10:
n = int(input('Digite um número entre 0 e 10: '))
if n <0 or n>10:
print(f'O valor digitado: {n}, não pertence ao intervalo! Tente novamente.')
if 0 <= n <= 10:
print(f'Você digitou o número {num[n]}.')
again = ' '
while again not in 'SN':
again = str(input('Quer continuar? ')).upper().strip()[0]
if again == 'N':
break
print('Fim do programa!')
|
8bf1f887af92ba134800da78c1751db32a0f719d | hunnble/leetcode | /206_ReverseLinkedList.py | 550 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
Reverse a singly linked list.
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
c, r, head.next = head, head.next, None
while r is not None:
n = r.next
r.next = c
c, r = r, n
return c |
fbd76821e4ddeaec04ef04e621c50e321c7a9f86 | Mrd278/Codeforces_Java | /chef and semi primes.py | 217 | 3.609375 | 4 | def check(a):
c=0
for i in range(1,a):
if a%i==0:
c=int(c+1)
if c==2:
return True
else:
return False
n=int(input())
for i in range(n):
x=int(input())
|
c61df8c498afd37f5cc8025dda100f9090cdd93a | elenameyerson/ToolBox-WordFrequency | /frequency.py | 1,949 | 4.4375 | 4 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
f = open(file_name, 'r')
lines = f.readlines()
curr_line = 0
while lines[curr_line].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1:
curr_line += 1
lines = lines[curr_line+1:]
#print(lines)
wordList = []
for line in lines:
if line in string.whitespace:
lines.remove(line)
else:
words = line.split()
for word in words:
wordList.append(word)
#only uses first 10 lines of book
for line in wordList[0:10]:
index = 0
for word in wordList:
a = word.strip(string.punctuation)
wordList[index] = a.lower()
index += 1;
return wordList
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequentlyoccurring
"""
myDictionary = dict()
for word in word_list:
myDictionary[word] = myDictionary.get(word,0) + 1
inverted = []
for word,number in myDictionary.items():
inverted.append((number,word))
inverted.sort(reverse = True)
return inverted[0:n-1]
if __name__ == "__main__":
print("Running WordFrequency Toolbox")
print(string.whitespace)
print(get_top_n_words(get_word_list('pg32325.txt'),20))
|
38eb5561a6bb930bdb475a769e8bb82b165ef25a | rohitproject123/mypython | /python.py | 4,669 | 3.9375 | 4 | NAME: ROHIT BISWAS
ROLL: 28100119037
SEM: 3rd SEM
YEAR:2nd year
## PROGRAMS ##
1. PYTHON PROGRAM:
1. GCD OF TWO NUMBERS:
code:
def hcf(a, b):
if(b == 0):
return a
else:
return hcf(b, a % b)
a = 60
b = 48
print("The gcd of 60 and 48 is : ", end="")
print(hcf(60, 48))
2. CHECK NUMBER IS PRIME OR NOT:
code:
def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(47))
3.DISPLAY TWIN PRIME USING FUNCTION:
code:
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def generate_twins(start, end):
for i in range(start, end):
j = i + 2
if(is_prime(i) and is_prime(j)):
print("{:d} and {:d}".format(i, j))
generate_twins(1,20)
4.NOT FABONACCI NUMBER
code:
def isPerfectSquare(x):
s = sqrt(x)
return (s * s == x)
def isFibonacci(N):
return isPerfectSquare(5 * N * N + 4) or \
isPerfectSquare(5 * N * N - 4)
def nextNonFibonacci(N):
if (N <= 3):
return 4
if (isFibonacci(N + 1)):
return N + 2
else:
return N
if __name__ == '__main__':
N = 3
print(nextNonFibonacci(N))
N = 4
print(nextNonFibonacci(N))
N = 7
print(nextNonFibonacci(N))
5. CHECK KRISHNAMURTI NUMBER:
code:
def factorial(n) :
fact = 1
while (n != 0) :
fact = fact * n
n = n - 1
return fact
def isKrishnamurthy(n) :
sum = 0
temp = n
while (temp != 0) :
rem = temp%10
sum = sum + factorial(rem)
temp = temp // 10
return (sum == n)
n = 145
if (isKrishnamurthy(n)) :
print("YES")
else :
print("NO")
6. PALINDROME NUMBER CHECKING:
CODE:
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
7.CHECK HOW MANY NON ZERO NUMBER IN A NUMBER
CODE:
def Counting(number):
Count = 0
while(number>0):
r= number%10
if(r!=0):
Count = Count+1
number = number//10
return Count
number=int(input("ENTER ANY NUMBER")
Count= Counting(number)
print("Number of Digits in given number = %d" %Count)
8. CHECKING OF PERFECT NUMBER
code:
def perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
print(perfect_number(7))
9. A POWER M
code
def power(base,exp):
if(exp==1)
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input(Enter base: ")
exp=int(int(intput("enter exp value: "
print("Result: ",power(base,exp))
10.CALCULATE FACTOR OF A NUMBER
code:
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = 120
print_factors(num)
11.ARMSTRONG NUMBER CHECKING
code:
def getSum (num):
if num=0:
return num
else:
return num
else:
return pow ((num%10), order) +get Sum (num//10)
num=int (input (“Enter a number :”))
order=len (str (num))
sum=getSum (num)
if sum=int (num):
print(num,”is an Armstrong Number.”)
else:
print(num,”is not an Armstrong Number.”)
12.FIBONACCI SERIES
code:
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
13. LUCAS NO
code:
def lucas(n):
if n==0:
return 2
if n==1:
return 1
return lucas(n-1) + lucas(n-2)
print(lucas(5))
14.PATTERN TYPE (RIGHT TRIANGLE)
code:
def binaryRightAngleTriangle(n):
for row in range(0, n):
for col in range(0, row + 1):
if (((row + col) % 2) == 0) :
print("0", end = "")
else:
print("1", end = "")
print("\t", end = "")
print("")
n = 4
binaryRightAngleTriangle(n)
15. PATTERN TYPE(SQUARE WITH DIAGONAL)
code:
def pattern(n) :
for i in range(0 , n) :
for j in range(0 , n) :
if (i == 0 or j == 0 or i == j
or i == n - 1 or j == n - 1
or i + j == n - 1) :
print( "*", end="")
else :
print(" ",end="")
print("")
n = 5
pattern(n)
THAT'S MY PRESENTATION
|
323d9e9d2e6671c2381c1dfcab17d2c78d9084f6 | kchaudhuri/Python | /dtb.py | 490 | 3.90625 | 4 | binList = []
binary=0
dec=input("enter the decimal > ")
n=0
while ((2**n) < dec):
n=n+1
msb = n-1
for var in range(msb,0,-1):
if (dec > (2**var)) or (dec == (2**var)):
dec = (dec - (2**var))
print 1
binary = ((binary + 1) * 10)
binList.append(1)
else:
print 0
binary = (binary * 10)
binList.append(0)
final = binary/10
print "the equialent binary is {0}".format(final)
##binList = list(final)
print binList
raw_input()
|
e11723178012aaf74ecd2aecddd9d7024af813f2 | Programacion-Algoritmos-18-2/trabajo-opcional-1er-bim-CarlosCastillo10 | /pregunta2/ejecutora.py | 1,467 | 3.5 | 4 | #Autor: Carlos Castillo
# Importamos todo de las 2 clases
from personal_academico.modelo import *
from sector_estudiantil.modelo2 import *
nombre_alumno = input("\nIngrese el nombre del estudiante: ")# Guarda el nombre del alumno
# Datos del docente de Matematicas
print("\nDatos del docente de Matematicas")
nombre_docente = input(("\n\tNombre: ")) # Guarda el nombre del docente de matematicas
apellido_docente = input(("\tApellido: "))# Guarda el apellido del docente de matematicas.
titulo = input("\tTitulo: ")# Guarda el titulo del docente de matematicas
# Crea el objeto de tipo docente y envia los parametros del constructor
d1 = Docente(nombre_docente,apellido_docente,titulo)
# Datos del docente de sociales
print("\nDatos del docente de Sociales")
nombre_docente = input(("\n\tNombre: ")) # Guarda el nombre del docente de sociales
apellido_docente = input(("\tApellido: "))# Guarda el apellido del docente de sociales
titulo = input("\tTitulo: ")# Guarda el titulo del docente de sociales
# Crea el objeto de tipo docente y envia los parametros del constructor
d2 = Docente(nombre_docente,apellido_docente,titulo)
# Crea el objeto de tipo alumno.
a1 = Alumno(nombre_alumno,d1,d2)
print("\n%20s\n%s\n\tDocente Matematicas\n%s\n\n\tDocente Sociales\n%s\n\n"%("REPORTE",a1.presentar_datos()
,d1.presentar_datos(),d2.presentar_datos()))# Presenta en pantalla los datos. |
0393473b34887ba5293c335cb6b32cfa947b1ac3 | basilije/CIS104 | /H2P1.py | 641 | 4.25 | 4 | human_age = input("Enter your age: ") # Ask user for their age
human_age_after_ten_years = human_age + 10 # Calculate the age after ten years
print("In ten years you will be %i years old." % human_age_after_ten_years) # Print the calculated age
temperature_in_degrees_fahrenheit = input("Enter temperature in degrees Fahrenheit: ") # Ask user for the temperature in degrees Fahrenheit
temperature_in_degrees_celsius = (temperature_in_degrees_fahrenheit - 32 ) * 5. / 9. # Calculate the temperature in degrees Celsius
print("It is %3.1f in degrees Celsius." % temperature_in_degrees_celsius) # Print the temperature in degrees Celsius
|
6e3d64b2c84e8068d2f6702371bec9cefdc48d62 | huragok/Practice | /Tim_Wilson/Guessing game/Guessing_game.py | 1,106 | 3.90625 | 4 | #! /usr/bin/env python3
import random
def get_int(msg):
while True:
try:
x = int(input(msg))
if x < 1 or x > 100:
raise ValueError("You need to guess a number between 1 and 100!")
return x
except ValueError as err:
print(err)
class Guessing_game:
def __init__(self):
self.right_number = random.randint(1, 100)
self.last_guess = None
self.count_guess = 0
print("Time to play a guessing game.\n")
def run(self):
while self.last_guess != self.right_number:
if self.count_guess == 0:
self.last_guess = get_int("Enter a number between 1 and 100: ")
elif self.last_guess > self.right_number:
self.last_guess = get_int("Too high. Try again: ")
else:
self.last_guess = get_int("Too low. Try again: ")
self.count_guess += 1
print("\nCongratulations! You got it in {0} guesses".format(self.count_guess))
if __name__ == "__main__":
Guessing_game().run()
|
ca02a9bfed4eb5977f78caecebb339ef87d775ff | never-finished/spaceGame | /enemies.py | 1,382 | 3.609375 | 4 | import pygame
from pygame.sprite import Sprite
class Enemy(Sprite):
def __init__(self, s1, screen):
super(Enemy, self).__init__()
self.screen = screen
self.s1 = s1
self.image = pygame.image.load("UFO.bmp")
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#sets starting position
self.rect.x = self.rect.width
self.x = float(self.rect.x)
self.rect.y = self.rect.height
self.y = float(self.rect.y)
#sets up a movement flag so if true we move, default to false
self.moving_right = True
self.moving_left = False
def update(self):
#moves ship if the flag is true and if we aren't going off the screen
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x += self.s1.enemy_speed
else:
self.moving_right = False
self.moving_left = True
if self.moving_left and self.rect.left > 0:
self.x -= self.s1.enemy_speed
else:
self.moving_right = True
self.moving_left = False
self.y += self.s1.alien_descent
self.rect.x = self.x
self.rect.y = self.y
def blitme(self):
self.screen.blit(self.image, self.rect)
|
089ebdac1def1a3ace503063c47c834eca6f33fb | Reboare/Euler | /001/Euler1.py | 160 | 3.734375 | 4 | def main():
summation = 0
for i in xrange(1, 1000):
if i % 3 == 0 or i % 5 == 0:
summation += i
return summation
print(main()) |
dab069e9cebe7a3eea57741f29ce41af88baf7f3 | arlin13/LearningPython | /ImportingModules/FootballPlayer.py | 453 | 3.515625 | 4 | from Player import *
class FootballPlayer(Player):
is_offense = None
def __init__(self, name, last_name, is_offense):
self.name = name
self.last_name = last_name
self.is_offense = is_offense
def get_sport(self):
return "Football"
def is_offense(self):
return self.is_offense
def get_type_of_player(self):
return "Type of player: " + ("Offense" if self.is_offense else "Defense")
|
77249768f3b5c0962a9b0bf83d70a0815354fb6e | wassname/pysle | /test/dictionary_search.py | 1,926 | 3.671875 | 4 | #encoding: utf-8
'''
Created on July 08, 2016
@author: tmahrt
Basic examples of common usage.
'''
import random
from pysle import isletool
tmpPath = r"C:\Users\Tim\Dropbox\workspace\pysle\test\ISLEdict.txt"
isleDict = isletool.LexicalTool(tmpPath)
def printOutMatches(matchStr, numSyllables=None, wordInitial='ok',
wordFinal='ok', spanSyllable='ok', stressedSyllable='ok',
multiword='ok', numMatches=None, matchList=None):
if matchList is None:
matchList = isleDict.search(matchStr, numSyllables, wordInitial,
wordFinal, spanSyllable, stressedSyllable,
multiword)
else:
matchList = isletool.search(matchList, matchStr, numSyllables, wordInitial,
wordFinal, spanSyllable, stressedSyllable,
multiword)
if numMatches is not None and len(matchList) > numMatches:
random.shuffle(matchList)
for i, matchTuple in enumerate(matchList):
if numMatches is not None and i > numMatches:
break
word, pronList = matchTuple
print("%s: %s" % (word, ",".join(pronList)))
print("")
return matchList
# 2-syllable words with a stressed syllable containing 'dV' but not word initially
printOutMatches("dV", stressedSyllable="only", spanSyllable="no",
wordInitial="no", numSyllables=2, numMatches=10)
# 3-syllable word with an 'ld' sequence that spans a syllable boundary
printOutMatches("lBd", wordInitial="no", multiword='no',
numSyllables=3, numMatches=10)
# words ending in 'inth'
matchList = printOutMatches(u"ɪnɵ", wordFinal="only", numMatches=10)
# that also start with 's'
matchList = printOutMatches("s", wordInitial="only", numMatches=10,
matchList=matchList, multiword="no")
|
c12adede42da33c9dcd0bdfd8f9ea03ebe0f493f | vlvs/pratusevich-exercises | /07_list_comprehensions.py | 421 | 4.25 | 4 | '''
Write one line of Python that takes a previsouly generated random list
and makes a new list that has only the even elements of the random list.
'''
import random
random_list = random.sample(range(100), random.randint(0, 30))
even_list = [number for number in random_list if number % 2 == 0]
print(f'''
The random list:\n{sorted(random_list)}
The list containing only its even elements:\n{sorted(even_list)}
''')
|
5a7a9dac5e7d91fdee3d657cec4b5ea3b00006b2 | mishra-aayush/snake-turtle | /snakefg.py | 1,810 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 19 21:34:14 2020
Snake game using the turtle module
@author: AAYUSH MISHRA
"""
from random import *
import turtle as t
from freegames import square, vector
t.title("Snake")
root = t.Screen()._root
t.bgcolor('#111111')
food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)
def change(x, y):
aim.x = x
aim.y = y
def inside(head):
return -200 < head.x < 190 and -200 < head.y < 190
def move():
head = snake[-1].copy()
if len(snake) > 1:
headnext = snake[-2].copy()
if head.x-headnext.x > 0 and aim.x < 0:
aim.x = 10
elif head.x-headnext.x < 0 and aim.x > 0:
aim.x = -10
elif head.y-headnext.y > 0 and aim.y < 0:
aim.y = 10
elif head.y-headnext.y < 0 and aim.y > 0:
aim.y = -10
head.move(aim)
if not inside(head) or head in snake:
square(head.x, head.y, 9, '#FFDC00')
square(0, 0, 9, '#111111')
t.update()
t.color('white')
style = ('Arial', 30, 'bold')
t.write('Score: '+ str(len(snake)-1), font=style, align='center')
return
snake.append(head)
if head == food:
food.x = randrange(-15, 15) * 10
food.y = randrange(-15, 15) * 10
else:
snake.pop(0)
t.clear()
for body in snake:
square(body.x, body.y, 9, '#c7291e')
square(food.x, food.y, 9, '#2ECC40')
t.update()
t.ontimer(move, 100)
t.setup(420, 420, 370, 0)
t.hideturtle()
t.tracer(False)
t.listen()
t.onkey(lambda: change(10, 0), 'Right')
t.onkey(lambda: change(-10, 0), 'Left')
t.onkey(lambda: change(0, 10), 'Up')
t.onkey(lambda: change(0, -10), 'Down')
move()
t.done() |
fae5ed2ce82191cc541a49c6afbf4bd9712c41e3 | jfriend08/LeetCode | /MaximumProductofWordLengths.py | 1,349 | 3.921875 | 4 | '''
Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Example 1:
Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn".
Example 2:
Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd".
Example 3:
Given ["a", "aa", "aaa", "aaaa"]
Return 0
No such pair of words.
'''
import sys
class Solution(object):
def getNoInterLetters(self, intersect, word):
result = []
for w in word:
if w not in intersect:
result.append(w)
return result
def maxProduct(self, words):
maxProduct = -sys.maxint-1
for i in xrange(0, len(words)-1):
for j in xrange(i, len(words)):
word1, word2 = words[i], words[j]
intersect = set([w for w in word1]) & set([w for w in word2])
maxProduct = max(maxProduct, len(self.getNoInterLetters(intersect, word1)) * len(self.getNoInterLetters(intersect, word2)))
return maxProduct
sol = Solution()
print sol.maxProduct(["abcw", "baz", "foo", "bar", "xtfn", "abcdef"])
print sol.maxProduct(["a", "ab", "abc", "d", "cd", "bcd", "abcd"])
print sol.maxProduct(["a", "aa", "aaa", "aaaa"])
|
25e8b53215ccfe7b7a39ae22903f5b0b6fc33c8e | binarics/Noughts-Crosses | /noughts_and_crosses.py | 4,245 | 3.5 | 4 | import random
# Global variables
winner = None
player = ' X '
board = [' - ' for x in range(9)]
win_combinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]]
semi_positions = [[0, 1, 2], [0, 2, 1], [1, 2, 0],
[3, 4, 5], [3, 5, 4], [4, 5, 3],
[6, 7, 8], [6, 8, 7], [7, 8, 6],
[0, 3, 6], [0, 6, 3], [3, 6, 0],
[1, 4, 7], [1, 7, 4], [4, 7, 1],
[2, 5, 8], [2, 8, 5], [5, 8, 2],
[0, 4, 8], [0, 8, 4], [4, 8, 0],
[2, 4, 6], [2, 6, 4], [4, 6, 2]]
# display the game board
def display_board():
print(board[0] + '|' + board[1] + '|' + board[2])
print(board[3] + '|' + board[4] + '|' + board[5])
print(board[6] + '|' + board[7] + '|' + board[8])
# validate and play the turn of the current player
def play_a_turn():
print(player + "'s turn")
move = input("Where do you want to make a move? (1-9): ")
while move not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
print("Invalid input")
move = input("Where do you want to make a move? (1-9): ")
move = int(move) - 1
while True:
if board[move] == " X " or board[move] == " O ":
print("invalid move, try again")
print(player + "'s turn")
move = input("Where do you want to make a move? (1-9): ")
move = int(move) - 1
continue
else:
board[move] = player
break
# AI for the computer to play a turn
def computers_turn():
possiblemoves = [iterat for iterat, mov in enumerate(board) if mov == ' - ']
semis = []
for i, h, r in semi_positions:
if board[i] == ' O ' and board[h] == ' O ':
if board[r] == ' - ':
semis.append(r)
elif board[i] == ' X ' and board[h] == ' X ':
if board[r] == ' - ':
semis.append(r)
if len(semis) > 0:
move = semis[(random.randrange(len(semis)))]
board[move] = player
else:
corner_moves = []
for i in possiblemoves:
if i in [0, 2, 6, 8]:
corner_moves.append(i)
if len(corner_moves) > 0:
move = corner_moves[(random.randrange(len(corner_moves)))]
board[move] = player
else:
edge_moves = []
for i in possiblemoves:
if i in [1, 3, 5, 7]:
edge_moves.append(i)
if len(edge_moves) > 0:
move = edge_moves[(random.randrange(len(edge_moves)))]
board[move] = player
# change the player
def change_player():
global player
if player == " X ":
player = " O "
elif player == " O ":
player = " X "
# check if there is a winner or a tie
def check_for_win():
global winner
for i, h, r in win_combinations:
if board[i] == board[h] == board[r] != " - ":
winner = board[i]
if winner == " X " or winner == " O ":
display_board()
print(winner + "won!")
stop_game()
else:
check_for_tie()
def check_for_tie():
global winner
if ' - ' not in board:
winner = " "
display_board()
print("it's a tie")
stop_game()
def stop_game():
global winner, player
while True:
playagain = input("Play again? (y/n) ")
if playagain.lower() == "y":
for i in range(len(board)):
board[i] = ' - '
break
elif playagain.lower() == "n":
exit()
elif playagain not in ("y", "n"):
continue
winner = None
player = ' X '
play_the_game()
# run the entire game
def play_the_game():
global winner
players_1or2 = input("1 Player or 2 Players? (1/2) ")
while players_1or2 not in ("1", "2"):
players_1or2 = input("try again")
while winner is None:
display_board()
play_a_turn()
check_for_win()
change_player()
if int(players_1or2) == 1:
computers_turn()
check_for_win()
change_player()
play_the_game()
|
a1de15902a9f89a9e3fe5755e4aeb59bc02a714e | saubhik/leetcode | /problems/add_and_search_word_data_structure_design.py | 1,632 | 3.765625 | 4 | import re
class WordDictionary:
# This leads to TLE
def __init__(self):
"""
Initialize your data structure here.
"""
self.words = []
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
self.words.append(word)
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot
character '.' to represent any one letter.
"""
for wd in self.words:
if re.compile(pattern=word).fullmatch(wd):
return True
return False
class WordDictionaryTwo:
def __init__(self):
self.trie = {"_root": dict()}
def addWord(self, word: str) -> None:
dic = self.trie.get("_root")
for ch in word:
dic = dic.setdefault(ch, dict())
dic["_end"] = "_end"
def search(self, word: str, dic: dict = None) -> bool:
if dic is None:
dic = self.trie.get("_root")
for i, wd in enumerate(word):
if wd == ".":
for ch in dic:
if ch != "_end" and self.search(
word=word[i + 1 :], dic=dic.get(ch)
):
return True
return False
else:
if wd not in dic:
return False
dic = dic[wd]
return "_end" in dic
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
|
a9ca3e0c3788acf313df682f81d0827c1509943f | vangaru/labs | /DM labs/lab 2/src/main.py | 1,347 | 3.609375 | 4 | #ОТНОШЕНИЯ
import funcs
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
R1 = funcs.get_R1(A)
R2 = funcs.get_R2(A)
#ЗАДАНИЕ 1
print("МАТРИЦА ОТНОШЕНИЙ R1")
print(funcs.matrix_build(R1, A))
print("МАТРИЦА ОТНОШЕНИЙ R2")
print(funcs.matrix_build(R2, A))
print("ОБРАТНОЕ ОТНОШЕНИЕ R1")
print(funcs.get_inverse_relation(R1))
print("ОБРАТНОЕ ОТНОШЕНИЕ R2")
print(funcs.get_inverse_relation(R2))
print("ДОПОЛНЕНИЕ ОТНОШЕНИЯ R1")
print(funcs.get_relation_addition(A, R1))
print("ДОПОЛНЕНИЕ ОТНОШЕНИЯ R2")
print(funcs.get_relation_addition(A, R2))
print("ТРАНЗИТИВНОЕ ЗАМЫКАНИЕ ОТНОШЕНИЯ R2")
print(funcs.get_transitive_closure(matrix = funcs.matrix_build(R2, A)))
print("КОМПОЗИЦИЯ ОТНОШЕНИЙ R1 И R2")
print(funcs.attitudes_composition([[1, 4], [5, 2], [6, 3], [4, 5]], [[4, 5], [3, 5], [5, 1], [3, 5]]))
print("КОМПОЗИЦИЯ ОТНОШЕНИЙ R2 И R1")
print(funcs.attitudes_composition([[4, 5], [3, 5], [5, 1], [3, 5]], [[1, 4], [5, 2], [6, 3], [4, 5]]))
#ФУНКЦИИ
#ЗАДАНИЕ 1
B = [1, 2, 3, 4]
C = [5, 6, 7]
S = [[1, 5], [2, 7], [4, 7], [3, 6]]
print("ЯВЛЯЕТСЯ ЛИ ОТНОШЕНИЕ S ФУНКЦИЕЙ")
funcs.func_type(B, C, S)
print(1 & 0)
|
7da73a6879390b306e1040bcbb5b1c2d5a8dd1ba | sundaygeek/book-python-data-minning | /code/2/2-4-5.py | 180 | 3.671875 | 4 | # -*- coding:utf-8 -*-
print('''创建集合''')
set1 = {1,2,3} # 直接创建集合
set2 = set([2,3,4]) # set()创建
print(set1,set2)
# result: set([1, 2, 3]) set([2, 3, 4])
|
b4fa1ead8ca2895949ef36642bb18c818a755774 | AbbyDebell/PythonChallenges | /inputspy.py | 536 | 4.15625 | 4 | name = input("Enter your name: ")
print("Your name is " + name)
# DOB = int(input("Enter the year you were born "))
# print(DOB)
DOB = str(input("Enter your date of birth dd/mm/yyyy/"))
if len(DOB) == 10:
print("Your date of birth is " + DOB)
else:
print("This is not the correct format, please retry")
year = DOB[6:11]
print(year)
thisYear = 2018
age = thisYear - int(year)
print("You are "+ str(age) + " years old")
#if 10 > 6:
# print("Your date of birth is " + DOB)
# else:
# print("This is not the correct format")
|
889e0d8b43b01a555307d41639e99a07c6021cce | BhushanTayade88/Core-Python | /phoneno.py | 490 | 3.609375 | 4 | import random
def phoneno():
first = str(random.randint(777, 999))
second = str(random.randint(0, 999))
last = str(random.randint(0, 9998))
return '{}{}{}'.format(first, second, last)
n = int(input("Enter Value of n: "))
for i in range(0, n):
print(phoneno())
def phn():
n = '0000000000'
while '9' in n[3:6] or n[3:6]=='000' or n[6]==n[7]==n[8]==n[9]:
n = str(random.randint(10**9, 10**10-1))
return n[:3] + '-' + n[3:6] + '-' + n[6:]
print(phn())
|
518fae19f30c7f085e6eddadd115f5073a095b9b | katherine0325/machine_learning | /KNN/index.py | 342 | 3.5625 | 4 | # -*- coding: UTF-8 -*-
import numpy as np
import sklearn
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
X_train = np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
Y_train = ['A','A','B','B']
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train, Y_train)
result = knn.predict([[5,0],[4,0]])
print(result) |
db3bedf7e0eb9165514e990b4d891efcb41c4cc9 | southpawgeek/perlweeklychallenge-club | /challenge-109/abigail/python/ch-2.py | 2,310 | 3.578125 | 4 | #!/opt/local/bin/python
#
# See ../README.md
#
#
# Run as: python ch-2.py < input-file
#
import fileinput
SIZE = 7
fmt = "{:d} {:d} {:d} {:d} {:d} {:d} {:d}"
#
# Brute forcing all possiblities, with an early return
#
for line in fileinput . input ():
numbers = list (map (lambda x: int (x), line . split ()))
for a_i in range (0, SIZE):
for b_i in range (0, SIZE):
if a_i == b_i:
continue
target = numbers [a_i] + numbers [b_i]
for c_i in range (0, SIZE):
if c_i == a_i or c_i == b_i:
continue
for d_i in range (0, SIZE):
if d_i == a_i or d_i == b_i or d_i == c_i:
continue
if target != numbers [b_i] + numbers [c_i] + numbers [d_i]:
continue
for e_i in range (0, SIZE):
if e_i == a_i or e_i == b_i or e_i == c_i or \
e_i == d_i:
continue
for f_i in range (0, SIZE):
if f_i == a_i or f_i == b_i or f_i == c_i or \
f_i == d_i or f_i == e_i:
continue
if target != numbers [d_i] + numbers [e_i] + \
numbers [f_i]:
continue
for g_i in range (0, SIZE):
if g_i == a_i or g_i == b_i or g_i == c_i or \
g_i == d_i or g_i == e_i or g_i == f_i:
continue
if target != numbers [f_i] + numbers [g_i]:
continue
print (fmt . format (numbers [a_i],
numbers [b_i],
numbers [c_i],
numbers [d_i],
numbers [e_i],
numbers [f_i],
numbers [g_i]))
|
b0cfd019e06d0ebb5af1561236faabe92ae5d4b1 | rmahsem/AnalysisDatasetManager | /modifySets.py | 6,594 | 3.546875 | 4 | #!/usr/bin/env python
import os
import json
import argparse
from modifyHelper import *
"""
Weird code I wrote to set global variables of analysis etc.
Call the ana(), sel(), inp() and it takes care of finding choices
and picking a choice
TODO: allow ability to add ana, sel, inp, etc
"""
Analysis=""
InputTier=""
Selection=""
def ana():
global Analysis
if Analysis != "":
return Analysis
else:
anaList = getAnalysis()
if len(anaList) == 0:
print "Can't find analysis!"
exit(0)
elif len(anaList) == 1:
Analysis = anaList[0]
else:
Analysis = menu("Choose an Analysis to Modify", anaList)
return Analysis
def inp():
global InputTier
if InputTier != "":
return InputTier
else:
inputList = getInputs(ana())
if len(inputList) == 0:
print "Can't find InputTier!"
exit(0)
elif len(inputList) == 1:
InputTier = inputList[0]
else:
InputTier = menu("Choose an InputTier to Modify", inputList)
return InputTier
def sel():
global Selection
if Selection != "":
return Selection
else:
selList = getSelections(ana())
if len(selList) == 0:
print "Can't find selection!"
exit(0)
elif len(selList) == 1:
Selection = selList[0]
else:
Selection = menu("Choose an Selection to Modify", selList)
return Selection
def menu(beginText, lister):
"""
Takes list of options and print text and chooses one of those options
Does all of the checking that it's a valid choice so it return only
good options
"""
print beginText
returnText = ""
half = int((len(lister)+1)/2)
for i in xrange(int((len(lister))/2)):
print "%2s: %-25s %2s: %-25s" % (i+1, lister[i], i+half+1, lister[i+half])
if len(lister) % 2 == 1:
print "%2s: %-25s" % (half, lister[half-1])
ans=True
while ans:
ans=raw_input("$ ")
try:
choice = int(ans)
if choice <= len(lister) and choice > 0:
returnText = lister[choice-1]
break
else:
print("\nNot Valid Choice Try again")
except ValueError:
print("\nNot Valid Choice Try again")
print
return returnText
#################################################################
# Main functions used for setting up Adding things to the files #
# based on the names in the main menu. #
# NOTE: capital "Add" used to note this is a menu option #
#################################################################
def AddHistogram(ana, sel):
inpVars = []
questions = ["What is the Name of the Histogram: ",
"What is the Number of bins: ",
"What is the low value: ",
"What is the high value: ",
"What is the X Axis Name: ",
"What is the Y Axis Name: ",
]
for q in questions:
try:
answer = raw_input(q)
except SyntaxError:
answer = ""
inpVars.append(answer)
addPlotObject(ana, sel, inpVars)
def AddFile(ana, inp, file_path):
#### to do
groups=getGroups(ana)
groups.append("New Group")
group_choice = menu("Which group will this go with?", groups)
if group_choice == "New Group":
group_choice = raw_input("What is abbreviated name of the Group: ")
addPlotGroup(ana, group_choice)
print
mcList = getMCNames()
mcList.sort()
mcList.append("New Name")
mc_choice = menu("What do you want to name it", mcList)
if mc_choice == "New Name":
mc_choice = raw_input("What do you want the new Name to be: ")
addMCItem(mc_choice)
print
addFileInfo(ana, inp, mc_choice, group_choice, file_path)
addMember(ana, group_choice, mc_choice)
return
############################
# ___ ___ ___ __ __ __ #
# ||\\//|| // \\ || ||\ || #
# || \/ || ||=|| || ||\\|| #
# || || || || || || \|| #
############################
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--selection", type=str, default="",
help="Name of selection to make, "
" as defined in Cuts/<analysis>/<selection>.json")
parser.add_argument("-a", "--analysis", type=str, required=False, default="",
help="Analysis name, used in selecting the cut json")
parser.add_argument("-i", "--input_tier", type=str, default="",required=False)
parser.add_argument("--AddFile", type=str, default="",
help="Go straight to AddFile and add filename given")
parser.add_argument("--AddHistogram", action='store_true',
help="Go straight to AddHistogram and add filename given")
args = parser.parse_args()
Analysis = args.analysis
Selection = args.selection
InputTier = args.input_tier
if args.AddFile:
AddFile(ana(), inp(), args.AddFile)
exit(0)
elif args.AddHistogram:
AddHistogram(ana(), sel())
exit(0)
#############
# Main Menu #
#############
actionList = ["Add a File", "Add a Histogram", "List Data", "List MC", "List Histograms", "Quit"]
while True:
action = menu("What action do you want to do?", actionList)
# Add a file
if action == "Add a File":
file_path=raw_input("What is the File Path: ")
AddFile(ana(), inp(), file_path)
# Add a Histogram
elif action == "Add a Histogram":
AddHistogram(ana(), sel())
# List Data
elif action == "List Data":
files = getFiles(ana(), inp())
for val in files:
if "data" in val:
print val
print
# List MC
elif action == "List MC":
files = getFiles(ana(), inp())
for val in files:
if "data" not in val:
print val
print
# List Histograms
elif action == "List Histograms":
hists = getHistograms(ana(), sel())
hists.append("END")
while True:
histChoice = menu("Look at histogram info? (END to return to menu)", hists)
if histChoice == hists[-1]:
break
else:
print json.dumps(getHistogramInfo(Analysis, Selection, histChoice), indent=2)
print
# Quit
elif action == actionList[-1]:
print actionList[-1]
break
|
32a7a043dd8f92557c2144077bd70bbb836f3b74 | sriharsha004/LeetCode | /Tree/Leetcode 426. Convert Binary Search Tree to Sorted Doubly Linked List.py | 533 | 3.640625 | 4 | class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root:
return None
dummy = Node(-1)
pre = dummy
stack = []
while stack or root:
while root:
stack.append(root)
root = root.left
cur = stack.pop()
pre.right = cur
cur.left = pre
pre = cur
root = cur.right
head = dummy.right
head.left = pre
pre.right = head
return head |
392ec1ebd25742be61cd1642def6aebfcc082c28 | Jevon211/Python-Exercise | /dict-selection hal153.py | 696 | 3.546875 | 4 | from __future__ import print_function
# mendefinisikan fungsi tambah()
def tambah (a, b):
return a + b
# fungsi kurang()
def kurang (a, b):
return a - b
# fungsi kali()
def kali (a, b):
return a * b
# fungsi bagi()
def bagi (a, b):
return a / b
def main():
a = float(raw_input("Masukkan bilangan ke-1: "))
b = float(raw_input("Masukkan bilangan ke-2: "))
op = raw_input("Masukkan operator : ")
# membuat dictionary yang nilainya berupa fungsi
d = {
'+' : tambah (a, b),
'-' : kurang (a, b),
'x' : kali (a, b),
':' : bagi (a,b)
}
print("\n%f %s %f = %f" % (a, op, b , d[op]))
if __name__ == "__main__":
main() |
9c811234b49a56b44b13ebcc6105a7d3c3b9fec4 | Kronooooo/Codewars-projects | /rgb to hex.py | 254 | 3.515625 | 4 | def rgb(r: int, g: int, b: int):
out = ''
for x in [r, g, b]:
if x <= 0:
out += '00'
elif x >= 255:
out += 'FF'
else:
out += f'{hex(x)[2:]:>02}'
return out.upper() |
876de5f60fe378f0c5025b8af6332290068d61a4 | YLyeliang/now_leet_code_practice | /tree/diameter_of_binary_tree.py | 1,293 | 4.34375 | 4 | # Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
#
# Example:
# Given a binary tree
# 1
# / \
# 2 3
# / \
# 4 5
# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
#
# Note: The length of path between two nodes is represented by the number of edges between them.
# 分析:这个题目要求的是找到任意两个节点的最长路径。
# 先分析一下,对于每一个节点,它的最长路径=左子树最长路径+右子树最长路径,比如,值为2的节点,其最长路径为4-2-5,左右子树长度均为1.其最长为=1+1
# 比如值为1的节点,长度=2+1=3。
# 这样,就可以在遍历的时候,依次计算每个节点的长度,并取最大值得到最终的结果。
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.ans = 0
def depth(p):
if not p: return 0
left, right = depth(p.left), depth(p.right)
self.ans = max(self.ans, left + right)
return 1 + max(left, right)
depth(root)
return self.ans
|
9314fa31544966c824910499f4976becbfaecbd3 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/ian_letourneau/Lesson03/strformat_lab.py | 1,816 | 4.3125 | 4 | ## Ian Letourneau
## 5/2/2018
## A script to run multiple tasks utilizing string formatting
#Task One: Utilize string formatting to print a string in a specific output format
print ('file{:0>3} : {:.2f}, {:.2e}, {:.2e}'.format(2, 123.4567, 10000, 12345.67))
#Task Two: Utilize string formatting to print the string from Task One using keywords
print ('file{:{pad}} : {:{flt}}, {:{science}}, {:{science}}'.format(2, 123.4567, 10000, 12345.67, pad='0>3', flt='.2f', science='.2e'))
#Task Three: Utilize string formatting to run a function that returns a formatted string from a tuple of unspecified length
def formatter(t):
fstring = "the " + str(len(t)) + " numbers are:"
for i in range(0,len(t)):
fstring += " {:d}"
if i < len(t)-1:
fstring += ","
return (fstring.format(*t))
#Task Four: Utilize indexes to format and print a string from an unordered tuple
print ('{3:0>2}, {4}, {2}, {0:0>2}, {1}'.format(4, 30, 2017, 2, 27))
#Task Five: Utilize fstrings to format string and then apply string operations and print new string
things = ['orange', 1.3, 'lemon', 1.1]
print(f"The weight of an {things[0]} is {things[1]} and the weight of a {things[2]} is {things[3]}")
print(f"The weight of an {things[0].upper()} is {(things[1]*1.2)} and the weight of a {things[2].upper()} is {(things[3]*1.2)}")
#Task Six: Print a neat, aligned table with varying length names and numbers. Extra task, print a 10 item tuple using one short formatting line.
name = ['Jimmy', 'Joe', 'Barb']
age = [22, 33, 44]
cost = [67, 448, 1098]
print ('{:<10}{:<10}{:<10}'.format('Name', 'Age', 'Cost'))
for i in range(0,len(name)):
print ('{:<10}{:<10}{:<10}'.format(name[i], age[i], cost[i]))
extra_tuple = (23, 45, 678, 2, 1166, 79, 90, 901, 546, 10)
print (("{:<5}"*10).format(*extra_tuple))
|
bfc9a9648427103d5c5ba0bf170dde3f1d050270 | usmanity/practice | /python/fib.py | 233 | 4.09375 | 4 | #!/usr/local/bin/python
def fib1(n):
if n == 1 or n == 2:
return 1
return fib1(n-1) + fib1(n-2)
userInput = input("How many fibonacci steps do you want to take? ")
for i in range(1, userInput):
print (fib1(i))
|
6067143cd16288595dd193504177eca69e1549f0 | chris-peng-1244/python-quiz | /sunset_views.py | 462 | 3.796875 | 4 | def sunset_views(buildings):
views = 0
highest = 0
buildings.reverse()
for building in buildings:
if building > highest:
views += 1
highest = building
return views
def sunset_views_left(buildings):
views = []
for building in buildings:
while views and views[-1] <= building:
views.pop()
views.append(building)
return len(views)
sunset_views_left([3, 7, 8, 3, 6, 1]) |
a8079e27ea765201fa0af9fda03cffdb5cb2056d | greatblueheron/tyson-is-awesome | /ceasar.py | 1,941 | 4.28125 | 4 | import sys
def encrypt_some_string(text, s):
result = ""
for i in range(len(text)):
char = text[i]
result += chr(ord(char)+s)
return result
def encrypt(message_to_encrypt, file_to_write_the_encrypted_version_to):
# 1. load the text file into a string
file_to_read = open(message_to_encrypt, 'r')
read_in_text = file_to_read.read()
# 2. encrypt it
encrypted_version = encrypt_some_string(text=read_in_text, s=5)
# 3. write the encrypted version to disk
file_to_write_to = open(file_to_write_the_encrypted_version_to, 'w')
file_to_write_to.write(encrypted_version)
file_to_write_to.close()
return
def decrypt(message_to_decrypt, file_to_write_the_decrypted_version_to):
# 1. load the text file into a string
file_to_read = open(message_to_decrypt, 'r')
read_in_text = file_to_read.read()
# 2. decrypt it
decrypted_version = encrypt_some_string(text=read_in_text, s=-5)
# 3. write the decrypted version to disk
file_to_write_to = open(file_to_write_the_decrypted_version_to, 'w')
file_to_write_to.write(decrypted_version)
file_to_write_to.close()
return
def main():
# command line should have three args;
# either e message.txt scrambled or
# d scrambled message.txt
print('Number of arguments:', len(sys.argv), 'arguments.')
print('Argument List:', str(sys.argv))
first_argument = sys.argv[1]
second_argument = sys.argv[2]
third_argument = sys.argv[3]
if len(sys.argv) != 4:
print('Wrong number of arguments! Use either e message.txt scrambled or d scrambled message.txt')
if first_argument == 'e':
encrypt(second_argument, third_argument)
if first_argument == 'd':
decrypt(second_argument, third_argument)
if first_argument not in ['e', 'd']:
print('first argument has to be e or d')
if __name__ == "__main__":
sys.exit(main())
|
63e96a978bb28a007211fd0d3a0529af8ac79b7a | tshihui/pypaya | /codility_practices/binaryGap.py | 2,716 | 3.65625 | 4 | #########################################################
#------- Solution to identify largest binary gap -------#
#########################################################
#-----------------------------------------#
#---------- Final Version ----------------#
#-----------------------------------------#
#----- Functions -----#
def find0(binNum):
# find first 1
pos1 = binNum.find('1')
# find second 1
pos2 = binNum.find('1', pos1+2)
# return number of 0s
count0 = binNum[pos1:pos2+1].count('0')
# return cut string
newBinNum = binNum[pos2:len(binNum)]
return(count0, newBinNum)
def binaryGap(N):
# Needs to be improved
binNum = "{0:b}".format(N)
count0s = []
if binNum.count('0') > 0 and binNum.count('1') > 1:
while(len(binNum) > 2):
binAns = find0(binNum)
count0s.append(binAns[0])
binNum = binAns[1]
return(max(count0s))
else:
return(0)
#----- Main function -----#
if __name__ == '__main__':
print('---------- Running test cases: ')
print('When N = 53: ')
print(binaryGap(53))
print('')
print('When N = 1456: ')
print(binaryGap(1456))
print('')
print('When N = 10555501: ')
print(binaryGap(10555501))
print('')
#-------------------------------------#
#---------- Version 2 ----------------#
#-------------------------------------#
def find0(binNum):
# find first 1
pos1 = binNum.find('1')
# find second 1
pos2 = binNum.find('1', pos1+2)
# return number of 0s
count0 = binNum[pos1:pos2+1].count('0')
# return cut string
newBinNum = binNum[pos2:len(binNum)]
if count0 == 0:
return(0)
else:
return(count0, newBinNum)
def binaryGap(N):
# Needs to be improved
binNum = "{0:b}".format(N)
count0s = []
if binNum.count('0') > 0 and binNum.count('1') > 1:
while(len(binNum) > 2):
binAns = find0(binNum)
count0s.append(binAns[0])
binNum = binAns[1]
return(max(count0s))
else:
return(0)
#-------------------------------------#
#---------- Version 1 ----------------#
#-------------------------------------#
def binaryGap(N):
# Needs to be improved
binNum = "{0:b}".format(N)
count0s = []
pos1, pos2 = 0, 0
if binNum.count('0') > 0 and binNum.count('1') > 1:
pos1 = binNum.find('1')
while (pos1+2) <= len(binNum):
pos2 = binNum.find('1', pos1+2)
count0s.append(binNum[pos1:pos2+1].count('0'))
pos1 = pos2
return(max(count0s))
else:
return(0)
|
b1c3c528970fa3026e67f105fd77fc7f154c5814 | raj13aug/Python-learning | /Course/5-Data-Structure/comprehensions.py | 372 | 3.71875 | 4 | items = [
("Product1", 10),
("Product2", 20),
("Product3", 13)
]
# comprehensions is cleaner and more performance
prices = list(map(lambda item: item[1], items))
prices = [item[1] for item in items]
# explanation:
# expression for item in items
filtered = list(filter(lamnda item: item[1] >= 10, items))
filtered = [item for item in items if item[1] >= 10]
|
625687af6a0a2876cc2bc00c4a16761becb7fd62 | AlexZhaoZt/RL | /maze/maze.py | 285 | 3.671875 | 4 | class maze:
def __init__(self):
self.road_open = []
for x in range(5):
for y in range(5):
self.road_open[x][y] = True
for x in range(2):
for y in range(2):
self.road_open[x+1][y+1] = True
|
89ef088c7e48f8857311c32ef9814d1d7110c428 | javarishi/LearnPythonJune2021 | /learn_day06/03ReturnAFunction.py | 429 | 3.84375 | 4 | def calculator(num, name):
function_name = None
def square():
return num*num
def cube():
return num*num*num
if name=="square":
print("square function is selected")
function_name = square
else:
print("cube function is selected")
function_name= cube
return function_name
retruned_function = calculator(5, "cube")
print(retruned_function()) |
4299a4fb5df986a0f32c9b69ebd6e033c1582699 | DominiqueGregoire/cp1404practicals | /prac_03/password_check.py | 414 | 4.375 | 4 | """Checks that a password has at least the minimum length specified"""
def main():
minimum_password_length = int(input("Enter minimum password length: "))
password = input('Enter password')
while len(password) < 8:
print('Password invalid. Please enter a password with at least {} '
'characters.'.format(minimum_password_length))
password = input('Enter password')
print("*" * len(password))
|
97671aac092f953735278f243cfbc7187e2db3bd | khushboo011/python-programs | /array/rotated_sorted_array_search.py | 1,315 | 4.125 | 4 |
from array.binary_search import _binary_search_impl
def search_in_rotated_array(elements, num):
"""Returns index of the num in a left rotated sorted array.."""
if type(elements) != list or len(elements) == 0 or num is None:
return -1
end_index = len(elements) - 1
pivot = find_pivot(elements, 0, end_index)
if pivot == (len(elements) - 1):
return _binary_search_impl(elements, 0, end_index, num)
if num == elements[pivot]:
return pivot
if num < elements[0]:
_binary_search_impl(elements, pivot + 1, end_index, num)
else:
_binary_search_impl(elements, 0, pivot - 1, num)
def find_pivot(arr, start, end):
"""Returns the pivot index of the left rotated array: pivot index is the end index of
first half sorted array [0...pivotInfrx...end]
>>> find_pivot([3,4,5,6,1,2], 0, 5)
3
"""
if start == end:
return start
elif start < end:
mid = int(start + (end- start)/2)
if mid < end and arr[mid] > arr[mid + 1]:
return mid
elif mid > start and arr[mid] < arr[mid -1]:
return mid -1
if arr[start] > arr[mid]:
return find_pivot(arr, start, mid - 1)
else:
return find_pivot(arr, mid + 1, end)
else:
return -1
|
5a24ec408e292439965d161485aa6db187b27de1 | crucis-onishi/tk_practice | /kitchen_timer.py | 6,094 | 3.5 | 4 | import tkinter as tk
import time
import math
# tk.Frameを継承したApplicationクラスを作成
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
# ウィンドウの設定
master.title("キッチンタイマー")
master.geometry("430x280") # タイマーの幅は430x280
# 変数定義
self.timer_on = False # タイマーの状態
self.start_time = 0 # 開始時間
self.set_time = 0 # セット時間
self.elapsed_time = 0 # 経過時間
self.left_time = 0 # 残り時間
self.left_min = 0 # 残り時間(分)
self.left_sec = 0 # 残り時間(秒)
self.after_id = 0 # after_id変数を定義
# 実行内容
self.pack()
self.create_widget()
# create_widgetメソッドを定義
def create_widget(self):
# 全体の親キャンバス
self.canvas_bg = tk.Canvas(self.master, width=430, height=280)
self.canvas_bg.pack()
# タイマー用のキャンバス
self.canvas_time = tk.Canvas(self.canvas_bg, width=410, height=80, bg="lightgreen")
self.canvas_time.place(x=10, y=10)
# タイマーに数字を表示
self.update_min_text() # 分の表示更新
self.update_sec_text() # 秒の表示更新
# 分ボタン
self.min_button = tk.Button(self.canvas_bg, width=8, height=2, text="分", font=("MSゴシック体", "18","bold"), command=self.min_button_clicked)
self.min_button.place(x=10, y=100)
# 秒ボタン
self.sec_button = tk.Button(self.canvas_bg, width=8, height=2, text="秒", font=("MSゴシック体", "18","bold"), command=self.sec_button_clicked)
self.sec_button.place(x=150, y=100)
# リセットボタン
self.reset_button = tk.Button(self.canvas_bg, width=8, height=2, text="リセット", font=("MSゴシック体", "18","bold"), command=self.reset_button_clicked)
self.reset_button.place(x=290, y=100)
# スタート/ストップボタン
start_button = tk.Button(self.canvas_bg, width=27, height=2, text="スタート/ストップ", font=("MSゴシック体", "18","bold"), command=self.start_button_clicked)
start_button.place(x=10, y=190)
# 各ボタンを押した時の処理
# minボタンを押した時
def min_button_clicked(self):
if self.left_min < 59: # 最大59分まで
self.set_time += 60 # セット時間をプラス
self.left_min += 1 # 残り時間(分)をプラス
self.update_min_text() # 分の表示更新
# secボタンを押した時
def sec_button_clicked(self):
if self.left_sec < 59: # 最大59秒まで
self.set_time += 1 # セット時間をプラス
self.left_sec += 1 # 残り時間(秒)をプラス
self.update_sec_text() # 秒の表示更新
# resetボタンを押した時
def reset_button_clicked(self):
self.set_time = 0 # セット時間をリセット
self.left_min = 0 # 残り時間(分)をリセット
self.left_sec = 0 # 残り時間(秒)をリセット
self.update_min_text() # 分の表示更新
self.update_sec_text() # 秒の表示更新
#startボタンを押した時
def start_button_clicked(self):
if self.set_time >= 1:
if self.timer_on == False:
self.timer_on = True
# 各種ボタンを押せなくする
self.min_button["state"] = tk.DISABLED
self.sec_button["state"] = tk.DISABLED
self.reset_button["state"] = tk.DISABLED
self.start_time =time.time() # 開始時間を代入
self.update_time() # updateTime関数を実行
elif self.timer_on == True:
self.timer_on = False
# 各種ボタンを押せるようにする
self.min_button["state"] = tk.NORMAL
self.sec_button["state"] = tk.NORMAL
self.reset_button["state"] = tk.NORMAL
self.set_time = self.left_time
app.after_cancel(self.after_id)
# 個別の処理
# 時間更新処理
def update_time(self):
self.elapsed_time = time.time() - self.start_time # 経過時間を計算
self.left_time = self.set_time - self.elapsed_time # 残り時間を計算
self.left_min = math.floor(self.left_time // 60) # 残り時間(分)を計算
self.left_sec = math.floor(self.left_time % 60) # 残り時間(秒)を計算
self.update_min_text() # 分の表示更新
self.update_sec_text() # 秒の表示更新
if self.left_time > 0.1:
self.after_id = self.after(10, self.update_time)
else:
self.timer_on = False
# 各種ボタンを押せるようにする
self.min_button["state"] = tk.NORMAL
self.sec_button["state"] = tk.NORMAL
self.reset_button["state"] = tk.NORMAL
self.set_time = self.left_time
app.after_cancel(self.after_id)
# 分の表示更新
def update_min_text(self):
self.canvas_time.delete("min_text") # 表示時間(分)を消去
self.canvas_time.create_text(250, 40, text=str(self.left_min).zfill(2) + ":", font=("MSゴシック体", "36", "bold"), tag="min_text", anchor="e") # 分を表示
# 秒の表示更新
def update_sec_text(self):
self.canvas_time.delete("sec_text") # 表示時間(秒)を消去
self.canvas_time.create_text(250,40,text=str(self.left_sec).zfill(2), font=("MSゴシック体", "36", "bold"), tag="sec_text", anchor="w") # 秒を表示
if __name__ == "__main__":
root = tk.Tk()
app = Application(master=root)
app.mainloop()
|
78e8ca6453aa34bdda701cd4692a1dae8663c543 | wfordh/advent_of_code | /scripts/advent_of_python/2020_puzzles/day16puzzle1.py | 1,366 | 3.65625 | 4 | """
Advent of Code 2020
Day: 16
Puzzle: 1
Language: Python
"""
import re
def main():
# get rules as tuples ((x, y), (m, n)) and string together?
infile_path = "../../../data/2020_day_16.txt"
with open(infile_path, "r") as infile:
rules = list()
my_ticket = list()
nearby_tix = list()
data_block = 0
for line in infile:
if line.startswith("your ticket") or line.startswith("nearby tickets"):
data_block += 1
continue
if line.strip() == "":
continue
if data_block == 0:
rule = re.findall(r"(\d+)", line.strip())
rules.append([int(num) for num in rule])
elif data_block == 1:
my_ticket.extend([int(num) for num in line.strip().split(",")])
else:
nearby_tix.append([int(num) for num in line.strip().split(",")])
error = 0
for ticket in nearby_tix:
for number in ticket:
success = 0
for rule in rules:
if (number >= rule[0] and number <= rule[1]) or (
number >= rule[2] and number <= rule[3]
):
success += 1
if success == 0:
error += number
print(error)
if __name__ == "__main__":
main()
|
a9b1035754a5c46c5fee222bd33837eada7f74e5 | UncleTed/adventOfCode2020 | /day12/day12.py | 1,302 | 3.859375 | 4 | import re
class Ship():
def __init__(self, facing):
self.facing = facing
self.compass = {
0: 'N',
90: 'E',
180: 'S',
270: 'W'
}
self.north_south = 0
self.east_west = 0
def __str__(self):
return f'facing: {self.compass[self.facing]}, north: {self.north_south}, east: {self.east_west}, distance: {self.distance()}'
def move(self, direction, distance):
if direction == 'N':
self.north_south += distance
if direction == 'S':
self.north_south -= distance
if direction == 'E':
self.east_west += distance
if direction == 'W':
self.east_west -= distance
if direction == 'F':
self.move(self.compass[self.facing], distance)
if direction == 'R':
self.facing += distance
self.facing %= 360
if direction == 'L':
self.facing -= distance
self.facing %= 360
def distance(self):
return abs(self.north_south) + abs(self.east_west)
s = Ship(90)
with open("./input.txt", "r") as f:
for line in f:
s.move(line[0:1], int(line[1:len(line)]))
# s.move('N', 3)
# s.move('F', 3)
# s.move('R', 90)
# s.move('F', 10)
print(s)
|
29b3fe9c7cdfda15747839a455665b0a65260de3 | chankruze/challenges | /sololearn/DejaVu/DejaVu.py | 188 | 3.53125 | 4 | in_str = list(str(input()))
str_len = len(in_str)
# letters set
set_letters = set(in_str)
set_len = len(set_letters)
if str_len == set_len:
print("Unique")
else:
print("Deja Vu") |
fed9a6a5ba4a71884db4a8369f3640ed3cfbb2b6 | ralevn/Python_scripts | /PyCharm_projects_2020/Advanced/Error_handling/email_validator.py | 1,130 | 4.03125 | 4 | class Error(Exception):
""" Base error"""
pass
class NameTooShort(Error):
"""User name must be more than three characters"""
class MustContainAtSymbolError(Error):
"""Mail must have "@" symbol"""
class InvalidDomainError(Error):
"""Domain must be one of .com, .bg, .org, .net"""
def validate_name(txt):
name = txt.split('@')[0]
if len(name) <= 4:
raise NameTooShort("Name must be more than 4 characters")
def validate_at_symbol(txt):
if ("@" not in txt) or \
("@" in txt.split('.')[-1]):
raise MustContainAtSymbolError("Email must contain @ and it must not be in domain")
def validate_domain(txt, domain_set):
domain = txt.split('.')[-1]
if domain not in domain_set:
raise InvalidDomainError(f"Domain must be one of the following: .{', .'.join(domain_set)}")
while True:
line = input()
valid_domains = ('com', 'bg', 'net', 'org')
if line == "End":
break
validate_name(line)
validate_at_symbol(line)
validate_domain(line, valid_domains)
print("Email is valid")
|
3d04a6518785a52aa84fd898fef0911ab448fb46 | ownnow/Python3_Base | /src/Program_Design_Ideas/calendar.py | 1,624 | 3.828125 | 4 | def getYear():
print('This program prints the calendar of a given year.')
year = int(input('Please enter a year (after 1900):'))
return year
def firstDay(year):
k = leapyears(year)
n = (year - 1900)*365 + k
return (n+1)%7
def leapyears(year):
count = 0
for y in range(1900,year):
if y%4 == 0 and (y%100 != 0 or y%400 == 0):
count = count + 1
return count
def printCalendar(year,w):
print()
print('==============='+ str(year) + '=================')
first = w
for month in range(12):
heading(month)
first = oneMonth(year,month,first)
def heading(m):
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept',
'Oct','Nov','Dec']
print('%10s' %(months[m]))
print('Mon Tue Wed Thu Fri Sat Sun')
def oneMonth(year,month,first):
d = days(year,month)
frame = layout(first,d)
printMonth(frame)
return(first + d)%7
def days(y,m):
month_days = [31,28,31,30,31,30,31,31,30,31,30,31]
d = month_days[m]
if(m == 1)and(y%4 == 0 and (y%100 != 0 or y%400 == 0)):
d = d + 1
return d
def layout(first,d):
frame = 42 * ['']
if first == 0:
first = 7
j = first -1
for i in range(1,d+1):
frame[j] = i
j = j + 1
return frame
def printMonth(frame):
for i in range(42):
print('%3s' %(frame[i]),end=' ')
if (i+1)%7 == 0:
print()
def main():
year = getYear()
w = firstDay(year)
printCalendar(year, w)
main()
|
2adb43b46224f99ff77681fe1591b33fc3a81f49 | Madhav2108/Python- | /string/format_method5.py | 294 | 3.796875 | 4 | # integer numbers with right alignment
print("{:5d}".format(12))
# float numbers with center alignment
print("{:^10.3f}".format(12.2346))
# integer left alignment filled with zeros
print("{:<05d}".format(12))
# float numbers with center alignment
print("{:=8.3f}".format(-12.2346)) |
a16d9b97fb360050282643789ff381af7c2315a4 | coobee0620/pythoncookbook | /chapter1/1.9.py | 1,415 | 4.21875 | 4 | #!/usr/bin/env python
a = {
'x': 1,
'y': 2,
'z': 3
}
b = {
'w': 10,
'x': 11,
'y': 2
}
# Find keys in common
# { 'x', 'y' }
print(a.keys() & b.keys())
# Find keys in a that are not in b
# { 'z' }
print(a.keys() - b.keys())
# Find (key,value) pairs in common
# { ('y', 2) }
print(a.items() & b.items())
# 字典的 keys() 方法返回一个展现键集合的键视图对象。 键视图的一个很少被了解的特性就是它们也支持集合操作,比如集合并、交、差运算。
# 所以,如果你想对集合的键执行一些普通的集合操作,可以直接使用键视图对象而不用先将它们转换成一个set。
print(a.keys())
# 字典的 items() 方法返回一个包含(键,值)对的元素视图对象。 这个对象同样也支持集合操作,并且可以被用来查找两个字典有哪些相同的键值对。
print(a.items()) # like Map.Entry,entrySet
# 尽管字典的 values() 方法也是类似,但是它并不支持这里介绍的集合操作。 某种程度上是因为值视图不能保证所有的值互不相同,这样会导致某些集合操作会出现问题。
# 不过,如果你硬要在值上面执行这些集合操作的话,你可以先将值集合转换成set,然后再执行集合运算就行了。
print(a.values())
for x in a.values():
print(x)
for x in a.items():
print(x)
for x in a.keys():
print(x) |
26150b8e99ec8e94b4a33c8e944313602887646e | estraviz/codewars | /7_kyu/Numerical Palindrome #1/test_palindrome.py | 586 | 3.59375 | 4 | from palindrome import palindrome
def test_should_return_true():
assert palindrome(1221) is True
assert palindrome(110011) is True
assert palindrome(1456009006541) is True
assert palindrome(1) is True
def test_should_return_false():
assert palindrome(123322) is False
assert palindrome(152) is False
assert palindrome(9999) is True
def test_should_return_not_valid():
assert palindrome("ACCDDCCA") == "Not valid"
assert palindrome("1221") == "Not valid"
assert palindrome(-450) == "Not valid"
assert palindrome("@14AbC") == "Not valid"
|
20677a626f91138d7d561003ae832a168c2f3434 | AStillwell/Py_Ch_10 | /Exercise1.py | 4,644 | 3.5625 | 4 | # Exercise1, chapter10
# Author: Alton Stillwell
# Date: 3/6/15
###############
# Mad Lib Program
###############
from tkinter import *
#############
class Application(Frame):
def __init__(self,master):
super(Application,self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self, text = "Enter information for a new story").grid(row = 0, column = 0, columnspan = 2, sticky = W)
Label(self, text = "Hero: ").grid(row = 1, column = 0, sticky = W)
self.hero_ent = Entry(self)
self.hero_ent.grid(row = 1, column = 1, sticky = W)
Label(self, text = "Villian: ").grid(row = 2, column = 0, sticky = W)
self.villian_ent = Entry(self)
self.villian_ent.grid(row = 2, column = 1, sticky = W)
Label(self, text = "Weapon: ").grid(row = 3, column = 0, sticky = W)
self.weapon_ent = Entry(self)
self.weapon_ent.grid(row = 3, column = 1, sticky = W)
Label(self, text = "Plural Noun: ").grid(row = 4, column = 0, sticky = W)
self.pluralNoun_ent = Entry(self)
self.pluralNoun_ent.grid(row = 4, column = 1, sticky = W)
Label(self, text = "Verb: ").grid(row = 5, column = 0, sticky = W)
self.verb_ent = Entry(self)
self.verb_ent.grid(row =5, column = 1, sticky = W)
Label(self, text = "Adjective(s): ").grid(row = 6, column = 0, sticky = W)
self.is_ugly = BooleanVar()
Checkbutton(self, text = "ugly", variable = self.is_ugly).grid(row = 7, column = 0, sticky = W)
self.is_depressed = BooleanVar()
Checkbutton(self, text = "depressed",variable = self.is_depressed).grid(row = 8, column = 0, sticky = W)
self.is_smelly = BooleanVar()
Checkbutton(self, text = "smelly",variable = self.is_smelly).grid(row = 9, column = 0, sticky = W)
Label(self, text = "Body Part: ").grid(row = 6, column = 1, sticky = W)
self.body_part = StringVar()
self.body_part.set(None)
body_parts = ["eye ball","spleen","face"]
row = 7
for part in body_parts:
Radiobutton(self, text = part, variable = self.body_part, value = part).grid(row = row, column = 1, sticky = W)
row += 1
Button(self,text = "Click for story", command = self.tell_story).grid(row = 10, column = 0, sticky = W)
self.story_txt = Text(self, width = 75, height = 10, wrap = WORD)
self.story_txt.grid(row = 11, column = 0, columnspan = 4)
def tell_story(self):
# set variables
hero = self.hero_ent.get()
villian = self.villian_ent.get()
weapon = self.weapon_ent.get()
noun = self.pluralNoun_ent.get()
verb = self.verb_ent.get()
adjectives = ""
if self.is_ugly.get():
adjectives += "ugly, "
if self.is_depressed.get():
adjectives += "depressed, "
if self.is_smelly.get():
adjectives += "smelly, "
body_part = self.body_part.get()
# create story
story = "There was once a mighty hero named '"
story += hero
story += "', who protected his proud country of "
story += adjectives
story += " peoples with his bestie "
story += villian
story += ". Then one day, everything changed. "
story += hero
story += " purchased some new "
story += noun
story += ". This would have been fine, if he had bought some for his bestie "
story += villian
story += ". Needless to say, "
story += villian
story += " now felt unwanted, and turned to a life of crime to try and get "
story += hero
story += " to finally notice him again. "
story += villian
story += " started pirating movies! This injustice would not stand, "
story += hero
story += " decided. Grabing his trusty "
story += weapon
story += ", he set out to "
story += verb
story += " "
story += villian
story += "'s "
story += body_part
story += ". "
story += villian
story += " was defeated easily by "
story += hero
story += "'s "
story += weapon
story += ". Thus, saving the day! "
story += villian
story += " would go on to be the developer of FNAF."
# display story
self.story_txt.delete(0.0,END)
self.story_txt.insert(0.0, story)
############################################
# main
root = Tk()
root.title("Mad Lib")
app = Application(root)
root.mainloop()
|
1a6f2682d417312be2e9ff3905d6a6c2a8ee927b | sreejakvs/Absolute_beginner | /temp.py | 92 | 3.578125 | 4 | def Temp(t):
temp=(t*9/5)+32
print("%.2f" %temp)
celcius=int(input())
Temp(celcius) |
7b435f4ec92c0d23cb253963ce1b1b24a011e2eb | AdamZhouSE/pythonHomework | /Code/CodeRecords/2266/60671/283641.py | 392 | 3.671875 | 4 | num=int(input())
str0=input()
if(num==5)and(str0=="1 2"):
print(1,end='')
elif(num==40)and(str0=="30 29"):
print(18,end='')
elif(num==50)and(str0=="44 15"):
print(40,end='')
elif(num==2000)and(str0=="1953 509"):
print(368,end='')
elif(num==2000)and(str0=="544 1892"):
print(643,end='')
elif(num==2000)and(str0=="753 1294"):
print(1953,end='')
else:
print(num,str0) |
48e702000649263b94339752fb9995a43e00070c | hsnyxfhyqhyh/python3 | /pythonExcise/pythonExcise/projectEuler/done/Problem0002.py | 1,642 | 3.515625 | 4 | '''
Question 0002: https://projecteuler.net/problem=2
Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.'''
# -*- coding: UTF-8 -*-
CAP_NUMBER = 4000000
#CAP_NUMBER = 200
def getResult():
number1 = 1
number2 = 2
nextNumber = 0
l = []
l.append(number1)
l.append(number2)
evenList = []
evenList.append(number2)
sum = 2
while nextNumber <= CAP_NUMBER:
nextNumber = number1 + number2
if nextNumber > CAP_NUMBER:
break
number1 = number2
number2 = nextNumber
l.append(nextNumber)
if nextNumber % 2 == 0 : #either one is correct but not both
sum = sum + number2
evenList.append(nextNumber)
print (l)
print (evenList)
return sum
print ("\n************* Solution 1 starts ************\n")
print (getResult())
print ("\n************* Solution 1 ends ************\n")
print ("\n************* Solution 2 starts ************\n")
Fibonacci = [1, 2] # 这里Fibonnacci 只是数组名
while (Fibonacci[-1] + Fibonacci[-2]) < 4000000:
Fibonacci.append(Fibonacci[-1] + Fibonacci[-2])
even_F = [i for i in Fibonacci if i % 2 == 0]
print(sum(even_F))
print ("\n************* Solution 2 ends ************\n")
|
bb76bf3e309d34819212b6f7ee92eab0bc0220a4 | rdadan/python- | /数据控制/for.py | 226 | 3.53125 | 4 | # 1 for循环遍历列表
lists01 = ['aa', 'bb', 'cc', 'EM算法']
num = 0
for list01 in lists01:
num += 1
print(list01.title() + " in for" + " 这是第%d个\n" % num)
print("循环结束,一共循环%d次" % num)
|
b56d2eddf48c0771741eb2406e58ae1036985761 | excalibur-kvrv/git-pre-commit-push-example | /src/main/backend/globals/constants.py | 1,949 | 3.9375 | 4 | import os
"""
The below constants are used in cryptographic algorithms
:constant TOTAL_CHARS -> This is used to specify the range of characters, what should be considered which
encrypting or decrypting a cipher.
:constant FIRST_CHAR_ASCII_VALUE -> This is used to specify the starting value of the range(inclusive).
:constant LAST_CHAR_ASCII_VALUE -> This is used to specify the ending value of the range(exclusive).
char range = [FIRST_CHAR_ASCII_VALUE, LAST_CHAR_ASCII_VALUE)
:constant STRATEGY -> used to indicate the cryptographic algorithm to be used.
"""
TOTAL_CHARS = 26
FIRST_CHAR_UNICODE_VALUE = ord("A")
LAST_CHAR_UNICODE_VALUE = FIRST_CHAR_UNICODE_VALUE + TOTAL_CHARS
STRATEGY = "seaser"
"""
The below constant is used for pointing to the file containing the kingdom data, it should be in a json file,
of the format:-
{
"rulers": {
"kingdom_name1": "emblem_name",
.
.
.
"kingdom_nameN": "emblem_name",
},
"allies": {
"kingdom_name1": "emblem_name",
.
.
.
"kingdom_nameN": "emblem_name",
}
}
"""
KINGDOM_DATA = os.path.join("src", "main", "resources", "kingdoms.json")
"""
The below constants are used for output generation type
:constant OUTPUT_TYPE -> Used to imply whether the output should be printed to console or to a file
values taken by OUTPUT_TYPE = "console", "file"
:constant SAVE_PATH -> Used to indicate the directory of where to save the output
output will be stored as "actual-'input-file-name'"
"""
OUTPUT_TYPE = "console"
SAVE_PATH = os.path.join("src", "tests", "resources")
"""
The below constants is used to indicate the pattern to be used to validate the input file
:constant FILE_PATTERN -> used to check if the input file follows the below pattern.
:constant RUN_VALIDATION -> used to run validation of input file.
"""
FILE_PATTERN = r"^\s*[a-z]+ .+$"
RUN_VALIDATION = True
|
211a3bd7c08bc8c4d12adee2266d66ba2e584d78 | yangyuxiang1996/leetcode | /剑指 Offer 44. 数字序列中某一位的数字.py | 1,072 | 3.53125 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-18 10:11:39
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-18 10:28:10
FilePath: /leetcode/剑指 Offer 44. 数字序列中某一位的数字.py
Description:
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
'''
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
# count = digit*start*9
if n < 10:
return n
# 先找n位对应的位数digit
digit, start, count = 1, 1, 9
while n > count:
n -= count
start *= 10
digit += 1
count = digit * start * 9
# 找n位在哪个数字中
num = start + (n - 1)//digit
# 找n位对应的数字
s = str(num)
res = s[(n-1)%digit]
return int(res)
|
b5e5332976f17ecefa5e82a2d5fb8f6bc1c6db19 | ojhaanshu87/data_structures | /Miscellaneous_Archive/joseph_problem.py | 3,907 | 3.5 | 4 | #PROBLEM
'''
There are people standing in a circle waiting to be executed.
The counting out begins at some point in the circle and
proceeds around the circle in a fixed direction. In each step,
a certain number of people are skipped and the next person
is executed. The elimination proceeds around the circle
(which is becoming smaller and smaller as the executed people
are removed), until only the last person remains, who is given freedom.
'''
#ALGORITHM
'''
When the Number of Participants is a Power of Two :
The elimination process works like this: the first pass starts at person 1 and proceeds clockwise,
and each new pass starts every time person 1 is reached.
The people eliminated on a pass are crossed out,
and are marked to indicate the order in which they were eliminated.
Eliminated people are then omitted in subsequent diagrams.
Three passes are required to determine the winner:
Pass 1 eliminates four people: 2, 4, 6, 8.
Pass 2 eliminates two people: 3, 7.
Pass 3 eliminates one person: 5.
This leaves person 1 the winner.
Regardless of the number of participants n,
person 1 survives the first pass. Since n is even,
as every positive power of two is, person 1 survives the second pass as well.
In the first pass, the process goes like this: person 1 is skipped, person 2 is eliminated,
person 3 is skipped, person 4 is eliminated, person n-1 is skipped, person n is eliminated.
The second pass starts by skipping person 1.
As long as the number of participants per pass is even,
as it will be for a power of two starting point, the same pattern is followed:
person 1 is skipped each time. Therefore, for any power of two, person 1 always wins.
When the Number of Participants is NOT Power of Two :
we know this much as person 1 can not be the winner.
This is because at least one pass will have an odd number of participants.
Once the first odd participant pass is complete,
person 1 will be eliminated at the start of the next pass.
So is there an easy way to determine who is the winner?
Lets step back and take a closer look at the elimination process in the 13 person example
Four passes are required to determine the winner:
Pass 1 eliminates six people: 2, 4, 6, 8, 10, 12.
Pass 2 eliminates four people: 1, 5, 9, 13.
Pass 3 eliminates one person: 7.
Pass 4 eliminates one person: 3.
This leaves person 11 the winner.
'''
#APPROCH
'''
The Equations
We can solve both cases or in other words,
for an arbitrary number of participants we have to use a little math.
Write n as n = 2m + k,
where 2m is the largest power of two less than or equal to n.
k people need to be eliminated to reduce the problem to a power of two,
which means 2k people must be passed over. The next person in the circle,
person 2k + 1, will be the winner. In other words, the winn
er w is w = 2k + 1.
Lets apply these equations to a few examples
n = 8: The equations still apply, although using them is unnecessary:
n = 8 + 0, so k = 0 and w = 0 + 1 = 1.
n = 13: n = 8 + 5, so k = 5 and w = 2*5 + 1 = 11.
n = 1000:
n = 1000 = 512 + 488, so k = 488 and w = 2*488 + 1 = 977.
The Formula
We can combine the equations n = 2m + k and w = 2k + 1 to get a single formula for w
Rearrange n is equals 2m plus k to isolate k as k equals n minus 2m.
Substitute this expression for k into w = 2k + 1.
w equals 2 times of n minus 2m plus 1 (where 2m is largest power of two <=n)
'''
#IMPEMENTATION
def largest_pow_of_two_less_than_num(num):
assert num > 0
last = num
num &= num - 1
while num:
last = num
num &= num - 1
return last
#the person who survive last
def winner_person(number_of_persons):
largest_pow_less_than_num = largest_pow_of_two_less_than_num(number_of_persons)
winner = 2 *(number_of_persons-largest_pow_less_than_num) +1
return winner
|
2ec6cc14924a10de317364802ab75eb6c18a9c54 | ckitagawa/PythonSnippets | /Challenge242Easy.py | 359 | 3.765625 | 4 | import unittest
def FunnyPlant (people, fruit):
i = 1
fruittrees = [0] * fruit
while True:
fruittrees = list(map(lambda x: x + 1, fruittrees))
i +=1
if sum(fruittrees) >= people:
return i
else:
fruittrees += [0] * sum(fruittrees)
print(FunnyPlant(15, 1))
print(FunnyPlant(200, 15))
print(FunnyPlant(50000, 1))
print(FunnyPlant(150000, 250)) |
afdd93ba90b24ed3ae45e116e9abf9370c4b7262 | ZohidilloPr/calculateQAZOinTERMINAL | /main.py | 3,228 | 3.828125 | 4 | from time import sleep
from datetime import date
def now():
today = date.today()
return today
def timer():
timer = sleep(3)
def check_Date(i):
if i['o'] > 12 or i['k'] > 31:
oy = i['o']
kun = i['k']
print(f'Siz oy yoki kuni xato kiritdingiz ? oy-->{oy}, kun-->{kun}')
survey()
def survey():
v = ""
global a, b
print('Salom Men Qancha Qazo nomozingiz borligini taxminan hisoblab beraman')
s = input('Boshlashimiz uchun sizdan bazi bir narsalarni sorashim kerak rozimisiz ? xa/yoq ')
if s == 'xa':
name = input('Ismingiz ')
jins = input('Siz erkak/ayol ? ')
print('Tug\'ulgan yil oy kuni kiriting!')
a = {
'y': int(input('yil ')),
'o': int(input('oy ')),
'k': int(input('kun ')),
}
check_Date(a)
n = input('Nomoz o\'qishni boshlaganmisiz xa/yoq ')
if n == 'xa':
print('Nomoz o\'qishni boshlagan taxminiy sanani kiriting!\n(Haqiqatdan 5 mahal o\'qishni boshlagan sanani)')
b = {
'y': int(input('yil ')),
'o': int(input('oy ')),
'k': int(input('kun ')),
}
check_Date(b)
elif n == 'yoq':
print('Unday bo\'lsa "bugun" deb yozing !')
v = input("... ")
else:
survey()
if jins == 'erkak':
a['y'] += 12
elif jins == 'ayol':
a['y'] += 9
else:
print('bunday tanlov yoq')
survey()
if v != "":
if v == 'bugun':
r1 = a['y'] - now().year
r2 = a['o'] - now().month
r3 = a['k'] - now().day
else:
r1 = a['y'] - b['y']
r2 = a['o'] - b['o']
r3 = a['k'] - b['k']
qy = r1 * 365
qo = r2 * 31
qr = qy + qo + r3
print(f'Xurmatli {name} siz {r1} yil {r2} oy {r3} kun Nomoz O\'qimagansiz (Bu taxminiy hisob)')
if qr != 0:
print(f' Bu {qr} kun nomoz o\'qimagansiz degani :( ')
if qr != 0:
m = input('Maslahat beraymi :) xa/yoq ')
if m == 'xa':
print(f'Yaxshi Tanlov {name} Har kuni qolib ketgan bir kunik nomozingizni o\'qing!')
timer()
print('Bunga o\'rtacha 20 daqiqa yoki kamroq ham ketishi mumkun. Chunki qolib ketgan nomozni faqat farzni o\'qiysiz:)')
timer()
print('Axir kunlik 20 daqiqa nomoz uchun sariflasangiz nima bolibdi :) Tog\'rimi! ')
timer()
l = input(f'Nimani Unitganizni aytaymi ? {name} xa/yoq ')
if l == 'xa':
print('Istixfforni....')
elif l == 'yoq':
print(f'Mayli Nima ham deya olardik Bilimdon {name.upper()}ga :] ')
elif m == 'yoq':
print(f'O\'zingiz bilasiz {name.upper()}')
elif qr == 0:
print('qoyil !')
timer()
print('Menimcha men sizga kerak emasman :)')
elif s == 'yoq':
print('Ha tushunarli xayr :(')
survey()
a = input('Dasturdan chiqish uchun enterni bosing :) ')
|
d88bb0cb49faf502e4b7595e23f897f581f915fe | swatia-code/data_structure_and_algorithm | /trees/fix_two_nodes_of_bst.py | 6,982 | 3.71875 | 4 | '''
PROBLEM STATEMENT
-----------------
Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST by swapping them back. Do not change the structure of the tree.
Note: It is guaranteed than the given input will form BST, except for 2 nodes that will be wrong.
Example 1:
Input:
10
/ \
5 8
/ \
2 20
Output: 1
Explanation:
Example 2:
Input:
11
/ \
3 17
\ /
4 10
Output: 1
Your Task:
You don't need to take any input. Just complete the function correctBst() that takes root node as parameter. The function should return the root of corrected BST. BST will then be checked by driver code and 0 or 1 will be printed.
Expected Time Complexity : O(n)
Expected Auxiliary Space : O(1)
Constraints:
1 <= Number of nodes <= 1000
LOGIC
-----
The inorder traversal of a BST produces a sorted array. So a simple method is to store inorder traversal of the input tree in an auxiliary array. Sort the auxiliary array. Finally, insert the auxiliary array elements back to the BST, keeping the structure of the BST same. The time complexity of this method is O(nLogn) and the auxiliary space needed is O(n).
We can solve this in O(n) time and with a single traversal of the given BST. Since inorder traversal of BST is always a sorted array, the problem can be reduced to a problem where two elements of a sorted array are swapped. There are two cases that we need to handle:
1. The swapped nodes are not adjacent in the inorder traversal of the BST.
For example, Nodes 5 and 25 are swapped in {3 5 7 8 10 15 20 25}.
The inorder traversal of the given tree is 3 25 7 8 10 15 20 5
If we observe carefully, during inorder traversal, we find node 7 is smaller than the previous visited node 25. Here save the context of node 25 (previous node). Again, we find that node 5 is smaller than the previous node 20. This time, we save the context of node 5 (the current node ). Finally, swap the two node’s values.
2. The swapped nodes are adjacent in the inorder traversal of BST.
For example, Nodes 7 and 8 are swapped in {3 5 7 8 10 15 20 25}.
The inorder traversal of the given tree is 3 5 8 7 10 15 20 25
Unlike case #1, here only one point exists where a node value is smaller than the previous node value. e.g. node 7 is smaller than node 8.
How to Solve? We will maintain three-pointers, first, middle, and last. When we find the first point where the current node value is smaller than the previous node value, we update the first with the previous node & the middle with the current node. When we find the second point where the current node value is smaller than the previous node value, we update the last with the current node. In the case of #2, we will never find the second point. So, the last pointer will not be updated. After processing, if the last node value is null, then two swapped nodes of BST are adjacent.
SOURCE
------
geeksforgeeks
CODE
----
'''
def correct_bst_helper(root, first, middle, last, prev):
if root:
correct_bst_helper(root.left, first, middle, last, prev)
if (prev[0] and root.data < prev[0].data):
if not(first[0]):
first[0] = prev[0]
middle[0] = root
else:
last[0] = root
prev[0] = root
correct_bst_helper(root.right, first, middle, last, prev)
def correctBST(root):
# code here
# swap the 2 incorrectly placed nodes
# and return the root of tree
first = [None]
middle = [None]
last = [None]
prev = [None]
correct_bst_helper(root, first, middle, last, prev)
if (first[0] and last[0]):
first[0].data, last[0].data = last[0].data, first[0].data
elif (first[0] and middle[0]):
first[0].data, middle[0].data = middle[0].data, first[0].data
return root
#{
# Driver Code Starts
#Initial Template for Python 3
from collections import deque
# Tree Node
class Node:
def __init__(self, val):
self.right = None
self.data = val
self.left = None
# Function to Build Tree
def buildTree(s):
#Corner Case
if(len(s)==0 or s[0]=="N"):
return None
# Creating list of strings from input
# string after spliting by space
ip=list(map(str,s.split()))
# Create the root of the tree
root=Node(int(ip[0]))
size=0
q=deque()
# Push the root to the queue
q.append(root)
size=size+1
# Starting from the second element
i=1
while(size>0 and i<len(ip)):
# Get and remove the front of the queue
currNode=q[0]
q.popleft()
size=size-1
# Get the current node's value from the string
currVal=ip[i]
# If the left child is not null
if(currVal!="N"):
# Create the left child for the current node
currNode.left=Node(int(currVal))
# Push it to the queue
q.append(currNode.left)
size=size+1
# For the right child
i=i+1
if(i>=len(ip)):
break
currVal=ip[i]
# If the right child is not null
if(currVal!="N"):
# Create the right child for the current node
currNode.right=Node(int(currVal))
# Push it to the queue
q.append(currNode.right)
size=size+1
i=i+1
return root
def isBST(n,lower,upper):
if n is None:
return True
if n.data<=lower or n.data>=upper:
return False
return isBST(n.left,lower,n.data) and isBST(n.right,n.data,upper)
def compare(a,b,mismatch):
if a is None and b is None:
return True
if a is None or b is None:
return False
if a.data != b.data:
mismatch.append( (a.data,b.data) )
return compare(a.left,b.left,mismatch) and compare(a.right,b.right,mismatch)
if __name__=="__main__":
t=int(input())
for _ in range(t):
s=input()
root = buildTree(s)
duplicate = buildTree(s)
root = correctBST(root)
# check 1: is tree now a BST
if not isBST(root,0,1000000000):
print(0)
continue
# check 2: comparing with duplicate tree
mismatch = []
# a list to store data of mismatching nodes
if not compare(root, duplicate, mismatch):
# false output from this function indicates change in tree structure
print(0)
if len(mismatch)!=2 or mismatch[0][0]!=mismatch[1][1] or mismatch[0][1]!=mismatch[1][0]:
print(0)
else:
print(1)
# } Driver Code Ends
|
dd050cd3814e33bc1519880253e5735434fac906 | UniqMartin/adventofcode-2015 | /day-09/main.py | 2,016 | 3.671875 | 4 | """Advent of Code 2015 - Day 9."""
import itertools
import re
from pathlib import Path
def read_input():
"""Read input file and split into individual lines returned as a list."""
return Path(__file__).with_name('input.txt').read_text().splitlines()
class CityMap:
"""Map of cities and their mutual distances."""
# Regular expression for parsing city pair distances from the input file.
CITY_PAIR_REGEXP = re.compile(r'^(.+) to (.+) = (\d+)$')
@classmethod
def from_lines(cls, lines):
"""Initialize a map from lines read from the input file."""
city_map = cls()
for line in lines:
source, target, dist = cls.CITY_PAIR_REGEXP.search(line).groups()
city_map.add_city_pair(source, target, int(dist))
return city_map
def __init__(self):
"""Initialize an empty map."""
self.city = {}
self.link = {}
def add_city_pair(self, source, target, dist):
"""Add a pair of cities and their mutual distance to the map."""
source_id = self.city.setdefault(source, len(self.city))
target_id = self.city.setdefault(target, len(self.city))
self.link[(source_id, target_id)] = dist
self.link[(target_id, source_id)] = dist
def routes(self):
"""Yield all possible routes between cities."""
for city_list in itertools.permutations(self.city.values()):
yield city_list[:-1], city_list[1:]
def route_lengths(self):
"""Yield the lengths of all possible routes between cities."""
for sources, targets in self.routes():
yield sum(self.link[pair] for pair in zip(sources, targets))
def main():
"""Main entry point of puzzle solution."""
route_lengths = list(CityMap.from_lines(read_input()).route_lengths())
part_one = min(route_lengths)
part_two = max(route_lengths)
print('Part One: {}'.format(part_one))
print('Part Two: {}'.format(part_two))
if __name__ == '__main__':
main()
|
20daa2d58b319f96d8566ec214d7058c179d688d | diesgaro/holbertonschool-web_back_end | /0x00-python_variable_annotations/8-make_multiplier.py | 656 | 4.1875 | 4 | #!/usr/bin/env python3
'''
8. Complex types - functions
'''
from typing import Callable
def make_multiplier(multiplier: float) -> Callable[[float], float]:
'''
Function that make a function to multiplies a float argument
Arguments:
multiplier (float): A float number
Return:
Callable: a function that multiplies
'''
def f(n: float):
'''
Function that multiplies two arguments
Arguments:
n (float): A float number
Return:
Float: the result of multiplies
'''
return n * multiplier
return f
|
6e02db977ca1ff5ffea1694588d7db11755be4a8 | GerardoSGG/Portfolio | /Practices/Python/Programa_3.py | 206 | 3.96875 | 4 | cadena=input("Escriba una cadena")
cadena=cadena.replace(" ", "")
valida= cadena[::-1]
if cadena==valida:
print("La cadena leida es un palindromo")
else:
print("La cadena leida no es un palindromo") |
2adc96e63f267d0b59e1a2db94ff41665d58aa78 | gonzalouy/Python | /Promedios_con_funciones.py | 1,058 | 3.78125 | 4 | #Calculo del Promedio
def Calculo_Promedio(Nota_matematicas, Nota_literatura, Nota_fisica):
Valor = ((Nota_matematicas + Nota_literatura + Nota_fisica) / 3)
return Valor
#Imprimir datos
def datos_del_alumno (Nombre,Apellido,Promedio):
print('La nota promedio de ' + (str(Nombre)) + ' ' + (str(Apellido)) + ' es ' + (str(Promedio)))
def aprobacion(Promedio):
if Promedio < 4:
print('Insuficiente')
if 4 <= Promedio <= 5.99999:
print('A recuperatorio')
if Promedio >= 6:
print('Aprobado')
if Promedio >= 9:
print('Alumno destacado')
else:
Promedio = 0
#Ingreso de datos
Nombre = input('Ingrese su nombre ')
Apellido = input('Ingrese su apellido ')
Nota_matematicas = int(input('Ingrese la nota de matematicas '))
Nota_literatura = int(input('Ingrese la nota de literatura '))
Nota_fisica = int(input('Ingrese la nota de fisica '))
Promedio=Calculo_Promedio(Nota_fisica,Nota_matematicas, Nota_literatura)
datos_del_alumno(Nombre,Apellido,Promedio)
aprobacion(Promedio)
|
3644ec819f6005126399882f61a2724da45523cd | AaravAgarwal1/Atm | /Atm.py | 566 | 3.78125 | 4 |
class Atm(object):
def __init__(self, Atm_card_number, Atm_Pin):
self.Atm_card_number=Atm_card_number
self.Atm_Pin=Atm_Pin
def BalanceEnquiry(self):
return("You have the total balance of 100$ left. ")
def CashWithdrawl(self):
amount=int(input("How much do you want to withdraw: "))
balance=100-amount
return(f"You succesfully withdrawed {amount}! You now have left {balance}.")
user=Atm(211,53)
print(user.BalanceEnquiry())
print(user.CashWithdrawl())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.