blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
73a63fb3542c23d1158f750c5a4d14520764a84b | shoroogAlghamdi/test | /Unit3/unit3-challenge4.py | 265 | 3.5 | 4 | # Slide 94
BONUS = 1000
salaryBeforeBonus = input("Please, enter your current salary: ")
salaryBeforeBonus = eval(salaryBeforeBonus)
salaryAfterBonus = BONUS + salaryBeforeBonus
print("Your salary after adding a bonus of ", BONUS, "SR is ", salaryAfterBonus, "SR")
|
85697099c9023bd752fb057e8461f65f543a099a | guidozamora/Data-Structures-Algorithms-Python | /LeetCode Solutions/1480_running_sum_1d_array.py | 353 | 4.09375 | 4 | """
Solution steps:
- Create a sum variable and set it to zero
- Loop thru the array
- Add the value of each element to a the sum variable
- Add each sum to a new list
"""
def runningSum (nums):
sum = 0
sum_nums = []
for number in nums:
sum += number
sum_nums.append(sum)
return sum_nums
print(runningSum([1,1,1,1,1]))
|
577300e6a53ea8d2eed2928877c11a0f5ac57a63 | nerunerunerune/kenkyushitukadai | /19.py | 520 | 4.09375 | 4 | #ITP1_5_C: Print a Chessboard
#たてH cm よこ W cm のチェック柄の長方形を描くプログラムを作成
#Draw a chessboard which has a height of H cm and a width of W cm.
#For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm.
while True:
H,W = map(int, input().split())
if (H == 0 and W == 0):
break
for j in range(H):
for i in range(W):
print('#.'[(i+j) % 2] , end="")
print()
print() |
b1b464a2e114a253c06a0c2507e9808485d0e6c3 | cedie1/Python_guanabara_100-exerc-cios- | /ex35.py | 632 | 4.09375 | 4 | #Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
#Resolução.
a = float(input('Coloque o valor de um lado: '))
b = float(input('Coloque o valor de outro lado: '))
c = float(input('Coloque o valor de outro lado: '))
if abs(b - c) < a < b + c and abs(a - c) < b < a + c and abs(a - b) < c < a + b:
print('Os lados {}, {} e {} podem formar triângulo.'.format(a, b, c))
else:
print('Os lados {}, {} e {} não podem formar triângulo.'.format(a, b, c))
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= FIM =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
|
47e520361361dd645310e497c14d178046ffcc8a | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/9d1365b398d84f7aadc1fbbe766607b1.py | 918 | 3.875 | 4 | from string import digits, punctuation, whitespace
# use sets for quicker lookups
digits = set(digits)
punctuation = set(punctuation)
whitespace = set(whitespace)
def contains_lowercase_letters(text):
for letter in text:
if letter.islower():
return True
return False
def contains_no_letters(text):
numdigs = [l for l in text if l in digits or l in punctuation or l in whitespace ]
return len(numdigs) == len(text)
def hey(what):
#strip whitespace
what = what.strip()
#if empty message
if what == "":
return "Fine. Be that way!"
#a shout contains no lowercase letters but isn't just numbers
if not contains_lowercase_letters(what) and not contains_no_letters(what):
return "Whoa, chill out!"
#question ends in questionmark
if what[-1] == "?":
return "Sure."
#if nothing else, return whatever
return "Whatever."
|
a26dec60b7b24e18ca7b36f7c4cf70b9895d3609 | tws0002/pop2-project | /Pipeline/the_LATEST/sys_PY/py_MODULES/syncmeister/controller/engine (selecao's conflicted copy 2016-03-06).py | 4,791 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
All methods governing searching within files and lines of strings, determining
rules for how and in what way information should be retrieved, and, to a lesser
extent, defines how to process the retrieved information
.. important::
Currently, the regex that gets lines in quotes ""s is VERY basic. It only
returns arguments in quotes without said quotes. Luckily, I plan to use it
to search and replace paths so it's OK to not have the original string that
it came with
.. authornote::
In a future build, it would be good to make a regex rule that gets not just
the quoted element but whatever string came before and after it, so that
way I can just replace strings within lines/dicts and join the strings
together, instead of using .replace() or re.replace() to modify quote paths
"""
# IMPORT STANDARD LIBRARIES
import re
import functools
CURRENT_LINE = ""
class LineGrabber(object):
def __init__(self):
super(LineGrabber, self).__init__()
self.rules = {}
self.init_rules()
# end __init__
def match_line(self, reCompile, currentLine):
reMatch = re.findall(reCompile, currentLine)
# reMatch = [m.groupdict() for m in reCompile.finditer(currentLine)] # used with list of dict with quoted keys
return reMatch
# end match_line
def init_rules(self):
"""
Makes rules, currently for catching and idenifying relative paths
"""
reCompile = r"""["|'](.*?)["|']"""
reCompile = re.compile(reCompile)
function = lambda CURRENT_LINE: self.match_line(reCompile, CURRENT_LINE)
rule = Rule()
rule.add_rule(function, None)
self.rules.update({"quoteRule1": rule})
# end init_rules
def eval_rules(self, popAfterEval=False):
"""
Activates dormant rules and either keeps or unloads them on comparison
"""
for condition, comparison in self.rules["quoteRule1"].rulebook.iteritems():
ruleOutput = condition(CURRENT_LINE)
if ruleOutput != comparison:
break
if popAfterEval:
self.rules["quoteRule1"].pop(condition, None)
else:
return False # only runs if no break occurredd
return ruleOutput # some break occurred, therefore the eval must return False
# end eval_rules
# end LineGrabber
class Rule(object):
def __init__(self, **kwargs):
super(Rule, self).__init__()
if kwargs is not None:
self.rulebook = kwargs
# end __init__
def add_rule(self, condition, comparison):
"""
Generic method to create simple conditional statements. Its intended
use is to add
"""
self.rulebook.update({condition: comparison})
# end add_rules
def eval_rules(self):
"""
Activates dormant rules and either keeps or unloads them on comparison
"""
for condition, comparison in self.rulebook.iteritems():
if condition(CURRENT_LINE) != comparison:
break
else:
return False # only runs if no break occurredd
return True # some break occurred, therefore the eval must return False
# end Rule
def get_substring_from_quotes(dataH):
"""
Gets a dictionary that represents every line that must be changed, with
its information at the time it was read.
"""
modifiedDictH = {}
lineGrabber = LineGrabber()
global CURRENT_LINE
for index, line in enumerate(dataH):
# lineGrabber.currentLine = line
CURRENT_LINE = line
checkRules = lineGrabber.eval_rules()
if lineGrabber.eval_rules() is not False and checkRules != []:
modifiedDictH.update({index: checkRules})
return modifiedDictH # the lines that matched the proper rules
# end get_substring_from_quotes
def test_replace_lines_from_dict(dictH, dataH):
# use keys from dictionary, which are integers, to replace indices of dataH
for line, replacements in dictH.iteritems():
for replace in replacements:
dataH[line] = dataH[line].replace(replace, 'asdfasfd', 1) # first occurrence only. VERY IMPORTANT
return dataH
# end test_replace_lines_from_dict
def test_line_mod():
fileLocation = r"/home/selecaotwo/Desktop/basic_test.ma"
with open(fileLocation, "r") as f:
data = f.readlines()
lines = get_substring_from_quotes(data)
return test_replace_lines_from_dict(lines, data)
# ened test_line_mod
if __name__ == "__main__":
for x in test_line_mod():
print x
|
ce10fe0187095c2b6af76f192a947fe6b8001598 | hoyeonkim795/solving | /progeammers/튜플.py | 473 | 3.78125 | 4 | import re
def solution(s):
s = re.split('{|}',s)
ans_s = []
for i in range(len(s)):
if len(s[i]) > 0 and s[i] != ',':
mid_s = list(map(int,s[i].split(',')))
ans_s.append(mid_s)
new_s = quickSort(ans_s)
ans = []
for i in range(len(new_s)):
for j in range(len(new_s[i])):
if new_s[i][j] not in ans:
ans.append(new_s[i][j])
else:
pass
return ans |
54fdc342c2a4cca096af4b64f4ffdd18161fc3e6 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2585/60717/241172.py | 121 | 3.640625 | 4 | list1=list(input())
list2=list(input())
list1.sort()
list2.sort()
if list1==list2:
print(True)
else:
print(False) |
2f5dd8ba01c7d122177539f6e716eacc78170d21 | sandip308/python-program-for-beginners | /HCF with recursion.py | 351 | 3.90625 | 4 | def HCF(f,s):
if s==0:
return f
else:
return HCF(s,f%s)
if __name__ == '__main__':
r = int(input("Enter a first number "))
c = int(input("Enter second number "))
if r >= c:
z = HCF(r, c)
print("The HCF value is=",z)
else:
z = HCF(c, r)
print("The HCF value is=",z)
|
28d84bb855913c1dc28a91eb809142167ae9295e | zhengzhenxing/cookbook | /python/design_patterns/singleton.py | 939 | 4.25 | 4 | """
1. override __new__ method (which is called before __init__) to get or create a class instance
1. add state to track if already initialized in __init__ method - this is only needed if the __init__ method has a side effect.
"""
class Singleton(object):
_instance = None
_inited = False
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, *args, **kwargs):
if type(
self
)._inited: # only necessary if there is a side effect in the __init__method (ie; self.x = 1)
return
self.x = 1
type(self)._inited = True
def increment_thing(self):
self.x += 1
if __name__ == "__main__":
s1 = Singleton()
s2 = Singleton()
if id(s1) == id(s2):
print("Same instance")
else:
print("Different instance")
|
cf5d0719279041256e32fdd587cf2b62db655237 | xuedagong/hello | /pat/1008.py | 1,329 | 3.609375 | 4 | #coding=utf-8
'''
一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(M>=0)个位置,即将A中的数据由(A0 A1……AN-1)变换为(AN-M …… AN-1 A0 A1……AN-M-1)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
输入格式:每个输入包含一个测试用例,第1行输入N ( 1<=N<=100)、M(M>=0);第2行输入N个整数,之间用空格分隔。
输出格式:在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。
输入样例:
6 2
1 2 3 4 5 6
输出样例:
5 6 1 2 3 4
'''
if __name__ == "__main__" :
n,move=raw_input().split(" ")
n=int(n)
move=int(move)
move=move%n
lst=raw_input().split(" ")
for i in xrange(move):
temp=lst[n-1]
for k in xrange(n-1,0,-1):
lst[k]=lst[k-1]
lst[0]=temp
print " ".join(lst)
#
# if __name__ == "__main__" :
# num = raw_input().split(' ')
# n = int(num[0])
# m = - int(num[1])
#
# num = raw_input().split(' ')
# while m + n <= 0 :
# m = m + n
#
# for i in range(n) :
# print num[i+m], |
a35a7b2af9566f201f0033e198fb937747a67188 | ankithakumari/InformationRetrieval | /bfscrawler.py | 3,137 | 3.625 | 4 | """ Python implementation to perform Breadth first crawling of the web.
Starts from the url https://en.wikipedia.org/wiki/Space_exploration and downloads all
links to other wiki articles in a breadth first manner.
Only downloads english articles, ignores links to sections in the same page, links to images etc.
"""
import requests
from bs4 import BeautifulSoup
import time
import os
import collections
# Global variables
url_init = "https://en.wikipedia.org" # Site url
url_visited = []
# This method will check if the url points to a site in English or not
# Also checks for sections within the same page, images and administrative links
def excludeURL(url):
not_english = False
not_new_urls = (url.startswith('#') or url.endswith('.jpg') or url.startswith('//') or url.startswith('/w/index.php')
or ':' in url)
if "https" in url:
url = url.replace("https://", "")
not_english = not(url.startswith("en"))
return not_new_urls or not_english
# This method will save the page
def save_page(content, n):
f = open("result" + str(n) + ".txt", 'w+')
f.write(str(content))
f.close()
def bfs_crawler(seed):
url_count = 0
url_depth = []
url_queue = collections.deque([{'link': seed, 'depth': 1}]) # Initialize url queue with link and depth
while len(url_queue) > 0 and len(url_visited) < 1000:
to_visit = url_queue.pop() # Get url from the queue
if to_visit['link'] not in url_visited: # Proceed only if it has not been already crawled
curr_depth = to_visit['depth']
url_visited.append(to_visit['link']) # Append to visited list
url_count += 1
url_depth.append(curr_depth)
# Sleep for a second before crawling
time.sleep(1)
page = requests.get(to_visit['link'])
save_page(page.content, url_count) # Call to save page
soup = BeautifulSoup(page.content, 'html.parser') # Use beautiful soup object to parse the document
urls = soup.findAll("a", href=True) # Fetch all links from the document
if curr_depth < 6: # Fetch more urls only if the link is within depth 6.
for i in urls:
# For a url in depth 6, we need not add more urls to the queue
if not excludeURL(i['href']):
url = url_init + i['href'] if i['href'].startswith('/') else i['href'] # append site url if not already present
url_queue.append({'link': url, 'depth': curr_depth + 1}) # add to queue to be crawled
return url_visited, url_count, url_depth
if __name__ == "__main__":
seed = "https://en.wikipedia.org/wiki/Space_exploration"
# 1. Call BFS crawling
url_list, url_count, url_depth = bfs_crawler(seed)
print('Url Count: ', url_count)
print('Url Depth: ', url_depth)
f = open("bfs_urls.txt", 'w+')
for item in url_list:
f.write("%s\n" % item)
f.close()
|
576184d710e94115f5dee93e2c4a2451c9ca1917 | huiyi999/leetcode_python | /Valid Mountain Array.py | 1,835 | 4.1875 | 4 | '''
Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < A[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 104
'''
from typing import List
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3:
return False
# peek = max(arr)
peek = float("-inf")
# print(peek)
index = 0
for i, num in enumerate(arr):
if num > peek:
peek = num
index = i
elif num == peek:
return False
else:
break
# print(index)
if index == len(arr) - 1 or index == 0:
return False
for num in arr[index + 1:]:
if num >= peek:
return False
else:
peek = num
return True
def validMountainArray2(self, A: List[int]) -> bool:
n = len(A)
if n < 3: return False
inc = A[0] < A[1]
k = 0
for i in range(1, n):
if inc and A[i - 1] >= A[i]:
k += 1
inc = False
if not inc and A[i - 1] <= A[i]:
return False
return k == 1
solution = Solution()
print(solution.validMountainArray([0, 3, 2, 1]))
print(solution.validMountainArray([2, 1]))
print(solution.validMountainArray([3, 5, 5]))
print(solution.validMountainArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
'''
Example 1:
Input: arr = [2,1]
Output: false
Example 2:
Input: arr = [3,5,5]
Output: false
Example 3:
Input: arr = [0,3,2,1]
Output: true
'''
|
84d682bab7fdfb00b7df9851f7e3fdeaacf67633 | dvcolin/Intro-Python-I | /src/14_cal.py | 1,713 | 4.5 | 4 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
"""
import sys
import calendar
from datetime import datetime
current_year = datetime.now().year
current_month = datetime.now().month
user_input = input(
'Enter month and year (optional) separated by a space: ').split(' ')
def generate_calendar(ui):
if len(ui) == 1 and ui[0] == '':
print(calendar.month(current_year, current_month))
elif len(ui) == 1:
try:
monthInt = int(ui[0])
print(calendar.month(2019, monthInt))
except ValueError:
print('Only numbers can be entered.')
elif len(ui) == 2:
try:
monthInt = int(ui[0])
yearInt = int(ui[1])
print(calendar.month(yearInt, monthInt))
except ValueError:
print('Only numbers can be entered.')
else:
print('Only accepts two arguments.')
generate_calendar(user_input)
|
2e0beb29fcf3ff4015a591714c5d94d9bb1c9aaf | programiranje3/v2020 | /Lab1/lab1.py | 5,491 | 4.28125 | 4 | # Task 1
# Write a function that asks the user for a number, and depending on whether
# the number is even or odd, prints out an appropriate message.
def odd_or_even():
number_str = input("Please enter a whole number\n")
# Option 1:
# if int(number_str) % 2 == 0:
# print("EVEN number")
# else:
# print("ODD number")
result = "EVEN" if int(number_str) % 2 == 0 else "ODD"
print("Number", number_str, "is", result)
# Task 2
# Write a function to calculate the factorial of a number.
# The function accepts the number (a non-negative integer)
# as an argument. The computed factorial value should be
# printed to the console.
def factorial(number):
result = 1
for i in range(1, number+1):
result *= i
print("Factorial of number", number, "is", result)
# Task 3
# Write a function that returns n-th lowest value of an iterable
# (1st input parameter). The function return the lowest
# value if n (2nd input parameter) is greater than the number of
# elements in the iterable.
def nth_lowest(iterable, n):
if len(iterable) < n:
return min(iterable)
return sorted(iterable)[n-1]
# Task 4
# Write a function that receives a list of numbers and returns
# a tuple with the following elements:
# - the list element with the smallest absolute value
# - the list element with the largest absolute value
# - the sum of all positive elements in the list
# - the product of all negative elements in the list
def list_stats(numbers):
abs_numbers = list()
sum_pos = 0
prod_neg = 1
for number in numbers:
abs_numbers.append(abs(number))
if number > 0: sum_pos += number
elif number < 0: prod_neg *= number
return min(abs_numbers), max(abs_numbers), sum_pos, prod_neg
# Task 5
# Write a function that receives a list of numbers and a
# threshold value (number). The function:
# - makes a new list that has unique elements from the input list
# that are below the threshold
# - prints the number of elements in the new list
# - sorts the elements in the new list in the descending order,
# and prints them, one element per line
def list_operations(numbers, threshold):
unique_nums = list()
for num in set(numbers):
if num < threshold: unique_nums.append(num)
print("The new list has", len(unique_nums), "elements")
unique_nums.sort(reverse=True)
for i, num in enumerate(unique_nums):
print(str(i+1) + ". " + str(num))
# Task 6
# Write a function that receives two strings and checks if they
# are anagrams. The function returns appropriate boolean value.
# Note: An anagram is a word or phrase formed by rearranging the
# letters of a different word or phrase, typically using all the
# original letters exactly once
def anagrams(s1, s2):
s1_list = list()
s2_list = list()
for ch in s1:
if ch.isalpha(): s1_list.append(ch.lower())
for ch in s2:
if ch.isalpha(): s2_list.append(ch.lower())
# s1_list.sort()
# s2_list.sort()
# return s1_list == s2_list
return sorted(s1_list) == sorted(s2_list)
# Task 7
# Write a function that receives a string and checks if the
# string is palindrome. The function returns appropriate boolean value.
# Note: a palindrome is a word, phrase, or sequence that reads the same
# backwards as forwards, e.g. "madam" or "nurses run".
def palindrome(string):
alpha_num = list()
for ch in string:
if ch.isalnum(): alpha_num.append(ch.lower())
return alpha_num == list(reversed(alpha_num))
# Task 8
# Write a function to play a guessing game: to guess a number between 1 to 9.
# Scenario: user is prompted to enter a guess. If the user guesses wrongly,
# the prompt reappears; the user can try to guess max 3 times;
# on successful guess, user should get a "Well guessed!" message,
# and the function terminates. If when guessing, the user enters a number
# that is out of the bounds (less than 1 or greater than 9), or a character
# that is not a number, he/she should be informed that only single digit
# values are allowed.
#
# Hint: use function randint from random package to generate a number to
# be guessed in the game
def guessing_game():
from random import randint
hidden_number = randint(1,9)
trial = 1
while(trial <= 3):
trial += 1
guess = input("Make a guess (number between 1 and 9)\n")
if (len(guess)) > 1 or (guess.isdigit() == False):
print("Only digits between 1 and 9 are allowed. Try again")
continue
if int(guess) == hidden_number:
print("Well guessed! Congrats!")
return
else:
print("Wrong! Try again")
print("No more trials left. More luck next time")
if __name__ == '__main__':
# odd_or_even()
# factorial(9)
# a = [31, 72, 13, 41, 5, 16, 87, 98, 9]
# print(nth_lowest(a, 3))
# print(nth_lowest(['f', 'r', 't', 'a', 'b', 'y', 'j', 'd', 'c'], 6))
# print(nth_lowest('today', 2))
# print(list_stats([1.2, 3.4, 5.6, -4.2, -5.6, 9, 11.3, -23.45, 81]))
# print_new_list([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], 9)
# print(anagrams('School master', 'The classroom'))
# print(anagrams('Dormitory', 'Dirty room'))
# print(anagrams('Conversation', 'Voices rant on'))
# print(anagrams('Bob', 'Bill'))
# print(palindrome("madam"))
# print(palindrome("nurses run"))
# print(palindrome("nurse run"))
guessing_game() |
89a3343de096950f6031477369cf477e3ce10479 | CP-NEMO/Basics-of-python | /Greatest_of_three.py | 205 | 4.125 | 4 | #which number amoung 3 are greatest
x=int(input())
y=int(input())
z=int(input())
if(x>y and x>z):
print(x,"is greatest")
elif(y>x and y>z):
print(y,"is greatest")
else:
print(z,"is greatest") |
f347c72bf9da719ef4c5de208c5bdd2efdd59902 | ShreyasMugali/Leetcode-Solutions | /Python/Longest_Substring_Without_Repeating_Characters.py | 1,051 | 4.0625 | 4 | # Time: O(n)
# Space: O(1)
#
# Given a string, find the length of the longest substring without repeating characters.
# For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
# For "bbbbb" the longest substring is "b", with the length of 1.
# Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
lastRepeating = -1
longestSubstring = 0
positions = {}
for i in range(0, len(s)):
if s[i] in positions and lastRepeating<positions[s[i]]:
lastRepeating = positions[s[i]]
if i-lastRepeating > longestSubstring:
longestSubstring = i-lastRepeating
positions [s[i]]=i
return longestSubstring
if __name__ == "__main__":
print (Solution().lengthOfLongestSubstring("pwwkew"))
|
69b6f46c282013f6da344555b2c78dc74b2e271d | memoizr/python-scratchbook | /compare.py | 864 | 3.671875 | 4 | import time
class Compare:
def compare_n2(self, n):
minimum = None
for i in n:
is_min = True
for j in n:
if j < i:
is_min = False
if is_min:
minimum = i
return minimum
def compare(self, n):
minimum = n[0]
for i in n:
if i <= minimum:
minimum = i
return minimum
array = [3,1,2,4,6,8,5,0,-1,21,-4,88,23,49,45,41,68,12,67,13,14,15,16,17,18,19,20,21,43,55,67,78,90,123,23,54,73,96,128,9871,2878,518,2348,248,12,8,35,98,3,87,354,9,54464,354,327,654,-64,-58,5448,5452,579,963,557]
time1 = time.time()
i = Compare.compare_n2(Compare(),array)
time2 = time.time()
print time2-time1
print i
time3 = time.time()
j = Compare.compare(Compare(),array)
time4 = time.time()
print time4-time3
print j
|
9d0754e0ba371ed5f9ec52fd242ca0cd1adfbd81 | varshajoshi36/practice | /leetcode/python/easy/longestCommonPrefix.py | 592 | 3.90625 | 4 | #! /usr/bin/python
import sys
#Write a function to find the longest common prefix string amongst an array of strings.
#working solution
def longestCommonPrefix(strs):
common_prefix = ""
num_strings = len(strs)
if num_strings == 0:
return common_prefix
shortest_len = len(min(strs, key = len))
for i in range(shortest_len):
j = 1
while j < num_strings and strs[0][i] is strs[j][i]:
print "in while j:", j
j += 1
if j == num_strings:
common_prefix += strs[0][i]
else:
break
return common_prefix
strs = ["aca", "acba"]
print longestCommonPrefix(strs)
|
d693729d68bb3f5a9faa2b5672affa3108e2df22 | sw30637/assignment5 | /lf1414/assignment5.py | 4,224 | 4.03125 | 4 | '''Defining class interval that represents the range of integers between a lower and upper bound. Either of the bounds of an interval can be “inclusive” or “exclusive” and can be positive or negative. The bounds must always meet the requirement that lower <= upper if both bounds are inclusive, lower < upper if one bound is exclusive and one inclusive, or lower < upper-1 if both are exclusive. When the class is printed, intervals are displayed using square brackets [ ] for inclusive bounds or parenthesis ( ) for exclusive bounds.'''
class interval(object):
def __init__(self, input_string):
#input_string is the interval written in string form
#list_from_string will split the string into a lower and upper portion
list_from_string = input_string.split(",")
#open_bracket is the first character of the first item in the new list
open_bracket = list_from_string[0][0]
#close_bracket is the last character of the last item in the new list
close_bracket = list_from_string[-1][-1]
lower = int(list_from_string[0][1:])
upper = int(list_from_string[1][:-1])
global valid
valid = True #initialize boolean that will check if string is valid string
#checks if string format conforms to requirements
if (open_bracket == '[') & (close_bracket == ']') & (lower <= upper):
pass
elif (open_bracket == '(') & (close_bracket == ')') & (lower < upper-1):
pass
elif lower < upper:
pass
else:
valid = False
self.lower = lower
self.upper = upper
self.open = open_bracket
self.close = close_bracket
if open_bracket == '[':
self.first_num = lower
else:
self.first_num = lower+1
if close_bracket == ']':
self.last_num = upper
else:
self.last_num = upper-1
def __repr__(self):
if valid == True:
return self.open + str(self.lower) + "," + str(self.upper) + self.close
else:
return "Invalid interval"
'''function mergeIntervals(int1, int2) that takes two intervals, and if the intervals overlap returns a merged interval.'''
def mergeIntervals(int1, int2):
overlap = True #initialize overlap, assuming true
if ((int1.last_num < int2.first_num) & (int1.first_num < int2.first_num)) or ((int2.last_num < int1.first_num) & (int2.first_num < int1.first_num)):
overlap = False
# if ((int1.first_num == int2.first_num) & (int1.last_num == int2.last_num)):
# overlap = False
if int1.first_num < int2.first_num:
open_bracket = int1.open
lower = int1.lower
else:
open_bracket = int2.open
lower = int2.lower
if int1.last_num > int2.last_num:
close_bracket = int1.close
upper = int1.upper
else:
close_bracket = int2.close
upper = int2.upper
if overlap == True:
merged_int_string = open_bracket + str(lower) + "," + str(upper) + close_bracket
merged_int = interval(merged_int_string)
return merged_int
else:
return None
'''function mergeOverlapping(intervals) that takes a list of intervals and merges all overlapping intervals.'''
def mergeOverlapping(intervals):
#intervals is a list of string intervals
#let return_list be an empty list to append merged intervals into
return_list = []
return_list.append(intervals[0])
while len(intervals)>1:
del intervals[0]
merged = mergeIntervals(return_list[0], intervals[0])
if merged != None:
return_list[0] = merged
else: return_list.append(intervals[0])
return return_list
'''function insert(intervals, newint) that takes two arguments: a list of non-overlapping intervals; and a single interval. The function should insert newint into intervals, merging the result if necessary.'''
def insert(intervals, newint):
appended_list = intervals
appended_list.insert(0, newint)
return mergeOverlapping(appended_list)
'''function string_reader(string) takes a string input and turns it into a list of interval objects'''
def string_reader(string):
list_from_string = string.split(", ")
intervals_list = []
for item in list_from_string:
intervals_list.append(interval(item))
return intervals_list
'''ran into issues with program-writing'''
interval_list = raw_input("List of intervals?")
interval_list = string_reader(interval_list)
newint = interval(raw_input("Interval?"))
interval_list = insert(interval_list, newint)
print interval_list |
820aedf685ecd0d44c961d99bf94ab6d998233f6 | syahn/Problem-solving | /Codewars/python/[6kyu] Multiples of 3 and 5.py | 621 | 4.15625 | 4 | // 1. Reflection
# - solved
# - It's pythonic, but not the best practice
// 2. Problem
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
# Note: If the number is a multiple of both 3 and 5, only count it once.
// 3. Initial solution( complexity: time=>O() space=>O())
def solution(number):
return sum([n for n in range(1, number) if n % 3 is 0 or n % 5 is 0])
// 4. Improved solution( complexity: time=>O() space=>O() )
|
596399b611b2dcdd174025036556faf3f6b63d5b | nadiabahrami/Data-Structures-2.0 | /src/bst.py | 13,696 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""Binary Search Tree Module."""
from collections import deque
import random
import io
class Node(object):
"""Define a node class."""
def __init__(self, value=None, parent=None, left=None, right=None):
"""Initialize a Node object."""
self.value = value
self.parent = parent
self.left = left
self.right = right
def depth(self):
"""Return the number of levels in the tree."""
if self.value is None:
return 0
elif self.left is None and self.right is None:
return 1
else:
left_depth = self.left.depth() if self.left is not None else 0
right_depth = self.right.depth() if self.right is not None else 0
return max(left_depth, right_depth) + 1
def balance(self):
"""Return a positive integer, 0, or negative integer."""
if self.value is None:
return 0
elif self.left is None and self.right is None:
return 0
else:
left_depth = self.left.depth() if self.left is not None else 0
right_depth = self.right.depth() if self.right is not None else 0
return (left_depth - right_depth)
def pre_order(self):
"""Traverse a tree pre-order."""
yield self.value
if self.left:
for ii in self.left.pre_order():
yield ii
if self.right:
for ii in self.right.pre_order():
yield ii
def in_order(self):
"""Traverse a tree in-order."""
if self.left:
for ii in self.left.pre_order():
yield ii
yield self.value
if self.right:
for ii in self.right.pre_order():
yield ii
def post_order(self):
"""Traverse a tree post-order."""
if self.left:
for ii in self.left.pre_order():
yield ii
if self.right:
for ii in self.right.pre_order():
yield ii
yield self.value
def balance_tree(self):
"""Balance the tree to optimal structure and minimize O(n) calls."""
while self:
if self.balance() > 1:
b, c = self, self.left
if c.balance() > 0:
b._rotate_right()
elif c.balance() < 0:
b._pull_left()
b.balance_tree()
else:
b._rotate_right()
elif self.balance() < -1:
b, c = self, self.right
if c.balance() < 0:
b._rotate_left()
elif c.balance() > 0:
b._pull_right()
b.balance_tree()
else:
b._rotate_left()
cursor = self
self = self.parent
return cursor
def _pull_left(self):
"""Pull the node balance to load left side strong."""
c = self.left
if c.left is None:
c.value, c.right.value = c.right.value, c.value
c.left, c.right = c.right, None
else:
c._rotate_left()
def _pull_right(self):
"""Pull the node balance to load left side strong."""
c = self.right
if c.right is None:
c.value, c.left.value = c.left.value, c.value
c.right, c.left = c.left, None
else:
c._rotate_right()
def _rotate_right(self):
"""Rotate self around right to rebalance."""
a, b, c = self.parent, self, self.left
if a is None:
try:
c.parent, b.parent = a, c
b.left, c.right.parent, c.right = c.right, b, b
except AttributeError:
c.parent, b.parent = a, c
b.left, c.right = c.right, b
else:
try:
if a.value > b.value:
c.parent, b.parent, a.left = a, c, c
b.left, c.right.parent, c.right = c.right, b, b
else:
c.parent, b.parent, a.right = a, c, c
b.left, c.right.parent, c.right = c.right, b, b
except AttributeError:
if a.value > b.value:
c.parent, b.parent, a.left = a, c, c
b.left, c.right = c.right, b
else:
c.parent, b.parent, a.right = a, c, c
b.left, c.right = c.right, b
def _rotate_left(self):
"""Rotate self around left to rebalance."""
a, b, c = self.parent, self, self.right
if a is None:
try:
c.parent, b.parent = a, c
b.right, c.left.parent, c.left = c.left, b, b
except AttributeError:
c.parent, b.parent = a, c
b.right, c.left = c.left, b
else:
try:
if a.value < b.value:
c.parent, b.parent, a.right = a, c, c
b.right, c.left.parent, c.left = c.left, b, b
else:
c.parent, b.parent, a.left = a, c, c
b.right, c.left.parent, c.left = c.left, b, b
except AttributeError:
if a.value < b.value:
c.parent, b.parent, a.right = a, c, c
b.right, c.left = c.left, b
else:
c.parent, b.parent, a.left = a, c, c
b.right, c.left = c.left, b
def _get_dot(self):
"""Recursively prepare a dot graph entry for this node."""
if self.left is not None:
yield "\t%s -> %s;" % (self.value, self.left.value)
for i in self.left._get_dot():
yield i
elif self.right is not None:
r = random.randint(0, 1e9)
yield "\tnull%s [shape=point];" % r
yield "\t%s -> null%s;" % (self.value, r)
if self.right is not None:
yield "\t%s -> %s;" % (self.value, self.right.value)
for i in self.right._get_dot():
yield i
elif self.left is not None:
r = random.randint(0, 1e9)
yield "\tnull%s [shape=point];" % r
yield "\t%s -> null%s;" % (self.value, r)
class BST(object):
"""Define Binart Search Tree class(BST)."""
def _reset(self):
"""Reset class variables for testing."""
self.length = 0
self.top = None
def __init__(self, values=[]):
"""Initialize BST class."""
self._reset()
if isinstance(values, list):
for value in values:
self.insert(value)
else:
raise TypeError("Please package your item into a list!")
def insert(self, value):
"""Insert a value into the binary heap."""
try:
float(value)
if self.contains(value):
pass
else:
cursor = self.top
new_node = Node(value)
if self.top is None:
self.top = new_node
else:
while cursor is not None:
if cursor.value > new_node.value:
old_cursor = cursor
cursor = cursor.left
else:
old_cursor = cursor
cursor = cursor.right
if old_cursor.value > new_node.value:
new_node.parent = old_cursor
old_cursor.left = new_node
else:
new_node.parent = old_cursor
old_cursor.right = new_node
self.top = old_cursor.balance_tree()
self.length += 1
except (ValueError, AttributeError):
raise TypeError("This tree only accepts integers or floats.")
def contains(self, value):
"""Return a boolean if the node value is contained."""
if self.top:
cursor = self.top
while cursor is not None:
if value == cursor.value:
return True
if cursor.value > value:
cursor = cursor.left
else:
cursor = cursor.right
return False
def size(self):
"""Return the values in the tree."""
return self.length
def depth(self):
"""Return the number of levels in the tree."""
if not self.top:
return 0
return self.top.depth()
def balance(self):
"""Return a value representing the right to left balance."""
if not self.top:
return 0
return self.top.balance()
def pre_order(self):
"""Return a generator of a pre-order traversal."""
if self.top:
for ii in self.top.pre_order():
yield ii
else:
print('Empty Tree!')
def in_order(self):
"""Return a generator of a in-order traversal."""
if self.top:
for ii in self.top.in_order():
yield ii
else:
print('Empty Tree!')
def post_order(self):
"""Return a generator of a post-order traversal."""
if self.top:
for ii in self.top.post_order():
yield ii
else:
print('Empty Tree!')
def breath_first(self):
"""
Breadth First Traveral using a Deque as a queue.
Is used as a generator.
"""
d = deque([self.top])
while d:
vertex = d.popleft()
if vertex:
yield vertex.value
if vertex.left:
d.append(vertex.left)
if vertex.right:
d.append(vertex.right)
def _no_children(self, delete_node):
"""Delete the desired node with no children and return None."""
if delete_node.parent is not None:
if delete_node.value > delete_node.parent.value:
delete_node.parent.right = None
else:
delete_node.parent.left = None
else:
self.top = delete_node = None
def _one_child(self, delete_node, child_direction):
"""Delete a node with one child and return None."""
if delete_node.parent:
if child_direction == 'left':
if delete_node.value < delete_node.parent.value:
delete_node.parent.left = delete_node.left
delete_node.left.parent = delete_node.parent
else:
delete_node.parent.right = delete_node.left
delete_node.left.parent = delete_node.parent
else:
if delete_node.value > delete_node.parent.value:
delete_node.parent.right = delete_node.right
delete_node.right.parent = delete_node.parent
else:
delete_node.parent.left = delete_node.right
delete_node.right.parent = delete_node.parent
else:
if child_direction == 'left':
delete_node.left.parent = None
self.top = delete_node.left
else:
delete_node.right.parent = None
self.top = delete_node.right
def _two_children(self, del_node):
"""Delete a node with two children."""
cursor = del_node.right
while cursor.left is not None:
cursor = cursor.left
del_node.value, cursor.value = cursor.value, cursor.value + del_node.value
cursor = del_node.right
while cursor.left is not None:
cursor = cursor.left
if cursor.right:
self._one_child(cursor, 'right')
else:
self._no_children(cursor)
def delete(self, val):
"""Remove the value of choice from the BST."""
if self.top:
cursor = self.top
while cursor is not None:
if val == cursor.value:
self.length -= 1
if cursor.left and cursor.right:
self._two_children(cursor)
if cursor.parent is None:
cursor.balance_tree()
elif cursor.left:
self._one_child(cursor, 'left')
elif cursor.right:
self._one_child(cursor, 'right')
else:
self._no_children(cursor)
if cursor.parent is not None:
self.top = cursor.parent.balance_tree()
break
if cursor.value > val:
cursor = cursor.left
else:
cursor = cursor.right
def write_graph(self):
"""Write dots to a file."""
file = io.open('graph.gv', 'w')
file.write(self.get_dot())
file.close()
print('graph.gv is update')
def get_dot(self):
"""Return the tree with root 'self' as a dot graph."""
return "digraph G{\n%s}" % ("" if self.top is None else (
"\t%s;\n%s\n" % (
self.top.value,
"\n".join(self.top._get_dot())
)
))
if __name__ == '__main__':
list_ = [991, 482, 206, 326, 66, 859, 193, 10, 323]
b = BST()
for value in list_:
b.insert(value)
b.delete(713)
b.write_graph()
|
3f6088bf3a7198fde18a9854e2c07e104e2c9dfa | CurtisFord1997/Indian-Hills | /Python/Lab4/Challenge.py | 693 | 4.1875 | 4 | #chalange 1
for numRows in range(7,0,-1):
row = "" #starts the row blank
for stars in range(numRows): #concatinates the number of stars equal to the num rows left
row = row + "*"
print(row)
#chalange 2
row = "#" #starts row off with just a lonely hashtag
for numRows in range(7):
if numRows == 0:#row 0 has no spaces so don't add any spaces to the middle
row = row
elif numRows % 3 == 0:#if the row is divisible by three(counting from 0) add three spaces
row += " "
else:#if the row is not divisible by three add two spaces
row += " "
print(row+"#")#prints the row adding a hashtag on the end, but does not change sthe string row |
f57c603f6a43d1a9074c88cbe0ab8e2a63feed14 | nottsgeek/py | /examples/readfile.py | 456 | 3.75 | 4 | #!/usr/bin/python
#you should have a file named template in your path
#Read file and store data as a string
'''
f=open('template', 'r')
data=f.read()
f.close()
print data
'''
#Read file line by line and store all lines as a list
'''
f=open("template", 'r')
datalist=f.readlines()
f.close()
print datalist
'''
#Read and process file line by line
'''
f=open('template', 'r')
line=f.readline()
while line:
print line
line=f.readline()
f.close()
'''
|
8f838966cfa42e63cc2c29135dc8b5761513b1f3 | MahaSabry5/CS50-2020 | /Problem_set6/cash.py | 558 | 3.71875 | 4 | from cs50 import *
from math import *
# make sure that the change not negative just positive number
while True:
n = get_float("Change owed: ")
if (n >= 0):
break
count = 0
coins = round(n * 100)
# calculate cash that will be paid
while (coins != 0):
if (coins >= 25 ):
count += 1
coins -= 25
elif (coins >= 10 ):
count += 1
coins -= 10
elif (coins >= 5 ):
count += 1
coins -= 5
elif (coins >= 1 ):
count += 1
coins -= 1
print(count)
|
c081568084595ded1928e565c02f97accb6c779f | pushkaraditya/pythonds | /chapter5/exploringMazeProblem.py | 5,377 | 3.84375 | 4 | import turtle
blockCell = 'X'
openCell = ''
startingCell = 'S'
class Maze():
ch = 25 # cell height
cw = 25 # cell width
bc = 'grey' # color for blocked cell
dc = 'white' # color of open cell
wip = 'yellow'
dead = 'red'
path = 'green'
def __init__(self, turtle, maze):
self.m = maze
self.cm = None
self.t = turtle
self.pos = self.t.pos()
self.start = None
self.draw()
self.setStartPointer(self.start)
self.solve()
def getColor(self, v):
color = self.dc
if v == blockCell: # blocked
color = self.bc
elif v == startingCell:
color = self.wip
return color
def drawCell(self, i, j, color):
x, y = self.getCellStart(i, j)
self.t.up()
self.t.goto(x, y)
self.t.down()
self.t.fillcolor(color)
self.t.begin_fill()
self.t.goto(x + self.cw, y)
self.t.goto(x + self.cw, y + self.ch)
self.t.goto(x, y + self.ch)
self.t.goto(x, y)
self.t.end_fill()
def getCellStart(self, i, j):
y = self.pos[1] - i * self.cw
x = self.pos[0] + j * self.ch
return x, y
def draw(self):
i = 0
for row in self.m:
j = 0
for c in row:
if c == startingCell:
self.start = (i, j)
# print(self.start)
color = self.getColor(c)
self.drawCell(i, j, color)
j += 1
i += 1
def setStartPointer(self, p):
i, j = p
x, y = self.getCellStart(i, j)
self.t.up()
self.t.goto(x, y)
self.t.down()
def copyMaze(self):
self.cm = [[v for v in row] for row in self.m] # copied maze
def evaluate(self, i, j):
# 4 points, clock wise
# check if already evaluated
# if not, evaluate near by
# it could be wall
# do not move forward
# it could be red
# do not move forward
# it could be green
# do not move forward
# it could be wip
# do not move forward, it will be evaluated automatically later
# it could be open
# is it boundry
# mark it green
# else yellow and move forward
# print('evaluating ({}, {})'.format(i, j))
cv = self.cm[i][j]
if cv in [blockCell, 'red', 'green', 'yellow']:
# print('({}, {}) => {}'.format(i, j, cv))
return cv
elif cv == openCell:
if i == 0 or j == 0 or i == len(self.cm) - 1 or j == len(self.cm[i]) - 1:
# print('({}, {}) => green for boundary condition'.format(i, j))
self.cm[i][j] = 'green'
# print(self.cm)
self.drawCell(i, j, 'green')
return 'green'
else:
self.cm[i][j] = 'yellow'
self.drawCell(i, j, 'yellow')
# l = self.evaluate(i, j - 1)
# u = self.evaluate(i - 1, j)
# r = self.evaluate(i, j + 1)
# d = self.evaluate(i + 1, j)
# # print(l, u, r, d)
# if 'green' in [l, u, r, d]:
if self.evaluate(i, j - 1) == 'green' or self.evaluate(i - 1, j) == 'green' or self.evaluate(i, j + 1) == 'green' or self.evaluate(i + 1, j) == 'green':
self.cm[i][j] = 'green'
# print(self.cm)
self.drawCell(i, j, 'green')
return 'green'
else:
self.cm[i][j] = 'red'
# print(self.cm)
self.drawCell(i, j, 'red')
return 'red'
def solve(self):
i, j = self.start
self.copyMaze()
self.cm[i][j] = openCell
self.evaluate(i, j)
# self.drawCell(1, 1, self.wip)
# self.drawCell(2, 1, self.wip)
# self.drawCell(2, 1, self.path)
# self.drawCell(1, 1, self.path)
def main():
t = turtle.Turtle()
s = turtle.Screen()
t.up()
t.goto(-300, 220)
t.down()
x = blockCell
S = startingCell
o = openCell
# m = [
# [x,x,x,x,x],
# [x,o,o,o,x],
# [x,S,x,o,x],
# [x,x,o,o,x],
# [x,x,o,x,x]
# ]
# m = [
# [x,x,x],
# [x,S,x],
# [x,o,x]
# ]
# m = [
# [x,x,x,x],
# [x,S,o,x],
# [x,o,o,x],
# [x,x,x,x]
# ]
m = [
[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],
[x,o,o,o,x,o,o,o,x,x,o,x,x,o,o,o,o,o,x,o,o,o],
[x,o,x,o,o,o,x,o,o,o,o,o,o,o,x,x,x,o,x,o,x,x],
[x,o,x,o,x,o,o,x,x,o,o,x,x,x,x,o,o,o,x,o,x,x],
[x,x,x,o,x,x,x,x,x,x,o,o,o,o,x,x,x,o,x,o,o,x],
[x,o,o,o,o,o,o,o,o,o,o,x,x,o,o,x,x,o,o,o,o,x],
[x,x,x,x,x,o,x,x,x,x,x,x,o,o,o,x,x,x,x,x,o,x],
[x,o,o,o,o,o,x,o,o,o,x,x,x,x,x,x,x,o,o,x,o,x],
[x,o,x,x,x,x,x,x,x,o,o,o,o,o,o,S,o,x,o,o,o,x],
[x,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,x,o,x,x,x],
[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,o,x,x,x],
]
m = Maze(t, m)
s.exitonclick()
main() |
399cb6b08bbb9e4d6550098da2af12e1ac4aa987 | mbelalsh/Data_Structures_Algorithms_Specialization_Coursera | /2_Data_Structures/Assignments/week1_basic_data_structures/1_brackets_in_code/Check_brackets_Sub.py | 1,325 | 3.609375 | 4 | # python3
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data[-1]
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data.pop()
S = ArrayStack()
def find_mismatch(expression):
opening = '({['
closing = ')}]'
accum = 0
sec = 0
S = ArrayStack()
for index, x in enumerate(expression, start=1):
#accum = accum + 1
if x in opening:
S.push((index,x))
elif x in closing:
if S.is_empty():
return index
j, k = S.pop()
if closing.index(x) != opening.index(k):
return index
#if not S.is_empty():
# sec += 1
# accum = accum - 2
if S.is_empty():
return 'Success'
else:
index, x = S.pop()
return index
def main():
text = input()
mismatch = find_mismatch(text)
# Printing answer, write your code here
print(mismatch)
return
if __name__ == "__main__":
main() |
714b8d3e2ab85b3d0224d4aea85ecd8db58b9588 | 362515241010/TueyDH | /ChangeDay.py | 675 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
mm,dd,yyyy = (str(e) for e in input().split())
if mm == "01" :
print(dd, "JAN", yyyy)
elif mm == "02" :
print(dd, "FEB", yyyy)
elif mm == "03" :
print(dd, "MAR", yyyy)
elif mm == "04" :
print(dd, "APR", yyyy)
elif mm == "05" :
print(dd, "MAY", yyyy)
elif mm == "06" :
print(dd, "JUN", yyyy)
elif mm == "07" :
print(dd, "JUL", yyyy)
elif mm == "08" :
print(dd, "AUG", yyyy)
elif mm == "09" :
print(dd, "SEP", yyyy)
elif mm == "10" :
print(dd, "OCT", yyyy)
elif mm == "11" :
print(dd, "NOV", yyyy)
elif mm == "12" :
print(dd, "DEC", yyyy)
else:
print("ERROR")
# In[ ]:
|
4a85411c612e35b13926471056076c1f43d16a3a | namth2015/python | /1.DataScience/2.BigO/Green18/lec12_symmetrical_number.py | 1,109 | 3.609375 | 4 |
def check_inverse(a):
def inverse(n):
if n == 0:
return 0
step = n // 10
num = str(n % 10)
func = str(inverse(step))
return num + func
if a == int(inverse(a))/10:
return True
else:
return False
class node:
def __init__(self,data = None, next = None):
self.data = data
self.next = next
class linkedlist:
def __init__(self):
self.head = None
self.tail = None
def insertTail(self,data):
p = node(data)
if self.head == None:
self.head = self.tail = p
else:
self.tail.next = p
self.tail = p
def print(self):
itr = self.head
while itr:
print(itr.data, end = ' ')
itr = itr.next
ll = linkedlist()
idx = 0
while True:
n = int(input())
if n == -1:
break
ll.insertTail(n)
ll_idx = linkedlist()
itr = ll.head
while itr:
if check_inverse(itr.data):
ll_idx.insertTail(idx)
idx += 1
itr = itr.next
ll_idx.print()
# m = 121
# print(check_inverse(m)) |
b134be7668f89639b9745e63466eae390f138290 | Tuchev/Python-Fundamentals---january---2021 | /05.Lists_Advanced/03.Lists_Advanced_-_More_Exercises/03. Take-Skip Rope.py | 1,117 | 3.859375 | 4 | encrypted = input()
encrypted_list = []
if " " in encrypted:
for char in range(len(encrypted)):
encrypted_list.append(encrypted[char])
else:
encrypted.replace("", " ").split()
for char in range(len(encrypted)):
encrypted_list.append(encrypted[char])
numbers = []
decrypted = []
non_numbers = []
count = 0
index = 0
for x in range(len(encrypted_list)):
if encrypted_list[x].isnumeric():
numbers.append(int(encrypted_list[x]))
else:
non_numbers.append(encrypted_list[x])
take_list = [numbers[index] for index in range(len(numbers)) if index % 2 == 0]
skip_list = [numbers[index] for index in range(len(numbers)) if index % 2 == 1]
for i in range(len(take_list)):
current_take_part = int(take_list[i])
current_skip_part = int(skip_list[i])
for add in range(current_take_part):
decrypted.append(non_numbers[index])
if len(non_numbers) - 1 < index + 1:
break
else:
index += 1
count += (current_take_part + current_skip_part)
index = count
print("".join(decrypted)) |
f8d86b89f376f496a560ab8891cadb93e5249a89 | gvaldovi/CursoIA2021 | /dia5/PruebaPandas.py | 473 | 3.546875 | 4 | import pandas as pd
#Serie: Columna de una tabla
#DataFrame
a=[1,5,2]
b = pd.Series(a,index=['x','y','z'])
print(b)
print(b['x'])
calorias = {'Lunes':420,'Martes':300,'Miercoles':320}
c=pd.Series(calorias,index=['Lunes','Miercoles'])
print(c)
print(c['Lunes'])
#DataFrame
datos={
'calorias':[420,300,320],
'duracion':[50,40,45]
}
d=pd.DataFrame(datos,index=['Lunes','Martes','Miercoles'])
print(d)
print(d.loc[['Lunes','Miercoles']])
#datos.xlsx
#datos.csv |
cea0d78c8a8420416e7498fb553bd8fd6befd62d | emersonleite/python | /Introdução a Programação com Python - exercícios baixados do site oficial/Exercícios/exercicio-07-05.py | 962 | 4.40625 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2014
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/1012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios_resolvidos\capitulo 07\exercicio-07-05.py
##############################################################################
primeira = input("Digite a primeira string: ")
segunda = input("Digite a segunda string: ")
terceira = ""
for letra in primeira:
if letra not in segunda:
terceira += letra
if terceira == "":
print("Todos os caracteres foram removidos.")
else:
print("Os caracteres %s foram removidos de %s, gerando: %s" % (segunda, primeira, terceira))
|
e1a03c4b1df0f630e5c72808cbcca6e57f80c7a0 | selam-weldu/algorithms_data_structures | /leet_code/python/binary/add_numbers.py | 1,661 | 3.9375 | 4 | class Solution:
def getSum(self, a: int, b: int) -> int:
## RC ##
## APPROACH : BITWISE OPERATIONS ##
## LOGIC ##
# 1. For any two numbers, if their binary representations are completely opposite, then XOR operation will directly produce sum of numbers ( in this case carry is 0 )
# 2. what if the numbers binary representation is not completely opposite, XOR will only have part of the sum and remaining will be carry, which can be produced by and operation followed by left shift operation.
# 3. For Example 18, 13 => 10010, 01101 => XOR => 11101 => 31 (ans found), and operation => carry => 0
# 4. For Example 7, 5
# 1 1 1 1 1 1
# 1 0 1 1 0 1
# ----- -----
# 0 1 0 => XOR => 2 1 0 1 => carry => after left shift => 1 0 1 0
# 2 10
# now we have to find sum of 2, 10 i.e a is replace with XOR result and b is replaced wth carry result
# similarly repeating this process till carry is 0
# steps will be 7|5 => 2|10 => 8|4 => 12|0
## TIME COMPLEXITY : O(1) ##
## SPACE COMPLEXITY : O(1) ##
# 32 bit mask in hexadecimal
mask = 0xffffffff # (python default int size is not 32bit, it is very large number, so to prevent overflow and stop running into infinite loop, we use 32bit mask to limit int size to 32bit )
while(b & mask > 0):
carry = (a & b) << 1
a = a ^ b
b = carry
return (a & mask) if b > 0 else a |
08d6a2b740c1b22c711a6b14db16ad96422b58ba | AJ-Walker/DS | /Practical3.a.py | 961 | 4.09375 | 4 | # Implement the following for Stack:
# Perform Stack operations using Array implementation.
class Stack:
def __init__(self,data=[]):
self.data = []
def is_empty(self):
self.len_data = len(self.data)
return self.len_data
def push(self,elememt):
self.data.append(elememt)
def pop(self):
if self.is_empty():
print("Array is empty")
else:
self.data.pop()
def top_element(self):
print("Top element of stack : ",self.data[-1])
def display(self):
print(self.data)
print(self.is_empty())
stackOperation = Stack()
stackOperation.display()
stackOperation.push(23)
stackOperation.push(45)
stackOperation.push(12)
stackOperation.display()
stackOperation.top_element()
stackOperation.pop()
stackOperation.display()
stackOperation.pop()
stackOperation.pop()
stackOperation.display()
stackOperation.pop()
|
34d744b7259f2ad82d4fb67de05b7b084c33e9d1 | uu64/project-euler | /problem007.py | 333 | 3.640625 | 4 | # -*- coding: utf-8 -*-
prime_list = [2]
number = 3
while True:
for i in range(len(prime_list)):
if number % prime_list[i] == 0:
break
else:
if i == len(prime_list)-1:
prime_list.append(number)
if len(prime_list) == 10001:
break
number += 2
print(number)
|
b151de83dad84fe34f44aba7e7fbd108a11298c9 | railodain/TaskManager | /Task Manager/module/functions.py | 2,056 | 3.796875 | 4 | from classes import TaskInventory
# Main chat function
def start_working():
"Prints various methods of TaskInventory given input messages."
# An instance of TaskInventory
my_tasks = TaskInventory()
# Variable decides whether work session continues or not
user_working = True
while user_working:
# Default message
message = input("""\nWhat would you like to do? \n
- Input task \n
- Mark task completed \n
- Get schedule \n
- Get recommended task \n
- Rest for now \n\n""")
# Conditional for adding new tasks
if message.lower() == "input task":
task_name = input("\nWhat is the name of your task? \n")
task_due_date = input("What date is your task due? (dd/mm/yy) \n")
task_amt_time = input("How many hours will it take? \n")
task_difficulty = input("Is this task easy, or hard to focus on? \n")
my_tasks.add_task(task_name, task_due_date, task_amt_time, task_difficulty)
# Conditional for removing completed tasks
if message.lower() == "mark task completed":
completed_task = input("\n What task did you finish? (Case Sensitive) \n")
my_tasks.delete_task(completed_task)
print("\nLook at you go!")
# Conditional for printing a schedule of tasks, by order of due date
if message.lower() == "get schedule":
my_tasks.print_schedule()
# Conditional for printing recommended task
if message.lower() == "get recommended task":
mood = input("\nAre you feeling focused, or unfocused? \n")
print("\nSince you're feeling {}, I recommend you work on your task '{}'.".format(mood.lower(), my_tasks.recommend_task(mood)))
# Conditional for ending work session
if message.lower() == "rest for now":
print("\nGreat work!")
user_working = False
|
eb6cc67aa1d393850cd43bf191c60d5da5fc714f | bj1570saber/muke_Python_July | /cha_5_variable_operator/5-10-member_operator.py | 1,219 | 3.703125 | 4 | '''Summary:
1. compare type:
#can not compare child instance.
type(a)==type(b)
type(a)==int
#compare 'child instance' too.
A better type check: isinstance(a,int):return T F
2. a == b :compare value 1==1.0 True
3. a is b :compare id() 1 is 1.0 False
'''
# isinstance()
a = 'Hello'
b = 1.3
t_1 = (int, str, bool)
print(isinstance(a,t_1))#True
print(isinstance(b,t_1))#False
print('~'*20)
# Member operator in & not in
print(1 in [1,2,3])#True
print('a' in 'aim')#True
print(0 not in (1,2,3))#True
print(0 not in{0,1,2})#False
print()
# in dict, matc h key
print('a' in {'a':1, 'b':2})#True
print('a' in {1:'a', 2:'b'})#False
print('~'* 20)
# Identity operator
print('Identity operator:')
a = 1
b = 1
print(a==b)#True
print(a is b)#True !!!
print('\na = 1.0:')
a = 1.0
print(a==b)#True
print(a is b)#False is-> more accurate
print(id(a))
print(id(b))
print('a and b have different address.\n')
print('~'*20)
c = [1,2]
d = [1,2]
print(c==d)#True
print(c is d)#False
print()
#
e = {1,2,3}
f = {2,3,1}
print(e==f)#True
print(e is f)#False
print()
# tuple order is immutable.
g = (1,2,3)
h = (2,3,1)
print(g==h)#False
print(g is h)#False
z=1
y=2
x=3
print(z+y*x)
print(z or y and x) |
7dcadb894621e3c9c183e4000c427882f218872f | zeynepidil/gaih-students-repo-example | /Homeworks/HW3.py | 1,000 | 3.859375 | 4 | #Explain your work
#Day4Homework
def prime_first(num):
num=int(input("Please enter an integer value"))
def prime_second(num):
num=int(input("Please enter an integer value"))
for i in range(0,1000):
for i in range(0,500):
if num>1:
for i in range(2,num):
if (num%i)==0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
for i in range(500,1000):
if num>1:
for i in range(2,num):
if (num%i)==0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
|
8b4ca150fdcdc177493f2690e716fe372d032ef7 | onlinejudge95/materials | /creating-and-modifying-pdfs/source_code/01-extracting-text-from-a-pdf.py | 1,407 | 3.640625 | 4 | # ---------------
# Open a PDF File
# ---------------
from PyPDF2 import PdfFileReader
# You might need to change this to match the path on your computer
from pathlib import Path
pdf_path = (
Path.home()
/ "creating-and-modifying-pdfs"
/ "practice_files"
/ "Pride_and_Prejudice.pdf"
)
pdf = PdfFileReader(str(pdf_path))
print(pdf.getNumPages())
print(pdf.documentInfo)
print(pdf.documentInfo.title)
# ---------------------------
# Extracting Text From a Page
# ---------------------------
first_page = pdf.getPage(0)
print(type(first_page))
print(first_page.extractText())
for page in pdf.pages:
print(page.extractText())
# -----------------------
# Putting It All Together
# -----------------------
from pathlib import Path # noqa
from PyPDF2 import PdfFileReader # noqa
# Change the path below to the correct path for your computer.
pdf_path = (
Path.home()
/ "creating-and-modifying-pdfs"
/ "practice-files"
/ "Pride_and_Prejudice.pdf"
)
pdf_reader = PdfFileReader(str(pdf_path))
output_file_path = Path.home() / "Pride_and_Prejudice.txt"
with output_file_path.open(mode="w") as output_file:
title = pdf_reader.documentInfo.title
num_pages = pdf_reader.getNumPages()
output_file.write(f"{title}\\nNumber of pages: {num_pages}\\n\\n")
for page in pdf_reader.pages:
text = page.extractText()
output_file.write(text)
|
20361ae5a29ff8f76ab205e34138db60bfd48d31 | gabriellaec/desoft-analise-exercicios | /backup/user_029/ch84_2019_08_28_18_04_57_047001.py | 213 | 3.5625 | 4 | def inverte_dicionario(d):
novo_d = {}
for nome,idade in d.items():
if idade not in novo_d:
novo_d[idade]= [nome]
else:
novo_d[idade].append(nome)
return novo_d |
5d7db16b8b513f6e1916bbc2796567be1b978446 | creatist/neural_network_regression | /regression.py | 1,603 | 3.796875 | 4 | #该代码从https://blog.csdn.net/marsjhao/article/details/67042392 修改得来
import numpy as np
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
# 生成数据
X = np.linspace(-1, 1, 200) #在返回(-1, 1)范围内的等差序列
np.random.shuffle(X) # 打乱顺序
#Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, )) #生成Y并添加噪声
Y = X*X + np.random.normal(0, 0.05, (200, )) #生成Y并添加噪声
# plot
plt.scatter(X, Y)
plt.show()
X_train, Y_train = X[:160], Y[:160] # 前160组数据为训练数据集
X_test, Y_test = X[160:], Y[160:] #后40组数据为测试数据集
# 构建神经网络模型
model = Sequential()
model.add(Dense(input_dim=1, units=10))
model.add(Dense(10,activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(10,activation='relu'))
model.add(Dense(8,activation='relu'))
model.add(Dense(1))
# 选定loss函数和优化器
model.compile(loss='mse', optimizer='sgd')
# 训练过程
print('Training -----------')
for step in range(501):
cost = model.train_on_batch(X_train, Y_train)
if step % 50 == 0:
print("After %d trainings, the cost: %f" % (step, cost))
# 测试过程
print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights()
print('Weights=', W, '\nbiases=', b)
# 将训练结果绘出
Y_pred = model.predict(X_test)
plt.scatter(X_test, Y_test, c='b')
plt.scatter(X_test, Y_pred, c='r')
#plt.plot(X_test, Y_pred)
plt.show() |
59e55fc83c5bf49b88edbe42a2cfdc4736e73ae4 | aditi0330/Codecademy-Python-for-Data-Science | /Web Scraping/Web_Scraping_Beautiful_Soup.py | 3,377 | 3.765625 | 4 | import requests
webpage_response = requests.get('https://s3.amazonaws.com/codecademy-content/courses/beautifulsoup/shellter.html/http-requests')
webpage = webpage_response.content
print(webpage)
#Using Beautiful Soup
from bs4 import BeautifulSoup
webpage_response = requests.get('https://s3.amazonaws.com/codecademy-content/courses/beautifulsoup/shellter.html')
webpage = webpage_response.content
soup = BeautifulSoup(webpage, "html.parser")
print(soup)
#to print the first p tag
print(soup.p)
#to print string associated with the first p tag
print(soup.p.string)
for child in soup.ul.children:
print(child)
for parent in soup.li.parents:
print(parent)
#Above two loos print out the same thing.
#Loop through all of the children of the first div and print out each one.
for child in soup.div.children:
print(child)
#FindAll
#find all of the occurrences of a tag, instead of just the first one, we can use .find_all().
print(soup.find_all("h1"))
#Using Regex
#every <ol> and every <ul> that the page contains
import re
soup.find_all(re.compile("[ou]l"))
#we want all of the h1 - h9 tags that the page contains
import re
soup.find_all(re.compile("h[1-9]"))
#Using lists
#We can also just specify all of the elements we want to find by supplying the function with a list of the tag names we are looking for
soup.find_all(['h1', 'a', 'p'])
#Using
#We can pass a dictionary to the attrs parameter of find_all with the desired attributes of the elements we’re looking for. If we want to find all of the elements with the "banner" class, for example, we could use the command
soup.find_all(attrs={'class':'banner'})
soup.find_all(attrs={'class':'banner', 'id':'jumbotron'})
#Using a function
def has_banner_class_and_hello_world(tag):
return tag.attr('class') == "banner" and tag.string == "Hello world"
soup.find_all(has_banner_class_and_hello_world)
#This command would find an element that looks like this:
<div class="banner">Hello world</div>
#To find all the a elements
turtle_links = soup.find_all("a")
print(turtle_links)
#To select all of the elements that have the class 'recipeLink'
soup.select(".recipeLink")
#we wanted to select the element that has the id 'selected'
soup.select("#selected")
for link in soup.select(".recipeLink > a"):
webpage = requests.get(link)
new_soup = BeautifulSoup(webpage)
#This loop will go through each link in each .recipeLink div and create a soup object out of the webpage it links to.
# So, it would first make soup out of <a href="spaghetti.html">Funfetti Spaghetti</a>, then <a href="lasagna.html">Lasagna de Funfetti</a>, and so on.
turtle_links = soup.find_all("a")
links = []
#go through all of the a tags and get the links associated with them:
for a in turtle_links:
links.append(prefix+a["href"])
#Define turtle_data:
turtle_data = {}
#follow each link:
for link in links:
webpage = requests.get(link)
turtle = BeautifulSoup(webpage.content, "html.parser")
#Add your code here:
turtle_name = turtle.select(".name")[0]
turtle_data[turtle_name] = []
print(turtle_data)
stats = turtle.find("ul")
stats_text = stats.get_text("|")
turtle_data[turtle_name] = stats_text.split("|")
turtle_df = pd.DataFrame.from_dict(turtle_data, orient='index') |
45898d3feb15cf9243a5dd6be292b0ae0607000e | shayansaha85/pypoint_QA | /set 3/5.py | 196 | 3.828125 | 4 | ask = 'y'
arr = []
while ask.lower()=='y':
el=input('Enter the next element: ')
arr.append(el)
ask=input('Do you want to enter more? (y/n): ')
print(arr)
print('Thanks for entering') |
e20f3fad2a5afddc76e2fd8ea1eb99ed3959e0a7 | Pulsatio/ICC-UTEC-2020-I | /Simulacro-ICC/p3.py | 267 | 3.953125 | 4 | while 1:
lado = int(input("Ingrese el lado del cuadrado: "))
if 5<=lado and lado<=10:
break
for i in range(lado):
for j in range(lado):
if i==0 or j==0 or i==lado-1 or j==lado-1 or i==j or i+j==lado-1:
print("*",end="")
else:
print(" ",end="")
print() |
5200fbcd89b1afce2f20da42b0c8a6352d3b1bf6 | BaoziSwifter/MyPythonLeetCode | /pythonLeetcode/105.从前序与中序遍历序列构造二叉树.py | 1,464 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=105 lang=python
#
# [105] 从前序与中序遍历序列构造二叉树
#
# https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
#
# algorithms
# Medium (62.44%)
# Likes: 288
# Dislikes: 0
# Total Accepted: 34K
# Total Submissions: 54K
# Testcase Example: '[3,9,20,15,7]\n[9,3,15,20,7]'
#
# 根据一棵树的前序遍历与中序遍历构造二叉树。
#
# 注意:
# 你可以假设树中没有重复的元素。
#
# 例如,给出
#
# 前序遍历 preorder = [3,9,20,15,7]
# 中序遍历 inorder = [9,3,15,20,7]
#
# 返回如下的二叉树:
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 203/203 cases passed (176 ms)
# Your runtime beats 47.52 % of python submissions
# Your memory usage beats 11.94 % of python submissions (86.4 MB)
class Solution(object):
def buildTree(self, preorder, inorder):
if not preorder:
return None
rootValue = preorder[0]
index = inorder.index(rootValue)
root = TreeNode(rootValue)
root.left = self.buildTree(preorder[1:index+1],inorder[:index])
root.right = self.buildTree(preorder[index+1:],inorder[index+1:])
return root
# @lc code=end
|
1de9d8903f99406e83a0222dae68b4bfb77e4a96 | OyugoObonyo/alx-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 424 | 3.890625 | 4 | #!/usr/bin/python3
"""
Text identation
Contains:
text_identation()
"""
def text_indentation(text):
"""Idents the given text"""
if type(text) != str:
raise TypeError("text must be a string")
s = ""
for i in text:
if i in '.:?':
s += i
print(s.strip(" "), end="\n\n")
s = ""
else:
s += i
print(s.strip(" "), end="")
|
bfdd57f543072b232909069416e2b4576ee6d299 | Aasthaengg/IBMdataset | /Python_codes/p03555/s333885211.py | 103 | 3.640625 | 4 | a=input()
b=input()
if a[1]==b[1] and a[0]==b[2] and a[2]==b[0]:
print("YES")
else:
print("NO") |
484933f4d1a30557ad25dbbeb487161f53608b18 | jmontara/become | /Ch2/variables.py | 593 | 3.953125 | 4 | #
# Example file for variables
#
# declare variable and initialize items
f = 0
print(f)
# re-declaring the variabe works
f = 'abc'
print(f)
# ERROR, variables of different types can not be combined
# python is strongly typed, even though you don't need to declare
# the value. The type is inferred by the compiler/interperter.
print("this is a str ", str(1234))
# global vs local variables
f = 0
print(f)
def some_function():
f = 1
print(f)
some_function()
def some_function():
global f
print(f)
some_function()
# delete variable, should produce a problem
del f
# print(f) |
dfe45a2da92821e2e20155bc4aa0a4e9aa3d8a00 | ShengYg/algorithms | /Leetcode/153 Find Minimum in Rotated Sorted Array.py | 1,262 | 3.578125 | 4 | class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo = 0
hi = len(nums)
mini = float('inf')
while lo < hi:
mid = (lo + hi)/2
mini = min(mini, nums[mid])
if nums[lo] <= nums[mid] <= nums[hi-1]:
return min(mini, nums[lo])
elif nums[lo] > nums[mid] < nums[hi-1]:
hi = mid
else:
lo = mid+1
return mini
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo = 0
hi = len(nums) - 1
while lo < hi:
mid = (lo + hi)/2
if nums[mid] < nums[hi]:
hi = mid
elif nums[mid] > nums[hi]:
lo = mid+1
return nums[lo]
# if array is decreased
def findMin2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo = 0
hi = len(nums) - 1
while lo < hi:
mid = (lo + hi)/2 + 1
if nums[mid] > nums[lo]:
hi = mid - 1
elif nums[mid] < nums[lo]:
lo = mid
return nums[lo]
|
86af59493ad5cc5d80a6634fd715301743ec62ce | madjabal/abstract-algebra-polynomial | /polynomial.py | 2,338 | 3.859375 | 4 | # Rough Draft of Polynomial Object for the purposes of studying and manipulating field polynomials
class Polynomial:
coefficients_d = {}
coefficients_l = []
highest_degree = 0
field = 0
def __init__(self, coefficients, field):
# Checks for input type and edits the corresponding attribute, including highest degree
if type(coefficients) == dict:
for key in coefficients:
if coefficients[key] == 0:
del key
self.coefficients_d = coefficients
self.highest_degree = max(self.coefficients_d)
elif type(coefficients) == list:
index = coefficients[coefficients.length - 1]
while coefficients[index] != 0:
coefficients = coefficients[:-1]
self.coefficients_l = coefficients
self.highest_degree = coefficients
else:
print("Error: coefficients must be input as a list or dictionary with key or index referring to the degree "
"of the variable")
# Checks for field and modifies the corresponding attribute
if field == 0:
self.field = field
elif type(field) != int:
print("Error: field must be input as an integer, the field of reals is input as 0")
elif len([i for i in range(1, field) if field % i == 0]) != 0 or field == 1:
print("Error: the modulus of a field must be a prime number")
elif len([i for i in range(1, field) if field % i == 0]) == 0:
self.field = field
# for
# Fills in the remaining attribute (either coefficients_d or coefficients_l)
if type(coefficients) == dict:
for coef in range(self.highest_degree):
if coef in self.coefficients_d:
self.coefficients_l.append(self.coefficients_d[coef])
else:
self.coefficients_l.append(coef)
elif type(coefficients) == list:
for coef_i in range(self.coefficients_l):
if self.coefficients_l[coef_i] != 0:
self.coefficients_d[coef_i] = self.coefficients_l[coef_i]
# def __repr__(self):
# s = ""
# for coeff in self.coefficients_d:
# ADJUST THE FIELD CREATION TO MODULUS THE COEFFICIENTS
|
e37671d99fc9ea76e8f4bf0eb9eaecf72d8a7623 | LanderVanLuchene/test | /Lesweek2/Oefening 10.py | 149 | 3.53125 | 4 | def calculate (a, b, c, d):
return a + b - c + d
print (1, 2, 3, 4)
print (calculate(2, 2, 2, 2))
print (calculate(2,2,2,3)==calculate(1,2,3,4)) |
3b0c7b89447aaa2ac8fe685fe0451d7e2d49b38c | abaldeg/EjerciciosPython | /pypart.py | 250 | 3.828125 | 4 | #Alinear un número a la izquierda:
c="*{:<8}*".format(4)
print(c)
"""
*4 *
"""
#Alinear una cadena a la derecha:
c="*{:>8}*".format("Hola") # * Hola*
print(c)
#Alinear una cadena a la centrada:
c="*{:^8}*".format("Hola") # * Hola*
print(c) |
2898abedc3011ff90fc70253d8095cfc5c4385d8 | jinxing-star-design/easy-ppt | /python练习/面向对象/单向链表.py | 984 | 4 | 4 | class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
def __str__(self):
return '<{} -> {}>'.format(self.item,
self.next.item if self.next else 'None')
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.items = []
def append(self, item):
node = Node(item)
if self.head is None:
self.head = node
else:
self.tail.next = node
self.tail = node
self.items.append(node)
return self
def get(self, index):
return self.items[index]
def iternodes(self):
# current = self.head
# while current:
# yield current
# current = current.next
yield from self.items
ll = LinkedList()
ll.append(1)
ll.append(2).append(3)
for x in ll.iternodes():
print(x)
|
79dc270bd9d114f34f8493b9c5a8d24b2ccce6b1 | drewhutchison/dvlp2015 | /code/implementations/target.py | 334 | 3.546875 | 4 | def solution(pirates):
spoken = reduce(lambda spoken, dummy: (
spoken + [pirates[spoken[-1]]]
if pirates[spoken[-1]] not in spoken
else spoken),
pirates,
[0]
)
return len(spoken) - spoken.index(pirates[spoken[-1]])
|
85124e60549709a639c7483ce33f97a96acff648 | Dheerajdoppalapudi/Data-Structures | /linearsearch.py | 378 | 4 | 4 | #linear search python code
def linearSearch(arr, element):
for i in range(len(arr)):
if arr[i] == element:
return True
return False
string = input("Enter the number ")
arr = [int(x) for x in string.split()]
if linearSearch(arr,element = int(input('Enter the number to be search '))):
print("Number found ")
else:
print("Number not found ") |
3d8400607dca907058cf38ff5cd819d7adbf4e1a | s-mojtaba-a/DS | /DS package.py | 7,212 | 3.9375 | 4 | # A package including BST and LinkedList
# LinkedList
class node:
def __init__(self,data):
self.data=data
self.next=None # points to the next node
self.prev=None # points to the previous node
class linckedlist:
def __init__(self):
self.head=None
self.tail=None
# inserting a value to the tail of your linkedlist
def insert(self,val):
''' give me a value to insert it to the tail of your linkedlist '''
if not self.head :
self.head=node(val)
self.tail=self.head
else:
y=node(val)
self.tail.next=y
y.prev=self.tail
self.tail=y
# a method to delete the first node with the value = val
def delete(self,val):
''' give me the value which you want to delete
this method deletes the first node with the value = val '''
# finding the first node with data = val
x=x.head
while x.data!=val :
x=x.next
# deleting the node
if x!=x.head and x!=x.tail :
x.next.prev=x.prev
x.prev.next=x.next
elif x==self.head:
x.next.prev=None
self.head=x.next
elif x==x.tail and x.data==self.tail.data:
x.prev.next=None
self.tail=x.prev
else:
raise Exception ('{} did not found'.format(val))
# a method to find the k th element of your linkedlist
def find(self,k):
''' give a k in range ( 1 , lenght of your linkedlist )
this method will return the k th element of your linkedlist'''
x=x.head
if k==0:
raise Exception ('k is out of range')
while k>1:
try:
x=x.next
k-=1
except AttributeError:
raise Exception ('k is out of range')
if not x:
raise Exception ('k is out of range')
else:
return(x.data)
# a method to find the lenght of your linkedlist
def lenght(self):
''' this method will return the lenght of your linkedlist '''
k=1
x=self.head
while x!=self.tail:
x=x.next
k+=1
return k
# a method to delete the k th element of the list
def dell(self,k):
''' give a number in range ( 1 , lenght of your linkedlist ) '''
x=x.head
if k==0:
raise Exception ('k is out of range')
if k>self.lenght():
raise Exception ('k is out of range')
# finding the k th node
while k>1:
x=x.next()
k-=1
# deleting the k th node
if x!=x.head and x!=x.tail :
x.next.prev=x.prev
x.prev.next=x.next
elif x==self.head:
x.next.prev=None
self.head=x.next
elif x==x.tail and x.data==self.tail.data:
x.prev.next=None
self.tail=x.prev
# a method to print the linklist from head to tail
def printt(self):
''' it will print the linkedlist from head to tail '''
x=self.head
while x:
print(x.data,end=' ')
x=x.next
################################
############# BST ############
# making the bst's node
class nodee:
def __init__(self,data):
self.data=data
self.parent=None # points to the parent of a node
self.l=None # points to the left child
self.r=None # points to the right child
# making the bst class
class BST:
def __init__(self):
self.root=None # the root of our tree
# inserting a value to our tree
def insert(self,val):
''' inserts the value to the tree '''
if not self.root:
self.root=nodee(val)
return
x=self.root
y=nodee(val)
while True:
if x.data>= val :
if x.l:
x=x.l
else:
x.l=y
y.parent=x
break
else:
if x.r:
x=x.r
else:
x.r=y
y.parent=x
break
# searchs for a value and if the value is in tree , returns True and else returns False
def is_in_tree(self,val):
''' if val in tree :
returns True
else:
returns False
'''
if not self.root:
return False
x=self.root
while x.data!= val:
if val>x.data:
x=x.r
else:
x=x.l
if not x:
return False
return True
# a function to replace a nodde with it's child
def _replace(self,nodde,child):
if not nodde.parent: # nodde is the root of the tree
self.root=child
elif nodde.parent.l==nodde: # nodde is the left child of it's parent
nodde.parent.l=child
else: # nodde is the right child of it's parent
nodde.parent.r=child
child.parent=nodde.parent # changing the parent of child
# deleting a node
def delete(self,nodde):
''' deletes nodde from your tree '''
if not nodde.r:
self._replace(nodde,nodde.l)
elif not nodde.l :
self._replace(nodde,nodde.r)
else:
x=node.l
while x.r :
x=x.r
nodde.data=x.data
self.delete(x)
# printing in-order traversal of the tree starting from node x
def in_order(self,x):
''' it prints in-order traversal of the tree , starting from node x
if x = self.root , it will give you in-order traversal of the whole tree
'''
if not x:
return
self.in_order(x.l)
print(x.data,end=' ')
self.in_order(x.r)
# printing pre-order traversal of the tree starting from node x
def pre_order(self,x):
''' it prints pre-order traversal of the tree , starting from node x
if x = self.root , it will give you pre-order traversal of the whole tree
'''
if not x:
return
print(x.data,end=' ')
self.pre_order(x.l)
self.pre_order(x.r)
# printing post-order traversal of the tree starting from node x
def post_order(self,x):
''' it prints post-order traversal of the tree , starting from node x
if x = self.root , it will give you post-order traversal of the whole tree
'''
if not x:
return
self.post_order(x.l)
self.post_order(x.r)
print(x.data,end=' ')
if __name__ == '__main__':
my_bst=BST()
my_bst.insert(12)
my_bst.insert(1)
my_bst.insert(5)
my_bst.insert(-9)
my_bst.insert(3)
my_bst.insert(31)
my_bst.insert(1.8)
my_bst.insert(29)
my_bst.insert(33)
my_bst.insert(30)
my_bst.in_order(my_bst.root)
print()
my_bst.post_order(my_bst.root)
print()
my_bst.pre_order(my_bst.root)
print()
|
1959160771461fd8f934b83ea160bf8e9bc42235 | HimaniSoni/CtCI | /10.5 Sparse Search.py | 1,685 | 4 | 4 | def search(myList, start, end, target):
if start > end:
return -1
middle = (start + end) // 2
if target == myList[middle]:
return middle
if myList[middle] != '':
if target < myList[middle]:
return search(myList, start, middle - 1, target)
else:
return search(myList, middle + 1, end, target)
else:
before = after = middle
before, after = before - 1, after + 1
while (True):
# We look backwards
if before >= start:
if myList[before] != '':
if target == myList[before]:
return before
if target < myList[before]:
return search(myList, start, before - 1, target)
# Stop loking backwards
before = start - 1
else:
before -= 1
# We look forwards
elif after <= end:
if myList[after] != '':
if target == myList[after]:
return after
if target > myList[after]:
return search(myList, after + 1, end, target)
# Stop loking forwards
after = end + 1
else:
after += 1
# We arrived to both ends
else:
return -1
def sparseSearch(myList, target):
return search(myList, 0, len(myList) - 1, target)
if __name__ == "__main__":
myList = ['at', '', '', '', 'ball', '', '', 'car', '', '', 'dad', '', '', ]
print(sparseSearch(myList, 'ball'))
|
88fa5d8db82e4a9218bcc41689614ba11d617867 | n3n/CP2014 | /CodePython/pythonDuke/myPython.py | 728 | 3.765625 | 4 | def total_cost(type_car, isHasGPS, days, isSIIT):
return (cars_hire[type_car-1][1]*days + [0,200][isHasGPS]) * [1, 0.9][isSIIT]
cars_hire = [('BMW', 1800), ('Toyota', 1200), ('Honda', 600)]
# Choose car.
for i, car_hire in enumerate(cars_hire):
print str(i+1)+'.', car_hire[0], str(car_hire[1]) + '/day'
type_car = input('choose: ')
# want GPS ?
isHasGPS = False
if raw_input('Get GPS? 200/day (y/n)\nchoose: ') == 'y':
isHasGPS = True
# number of days of car hire.
days = input('Days for car hire: ')
# SIIT student ?
isSIIT = False
if raw_input('Are you SIIT student? (y/n)\nchoose: ') == 'y':
isSIIT = True
print '\nTotal cost: ' + str(total_cost(type_car, isHasGPS, days, isSIIT))
print 'Thanks you'
|
25c9e1ba1a6bcda1532a5b624f1f00b048389659 | ajinkyad13/LeetCode_For_Interviews | /Python_Solutions/79. Word Search.py | 1,038 | 3.6875 | 4 | class Solution:
def exist(board,word):
nrows = len(board)
ncols = len(board[0])
def backtrack(i, j, idx):
char = board[i][j]
if char != word[idx]:
return False
elif idx == len(word)-1:
return True
board[i][j] = ''
if i > 0 and backtrack(i-1, j, idx+1):
return True
if j > 0 and backtrack(i, j-1, idx+1):
return True
if i < nrows-1 and backtrack(i+1, j, idx+1):
return True
if j < ncols-1 and backtrack(i, j+1, idx+1):
return True
board[i][j] = char
return False
for i in range(nrows):
for j in range(ncols):
if backtrack(i, j, 0):
return True
return False
a = exist([['A','B','C','E'],['S','F','C','S'],['A','D','E','E']],"ABCCED")
print(a) |
149631ce889f74a12f7f06b3c2ff4796747214bd | VitBomm/CSC | /Module1/baikiemtra/bai_3.py | 1,408 | 3.671875 | 4 | # Tạo danh sách nhân viên kiểu dictionary với key là mã nhân viên,
# value bao gồm các thông tin : tên nhân viên, số điện thoại, lương.
# Cho phép người dùng lần lượt nhập các phần tử cho danh sách cho
# đến khi không muốn nhập nữa
# => Chương trình sẽ thực hiện những công việc sau:
# - Hiển thị danh sách nhân viên.
# - Cho phép người dùng tim kiếm theo mã nhân viên.
import copy
dict_temp = {}
print("Nhập thông tin danh sách nhân viên: ")
while(True):
manv = input("Nhập mã nhân viên: ")
tennv = input("Nhập tên nhân viên: ")
sdt = input("Nhập số điện thoại: ")
salary = eval(input("Nhập lương: "))
dict_temp[manv] = [tennv, sdt, salary]
con = int(input("Nhập giá trị tiếp hay không ? 1 Có, 0 : Không "))
if con == 0:
break
print("DSNV : ",dict_temp)
print('*'*50,'Danh sách nhân viên','*'*50)
print('Mã nv',' '*25,'Họ Tên',' '*25,'Số điện thoại',' '*25,'Lương')
for key,values in dict_temp.items():
print(key,' '*25,values[0], ' '*25, values[1], ' '*25,values[2])
x = input("Nhập mã nhân viên cần tìm: ")
if x in dict_temp.keys():
print("Thông tin nhân viên")
result = copy.copy(dict_temp[x])
result.insert(0,x)
print(result)
else:
print("Không tìm thấy nhân viên với mã: ",x)
|
ac132c19244b9ab6223da25e700f02491b0f23a3 | axeloh/hackerrank | /pythagorean_triplets.py | 1,196 | 4.375 | 4 | """
Given a list of numbers, find if there exists a pythagorean triplet
in that list.
A pythagorean triplet is 3 variables a, b, c where a^2 + b^2 = c^2
Example:
Input: [3, 5, 12, 5, 13]
Output: True
(5^2 + 12^2 = 13^2)
"""
def pythagorean_triplets(nums):
"""
Brute-force solution
Time: O(n^2)
Space: O(n)
"""
nums = list(set(nums)) # To get rid of duplicates
p_values = set([num**2 for num in nums]) # Store squared sums
exist = False
for i in range(len(nums)):
base_num = nums[i]
for j in range(i+1, len(nums)):
p_sum = base_num**2 + nums[j]**2
if p_sum in p_values:
print(f'{base_num}^2 + {nums[j]}^2 = {int(p_sum**0.5)}^2 ')
exist = True
# return True
if not exist:
print('Found no triplets.')
# return False
if __name__ == '__main__':
lst = [3, 5, 12, 4, 13,]
pythagorean_triplets(lst)
print('-'*30)
pythagorean_triplets(
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40])
|
99eafc14dcf383d24a4c56479c2c596cfcef5fe2 | JIEXUNHE/comp9414 | /searchGeneric.py | 5,923 | 3.53125 | 4 | # searchGeneric.py - Generic Searcher, including depth-first and A*
# AIFCA Python3 code Version 0.8.1 Documentation at http://aipython.org
# Artificial Intelligence: Foundations of Computational Agents
# http://artint.info
# Copyright David L Poole and Alan K Mackworth 2017.
# This work is licensed under a Creative Commons
# Attribution-NonCommercial-ShareAlike 4.0 International License.
# See: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en
from display import Displayable, visualize
class Searcher(Displayable):
"""returns a searcher for a problem.
Paths can be found by repeatedly calling search().
This does depth-first search unless overridden
"""
def __init__(self, problem):
"""creates a searcher from a problem
"""
self.problem = problem
self.initialize_frontier()
self.num_expanded = 0
self.add_to_frontier(Path(problem.start_node()))
super().__init__()
def initialize_frontier(self):
self.frontier = []
def empty_frontier(self):
return self.frontier == []
def add_to_frontier(self,path):
self.frontier.append(path)
@visualize
def search(self):
"""returns (next) path from the problem's start node
to a goal node.
Returns None if no path exists.
"""
while not self.empty_frontier():
path = self.frontier.pop()
self.display(2, "Expanding:",path,"(cost:",path.cost,")")
self.num_expanded += 1
if self.problem.is_goal(path.end()): # solution found
self.display(1, self.num_expanded, "paths have been expanded and",
len(self.frontier), "paths remain in the frontier")
self.solution = path # store the solution found
return path
else:
neighs = self.problem.neighbors(path.end())
self.display(3,"Neighbors are", neighs)
for arc in reversed(list(neighs)):
self.add_to_frontier(Path(path,arc))
self.display(3,"Frontier:",self.frontier)
self.display(1,"No (more) solutions. Total of",
self.num_expanded,"paths expanded.")
import heapq # part of the Python standard library
from searchProblem import Path
class FrontierPQ(object):
"""A frontier consists of a priority queue (heap), frontierpq, of
(value, index, path) triples, where
* value is the value we want to minimize (e.g., path cost + h).
* index is a unique index for each element
* path is the path on the queue
Note that the priority queue always returns the smallest element.
"""
def __init__(self):
"""constructs the frontier, initially an empty priority queue
"""
self.frontier_index = 0 # the number of items ever added to the frontier
self.frontierpq = [] # the frontier priority queue
def empty(self):
"""is True if the priority queue is empty"""
return self.frontierpq == []
def add(self, path, value):
"""add a path to the priority queue
value is the value to be minimized"""
self.frontier_index += 1 # get a new unique index
heapq.heappush(self.frontierpq,(value, -self.frontier_index, path))
def pop(self):
"""returns and removes the path of the frontier with minimum value.
"""
(_,_,path) = heapq.heappop(self.frontierpq)
return path
def count(self,val):
"""returns the number of elements of the frontier with value=val"""
return sum(1 for e in self.frontierpq if e[0]==val)
def __repr__(self):
"""string representation of the frontier"""
return str([(n,c,str(p)) for (n,c,p) in self.frontierpq])
def __len__(self):
"""length of the frontier"""
return len(self.frontierpq)
def __iter__(self):
"""iterate through the paths in the frontier"""
for (_,_,path) in self.frontierpq:
yield path
class AStarSearcher(Searcher):
"""returns a searcher for a problem.
Paths can be found by repeatedly calling search().
"""
def __init__(self, problem):
super().__init__(problem)
def initialize_frontier(self):
self.frontier = FrontierPQ()
def empty_frontier(self):
return self.frontier.empty()
def add_to_frontier(self,path):
"""add path to the frontier with the appropriate cost"""
value = path.cost+self.problem.heuristic(path.end())
self.frontier.add(path, value)
import searchProblem as searchProblem
def test(SearchClass, problem=searchProblem.problem1, solution=['g','d','c','b','a'] ):
"""Unit test for aipython searching algorithms.
SearchClass is a class that takes a problemm and implements search()
problem is a search problem
solution is the unique (optimal) solution.
"""
print("Testing problem 1:")
schr1 = SearchClass(problem)
path1 = schr1.search()
print("Path found:",path1)
assert path1 is not None, "No path is found in problem1"
assert list(path1.nodes()) == solution, "Shortest path not found in problem1"
print("Passed unit test")
if __name__ == "__main__":
#test(Searcher)
test(AStarSearcher)
# example queries:
# searcher1 = Searcher(searchProblem.acyclic_delivery_problem) # DFS
# searcher1.search() # find first path
# searcher1.search() # find next path
# searcher2 = AStarSearcher(searchProblem.acyclic_delivery_problem) # A*
# searcher2.search() # find first path
# searcher2.search() # find next path
# searcher3 = Searcher(searchProblem.cyclic_delivery_problem) # DFS
# searcher3.search() # find first path with DFS. What do you expect to happen?
# searcher4 = AStarSearcher(searchProblem.cyclic_delivery_problem) # A*
# searcher4.search() # find first path
|
c66c32278fa834ca34ab3ebc8fb97bbbe5f493e6 | Nikhil-naruto/Phython-project | /WindowGui.py | 325 | 3.703125 | 4 | from tkinter import *
window = Tk()
#widgets = GUI elements : buttons , lables, images
#window = serves as a container to hold or contain these widgets
window.geometry("420*420")
window.title("Hello world")
window.config(background="black")
icon = PhotoImage(file='naruto.jpg')
window.iconphoto(True, icon)
window.mainloop()
|
3ad4c330d54847f3788cebf6f8f927ffa3c44cc0 | geniyong/bkj-study | /level001/snail.py | 2,077 | 3.546875 | 4 | def print_result(rs):
for i in rs:
for index_j, j in enumerate(i):
print(j, end=" ")
if index_j % len(i) == len(i) - 1:
print("")
def find_val(arr, val):
n = len(arr)
for i in range(0, n):
for j in range(0, n):
if arr[i][j] == val:
return i+1, j+1
k = [
[9, 2, 3],
[8, 1, 4],
[7, 6, 5]
]
n = int(input())
p = int(input())
# print("입력된 N : {}".format(n))
for step in range(4, n+1):
# print("현재 STEP : {}".format(step))
t = [[0] * step for _temp_i in range(step)] # 한 단계 위의 2차원 배열 선언 (step X step)
# print("임시 배열 : {}".format(t))
snail_value = (step - 1) * (step - 1) # 달팽이가 지나갈때 남기는 흔적 값
# print("현재 달팽이 값 : {}".format(snail_value))
if step % 2 == 0 :
# 1. 현재 스텝이 짝수 일 때는 [0][j..step]번 라인 0으로 초기화 및 [0..step][step]번 라인 0으로 초기화
# for j in range(0, step+1):
# t[0][j] = 0 이미 0으로 초기화된 상태라서 그대로 두면 됨
# 1번 로직을 구현하는 방식이 아닌 1번 로직을 배제한채로 복사하는 방식으로 구현 함
for i in range(1, step):
for j in range(0, step - 1):
t[i][j] = k[i-1][j] # t 배열에 k 배열을 복사함
for j in range(0, step):
snail_value += 1
t[0][j] = snail_value
for i in range(1, step):
snail_value += 1
t[i][step-1] = snail_value
k = t
else:
for i in range(0, step-1):
for j in range(1, step):
t[i][j] = k[i][j-1]
for j in range(step-1, -1, -1):
snail_value += 1
t[step-1][j] = snail_value
for i in range(step-2, -1, -1):
snail_value += 1
t[i][0] = snail_value
k = t
print_result(k)
x, y = find_val(k, p)
print("{} {}".format(x, y))
|
66dbdca134b28fbaf1c672bd8a6d1878ca537593 | limiyou/Pyproject | /1python基础/class8_func2/d6_函数的作用域.py | 482 | 3.953125 | 4 | #全局作用域
#全局变量:函数外部定义的变量,叫做全局变量
#局部变量:在函数内部定义的变量,仅限函数内部可以使用,函数外部无法使用
def add(a,b):
#局部作用域
c=a+b
return c
#不能直接使用c
#TODO:局部变量不能在全局作用域获取
c=add(4,5)
print(c)
#TODO:局部作用域可以使用全局变量
C=6
def minus(a,b):
d=a+b
print(d-c)
return d-c
minus(3,7)
|
47de11304f81657bd1fb619e387e7ed02faf72ce | alekkswithak/arkera | /q2.py | 1,059 | 3.640625 | 4 | import unittest
def largest_loss(pricesList):
if len(pricesList) <= 1:
return 0
max_value = max(pricesList)
last_max_index = max(i for i, v in enumerate(pricesList) if v == max_value)
if last_max_index == 0:
return 0
min_value = min(pricesList[:last_max_index])
return max_value - min_value
class TestLargestLoss(unittest.TestCase):
def test_empty(self):
loss = largest_loss([])
self.assertEqual(0, loss)
def test_one(self):
loss = largest_loss([1])
self.assertEqual(0, loss)
def test_zero_one(self):
loss = largest_loss([0,1])
self.assertEqual(1, loss)
def test_one_zero(self):
loss = largest_loss(([1,0]))
self.assertEqual(0, loss)
def test_one_one(self):
loss = largest_loss([1,1])
self.assertEqual(0, loss)
def test_one_zero_one(self):
loss = largest_loss([1,0,1])
self.assertEqual(1, loss)
if __name__ == '__main__':
unittest.main() |
43cc27f33f0680df5fab3daee8c56af9fbd48bd6 | sushyanthp/fetch-rewards-exercise | /ec2_setup.py | 6,662 | 3.8125 | 4 | #!/usr/local/bin/python3
"""
This exercise takes a YAML configuration file as input and,
- Deploys a Linux AWS EC2 instance
- Configures it with two EBS volumes
- Configures two user accounts on the EC2 instance for SSH
It uses Boto3 which is a Amazon Web Services (AWS) SDK for Python.
"""
import yaml
import boto3
import random
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
def read_yaml():
""" This function is used to read the input file written in YAML (ec2_config.yaml) and return a dictionary object.
"""
with open("./ec2_config.yaml", 'r') as file:
try:
return(yaml.safe_load(file))
except yaml.YAMLError as exc:
print(exc)
def get_user_volume_details(ec2_config_dict):
""" This function parses the dictionary from input and returns required user and volume information from it.
"""
for key, value in ec2_config_dict.items():
# Parsing Users Information
users_info = value['users']
user1_login = users_info[0]['login']
user1_key = users_info[0]['ssh_key']
user2_login = users_info[1]['login']
user2_key = users_info[1]['ssh_key']
volumes_info = value['volumes']
datavol_device = volumes_info[1]['device']
datavol_type = volumes_info[1]['type']
datavol_mount = volumes_info[1]['mount']
return(user1_login, user1_key, user2_login, user2_key, datavol_device, datavol_type, datavol_mount)
def get_ami_id(ami_type, architecture, root_device_type, virtualization_type, device_name, root_volume_size):
""" This function called during the EC2 instance creation call is responsible for returning a random AMI Id
satisfying the requirements in input like architecture, owner, virtualization type and root volume type.
"""
response = ec2_client.describe_images(
ExecutableUsers=[
'all',
],
Filters=[
{
'Name': 'architecture',
'Values': [
architecture,
]
},
{
'Name': 'root-device-type',
'Values': [
root_device_type,
]
},
{
'Name': 'virtualization-type',
'Values': [
virtualization_type,
]
},
{
'Name': 'is-public',
'Values': [
"true",
]
},
{
'Name': 'block-device-mapping.device-name',
'Values': [
device_name,
]
},
],
Owners=[
'amazon',
]
)
image_list = []
for image_info in response['Images']:
for device_details in image_info['BlockDeviceMappings']:
if device_details['Ebs']['VolumeSize'] <= root_volume_size:
if ami_type in image_info['Name']:
image_list.append(image_info['ImageId'])
return(random.choice(image_list))
def ec2_instance_setup(ec2_config_dict, user_data):
""" This function parses the dictionary from input and utilizes the user_data script to create an EC2 instance
and returns the EC2 instance' public IP upon creation.
"""
for key, value in ec2_config_dict.items():
volumes_info = value['volumes']
instance = ec2.create_instances(
BlockDeviceMappings=[
{
'DeviceName': volumes_info[0]['device'],
'Ebs': {
'DeleteOnTermination': True,
'VolumeSize': volumes_info[0]['size_gb']
}
},
{
'DeviceName': volumes_info[1]['device'],
'Ebs': {
'DeleteOnTermination': True,
'VolumeSize': volumes_info[1]['size_gb']
}
},
],
ImageId=get_ami_id(value['ami_type'], value['architecture'], value['root_device_type'],
value['virtualization_type'], volumes_info[0]['device'], volumes_info[0]['size_gb']),
InstanceType=value['instance_type'],
MaxCount=value['min_count'],
MinCount=value['max_count'],
UserData=user_data,
NetworkInterfaces=[
{
'AssociatePublicIpAddress': True,
'DeleteOnTermination': True,
'Description': 'Public IP associated with Fetch DevOps EC2',
'DeviceIndex': 0
},
],
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'Name',
'Value': 'Fetch_DevOps_EC2'
},
{
'Key': 'Project',
'Value': 'Fetch_Hiring_Take_Home_Assignment'
},
{
'Key': 'Platform',
'Value': 'Fetch'
}
]
},
]
)
ec2_instance = instance[0]
ec2_instance.wait_until_running()
ec2_instance.load()
return(ec2_instance.public_ip_address)
def main():
""" Main function to call individual methods of this application and return the IP address of the EC2 instance
created for users to connect to.
"""
ec2_config_dict = read_yaml()
(user1_login, user1_key, user2_login,
user2_key, datavol_device, datavol_type, datavol_mount) = get_user_volume_details(ec2_config_dict)
user_data = '''
#!/bin/bash -x
USER1={0}
adduser $USER1
echo "$USER1 ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/cloud-init
mkdir /home/$USER1/.ssh
echo {1} >> /home/$USER1/.ssh/authorized_keys
USER2={2}
adduser $USER2
echo "$USER2 ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/cloud-init
mkdir /home/$USER2/.ssh
echo {3} >> /home/$USER2/.ssh/authorized_keys
DEVICE={4}
FILESYSTEM={5}
MOUNT={6}
sudo mkdir -p $MOUNT
sudo mkfs -t $FILESYSTEM $DEVICE
sudo mount $DEVICE $MOUNT
df -hT
'''
user_data_params = user_data.format(
user1_login, user1_key, user2_login, user2_key, datavol_device, datavol_type, datavol_mount)
print(ec2_instance_setup(ec2_config_dict, user_data_params))
if __name__ == "__main__":
main()
|
bb36b785bcdc3f0da89ca78804a9ac2d044f24b5 | HeberCooke/Python-Programming | /Chapter4/exercise6.py | 1,266 | 4.25 | 4 | """
Heber Cooke 10/17/2019
Chapter 4 Exercise 6
This program takes in a message converts the characters to ascii, adds 1, and left shifts the bit and
places it on the other side. It converts the bits back to ascii to print the code
"""
message = input("Enter a message: ")
word = message.split() # splits the mesage into words list
print("The CODE: ",end=" ")
for i in message: # each word
word = i
for j in word: # each letter
charValue = ord(j) + 1 # adding 1 to the ascii value
# convert decimal to binary
binaryString = ''
while charValue > 0:
remander = charValue % 2
charValue = charValue // 2
binaryString = str(remander) + binaryString
# bit wrap one place to the left
#print(binaryString)
num = binaryString
shiftAmount = 1
for i in range(0,shiftAmount):# shift Left
temp = num[0]
num = num[1:len(num)] + temp
# print(num)
# create the code from shifted bit string
decimal = 0
exponent = len(binaryString) - 1
for digit in binaryString:
decimal = decimal + int(digit) * 2 ** exponent
exponent = exponent -1
print(chr(decimal), end="")
print()
|
401f36be774e4bfdb4e1ad6c7880d19eb29d0334 | TheManTheLegend1/python_Projects | /heros_inventory2.py | 1,288 | 4.125 | 4 | # Heros Inventory 2.0
# Demonstrates tuples
# create a tuple with some items and diplay with a for loop
inventory = ("sword",
"armor",
"shield",
"healing portion")
print("Your items:")
for item in inventory:
print(item)
raw_input("\nPress the enter key to continue.")
# get the length of a tuple
print("You have"), len(inventory), ("items in your possession.")
raw_input("\nPress enter key to continue.")
# Test for membership with in
if "healing postion" in inventory:
print("You will live to fight another day.")
# Display one item through an index
index = int(raw_input("\nEnter the index number for an item in inventory: "))
print"At index", index, "is", inventory[index]
# display a slice
start = int(raw_input("\nEnter the index number to begin a slice: "))
finish = int(raw_input("Enter the index number to end the slice: "))
print"inventory[", start, ":", finish, "] is"
print inventory[start:finish]
raw_input("\nPress the enter key to continue.")
# concatenate two tuples
chest = ("gold", "gems")
print"You find a chest. It contains:"
print chest
print "You add the contents of the chest to you inventory."
inventory += chest
print "Your inventory is now: "
print inventory
raw_input("\n\nPress the enter key to exit.")
|
9c8a798549aa9028cfe4f1a4971f7fa253a6d324 | shants/LeetCodePy | /48.py | 753 | 3.84375 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
r = len(matrix)
c = len(matrix[0])
for i in range(r):
for j in range(i+1,c):
matrix[i][j], matrix[j][i]=matrix[j][i],matrix[i][j]
#print(matrix)
for i in range(r):
for j in range(c//2):
t = matrix[i][j]
matrix[i][j] = matrix[i][c-j-1]
matrix[i][c - j-1] = t
#return matrix
if __name__ == "__main__":
s = Solution()
mat = [
[ 1,2,3],
[ 4,5,6],
[7,8,9]
]
print(s.rotate(mat)) |
66bb9bdb591c2376f4a0bdc2dffa208e9e1b3f11 | Welvis3004/Aprendendo-Python | /Aula07aD011.py | 214 | 3.828125 | 4 | largura = float(input('Digite a Largura: '))
altura = float(input('Digite a Altura: '))
area = largura*altura
tinta = area/2
print('A area total é {} m², a tinta necessaria é {} litros.'.format(area, tinta)) |
78e5b6c0330f3fe8acfbacf98850071fffff5a20 | takahi-i/mlbook | /notebook/chapter00/oop.py | 221 | 3.734375 | 4 | class MyObject:
def __init__(self, num):
self.num = num
def add(self, x):
self.num += x
def show(self):
print(self.num)
o = MyObject(3)
o.show()
o.add(2)
o.show()
o.add(5)
o.show()
|
216d70883e60300d0f96e2c47c4306559dc1a14b | khorn89/PyCalc | /PyCalc.py | 2,863 | 4.40625 | 4 | import math
# from tkinter import *
#
# root = Tk()
#
# myLabel = Label(root, text="Hello World!")
# myLabel.pack()
# root.mainloop()
def calc_info():
print("The 'add' option activates addition.")
print("The 'subtract' option activates subtraction.")
print("The 'divide' option activates division.")
print("The 'multiply' option activates multiplication.")
print("The 'power' option raises a number to the power of another.")
print("The 'square' option finds the square root of a number.")
print("The 'cos' option finds the cosine of a number.\n")
def calculator():
while True:
calc_info()
user_input = input("Enter your command:")
# Add two numbers together
if user_input == 'add':
first_num = float(input("Enter the first number:"))
second_num = float(input("Enter the second number:"))
result = str(first_num + second_num)
print(f"the result is {result}")
# Subtract two numbers
elif user_input == 'subtract':
first_num = float(input("Enter the first number:"))
second_num = float(input("Enter the second number:"))
result = str(first_num - second_num)
print(f"the result is {result}")
# Divide two numbers
elif user_input == 'divide':
first_num = float(input("Enter the first number:"))
second_num = float(input("Enter the second number:"))
result = str(first_num / second_num)
print(f"the result is {result}")
# Multiply two numbers
elif user_input == 'multiply':
first_num = float(input("Enter the first number:"))
second_num = float(input("Enter the second number:"))
result = str(first_num * second_num)
print(f"the result is {result}")
# Raise to the power of another number
elif user_input == 'power':
first_num = float(input("Enter the first number:"))
second_num = float(input("Enter the second number:"))
result = str(first_num ** second_num)
print(f"the result is {result}")
# find the square root of a number
elif user_input == 'square':
first_num = float(input("Enter the number you want to find the square root of:"))
result = str(math.sqrt(first_num))
print(f"the result is {result}")
# find the cosine of a number
elif user_input == 'cos':
first_num = float(input("Enter the number you want to find the cosine of:"))
result = str(math.cos(first_num))
print(f"the result is {result}")
# Exit the program
elif user_input == "exit":
break
calculator()
|
d8dd6f51ee707aa26fc0db0354fe390d92f21c48 | xeon2007/machine-learning | /justin-python-ml/homeworks/hw1.py | 3,083 | 3.71875 | 4 | import numpy as np
import random
from pprint import pprint
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, training_set=None, testing_set=None, weights=None):
# Default weights to [0, 0, 0]
if weights == None:
self.weights = [0., 0., 0.]
else:
self.weights = weights
self.training_set = training_set
self.testing_set = testing_set
# Points 1 and 2 used to draw line
# aka produces our target function!
self.point1 = (np.random.uniform(-1, 1), np.random.uniform(-1, 1))
self.point2 = (np.random.uniform(-1, 1), np.random.uniform(-1, 1))
# 1/-1 for above/below the line
def getTargetLabel(self, feature):
x1, y1 = self.point1
x2, y2 = self.point2
# Remember, x0 is the default 1
x0, feature_x, feature_y = feature
slope = (y2 - y1) / (x2 - x1)
return 1 if feature_y > (y1 + slope * (feature_x - x1)) else -1
def hypothesis(self, feature):
return np.sign(np.dot(feature, self.weights))
def train(self):
misclassified = []
iterations = 0
while True:
# Grab misclassified points
for feature in self.training_set:
target_y = self.getTargetLabel(feature)
predicted_y = self.hypothesis(feature)
if predicted_y != target_y:
misclassified += [(feature, target_y)]
# If there are misclassified points, keep trying
if misclassified:
iterations += 1
feature, target_y = random.choice(misclassified)
adjustment = np.dot(feature, target_y)
self.weights += adjustment
misclassified = []
else:
break
return iterations
def test(self):
num_wrong = 0.
for feature in self.testing_set:
target_y = self.getTargetLabel(feature)
predicted_y = self.hypothesis(feature)
if predicted_y != target_y:
num_wrong += 1
return num_wrong / len(self.testing_set)
def runPLA(data_size=10, num_iterations=1000):
training_set = [[1., np.random.uniform(-1, 1), np.random.uniform(-1, 1)]
for i in xrange(data_size)]
testing_set = [[1., np.random.uniform(-1, 1), np.random.uniform(-1, 1)]
for i in xrange(data_size)]
avg_iterations = 0
avg_disagreement = 0
plot_weights = []
for i in range(num_iterations):
pla = Perceptron(training_set=training_set, testing_set=testing_set)
avg_iterations += pla.train()
avg_disagreement += pla.test()
plot_weights.append(pla.weights)
avg_iterations = avg_iterations / num_iterations
avg_disagreement = avg_disagreement / num_iterations
return avg_iterations, avg_disagreement
if __name__ == "__main__":
print 'With data_size = 10,', runPLA(data_size=10)
# print 'With data_size = 100,', runPLA(data_size=100)
|
2927d3a6a0845111ae3551b5e4c57cc041f54c4a | kenta-takeuchi/python_design_pattern | /構造に関するデザインパターン/flyweight.py | 1,173 | 3.515625 | 4 | import sys
def main():
h1 = Hoge1()
h2 = Hoge2()
h1.add_att7()
print(h1.att7)
# h2.add_att7() # => AttributeError
# print(h2.att7)
# calc memory size
print(h1.__dict__)
memory_size_h1 = sys.getsizeof(h1) + sys.getsizeof(h1.__dict__)
# print(h2.__dict__) # => AttributeError
memory_size_h2 = sys.getsizeof(h2)
print("h1: {}, h2: {}".format(memory_size_h1, memory_size_h2))
class Hoge1:
# __slots__ = ("att1", "att2", "att3", "att4", "att5", "att6")
def __init__(self, att1=0, att2=0, att3=0, att4=0, att5=0, att6=0):
self.att1 = att1
self.att2 = att2
self.att3 = att3
self.att4 = att4
self.att5 = att5
self.att6 = att6
def add_att7(self):
self.att7 = 7
class Hoge2:
__slots__ = ("att1", "att2", "att3", "att4", "att5", "att6")
def __init__(self, att1=0, att2=0, att3=0, att4=0, att5=0, att6=0):
self.att1 = att1
self.att2 = att2
self.att3 = att3
self.att4 = att4
self.att5 = att5
self.att6 = att6
def add_att7(self):
self.att7 = 7
if __name__ == "__main__":
main()
|
2e1e19378d76723b6dc563f648d0d2c1b11d0f04 | mjdecker-teaching/mdecke-1300 | /notes/python/strings.py | 2,938 | 3.96875 | 4 | ##
# @file strings.py
#
# strings in Python based on: https://docs.python.org/3/tutorial
#
# @author Michael John Decker, Ph.D.
#
# What type do you thing this is?
"butterscotch"
# How about this one?
'a'
# Both are strings
'butterscotch'
# Just as in C++, \ can be used to escape characters
'\'escaped\''
# Or use the other type of quote
"'no need to escape these'"
'"or these"'
# print, how real output is done, Python 2 requires no parenthesis (might be why people still use 2)
'"It\'s just a flesh wound." Black Knight'
print('"It\'s just a flesh wound." Black Knight')
# How do you think you print a '\'?
# escape
print('C:\\WINDOWS\\system32')
# raw strings
print(r'C:\WINDOWS\system32')
# What you always wanted, multi-line quotes.
"""This was a triump
I'm making a note here
HUGE SUCCESS
"""
# Can use either quote, no need to escape
'''It's hard to overstate
my satisfaction
Aperture Science
'''
# If you want to suppress new line being appended use \ (line continuation character?)
'''\
program arg [optional_arg]
* arg - an argument
* optional_arg - an optional argument\
'''
# concatenation
"Fat Man" + " and " + "Little Boy"
# string multiplication
"ha" * 3 + " " + "ha" * 7
# string next to each other are concatenated automatically
'Muffin ' 'Button'
# to break into long lines use parenthesis
# What type is this?
text = ('Your mother was a hamster and '
'your father smelt of elderberries!')
text
# must both be literals, not variables or expressions
prefix = 'Py'
#prefix 'thon'
#('un' * 3) 'ium'
prefix + 'thon'
# [] operator supported (well, arrays in general support these ops)
bird = 'word'
bird[0] # 0-position offset
bird[3]
bird[3][0] # these are strings of size 1
# bird[4] - errors
# negative numbers?
bird[-1] # negative offset cause -0 == 0
bird[-4]
# bird[-5] - error
# slicing in this case substring, but applies to other lists
word = 'Python'
word[0:2] # left included, right excluded [0,2)
word[2:5] # length is 5 - 2 == 3
# empty sides expand to remaining part of list (front or back)
word[:2]
word[2:]
# note, the indexing is on purpose so
word[:2] + word[2:]
word[:3] + word[3:]
# negatives with slicing?
# what you think we get
word[-2:]
# Way to think about it, numbers are the boundaries, take everything in between
# +---+---+---+---+---+---+
# | P | y | t | h | o | n |
# +---+---+---+---+---+---+
# 0 1 2 3 4 5 6
# -6 -5 -4 -3 -2 -1
word[-4:-1]
# out of bounds on slice? Gracefully handled.
word[4:42]
word[42:]
# strings are immutable!
#word[0] = 'C'
#word[2:] = 'py'
# have to create a new one
'C' + word[1:]
word[:2] + 'py'
# immutability. Some things in Python provide both a mutable (bytearray) and immutable version. Immutable has usage, for example, for hasing (a topic for latter)
# length (also for lists)
long_word = 'antidisestablishmentarianism'
len(long_word)
# unicode (python 2 is not unicode by default)
greek = 'αβγ'
|
fb925b1d5220466f09d69592b822a09646f8aa64 | dogancanulgu/arin-python-tutorial | /application1.py | 782 | 3.921875 | 4 | # a = 14
# a = 4.2
# a = 8
# a = 8 / 2
# print(a)
# print(type(a))
# print( (8 - 4) * 5 + (5 % 2))
# r = 5
# pi = 3.14159
# print(round(2 * pi * r, 3))
# print(pi * r * r)
# print(pi * (r**2))
# print(pi * pow(r, 2))
# import math
# r=5
# print(2 * math.pi * r)
# x = 21
# if(x % 2 == 0):
# print('X bir cift sayıdır')
# else:
# print('X bir tek sayıdır')
# print(abs(4-7) * (4 + 7))
# x = 'Welcome to python code'
# print(x)
# print(type(x))
# name = 'Dogan'
# print('My name is ' + name)
# print('My name is {}'.format(name))
# print(f'My name is {name}')
# name = 'Dogan'
# age = 26
# married = False
# print(name, age, married)
# x = '100'
# y = 50
# print(int(x) - y)
my_string = input('İsminiz nedir?')
print(my_string.upper())
print(my_string.lower()) |
f1e5f74734329b9c0065cfbcb4e525a69a77417f | tylercrompton/project-euler | /p052/p052.py | 227 | 3.53125 | 4 | def p052():
i = 1
while True:
if sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)):
return i
i += 1
if __name__ == '__main__':
print(p052())
|
279b755197729f18b451e34d7f426241830226c4 | JaredFlomen/LearningPython | /strings.py | 988 | 4.25 | 4 | #Day 4
#\n \t \\ \' \"
first_name = 'Jared'
last_name = 'Flomen'
language = 'Python'
formatted_string = 'I am %s %s. I\'m learning %s' % (first_name, last_name, language)
print(formatted_string)
radius = 10
pi = 3.14
area = pi * radius ** 2
formatted_string = 'The area of a circle with a radius %d is %.2f.' % (radius, area)
#2 refers to 2 decimals after the float
print(formatted_string)
#New Formatting
formatted_string = 'I am {} {}. I\'m learning {}'.format(first_name, last_name, language)
print(formatted_string)
formatted_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area)
print(formatted_string)
#String Interpolation
a = 5
b = 4
print(f'{a} + {b} = {a + b}')
#Slicing Strings
language = 'Python'
first_three = language[0:3]
last_three = language[3:6] #Or -3: or 3:
print(last_three)
#Reversing a string
print(language[::-1])
#Capitalize
string_example = 'jared flomen'
print(string_example.capitalize())
#Others: expandtabgs, find, endswith |
b142fdc9f75aa0b54d5e7643b1715abd643f4664 | Bobcat1238/HelloWorld-Python | /app.py | 635 | 3.953125 | 4 | import Utils
print('Greg Barth')
print('o----')
print(' ||||')
print('*' * 10)
""" numbers = [5, 1010, 2, 5, 2, 777, 2, 8, -2, 99, 3]
numbers.append(50)
numbers.append(50)
numbers.sort()
largest = numbers[0]
for item in numbers:
if item > largest:
largest = item
print(numbers)
numbers.reverse()
print(numbers)
print(f'The largest number in the list is: {largest}')
print(f'The number 50 exists {numbers.count(50)} times in the numbers list.') """
numberList = [5, 1010, 2, 5, 2, 777, 2, 8, -2, 99, 3]
print(numberList)
biggest = Utils.Utility.FindMax(numbers=numberList)
print()
tup = (1, 3, 5)
x, y, z = tup
print(tup)
|
c9deec6ed5d5a2b2df525dc996db85f8876e9b2a | thomasjurczyk/PythonProjects | /AnimalSubclass/animalGenerator.py | 2,268 | 4.1875 | 4 | from Animal import Animal, Mammal, Bird
print('Welcome to the animal generator!\nThis program creates Animal objects.')
animalList = []
while True:
print('\nWould you like to create a mammal or bird?\n1. Mammal\n2. Bird')
while True:
animalType = input('Which would you like to create? ')
if animalType != "1" and animalType != "2":
print("Please choose a valid option!")
continue
break
print()
if animalType == "2":
while True:
birdType = input('What type of bird would you like to create? ')
if birdType == '':
print("Please enter the type of bird")
continue
break
while True:
birdName = input('What is the bird\'s name? ')
if birdName == '':
print("Please enter the bird\'s name!")
continue
break
while True:
canFly = input('Can the bird fly? ')
if canFly == '':
print("Please enter whether the bird can fly!")
continue
break
animalList.append(Bird(birdType,birdName,canFly))
if animalType == '1':
while True:
mammalType = input('What type of mammal would you like to create? ')
if mammalType == '':
print("Please enter the type of mammal")
continue
break
while True:
mammalName = input('What is the mammal\'s name? ')
if mammalName == '':
print("Please enter the mammal\'s name!")
continue
break
while True:
hairColor = input('What color is the mammal\'s hair? ')
if hairColor == '':
print("Please enter the mammal\'s hair color!")
continue
break
animalList.append(Mammal(mammalType,mammalName,hairColor))
continueLoop = input('\nWould you like to add more animals (y/n)? ')
if continueLoop != "y":
break
print('\nAnimal List:')
for animal in animalList:
print(animal.get_name() + ' the ' + animal.get_animal_type() + ' is ' + animal.get_mood())
|
86327874f11083f8a97a78487fdc6848df101d8a | mgcarbonell/30-Days-of-Python | /20_map_filter_conditional_comprehension.py | 8,005 | 5.15625 | 5 | # Quick recap of comprehensions
# We only use a comprehension when we want to change something about the values
# when we make this new collection. For example, we might want to turn every
# string in a list to title case:
names = ['tom', 'dick', 'harry']
names = [name.title() for name in names]
# Tom, Dick, Harry
# What if we want the names list to be a set?
names = ['tom', 'dick', 'harry']
names = set(names)
# We don't have to bother with the more verbose version
names = ['tom', 'dick', 'harry']
names = {name for name in names}
# With this in mind, we can really think of comprehensions as a way of
# performing an action for every item in some iterable, and then storing the
# results.
# The MAP FUNCTION!
# map is a function that allows us to call some other function on every item in
# an iterable. Let's say we want to cube EVERY NUMBER in a list of numbers.
# What can we do? Use map().
def cube(number):
return number ** 3
numbers = [1,2,3,4,5,6,7,8,9]
cubed_numbers = map(cube, numbers)
# notice we pass in cube and not cube()
# if we try to print cubed_numbers, we'll just get its location in memory.
# <map object at 0x.....>
# This is because map objects are a lazy type, like zip enumerate or range.
# So how do we get something out of a map object? Iterate.
for number in cubed_numbers:
print(number)
# Since they're an iterable, we can also unpack them using *
def cube(number):
return number ** 3
numbers = [1,2,3,4,5,6,7,8,9]
cubed_numbers = map(cube, numbers)
print (*cubed_numbers, sep=", ")
# or we can convert them to a normal collection
def cube(number):
return number ** 3
numbers = [1,2,3,4,5,6,7,8,9]
cubed_numbers = list(map(cube, numbers))
# Map with multiple iterables
# One nice thing about map is that we can handle several iterables at once.
def add(a, b):
return a + b
odds = [1, 3, 5, 7, 9]
evens = [2, 4, 6, 8, 10]
totals = map(add, odds, evens)
print(*totals, sep=", ") # 3, 7, 11, 15, 19
# If the iterables of are differing lengths, map will stop as soon as it runs
# out of values, much like when using zip.
# map with lambda expressions
# map is frequently used for simple operations, which means it's often not
# worth defining a full blown function.
# Lambda expressions are often used instead because they allow us to define a
# function inline while calling map.
#
# Let's cube again!
numbers = [1,2,3,4,5,6]
cubed_numbers = map(lambda number: number ** 3, numbers)
# Easy and nice
# THE OPERATOR MODULE
# While lambda expressions are great, we often end up using lambda expressions
# to duplicate the functionality of some operator. For example:
# lambda number: number ** 3 is just a way of using the ** operator on each
# value.
# Since this kind of lambda expression is so common, there's a module in the
# standard library called OPERATOR which contains function versions of all the
# operators. It also includes some functions for making it easy to call methods
# or access values in collections.
# Let's revisist our add function.
def add(a, b):
return a + b
odds = [1,3,5,7,9]
evens = [2,4,6,8,10]
totals = map(add, odds, evens)
print(*totals, sep=", ") # 3, 7, 11, 15, 19
# We could easily do this as a lambda
odds = [1,3,5,7,9]
evens = [2,4,6,8,10]
totals = map(lambda a, b: a + b, odds, evens)
print(*totals, sep=", ")
# while this is messy and not as clear as writing add, we don't necessary need
# to define the add function even if we don't have to -- which we don't really
# need to do. However, operator also already has an add function!
from operator import __add__
odds = [1, 3,5,7,9]
evens = [2,4,6,8,10]
totals = map(add, odds, evens)
print(*totals, sep=", ")
# Another useful function from operator is methodcaller. methodcaller allows us
# to easily define a function that calls a method for us. We just have to
# provide the method name as a string. Let's use our old friend title()
from operator import methodcaller
names = ['tom', 'dick', 'harry']
title_names = map(methodcaller("title"), names)
# or to lambdafy it
title_names = map(lambda name: name.title(), names)
# not as clear as our method
# CONDITIONAL COMPREHENSIONS
# We can use comprehension for more than just performing an action for each
# item in an iterable, we can also perform filtering with comprehensions!
# We can do this by providing a condition at the end of our comprehension, and
# this condition determines whether or not an item makes it into our new
# collection. In cases where the condition evalues to True, the item is added;
# otherwise it is discarded.
# Let's say we have a set of numbers and we only want the even values, let's
# use a conditional comprehension to accomplish this.
numbers = [1, 56, 3, 5, 24, 19, 88, 37]
even_numbers = [number for number in numbers if number % 2 == 0]
# this is the same as the following:
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
# We can do this filtering operation with any kind of comprehension! Let's do
# the same thing for set comprehension!
numbers = [1,56,3,5,24,19,88,37]
even_numbers = {number for number in numbers if number % 2 == 0}
# THE FILTER FUNCTION
# Much like map is a functional anaologue for 'normal' comprehensions, filter
# performs the same role as a conditional comprehension.
# Much like map, filter calls a function (known as a predicate) for every item
# in an iterable, and it discards any values for which that function returns a
# falsy value.
# A predicate is a function that accepts some value as an argument and returns
# either True or Falsnumbers = [1, 56, 3, 5, 24, 19, 88, 37]
numbers = [1, 56, 3, 5, 24, 19, 88, 37]
even_numbers = filter(lambda number: number % 2 == 0, numbers)
# In this case we don't have an easy solution available in the operator module
# - though there is a mod function - so we have to use etiher a lambda or we
# define a function to call.
def is_even(number):
return number % 2 == 0
numbers = [1, 56, 3, 5, 24, 19, 88, 37]
even_numbers = filter(is_even, numbers)
# Just like map, filter gives us a lazy filter object so the values are not
# calculated until we need them. However, UNLIKE map, filter can only handle a
# SINGLE ITERABLE AT A TIME. Not a big problem, but something to be aware of.
# USING NONE WITH FILTER
# Instead of passing in a function to filter, it's possible to use None.
# This tells filter that we want to use the truth values of the values
# directly, instead of performing some kind of comparison or calculation. In
# this case, filter will keep all truthy values from the original iterable, and
# all falsy values will be discarded.
values = [0, "Hello", [], {}, 435, -4.2, ""]
truthy_values = filter(None, values)
print(*truthy_values, sep=", ") # Hello, 435, -4.2
# EXERCISES
# 1) Use map to call the strip method on each string in the following list:
humpty_dumpty = [
" Humpty Dumpty sat on a wall, ",
"Humpty Dumpty had a great fall; ",
" All the king's horses and all the king's men ",
" Couldn't put Humpty together again."
]
print(*map(lambda line: line.strip(), humpty_dumpty), sep="\n")
# method caller version
print(*map(methodcaller("strip"), humpty_dumpty), sep="\n")
# Print the lines of the nursery rhyme on different lines in the console.
# Remember that you can use the operator module and the methodcaller function
# instead of a lambda expression if you want to.
# 2) Below you'll find a tuple containing several names:
names = ("bob", "Christopher", "Rachel", "MICHAEL", "jessika", "francine")
# Use a list comprehension with a filtering condition so that only names with
# fewer than 8 characters end up in the new list. Make sure that every name in
# the new list is in title case.
names = [name.title() for name in names if len(name) < 8]
# 3) Use filter to remove all negative numbers from the following range: range
# (-5, 11). Print the remaining numbers to the console.
print(*filter(lambda number: number >= 0, range(-5, 11))) |
49254b22232940907e7706a1cd4018fb3a1e62a5 | Shazhul/HJ_FTP_Project | /Assignment3/oldcode/oldserver.py | 1,923 | 3.75 | 4 | # *****************************************************
# This file implements a server for receiving the file
# sent using sendfile(). The server receives a file and
# prints it's contents.
# *****************************************************
import sys
import socket
from cmds import FTP_COMMANDS
# Command line checks
if len(sys.argv) < 2:
print "USAGE python " + sys.argv[0] + " <SERVER_PORT>"
exit(0)
welcomePort = int(sys.argv[1])
# Create a welcome socket.
welcomeSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
welcomeSock.bind(('', welcomePort))
# Start listening on the socket
welcomeSock.listen(10)
# ************************************************
# Receives the specified number of bytes
# from the specified socket
# @param sock - the socket from which to receive
# @param numBytes - the number of bytes to receive
# @return - the bytes received
# *************************************************
def recvAll(sock, numBytes):
# The buffer
recvBuff = ""
# The temporary buffer
tmpBuff = ""
# Keep receiving till all is received
while len(recvBuff) < int(numBytes):
# Attempt to receive bytes
tmpBuff = sock.recv(numBytes)
# The other side has closed the socket
if not tmpBuff:
break
# Add the received bytes to the buffer
recvBuff += tmpBuff
return recvBuff
# Accept connections forever
while True:
print "Waiting for connections..."
# Accept connections
clientSock, addr = welcomeSock.accept()
print "Accepted connection from client: ", addr, "\n"
# The size of the incoming command
cmdSize = recvAll(clientSock, 4)
#get the size of the inc command
# Receive the first 10 bytes indicating the
# size of the command
cmdBuff = recvAll(clientSock, cmdSize)
serverCmd = FTP_COMMANDS(cmdBuff)
if serverCmd.isCommand:
serverCmd.RunCommand(ftpconnection)
# Close our side
clientSock.close()
|
b3ed7564400394aa041ac8cd66ba57b856eccb7e | georg-remer/python-project-lvl1 | /brain_games/games/engine.py | 2,552 | 3.890625 | 4 | """Game engine.
The flow is the following:
1. Print intro
2. Print game description if game is specified
3. Welcome user
4. Play the game n-rounds (or till first wrong answer) if game is specified:
4.1. Print question
4.2. Get answer from user
4.3. Check if asnwer is correct
"""
import prompt
from brain_games import settings
def ask_user():
"""
Ask user to provider answer.
Returns:
str
"""
return prompt.string(
'{prompt}: '.format(prompt=settings.PROMPT_FOR_ANSWER),
)
def inform_user(information):
"""Print information to user.
This is the only place that prints any information to user.
No other module uses 'print'
Args:
information: information to be printed out to user
"""
print(information)
def play(game):
"""Game flow.
Plays the game if specified, or just greets user
Args:
game: Game module
"""
# Print intro
inform_user(settings.INTRO)
# Get game setup and print it's description
inform_user('{description}\n'.format(description=game.GAME_DESCRIPTION))
# Welcome user and get user name
user_name = prompt.string(
'{prompt}: '.format(prompt=settings.PROMPT_FOR_NAME),
)
inform_user('{greeting}, {user_name}!\n'.format(
greeting=settings.GREETING, user_name=user_name,
))
# Get question and correct answer, play the game
for _ in range(settings.NUMBER_OF_ROUNDS):
(question, correct_answer) = game.get_question_with_answer()
inform_user('{phrase}: {question}'.format(
phrase=settings.QUESTION,
question=question,
))
user_answer = ask_user()
if user_answer == correct_answer:
inform_user('{phrase}'.format(phrase=settings.CASE_CORRECT))
else:
inform_user(
"'{user_answer}' {phrase}.".format(
user_answer=user_answer,
phrase=settings.CASE_INCORRECT_WRONG,
)
+ "{phrase} '{correct_answer}'.\n".format(
phrase=settings.CASE_INCORRECT_EXPECTED,
correct_answer=correct_answer,
)
+ '{phrase}, {user_name}!'.format(
phrase=settings.CASE_INCORRECT_REPEAT,
user_name=user_name,
),
)
break
else:
inform_user('{phrase}, {user_name}!'.format(
phrase=settings.CONGRATULATIONS,
user_name=user_name,
))
|
56cd8e467e4d94664a57439e49fe2ad397df0c13 | CleitonFurst/python_Blueedtech | /Exercicios_aula_09/Exercicio_07.py | 291 | 3.84375 | 4 | '''5. Faça um programa que mostre os valores numéricos inteiros ímpares situados
na faixa de 0 a 20.'''
lista = list(range(0,21))
lista2 = list()
for i in lista:
if i % 2 != 0:
lista2.append(i)
print(f'Os númeors impares dentro do intervalo de 0 a 20 são {lista2}')
|
14602f68310d1fd85807abf6d8c960e981160cb0 | karlhub/Python-Initial-Programs | /Py01-Initial Programs/Programa_22_Python_Matplotlib_Package_Extended.py | 1,281 | 4 | 4 | # Use of Python package: Matplotlib - Extended
# Import subpackage "pyplot"
# Documentation in internet: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
import matplotlib.pyplot as plt
import numpy as np
# Working with multiple figures and axes.
# MATLAB, and pyplot, have the concept of the current figure and the current axes.
# All plotting commands apply to the current axes.
# The function gca() returns the current axes (a matplotlib.axes.Axes instance)
# The function gcf() returns the current figure (matplotlib.figure.Figure instance).
# Normally, you don't have to worry about this, because it is all taken care of behind the scenes. Below is a script to create two subplots.
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
i=0.0
while True:
print("i:",i,"Exp(",-i,"):",np.exp(-i),"cos(",2*np.pi*i,"):",np.cos(2*np.pi*i))
i=i+0.1
if i>5.0:
break
print()
print("cos(pi):",np.cos(np.pi))
print("cos(2pi):",np.cos(2*np.pi))
print("cos(10pi):",np.cos(10*np.pi))
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
print ("=> End of program")
|
ff609c563a9669104a0c5bc74917159788d2c3db | klmcshane/klmcshane.github.io | /python/places.py | 131 | 3.921875 | 4 | city = ["London", "Reykjavik", "Florence", "Glasgow", "Cairo"]
for item in city:
print("I would like to visit " + item + ".")
|
44727976fee256c0f455db30facb7e20cafb6c4b | Baljot12/training | /operations on list.py | 547 | 3.75 | 4 | #concatenation
IndianBatsman=["VIRAT ","SHIKHAR ","YUVRAJ ","ROHIT "]
print(IndianBatsman+ ["RAINA","JADEJA"])
print(IndianBatsman)
print()
#repetition
print(IndianBatsman*2)
#membership
print("WATSON" in IndianBatsman)
print("A B DEVILLIES" not in IndianBatsman)
#indexing
print(IndianBatsman[2],"",IndianBatsman[3])
#slicing
print(IndianBatsman[1:3])
print(IndianBatsman[-1])
print(IndianBatsman[-1:-3])
#reversing
print(IndianBatsman[::-1])
print(IndianBatsman[::-2])
print(IndianBatsman[::2])
print(IndianBatsman(::1))
|
6b12d28524c803afde68b296ff7cfb635df253ae | HONOOUR/Algorithm_Test | /Algorithm_Python/GreedyProgramming_3.py | 1,047 | 3.75 | 4 | import sys
from typing import no_type_check_decorator
# https://leetcode.com/problems/jump-game-ii/
def getJumpToLast(nums):
jump_count = 0
left = right = 0 # start point
while right < len(nums):
farthest = 0
for i in range(left, right+1):
farthest = max(farthest, i + nums[i])
left = right + 1
right = farthest
jump_count += 1
return jump_count
nums = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 0]
getJumpToLast(nums)
# https://leetcode.com/problems/jump-game/
def canJumpNums(nums):
answer = True
if len(nums) == 1 and nums[0] == 0:
return answer
jump_count = 1
for i in range(len(nums)-2, -1, -1):
# 이전에 나오는 수가 다음 수로 점프할수 있는것이 가능한지 (횟수는 중요하지 않음)
if nums[i] >= jump_count:
jump_count = 1
answer = True
continue
else:
jump_count += 1
answer = False
return answer
nums = [2, 0]
canJumpNums(nums)
|
bbdfa7242903a494dc52564ece5e8aed8cfd440c | SeungMin-le/grade3 | /정보처리알고리즘/실습과제/ch03_closestpair_v20.py | 6,622 | 3.59375 | 4 | from math import sqrt
import timeit
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "Point(%.2f, %.2f)"%(self.x, self.y)
def __repr__(self):
return self.__str__()
def distPair( p ):
if (p[0] and p[1]):
d = sqrt( (p[1].x - p[0].x)*(p[1].x-p[0].x) + (p[1].y-p[0].y)*(p[1].y-p[0].y) )
return d
else:
return float('inf')
def dist ( p1, p2 ):
if ( p1 and p2 ):
d = sqrt( (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) )
return d
return float('inf')
def pivotSplit_in_X(S, left, p, right, descend=False):
S[p], S[left] = S[left], S[p]
i = left + 1
j = right
#print (S[left], left, right, S)
while ( i <= j ) :
#print (i, j)
while ( i <= j and ( ( descend==False and S[i].x <= S[left].x ) or
(descend ==True and S[i].x >= S[left].x ))):
i = i + 1
while ( i <= j and ( ( descend==False and S[j].x >= S[left].x ) or
( descend==True and S[j].x <= S[left].x))) :
j = j - 1
if ( i < j ) :
S[i], S[j] = S[j], S[i]
i = i + 1
j = j - 1
new_p = i - 1
S[left], S[new_p] = S[new_p], S[left]
return new_p
def quickSort_in_X(S, left, right, descend=False):
if (left < right ) :
p = int( (left + right) / 2 )
p = pivotSplit_in_X(S, left, p, right, descend)
quickSort_in_X(S, left, p-1, descend )
quickSort_in_X(S, p+1, right, descend )
def pivotSplit_in_Y(S, left, p, right, descend=False):
S[p], S[left] = S[left], S[p]
i = left + 1
j = right
while ( i <= j ) :
while ( i <= j and ( ( descend==False and S[i].y <= S[left].y ) or
(descend == True and S[i].y >= S[left].y ) )):
i = i + 1
while ( i <= j and ( ( descend==False and S[j].y >= S[left].y ) or
(descend == True and S[j].y <= S[left].y) ) ) :
j = j - 1
if ( i < j ) :
S[i], S[j] = S[j], S[i]
i = i + 1
j = j - 1
new_p = i - 1
S[left], S[new_p] = S[new_p], S[left]
return new_p
def quickSort_in_Y(S, left, right, descend=False):
if (left < right ) :
p = int( (left + right) / 2 )
p = pivotSplit_in_Y(S, left, p, right, descend)
quickSort_in_Y(S, left, p-1, descend )
quickSort_in_Y(S, p+1, right, descend )
def closestPairInThree( pair1, pair2, pair3 ) :
d1 = dist(pair1[0], pair1[1])
d2 = dist(pair2[0], pair2[1])
d3 = dist(pair3[0], pair3[1])
if d1 < d2 and d1 < d3 : return pair1
elif d2 < d1 and d2 < d3 : return pair2
else : return pair3
def extractCenterRegionInSLeft(S, d) :
theMostRight_In_S = S[-1]
for i in range( -1 , -len(S)-1, -1) :
if abs(theMostRight_In_S.x-S[i].x) > d :
return S[i+1:]
return S[:]
def extractCenterRegionInSRight(S, d) :
theMostLeft_In_S = S[0]
for i in range(0, len(S), 1) :
if abs(theMostLeft_In_S.x-S[i].x) > d :
return S[0:i]
return S[:]
### 아래의 코드는 미완성된 함수이다.
### TODO 부분을 채워서 완성하라.
def closestPairInCenter(S_left, S_right, d):
S_centerLeft = extractCenterRegionInSLeft(S_left, d)
S_centerRight = extractCenterRegionInSRight(S_right, d)
S_center = S_centerLeft + S_centerRight
quickSort_in_Y(S_center, 0, len(S_center)-1)
## print("S_center : ", S_center)
min_i = min_j = -1
min_d = d
for i in range(0, len(S_center)-1):
for j in range(i+1, len(S_center)):
j = i+1
dij = dist( S_center[i], S_center[j] )
if dij < min_d :
min_d = dij
min_i = i
min_j = j
if ( min_i >= 0) :
#print( S_centerLeft[min_i], S_centerRight[min_j], "d:", min_d)
return (S_center[min_i], S_center[min_j])
else: return (None, None)
def closestPair(S) :
i = len(S)
if i == 0 : return (None, None)
elif i == 1 : return (S[0], None)
elif i == 2 : return (S[0], S[1])
elif i == 3 :
return closestPairInThree( (S[0], S[1]), (S[1], S[2]), (S[0], S[2]) )
half_i = int(i / 2 + 0.5)
S_left = S[0:half_i]
S_right = S[half_i:]
#print ("Split: ", S_left, S_right)
cp_left = closestPair(S_left)
cp_right = closestPair(S_right)
d = min(distPair(cp_left), distPair(cp_right) )
#print ("d : ", d)
cp_center = closestPairInCenter(S_left, S_right, d)
#print ("cp_center", cp_center, "cp_d : ", distPair(cp_center))
return closestPairInThree(cp_left, cp_center, cp_right)
def simpleClosestPair(S):
# Compare all pairs and find the cloest pair
min_d = sqrt(box_h*box_h + box_w*box_w)
for i in range(0, len(S)):
for j in range(0, i):
#print (int(dist( S[i], S[j] )), end=', ' )
d = dist( S[i], S[j] )
if d < min_d :
min_d = d
min_i = i
min_j = j
#print ()
#print ("cloest Pair: ", S[min_i], S[min_j])
#print ("closest distance = ", min_d )
return ( S[min_i], S[min_j] )
def fastClosestPair(S) :
S1 = S[:]
## print ("Before Sort_in_X : ",S1)
quickSort_in_X(S1, 0, len(S1)-1)
#print ("After Sort_in_X : ", S1)
return closestPair(S1)
def generateRandomPoints(width, height, n):
from random import random
S = []
for i in range(n):
p = Point( random() * width , random() * height )
S.append(p)
return S
box_w = 500
box_h = 300
def simpleTest():
S = generateRandomPoints(box_w, box_h, 10)
print()
## print ("Points List : ", end='')
## print (S)
## print()
start_time1 = timeit.default_timer()
cp = simpleClosestPair(S)
end_time1 = timeit.default_timer()
ex_time1=end_time1-start_time1
print ("Simple Closest Pair: ", end='')
print (cp)
print ("Closest distance : %.2f"%distPair(cp))
print ()
start_time2 = timeit.default_timer()
cp = fastClosestPair(S)
end_time2 = timeit.default_timer()
ex_time2=end_time2-start_time2
print ("Faster Closest Pair: ", end='')
print (cp)
print ("Closest distance : %.2f"%distPair(cp))
print ()
print("excute time: %f" %ex_time1)
print("excute time: %f" %ex_time2)
if __name__=='__main__':
num=10
i=1
while i<num:
simpleTest()
i+=1
|
642e59a72021032956be2940e52550d970ce3bad | TheAlgorithms/Python | /bit_manipulation/binary_and_operator.py | 1,465 | 4.40625 | 4 | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_and(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
>>> binary_and(25, 32)
'0b000000'
>>> binary_and(37, 50)
'0b100000'
>>> binary_and(21, 30)
'0b10100'
>>> binary_and(58, 73)
'0b0001000'
>>> binary_and(0, 255)
'0b00000000'
>>> binary_and(256, 256)
'0b100000000'
>>> binary_and(0, -1)
Traceback (most recent call last):
...
ValueError: the value of both inputs must be positive
>>> binary_and(0, 1.1)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> binary_and("0", "1")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive")
a_binary = str(bin(a))[2:] # remove the leading "0b"
b_binary = str(bin(b))[2:] # remove the leading "0b"
max_len = max(len(a_binary), len(b_binary))
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1"))
for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
34e136246665689b382cc5292f2d514a8fcffa0a | katsuyamiz/PythonPractice | /sets.py | 242 | 3.640625 | 4 | my_set = set()
print(my_set)
my_set.add(1)
print(my_set)
my_set.add(2)
print(my_set)
my_set.add(2)
print(my_set)
# have to be unique value
# the same value cannot be added twice
my_set2 = set()
my_set2.add('mississippi')
print(my_set2)
|
f459228d2e707acb10133cab2e4cfa456ca5cd52 | kimjieun6307/itwill | /itwill/Python_1/chap01_Basic/exams/exam03.py | 1,101 | 3.875 | 4 | '''
step03 문제
'''
'''
문) 3개의 단어를 키보드로 입력 받아서 각 단어의 첫자를 추출하여 단어의 약자를 출력하시오.
조건1) 각 단어 변수(word1, word2, word3) 저장
조건2) 입력과 출력 구분선 : 문자열 연산
조건3) 각 변수의 첫 단어만 추출하여 변수(abbr) 저장
<<화면출력 결과>>
첫번째 단어 : Korea
두번째 단어 : Baseball
세번째 단어 : Orag
=================
약자 : KBO
'''
word1 = input("첫번째 단어 : ")
word2 = input("두번째 단어 : ")
word3 = input("세번째 단어 : ")
abbr = word1[0]+word2[0]+word3[0]
print("<<화면출력 결과>>","\n첫번째 단어 : %s"%word1, "\n두번째 단어 : %s"%word2, "\n세번째 단어 : %s"%word3)
print('='*20, '\n약자 : %s'%abbr)
#@@6
word1 = input("첫번째 단어 : ")
word2 = input("두번째 단어 : ")
word3 = input("세번째 단어 : ")
print("첫번째 단어 : %s"%word1)
print("두번째 단어 : %s"%word2)
print("세번째 단어 : %s"%word3)
print('='*20)
print('약자 : %s'%(word1[0]+word2[0]+word3[0]))
|
db860a1e84107f294571b2c5738359ae0239456a | Rogan003/Python-vezbe | /vezba3.py | 287 | 3.546875 | 4 | from math import sqrt as koren
import random
def randomLista(x):
lista=[]
for i in range(x):
lista.append(random.randint(5,15))
return lista
unos=int(input("Unesite neki broj: "))
lista=randomLista(unos)
print("Koren iz sume random liste je: "+str(koren(sum(lista)))) |
5c61c271002f42a183df4fff8ee0c3f7b673dc71 | qizongjun/Algorithms-1 | /牛客网/最短子数组.py | 1,281 | 3.78125 | 4 | '''
对于一个数组,请设计一个高效算法计算需要排序的最短子数组的长度。
给定一个int数组A和数组的大小n,请返回一个二元组,代表所求序列的长度。
(原序列位置从0开始标号,若原序列有序,返回0)。保证A中元素均为正整数。
测试样例:
[1,4,6,5,9,10],6
返回:2
'''
'''
从左到右找最右边一个当前值大于之前最大值的地方
再从右到左找最左边一个当前值小于之前最小值的地方
两个值代表的区间就是需要排序的最短子数组的长度
原理实在不懂...
'''
# -*- coding:utf-8 -*-
import sys
class Subsequence:
def shortestSubsequence(self, A, n):
# write code here
large, small = -sys.maxint, sys.maxint
left, right = None, None
for s in range(n):
if A[s] >= large:
large = A[s]
else:
right = s
for s in range(n - 1, -1, -1):
if A[s] <= small:
small = A[s]
else:
left = s
if not left and not right:
return 0
elif not left:
return right + 1
elif not right:
return n - left
else:
return right - left + 1
|
76959896dd2adc2694a856849786ed814da80a1e | gabriellaec/desoft-analise-exercicios | /backup/user_179/ch27_2020_03_25_11_40_34_374907.py | 190 | 3.765625 | 4 | duvida = True
while duvida:
resposta = input('Você ainda está com dúvidas? ')
if resposta = 'sim':
print ("Pratique mais")
else:
duvida = False
print ("Até a próxima") |
18842651d19615eb712c6a371a9a29ec417ced34 | kanhu-nahak-au26/attainu_first | /python lecture/input_output.py | 202 | 3.875 | 4 | print("hay!!,Enter some Age")
Age = input ()
print("hay !!, You have enter", "you are" , Age,"year old")
print("Hay !! Please Enter your name")
name = input ()
print("Hi ", name ,"how are you today")
|
045361f47a587b8c14e495583d374375257807ef | lchappellet/leet_code_problems | /Roman_to_integer_leet_code_13.py | 1,410 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 27 17:13:21 2020
@author: cyrilchappellet
"""
#I 1
#V 5
#X 10
#L 50
#C 100
#D 500
#M 1000
roman_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
roman_string = str(input('Please Input a string of roman numerals:')).upper()
#for value in roman_string:
# if value in 'IVXLCDM':
# continue
# else:
# print('You have input the wrong string value:')
# roman_string = str(input('Please Input a string of roman numerals'))
#print('join two strings:', ''.join(list(['one','two'])))
previous_value_small = False
list_numbers = []
for index,value in enumerate(roman_string):
# if index == 0:
# list_numbers.append(roman_dict[value])
# continue
if previous_value_small:
previous_value_small = False
value = ''.join([roman_string[index-1],roman_string[index]])
list_numbers.append(roman_dict[value])
continue
if roman_dict[roman_string[index]] < roman_dict[roman_string[index+1]]:
previous_value_small = True
continue
if value in roman_dict:
list_numbers.append(roman_dict[value])
print('LIST:',list_numbers)
print('Sum of list:', sum(list_numbers))
|
211f1940ec4d885976b3ac0ba657c89cf03f322b | Hellofafar/Leetcode | /Medium/457.py | 3,035 | 3.703125 | 4 | # ------------------------------
# 457. Circular Array Loop
#
# Description:
# You are given a circular array nums of positive and negative integers. If a number k at an
# index is positive, then move forward k steps. Conversely, if it's negative (-k), move
# backward k steps. Since the array is circular, you may assume that the last element's next
# element is the first element, and the first element's previous element is the last element.
#
# Determine if there is a loop (or a cycle) in nums. A cycle must start and end at the same
# index and the cycle's length > 1. Furthermore, movements in a cycle must all follow a
# single direction. In other words, a cycle must not consist of both forward and backward movements.
#
# Example 1:
# Input: [2,-1,1,2,2]
# Output: true
# Explanation: There is a cycle, from index 0 -> 2 -> 3 -> 0. The cycle's length is 3.
#
# Example 2:
# Input: [-1,2]
# Output: false
# Explanation: The movement from index 1 -> 1 -> 1 ... is not a cycle, because the cycle's
# length is 1. By definition the cycle's length must be greater than 1.
#
# Example 3:
# Input: [-2,1,-1,-2,-2]
# Output: false
# Explanation: The movement from index 1 -> 2 -> 1 -> ... is not a cycle, because movement
# from index 1 -> 2 is a forward movement, but movement from index 2 -> 1 is a backward
# movement. All movements in a cycle must follow a single direction.
#
# Note:
#
# -1000 ≤ nums[i] ≤ 1000
# nums[i] ≠ 0
# 1 ≤ nums.length ≤ 5000
#
# Follow up:
# Could you solve it in O(n) time complexity and O(1) extra space complexity?
#
# Version: 1.0
# 10/15/19 by Jianfa
# ------------------------------
class Solution:
def circularArrayLoop(self, nums: List[int]) -> bool:
if not nums:
return False
size = len(nums)
def getIndex(i):
return (i + nums[i]) % size
for i in range(size):
if nums[i] == 0:
continue
# slow and fast pointers
slow = i
fast = getIndex(i)
while nums[slow] * nums[fast] > 0 and nums[slow] * nums[getIndex(fast)] > 0:
if slow == fast:
if slow == getIndex(slow):
# the loop with only one element
break
return True
slow = getIndex(slow)
fast = getIndex(getIndex(fast))
# loop not found, set all elements along the way to 0
slow = i
val = nums[i]
while nums[slow] * val > 0:
nextIdx = getIndex(slow)
nums[slow] = 0
slow = nextIdx
return False
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Slow/fast pointers solution from: https://leetcode.com/problems/circular-array-loop/discuss/94148/Java-SlowFast-Pointer-Solution
#
# O(n) time and O(1) space |
af231a99969fee2b4d8cd10ace3ad3393a147aff | Roc-J/LeetCode | /300~399/problem345.py | 657 | 3.515625 | 4 | # -*- coding:utf-8 -*-
# Author: Roc-J
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
number1 = []
number2 = []
for item in s:
if item in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']:
number1.append(item)
else:
number2.append(item)
for i in range(len(s)):
if s[i] in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']:
number2.insert(i, number1.pop())
return ''.join(number2)
if __name__ == '__main__':
print Solution().reverseVowels("leetcode") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.