blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
782622f075b479f13757624c77b2a020c1511a49 | jgtavarez/Blackjack-Project | /classes/greeting.py | 1,188 | 4.34375 | 4 | #The 'Greeting' class is used to welcome the user and explain the rules.
class Greeting:
def __init__(self,name):
self.name = name
# The greeting method welcomes the user with their name previously entered.
def greet(self):
print('Hi {}! •ᴗ• Welcome to the table, do you want to read the rules before you start playing?...\n'.format(self.name))
#The 'read' method shows the rules to the user or not depending on his choice.
def read(self,choice):
if choice == 1:
print('\nBlackjack Rules (ง •̀_•́)ง ผ(•̀_•́ผ)\n')
print('1-The game consists of adding a value as close to 21 but without going over.')
print('2-The player at the table plays only against the dealer, trying to get a better play than this.')
print('3-The dealer is required to ask for a card as long as his score totals 16 or less.')
print('4-And forced to stand if he adds 17 or more.')
print('5-The number cards add up to their value, the figures add up to 10 and the Ace is worth 11.\n')
else:
print('\nOK, good luck! 。◕‿◕。\n')
|
cbccd04659832f6be0dc34d1ba2d8e79ef1ffb98 | whx4J8/machine-learn | /apriori/test.py | 757 | 3.59375 | 4 | # coding=utf-8
from itertools import combinations, chain
#
# def subsets(arr):
# return chain(*[combinations(arr, i + 1) for i, a in enumerate(arr)])
if __name__ == '__main__':
# test = combinations([1, 2, 3, 4], 2)
# for el in test:
# print el
arr = [1,2,3,4]
# for i, c in enumerate(arr):
# for el in combinations(arr, i + 1):
# print el
#
# print "================================="
# for value in chain(*[combinations(arr,i+1) for i,a in enumerate(arr)]):
# print value
#
# print type(chain(*[combinations(arr,i+1) for i,a in enumerate(arr)]))
chain(*[combinations(arr, i + 1) for i, a in enumerate(arr)])
for value in combinations([1,2,3],1):
print value
|
8c891dfef3e3ea89167651db40e79ae0227ad233 | ambarish710/python_concepts | /linked_list/doubly_linked_list.py | 4,692 | 3.5625 | 4 | """
Few tip while iterating over arrays recursively --
1. Always make sure you check (if ptr == None) should always be before the next iteration jump
2. Always make next iteration jump directly while calling the function,
CORRECT APPROACH
if ptr == None:
return
ret_str = self.print_dll_rev(ptr.next) --> DO THIS INSTEAD
print(ptr.data)
WRONG APPROACH
if ptr == None:
return
ptr = ptr.next --> DON'T DO THIS
ret_str = self.print_dll_rev(ptr)
print(ptr.data)
"""
class Node:
def __init__(self, prev=None, data=None, next=None):
self.prev = prev
self.data = data
self.next = next
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_element_at_start(self, data):
if self.head == None:
node_obj = Node(data=data)
self.head = node_obj
else:
node_obj = Node(data=data, next=self.head)
self.head.prev = node_obj
self.head = node_obj
def add_element_at_end(self, data):
if self.head == None:
node_obj = Node(data=data)
self.head = node_obj
iteration_obj = self.head
while iteration_obj != None:
prev_obj = iteration_obj
iteration_obj = iteration_obj.next
node_obj = Node(data=data, prev=prev_obj)
prev_obj.next = node_obj
def print_dll_fwd(self):
iteration_obj = self.head
dll_str = ""
while iteration_obj:
if iteration_obj.next == None:
dll_str += str(iteration_obj.data)
else:
dll_str += str(iteration_obj.data) + "-->"
iteration_obj = iteration_obj.next
print(dll_str)
def print_dll_rev(self, ptr):
if ptr == None:
return
ret_str = self.print_dll_rev(ptr.next)
if ret_str:
if ptr.prev == None:
ret_str += str(ptr.data)
else:
ret_str += str(ptr.data) + "-->"
else:
ret_str = str(ptr.data) + "-->"
return(ret_str)
def dll_length(self):
iteration_obj = self.head
iteration_count = 0
while iteration_obj:
iteration_count += 1
iteration_obj = iteration_obj.next
print(iteration_count)
return iteration_count
def delete_element_at(self, location):
dll_len = self.dll_length()
if location > dll_len or location < 0:
print("Location number out of linked list range")
print("Please provide a number in between 0-{}".format(dll_len))
elif location == 1:
self.head = self.head.next
self.head.prev = None
else:
iteration_obj = self.head
for i in range(0, location-1):
iteration_obj = iteration_obj.next
prev = iteration_obj.next.prev
iteration_obj.next = iteration_obj.next.next
iteration_obj.next.prev = prev
def delete_element_at_start(self):
if self.head == None:
print("Linked List empty!")
return
elif self.dll_length() == 1:
self.head = None
else:
self.head = self.head.next
self.head.prev = None
def delete_element_at_end(self):
dll_len = self.dll_length()
if self.head == None:
print("Linked List empty!")
return
elif dll_len == 1:
self.head = None
else:
iteration_obj = self.head
for i in range(0, dll_len-2):
iteration_obj = iteration_obj.next
iteration_obj.next = None
if __name__ == "__main__":
dll_obj = DoublyLinkedList()
dll_obj.add_element_at_start(15)
dll_obj.add_element_at_start(10)
dll_obj.add_element_at_end(20)
dll_obj.add_element_at_start(5)
dll_obj.add_element_at_end(25)
dll_obj.print_dll_fwd()
dll_obj.dll_length()
print(dll_obj.print_dll_rev(dll_obj.head))
dll_obj.delete_element_at(2)
dll_obj.dll_length()
dll_obj.print_dll_fwd()
print(dll_obj.print_dll_rev(dll_obj.head))
dll_obj.delete_element_at_start()
dll_obj.dll_length()
dll_obj.print_dll_fwd()
print(dll_obj.print_dll_rev(dll_obj.head))
dll_obj.delete_element_at_end()
dll_obj.dll_length()
dll_obj.print_dll_fwd()
print(dll_obj.print_dll_rev(dll_obj.head))
|
6bc385bd3b38d1d181641b3e0377d17e242e2117 | CcWang/data_science | /intro/date_functionality.py | 2,336 | 3.796875 | 4 | import pandas as pd
import numpy as np
print "Timestamp"
print pd.Timestamp('5/21/2017')
print "Period"
print pd.Period('3/5/2016')
print "DatetimeIndex"
t1 = pd.Series(list('abc'), [pd.Timestamp('2016-09-01'), pd.Timestamp('2016-09-02'), pd.Timestamp('2016-09-03')])
print t1
print type(t1.index)
print "PeriodIndex"
t2 = pd.Series(list('def'),[pd.Period('2016-09'),pd.Period('2016-10'), pd.Period('2016-11')])
print t2
print type(t2.index)
print "Converting to Datetime"
d1=['2 June 2013', 'Aug 29, 2014', '2015-06-26','7/12/16']
ts3 = pd.DataFrame(np.random.randint(10,100,(4,2)), index = d1,columns = list('ab'))
print ts3
# change different date format to datetime
# pandas.to_datetime
ts3.index = pd.to_datetime(ts3.index)
print "after to_datetime"
print ts3
print pd.to_datetime('4.7.12', dayfirst=True)
print "Timedeltas - time differences"
print pd.Timestamp('9/3/2016') - pd.Timestamp('9/1/2016')
print pd.Timestamp('9/2/2016 8:10AM') + pd.Timedelta('12D 3H')
print "working with Dates in a DataFrame"
# print "Suppose we want to look at nine measurements, taken bi-weekly, every Sunday. Starting in October
dates = pd.date_range('10-01-2016', periods = 9, freq='2W-SUN')
# let's create DataFrame using these dates, and some random data, and see what we can do with it.
df = pd.DataFrame({'Count 1': 100 + np.random.randint(-5,10,9).cumsum(),
'Count 2': 120+ np.random.randint(-5,10,9)}, index = dates)
print df
# we can see that all the dates in our index are on a Sunday
print df.index.weekday_name
# we can use diff to find the difference between each date's value
print df.diff()
# Suppose we wanted to know what the mean count is for each month in our DataFrame. We can do this using resample.
print df.resample('M').mean()
# to find particular year, month, slice range of dates
print df['2017']
print df['2016-12']
# after 2016-12
# could change the frequence use asfreq
# we use this to change the frequency from bi-weekly to weekly We'll end up with missing values every other week. So let's use the forward fill method on those missing values.
print df.asfreq('W', method='ffill')
print df['2016-12':]
print "plottng time series"
import matplotlib.pyplot as plt
%matplotlib inline
# from IPython import get_ipython
# get_ipython().run_line_magic('matplotlib', 'inline')
print df.plot()
|
8f7cfd0c6bfbf285e69ff4c91290b4c163d37b8a | Vipulhere/Coding-Ninja-Solutions--DS-Algo-with-Python | /17. DP-1.py | 3,431 | 3.953125 | 4 | #Min Steps To 1
"""
Given a positive integer n, find the minimum number of steps s, that takes n to 1.
You can perform any one of the following 3 steps.
1.) Subtract 1 from it. (n= n - 1) ,
2.) If its divisible by 2, divide by 2.( if n%2==0, then n= n/2 ) ,
3.) If its divisible by 3, divide by 3. (if n%3 == 0, then n = n / 3 ).
The time complexity of your code should be O(n).
Input format :
Line 1 : A single integer i.e. n
Output format :
Line 1 : Single integer i.e number of steps
"""
Sample Input 1 :
4
Sample Output 1 :
2
Sample Output 1 Explanation :
For n = 4
Step 1 : n = 4/2 = 2
Step 2 : n = 2/2 = 1
Sample Input 2 :
7
Sample Output 2 :
3
Sample Output 2 Explanation :
For n = 7
Step 1 : n = 7 - 1 = 6
Step 2 : n = 6 / 3 = 2
Step 3 : n = 2 / 2 = 1
Solution :
def minStepsTo1DP(n):
''' Return Minimum no of steps required to reach 1 using using Dynamic Prog'''
storage=[-1]*(n+1)
storage[0]=0
storage[1]=0
bigNumber=2147483647
for i in range(2,n+1):
op1=storage[i-1]
op2=storage[i//2] if i%2==0 else bigNumber
op3=storage[i//3] if i%3==0 else bigNumber
storage[i]=1+min(op1,op2,op3)
return storage[n]
pass
n=int(input())
print(minStepsTo1DP(n))
#Minimum Number Of Squares
"""
A number can always be represented as a sum of squares of other numbers.
Note that 1 is a square and we can always break a number as [(1 * 1) + (1 * 1) + (1 * 1) + …].
Given a number n, find the minimum number of squares that sum to n.
Input format:
The first and only line of input contains an integer N (1 <= N <= 10000)
Output format:
The first and only line of output contains the minimum number if squares that sum to n.
"""
Sample Test Cases:
Sample Input 1:
100
Sample Output 1:
1
Explanation:
We can write 100 as 10^2 also, 100 can be written as (5^2) + (5^2) + (5^2) + (5^2),
but this representation requires 4 squares.
So, in this case, the expected answer would be 1, that is, 10^2.
Solution :
import sys, math
def minStepsTo1(n):
dp = [-1 for i in range(n + 1)]
dp[0] = 0
for i in range(1, n + 1):
ans = sys.maxsize
root = int(math.sqrt(i))
for j in range(1, root + 1):
cur_ans = 1 + dp[i - (j ** 2)]
ans = min(ans, cur_ans)
dp[i] = ans
return dp[n]
n = int(input())
ans = minStepsTo1(n)
print(ans)
#Longest Increasing Subsequence
"""
Given an array with N elements,
you need to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in strictly increasing order.
Input Format
Line 1 : An integer N
Line 2 : Elements of arrays separated by spaces
Output Format
Line 1 : Length of longest subsequence
"""
Sample Input :
6
5 4 11 1 16 8
Sample Output 1 :
3
Sample Output Explanation
Length of longest subsequence is 3 i.e. (5,11,16) or (4,11,16).
Sample Input 2:
3
1 2 2
Sample Output 2 :
2
Solution :
def lis(arr):
n = len(arr)
dp = [-1 for i in range(n)]
dp[n - 1] = 1
i = n - 2
while i >= 0:
including_max = 1
further_including_max = 0
for j in range(i + 1, n):
if arr[j] > arr[i]:
further_including_max = dp[j]
including_max = max(including_max, 1 + further_including_max)
dp[i] = including_max
i -= 1
return max(dp)
n = int(input())
li = [int(ele) for ele in input().split()]
print(lis(li))
|
6dcf297f46ec56e712c7e68c1147beca9fd90cd0 | ayman-shah/Python-CA | /Python 1/12.2.py | 143 | 3.546875 | 4 | mood = input("How are you feeling today?")
if mood == "happy":
print("That's great!")
if mood == "sad":
print("Sorry to hear that")
|
bc96dc4fba6e79c7e5e7221a3adaa71ee34d1a79 | jreinstra/Scrabble.py | /Button.py | 1,026 | 3.8125 | 4 | from drawing import *
class Button :
##F68D5C#EBE39C
def __init__(self, x, y, width, height, text, color = "#fff2cc", outline = "Black") :
self.x1 = x
self.y1 = y
self.x2 = x + width
self.y2 = y + height
self.width = width
self.height = height
self.text = text
self.color = color
self.outline = outline
self.draw(color, outline)
def isInButton(self, x, y) :
return x >= self.x1 and x <= self.x2 and y >= self.y1 and y <= self.y2
def select(self) :
self.draw("#FFBF00")
def deselect(self) :
self.draw()
def updateText(self, text) :
self.text = text
self.remove()
self.draw()
def draw(self, color = None, outline = None) :
if color == None:
color = self.color
if outline == None:
outline = self.outline
draw.rect(self.x1, self.y1, self.x2, self.y2, fill=color, outline=outline)
draw.text(self.x2 - (self.width / 2), self.y2 - (self.height / 2), text=self.text)
def remove(self) :
draw.rect(self.x1, self.y1, self.x2, self.y2, fill="White", outline="White") |
e7f01c56f4482a45cb3a08380f6aab97603cac11 | shailendra-singh-dev/ProgrammingChallenges | /Caribbean Online Judge COJ/1445 - What's Next?.py | 237 | 3.6875 | 4 | while True:
a1, a2, a3 = map(int, raw_input().split())
if not a1 and not a2 and not a3:
break
if a3 - a2 == a2 - a1:
print "AP " + str(a3 + (a2 - a1))
else:
print "GP " + str(a3 * (a2 / a1)) |
4c8f586619ed713d5eaf88cf85f0e7daf2aa1be6 | agordon/agordon.github.io-DISABLED | /files/regex/regex-demo.py | 505 | 4.03125 | 4 | #!/usr/bin/env python
import re
# Python Regex Howto + Syntax
# https://docs.python.org/2/howto/regex.html
data = "chr1 65436543 rsID776"
# Build a Regex Object based on desired pattern
regex = re.compile('^chr')
if regex.search(data):
print "Found match! line starts with 'chr'"
# Regex to extract information (ie. 'grouping')
# Get the number following the 'chr', store in object 'm'
regex = re.compile('^chr([0-9]+)')
m = regex.search(data)
if m:
print "found chromosome: ", m.group(1)
|
eb399f47273b19979da1950543557836404f8f87 | valkata1220/Programming-Basics-Python | /10.For-Loop-Exercise/07.salary.py | 478 | 3.65625 | 4 | open_tabs_count = int(input())
salary = int(input())
facebook = 150
instagram = 100
reddit = 50
current_tab = None
for i in range(open_tabs_count):
current_tab = input()
if current_tab == 'Facebook':
salary -= facebook
elif current_tab == 'Instagram':
salary -= instagram
elif current_tab == 'Reddit':
salary -= reddit
if salary <= 0:
break
if salary <= 0:
print('You have lost your salary.')
else:
print(salary)
|
a40908ea8c02c94d138ca7df7ec31d83a9205e52 | Mereep/advent_of_code_2020_python | /day10/solution.py | 4,222 | 4.25 | 4 | from typing import List
import math
def count_removables(ordered_adapters: List[int],
first_index: int,
start: int) -> int:
"""
This function counts all correct ways of pluging the adapters
WARNING: This function is very slow and this is likely NOT the best way to do that.
In fact I didnt even bother to run it through the `input.txt´ file (However, you can verify on the other smaller
files)
:param ordered_adapters:
:param first_index:
:param start:
:return:
"""
if start == len(ordered_adapters) - 1:
return 1
if (ordered_adapters[start + 1] - ordered_adapters[first_index]) <= 3:
wo_score = count_removables(
ordered_adapters,
start=start + 1,
first_index=first_index)
w_score = count_removables(
ordered_adapters,
start=start + 1,
first_index=start)
return w_score + wo_score
else:
return count_removables(ordered_adapters,
start=start + 1,
first_index=start)
if __name__ == '__main__':
# read data
with open('input.txt', 'r') as f:
joltages: List[str] = f.readlines()
# ... and transform numbers to
joltages_as_numbers = [int(d) for d in joltages]
# ... sort the numbers in ascending order so we easily can iterate over them
joltages_as_numbers_sorted = sorted(joltages_as_numbers)
# count differences of one and 3 jolts between subsequent joltages (Task I)
n_differences_of_3 = 0
n_differences_of_1 = 0
# add the "voltage" of 0 before everything (simulates input)
joltages_as_numbers_sorted.insert(0, 0)
# and add a an entry of value `max + 3´ for the very last output (simulates output)
joltages_as_numbers_sorted.append(joltages_as_numbers_sorted[-1] + 3)
for index in range(1, len(joltages_as_numbers_sorted)):
difference = joltages_as_numbers_sorted[index] - joltages_as_numbers_sorted[index - 1]
if difference == 3:
n_differences_of_3 += 1
elif difference == 1:
n_differences_of_1 += 1
elif difference == 2:
break # This case is not of interest
elif difference > 3:
raise Exception("There can only be differences of max 3 jolts (Code: 938129)")
print("1 jolt differences: ", n_differences_of_1)
print("3 jolt differences: ", n_differences_of_3)
print("multiplication of those: ", n_differences_of_3 * n_differences_of_1)
# Part II: Count all valid ways to plug the adapters together (keeping the final valid output)
# remember that each time we `could´ remove on adapter from the chain that
# would be a valid permutation
# 0 1 2 3 4 5 6 4 5 6 8 9 10 13 14 17
# Max: n2^(len(adapters)) ways that could be theoretical checked
# --> most of them can NEVER be valid
# count "removable" adapters
# we split the joltages into parts, where each part consists of consecutive
# joltages where the difference < 3
# so we can solve this as a subproblem
joltages_split: List[List[int]] = []
current_split = []
for i in range(len(joltages_as_numbers_sorted) - 1):
diff_to_next = joltages_as_numbers_sorted[i+1] - joltages_as_numbers_sorted[i]
current_split.append(joltages_as_numbers_sorted[i])
if diff_to_next >= 3:
joltages_split.append(current_split)
current_split = [joltages_as_numbers_sorted[i]]
split_variations: List[int] = []
for i in range(0, len(joltages_split)):
split_variations.append(count_removables(joltages_split[i],
first_index=0,
start=1))
total_sum: int = 1
for split_variation in split_variations:
total_sum *= split_variation
print(total_sum)
|
bf0c82e4fc722ffd38846e16a7ab62ddc1fa532a | prajjaldhar/basic_python | /basic_python/05_string_function.py | 778 | 4.0625 | 4 | str='''A paragraph is a series of related sentences developing a central idea, called the topic.
Try to think about paragraphs in terms of thematic unity: a paragraph is a sentence or a group of sentences that supports one central, unified idea.
Paragraphs add one idea at a time to your broader argument'''
print(str)
print(len(str))
print(str.endswith("ment"))
print(str.count("p"))
print(str.upper())
print(str.lower())
print(str.find("sent"))
print(str.replace("paragraph","prajjal"))
letter=''' Dear <|NAME|>,
You Are Selected to Represent Team <|TEAM|>!!!!
Thanking You
Team <|TEAM|>'''
Name=input("ENTER NAME\n")
Team=input("ENTER TEAM NAME\n")
letter=letter.replace("<|NAME|>",Name)
letter=letter.replace("<|TEAM|>",Team)
print(letter) |
c1f322054a4cab95673bb858f8eeccc70759580e | angelicaperez37/cs224w-221-project | /fantasy_player_data/positions/csv2json.py | 880 | 3.6875 | 4 | print '{'
def parse(fname):
with open(fname) as f:
first = True
for line in f:
if first:
first = False
else:
print ' },'
name, team, pos, cost = line.rstrip().split(', ')
pid = name + '!' + team
print ' "{}": {{'.format(pid)
print ' "pid": "{}",'.format(pid)
print ' "name": "{}",'.format(name)
print ' "team": "{}",'.format(team)
print ' "pos": "{}",'.format(pos)
print ' "cost": {},'.format(int(float(cost) * 10))
print ' "py/object": "util.Player"'
first = True
for fname in ['goalkeepers', 'defenders', 'midfielders', 'forwards']:
if first:
first = False
else:
print ' },'
parse(fname)
print ' }'
print '}'
|
8fc725b2a080564cef9ae60e3a95043e84414e4d | Gaurav00206/Task-5 | /Task 5.py | 258 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[11]:
list1 = [12, -7, 5, 64, -14]
for number in list1 :
if number > 0:
print(number)
# In[12]:
list2 = [12, 14, -95, 3]
for number in list2:
if number>0:
print(number)
# In[ ]:
|
338ef2c2e4ec644af44a100ff2c34fcdcec02fa2 | pawelgoj/Examples-of-some-algorithms | /sort_and_search/binary_search.py | 403 | 3.6875 | 4 | list = (2, 5, 10, 25, 30, 50)
def binary_search(list, item):
min = 0
max = len(list) - 1
while min <= max:
mid = int((min + max) / 2)
if list[mid] == item:
return mid
elif list[mid] > item:
max = mid - 1
elif list[mid] < item:
min = mid + 1
return None
item_position = binary_search(list, 9)
print(item_position)
|
7bb871d52173d668cb65b566988c59078dc9c9a0 | epc0037/URI-CS | /CSC110/Accessing Data from Files/Class Challenge Week 5/group8.py | 1,156 | 3.765625 | 4 | # Group 8
# Secret Code
def getPasswordLetter(fileName, line_number, ch):
inFile = open(fileName , 'r')
for i in range(line_number):
line = inFile.readline()
letter = line[ch]
inFile.close()
return letter
def getPassword():
fileName = input("Enter the file name: ")
password = []
counter = 0
while counter < 12:
line = int(input("Enter the line number: "))
position = int(input("Enter the position: "))
reading = getPasswordLetter( fileName, line, position)
password = password + [reading]
counter = counter + 1
return password
def decryptLetter(letter, fileName):
inFile = open(fileName, 'r')
line = inFile.readline()
ch1, ch2 = line.split('-')
while letter != ch1:
line = inFile.readline()
ch1, ch2 = line.split('-')
return ch2.strip()
inFile.close()
def decrypt(secret_msg, fileName):
message = []
for i in range(len(secret_msg)):
letter = decryptLetter(secret_msg[i], 'group8_CodeSheet.txt')
message = message + [letter]
return message
|
1d0f9327adb4894803d39c04c261c2ca24be6745 | nithen-ac/Algorithm_Templates | /data_structure/linked_list_examples.py | 9,080 | 4.0625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# [237] https://leetcode.com/problems/delete-node-in-a-linked-list/
# Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
#
# change value
def deleteNode(node: ListNode):
# doesn't work, if node is tail
node.val, node.next = node.next.val, node.next.next
# [2] https://leetcode.com/problems/add-two-numbers/
# Add the two numbers and return it as a linked list.
#
# simulation
def addTwoNumbers1(l1, l2):
addends = l1, l2
dummy = end = ListNode(0)
carry = 0
while addends or carry:
carry += sum(a.val for a in addends)
addends = [a.next for a in addends if a.next]
end.next = end = ListNode(carry % 10)
carry /= 10
return dummy.next
# [2] https://leetcode.com/problems/add-two-numbers/
# Add the two numbers and return it as a linked list.
#
# convert to int
def addTwoNumbers2(l1, l2):
def toint(node):
return node.val + 10 * toint(node.next) if node else 0
def tolist(n):
node = ListNode(n % 10)
if n > 9:
node.next = tolist(n / 10)
return node
return tolist(toint(l1) + toint(l2))
# [21] https://leetcode.com/problems/merge-two-sorted-lists/
# Merge two sorted linked lists and return it as a new list.
#
# iteratively
def mergeTwoLists1(l1: ListNode, l2: ListNode) -> ListNode:
curr = dummy = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
# [21] https://leetcode.com/problems/merge-two-sorted-lists/
# Merge two sorted linked lists and return it as a new list.
#
# recursively
# first make sure a starts smaller, use its head as result, and merge the remainders behind it.
def mergeTwoLists2(a, b):
if a and b:
if a.val > b.val:
a, b = b, a
a.next = mergeTwoLists2(a.next, b)
return a or b
# [21] https://leetcode.com/problems/merge-two-sorted-lists/
# Merge two sorted linked lists and return it as a new list.
#
# recursively
# make sure that a is the "better" one (meaning b is None or has larger/equal value). Then merge the remainders behind a.
def mergeTwoLists3(a, b):
if not a or b and a.val > b.val:
a, b = b, a
if a:
a.next = mergeTwoLists3(a.next, b)
return a
# [24] https://leetcode.com/problems/swap-nodes-in-pairs/
# Given a linked list, swap every two adjacent nodes and return its head.
#
# Since the head doesn't have a previous node, I just use self instead.
# To go from "pre -> a -> b -> b.next" to "pre -> b -> a -> b.next", we need to change those three references.
# Instead of thinking about in what order I change them, I just change all three at once.
def swapPairs(self, head):
pre, pre.next = self, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
return self.next
# [234] https://leetcode.com/problems/palindrome-linked-list/
# Given a singly linked list, determine if it is a palindrome.
def isPalindrome(head: ListNode) -> bool:
check = None
slow = fast = head
# traverse and reverse first half link list at the same time
while fast and fast.next:
fast = fast.next.next
check, check.next, slow = slow, check, slow.next
# solve odd and even problem
if fast:
slow = slow.next
while slow and slow.val == check.val:
slow = slow.next
check = check.next
# check whether reach the end
return not check
# [82] https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
# Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
#
# change node
def deleteDuplicates1(head: ListNode) -> ListNode:
dummy = pre = ListNode(0)
dummy.next = head
while head and head.next:
if head.val == head.next.val:
while head and head.next and head.val == head.next.val:
head = head.next
head = head.next
pre.next = head
else:
pre = pre.next
head = head.next
return dummy.next
# [82] https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
# Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
#
# change value
def deleteDuplicates2(head: ListNode) -> ListNode:
dummy = ListNode(float('inf'))
cur = dummy.next = head
res, duplicated = [dummy.val], False
while cur:
if res[-1] == cur.val:
duplicated = True
else:
if duplicated:
res[-1] = cur.val
else:
res.append(cur.val)
duplicated = False
cur = cur.next
if duplicated:
res.pop()
cur = dummy
for v in res[1:]:
cur.next.val = v
cur = cur.next
cur.next = None
return dummy.next
# [25] https://leetcode.com/problems/reverse-nodes-in-k-group/
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
#
# iteratively
def reverseKGroup1(head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
dummy = jump = ListNode(0)
dummy.next = l = r = head
while True:
count = 0
while r and count < k: # use r to locate the range
r = r.next
count += 1
if count == k: # if size k satisfied, reverse the inner linked list
pre, cur = r, l
for _ in range(k): # do it k times
cur.next, cur, pre = pre, cur.next, cur # standard reversing
jump.next, jump, l = pre, l, r # connect two k-groups
else:
return dummy.next
# [25] https://leetcode.com/problems/reverse-nodes-in-k-group/
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
#
# recursively
def reverseKGroup2(head, k):
l, cur = 0, head
while cur:
l += 1
cur = cur.next
if k <= 1 or l < k:
return head
pre, cur = None, head
for _ in range(k):
post = cur.next
cur.next, pre, cur = pre, cur, post
head.next = reverseKGroup2(cur, k)
return pre
# [142] https://leetcode.com/problems/linked-list-cycle-ii/
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
def detectCycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
else: # reach the end, means no cycle
return None
while head != slow:
slow = slow.next
head = head.next
return head
# [146] https://leetcode.com/problems/lru-cache/
# Design and implement a data structure for Least Recently Used (LRU) cache.
#
# double linked node, or can use OrderedDict in collection
class DLinkedNode:
def __init__(self, key, val):
self.pre = None
self.next = None
self.key = key
self.val = val
class DLinkedList:
def __init__(self):
self.head = DLinkedNode(0, 0)
self.tail = DLinkedNode(0, 0)
self.__add(self.head, self.tail)
self.count = 0
def remove(self, node):
node.pre.next, node.next.pre = node.next, node.pre
self.count -= 1
@staticmethod
def __add(node1, node2):
node1.next, node2.pre = node2, node1
def push(self, node):
self.__add(self.tail.pre, node)
self.__add(node, self.tail)
self.count += 1
def pop(self):
first = self.head.next
self.__add(self.head, self.head.next.next)
self.count -= 1
return first
def __len__(self):
return self.count
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.queue = DLinkedList()
self.dict = {}
def get(self, key: int) -> int:
if key in self.dict:
node = self.dict[key]
self.queue.remove(node)
self.queue.push(node)
return node.val
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.dict:
node = self.dict[key]
node.val = value
self.queue.remove(node)
self.queue.push(node)
else:
if len(self.queue) == self.capacity:
del self.dict[self.queue.pop().key]
node = DLinkedNode(key, value)
self.dict[key] = node
self.queue.push(node)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
0778bdb82078c6c60fc3e9a581e8051d690b36bc | piggy1024/python-learn | /python-course/day-04/code/14.垃圾回收.py | 346 | 3.78125 | 4 | # 14.垃圾回收.py
# 垃圾回收就是将垃圾对象从内存中删除
class A:
def __init__(self):
self.name = 'A类'
def __del__(self):
print('A()对象被删除了~~',self)
a = A()
b = a
print(a.name)
a = None # 将a设置为了None,此时没任何变量被引用,它就是垃圾了
input('回车键退出')
|
3a8c887f50bdfec97df490e247ecc4740f7ffaf2 | Srinivasstt/epsilon-python | /pythonscripts/forlooptest.py | 219 | 3.8125 | 4 | a = "sofadsrinivas"
vowel="aeiou"
#for i in a:
# print(i)
i=0
while (i < len (a)):
# print(a[i])
if (a[i] in vowel):
print('vowel has reached "',a[i],'"')
i += 1
pass
#continue
#break
print(a[i])
i += 1
|
c19c3f2e26fe91e4ecb20b5a6f9df7ab0c63c368 | Protino/HackerRank | /Contests/Week of Code 26/game-with-cells.py | 426 | 3.625 | 4 | n,m = map(int, input().split())
#Number of 2x2 bases possible
_2x2_bases = (n//2)*(m//2)
#both are odd
if n%2!=0 and m%2!=0:
extras = (n//2+1)+(m//2+1)-1
#one of them is even or odd
elif (n%2==0 and m%2!=0)or(m%2==0 and n%2!=0):
extras = (n//2 if n%2==0 else 0) + (m//2 if m%2==0 else 0)
else:
extras = 0
print ((_2x2_bases+extras) if n and m!=0 else (0))
'''
# Test cases
2 2
1
3 2
2
0 1
0
0 0
0
1000 1000
'''
|
d785cbb2e2414b143f1d7aa2f06286753c999674 | junho5/python | /list_and_string.py | 676 | 3.6875 | 4 | alphabet_list = ['A', 'B', 'C', 'D', 'E', 'F']
print(alphabet_list[0])
print(alphabet_list[3])
print(alphabet_list[-1])
print(alphabet_list[0:5])
print(alphabet_list[:4])
print(alphabet_list[:4])
alphabet_string = "ABCDEF"
print(alphabet_string[0])
print(alphabet_string[3])
print(alphabet_string[-1])
print(alphabet_string[0:5])
print(alphabet_string[:4])
print(alphabet_string[4:])
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = list_1 + list_2
print(list_3)
print(len(list_1))
print(len(alphabet_string))
# list 와 문자열의 다른점
numbers = [1, 2, 3, 4]
numbers[0] = 5
print(numbers)
numbers_string = "1234"
numbers_string[0] = 5
print(numbers_string)
|
328dd762eb6df9f286f76fe6586dea4de44d46b5 | t0futac0/ICTPRG-Python | /arithmetic.py | 279 | 3.859375 | 4 | num1 = 25
num2 = 4
print('add')
print(num1 + num2)
print('subtract')
print(num1 - num2)
print('multipy')
print(num1 * num2)
print('divide')
print(num1 / num2)
print('double divide')
print(num1 // num2)
print('modulus')
print(num1 % num2)
print('power')
print(num1 ** num2) |
d4a3d9b42c7f18a3bbe769b74772ad29907e4705 | huizhe2016/Python-methods | /methods/port_scanning.py | 939 | 3.78125 | 4 | # -*- coding: utf-8 -*-
#python version 2.7
#ip port scanning
#use socket scanning
#建议使用多进程不然会很浪费时间
import socket
class PortService(object):
'''服务器端口检测及扫描(外部扫描65535个端口)'''
def __init__(self,ip):
self.ip = ip
@staticmethod
def detection(ip, port):
'''检测ip 端口是否正常(return 0 correct,异常返回其它)'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
conn = s.connect_ex((ip, port))
s.close()
return conn
except Exception,e:
s.close()
return e
def scanning(self,port_type=None,**kwargs):
'''扫描一个ip的所有端口'''
scann_results = []
for i in range(0,65536):
status = PortService.detection(self.ip,i)
scann_results.append([self.ip,status])
return scann_results |
89455734f676194a74180697501115689a1b7e36 | DaltonM98/Code-examples | /FallingDistance.py | 262 | 3.5 | 4 | def fdist( ftime ):
grav = 9.8
dist = ( 1 / 2 ) * grav * ( ftime ** 2 )
return dist
def main():
print( "Time\tFalling Distance\n" )
for ctime in range( 1, 11):
print( ctime, "\t", format( fdist( ctime ), ".2f" ) )
main()
|
fd63abbf9883444418008e3968960cc13a3fdc54 | cifpfbmoll/practica-5-python-Marat-Rafael | /practica5/practica5/p5e2.py | 413 | 3.84375 | 4 | #autor:Marat-Rafael
"""Escribe un programa que pida dos números y escriba qué números entre ese
par de números son pares y cuáles impares"""
num1=int(input("introduce primer numero por favor: "))
num2=int(input("introduce segundo numero, mayor que '{0}' : ".format(num1)))
for i in range(num1,num2):
if i%2==0:
print ((i),"es un numero par")
else:
print ((i),"es un numero impar") |
fb7d2a1e08fc2a43fc878825837887967be8d633 | Shakhrami/ProjEuler | /countingSundays.py | 930 | 4.3125 | 4 | #?/usr/bin/env python
#Prob 19: Counting Sundays
def days_per_month(month, year):
if(month == 1):
if((year % 4 == 0 and year % 100 != 0)or(year % 400 ==0)):
return 29
else:
return 28
if(month == 3 or month == 5 or month == 8 or month == 10):
return 30
else:
return 31
dayOfWeek = {0:"Sunday", 1:"Monday", 2:"Tuesday", 3:"Wednesday",
4:"Thursday", 5:"Friday", 6:"Saturday"}
weekday = 2 #Jan 1st 1901 is a tuesday
sunOnMon = 0
for year in range(1901, 2001):
for month in range(0,12):
daysThisMonth = days_per_month(month, year)
for i in range(0, daysThisMonth):
if(i == 0 and dayOfWeek[weekday] == "Sunday"):
sunOnMon +=1
#print"SunOnMon found at year", year, "month", month
weekday +=1
if(weekday == 7):
weekday = 0
print sunOnMon
|
be206759debfa580bc2224543ec72d5011ebbca4 | georgek2/Learn_Programming | /Projects/Sorting.py | 771 | 3.90625 | 4 |
'''
Storing items in a list. They have to be in a list and not a tuple since it is immutable
earth_metals = ["Beryllium", "Magnesium", "Calcium", "Strontium", "Barium", "Radium"]
earth_metals.sort()
print(earth_metals)
earth_metals.sort(reverse=True)
print(earth_metals)
'''
t = (
['jane', 'luke', 'mary'],
['jane', 'luke', 'mary'],
['jane', 'luke', 'mary']
)
guess_word = 'me'
guess = ''
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != guess_word and not out_of_guesses:
if guess_count < guess_limit:
guess = input('Please Enter Your guess: ')
guess_count += 1
else:
out_of_guesses = True
if guess == guess_word:
print('Congratulations, You win !!')
else:
print('Sorry!! out of guesses')
|
8aa3a7137e223340237ff48ebe1ec691d32e2753 | tjmer/restaurant-ratings | /ratings.py | 2,448 | 4.125 | 4 | import random
"""Restaurant rating lister."""
# put your code here
scores = open('scores.txt')
restaurant_scores = {}
choices = ''
def add_rating():
key = input(str('Enter store name(capitalize the first letter): '))
value = input('Enter rating 1-5:')
if int(value) > 5 or int(value) < 1:
print("Needs to be between 1-5")
add_rating()
else:
restaurant_scores[key] = value
def sort_print():
for line in scores:
key, value = line.rstrip().split(":")
restaurant_scores[key] = value
for line in sorted(restaurant_scores.items()):
print(line[0], 'is rated at', line[1])
def to_do():
select = input(str("What would you like to do?\n------\nadd: Add rating.\nupdate: Update a rating.\nupdate-rand: Update a random rating.\nratings: See all ratings\nexit: To quit\n------\nSelect: "))
return select
def update():
for line in scores:
key, value = line.rstrip().split(":")
restaurant_scores[key] = value
random_key = random.choice(list(restaurant_scores.items()))
print(random_key[0], "is rated at", random_key[1])
new_rate = int(input("What is the new rating: "))
if new_rate > 5 or new_rate < 1:
print("Need to be between 1-5.")
update()
else:
restaurant_scores[random_key[0]] = new_rate
def spec_update():
for line in scores:
key, value = line.rstrip().split(":")
restaurant_scores[key] = value
for line in sorted(restaurant_scores.items()):
print(line[0], 'is rated at', line[1])
print('')
store = str(input('What store(need to cap first letter): '))
print('')
new_rate = int(input('Enter new rating: '))
if new_rate > 5 or new_rate < 1:
print('Needs to be between 1-5')
spec_update()
else:
restaurant_scores[store] = new_rate
def main():
choices = to_do()
while choices != "exit":
if choices == "add":
add_rating()
choices = to_do()
print('')
elif choices == "update-rand":
update()
choices = to_do()
print('')
elif choices == "update":
spec_update()
choices = to_do()
print('')
elif choices == "ratings":
sort_print()
choices = to_do()
print('')
else:
choices = to_do()
print('')
main() |
2bf0ebd78b556baa2b4aa54ef510845815cb6538 | MIDHUnRaj647/DJANGO_PYTHON | /flowcontrol/loopingstrings/forloop/nestedforloop.py | 393 | 3.953125 | 4 |
# for i in range(1,5):#i=0
# for j in range (0,i):#j(0,4)
# print(j,end=' ')
# print()
# for i in range(1,5):#i=0
# for j in range (0,i):#j(0,4)
# print('*',end=' ')
# print()
for row in range(1,5):
for col in range(1,8):
if (row==4 or row+col==5 or col-row==3):
print('*',end='')
else:
print(end=' ')
print()
|
55122e696feb12901ea45fc31083b01d94ed0e17 | AlexMetodieva/SoftUni | /deposit_calculator.py | 271 | 3.75 | 4 | deposit_sum = float(input())
duration_deposit_month = int(input())
yearly_percentage = float(input())
interest = deposit_sum * (yearly_percentage/100)
interest_per_moth = interest/12
result_sum = deposit_sum + duration_deposit_month * interest_per_moth
print(result_sum) |
a2e4ce0562db171982d1652dafe299544bbaa18b | Jabuf/projecteuler | /problems/problem5/Problem5.py | 714 | 3.65625 | 4 | """
https://projecteuler.net/problem=5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
from locals import *
def solution():
answer_found = False
smallest_number = 2520
while not answer_found:
smallest_number += 2520
answer_found = is_evenly_divisible(smallest_number)
return smallest_number
def is_evenly_divisible(x):
for i in range(1, 20):
if not (x % i == 0):
return False
return True
with Timer() as timed:
print(solution())
print("Seconds taken: {0}".format(timed.elapsed))
|
3f1efa2266219af8ce4111c16c4af7f5c63b6fa9 | prithvidiamond1/Algorithms | /maze_builderV2.py | 6,336 | 3.953125 | 4 |
# Maze generator - v2: Generates mazes that look like city streets (more or less...)
from copy import deepcopy
from random import randint, choice
order = 10
space = ['X']+['_' for x in range(order)]+['X']
maze = [deepcopy(space) for x in range(order)]
maze.append(['X' for x in range(order+2)])
maze.insert(0, ['X' for x in range(order+2)])
maze[1][1] = 'S' # Initializing a start position
maze[order][order] = 'O' # Initializing a end position
finalpos = (order, order)
pos = (1, 1)
def spit():
for x in maze:
print(x)
# spit()
# Rules:
# Not more than 5x2 or 2x5 (HorizontalxVertical) blocks
# No block connected.
# Every freespace must be connected to atleast two other freespaces. $$
blocks = []
freespaces = [(x, y) for x in range(1, order+1) for y in range(1, order+1)]
def mazebuilder(maze):
def blockbuilder(kind):
param1 = param2 = 0
double = randint(0, 1)
if kind == 0:
param2 = randint(3, 5)
if double:
param1 = 2
else:
param1 = 1
else:
param1 = randint(3, 5)
if double:
param2 = 2
else:
param2 = 1
for a in range(blockstarter[0], blockstarter[0]+param2):
for b in range(blockstarter[1], blockstarter[1]+param1):
if (a+1, b) in blocks or (a-1, b) in blocks or (a, b+1) in blocks or (a, b-1) in blocks or (a, b) in blocks or (a+1, b+1) in blocks or (a-1, b+1) in blocks or (a+1, b-1) in blocks or (a-1, b-1) in blocks:
pass
else:
if a > order+1 or b > order+1:
pass
else:
if maze[a][b] == 'X':
blocks.append((a, b))
else:
spaces = [(a+1, b), (a-1, b), (a, b+1), (a, b-1)]
for c in spaces:
if maze[c[0]][c[1]] == 'X':
break
else:
maze[a][b] = 'X'
blocks.append((a, b))
for x in range(1, order+1):
for y in range(1, order+1):
if (x, y) in freespaces:
t = [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
i = 0
while i < len(t):
if maze[t[i][0]][t[i][1]] == 'X' or (t[i][0], t[i][1]) == pos or (t[i][0], t[i][1]) == finalpos:
del t[i]
else:
i += 1
if len(t) > 2:
blockstarter = t[randint(0, len(t)-1)]
kind = randint(0, 1) # 0 - vertical, 1 - horizontal
blockbuilder(kind)
else:
pass
# Randomize inside while loop - Fail
# Randomize outside while loop - Pass
# rch = choice(['d', 'u', 'r', 'l'])
b = 0
while b < len(blocks):
block = blocks[b]
t = {'d':(block[0]+2, block[1]), 'u':(block[0]-2, block[1]), 'r':(block[0], block[1]+2), 'l':(block[0], block[1]-2)}
rch = choice(['d', 'u', 'r', 'l'])
z = t[rch]
# if z[0] > order+1 or z[1] > order+1 or z[0] < 1 or z[1] < 1:
if z[0] > order-2 or z[1] > order-2 or z[0] < 2+2 or z[1] < 2+2: # Decreased chance of having non solvable maze being generated...
pass
else:
if maze[z[0]][z[1]] == 'X':
if randint(0, 1):
set = None
if rch == 'u':
set = (z[0]+1, z[1])
elif rch == 'd':
set = (z[0]-1, z[1])
elif rch == 'r':
set = (z[0], z[1]-1)
elif rch == 'l':
set = (z[0], z[1]+1)
else:
pass
if maze[set[0]][set[1]] == '_':
# Checks so that no walls that block the entire way are formed
# Makes sure maze is solvable
sets, count = [(set[0]+1, set[1]), (set[0]-1, set[1]), (set[0], set[1]+1), (set[0], set[1]-1)], 0
for blyat in sets:
while blyat[0] != 0 and blyat[1] != 0 and blyat[0] != order+1 and blyat[1] != order+1:
ch = [(blyat[0]+1, blyat[1]), (blyat[0]-1, blyat[1]), (blyat[0], blyat[1]+1), (blyat[0], blyat[1]-1)]
suka = []
for i in ch:
if ch not in suka:
if maze[i[0]][i[1]] == 'X':
blyat = i
break
else:
pass
suka.append(ch)
else:
pass
else:
blyat = None
if blyat == None:
break
else:
pass
else:
count += 1
if count < 1:
maze[set[0]][set[1]] = 'X'
blocks.append(set)
else:
pass
# check1 = [(set[0], y) for y in range(1, order+1) if maze[set[0]][y]=='X']
# check2 = [(x, set[1]) for x in range(1, order+1) if maze[x][set[1]]=='X']
# if len(check1) == 9 or len(check2) == 9:
# pass
# else:
# maze[set[0]][set[1]] = 'X'
# blocks.append(set)
else:
pass
else:
pass
b += 1
if __name__ == "__main__":
mazebuilder(maze=maze)
spit()
|
0bbf02898563e1833cc5c969f1233612a4bcc366 | virginiah894/python_codewars | /6KYU/two_sum.py | 790 | 3.703125 | 4 | from typing import List
def two_sum(numbers: List[int], target: int) -> List[int]:
for i in range(len(numbers)) :
for j in range(i + 1, len(numbers)):
if numbers[j] + numbers[i] == target :
return [i, j]
# from typing import List
# from itertools import combinations
# def two_sum(numbers: List[int], target: int) -> List[int]:
# list_of_combinations = list(combinations(numbers, 2))
# for el in list_of_combinations:
# if sum(el) == target:
# first_el, second_el = numbers.index(el[0]), numbers.index(el[1])
# if first_el == second_el:
# return [i for i, x in enumerate(numbers) if x == el[0]]
# else:
# return [numbers.index(el[0]), numbers.index(el[1])]
|
a32a5bca345d85ac6614425d063a98162ab8a16d | Sasha1152/Training | /dictionary/molule_defaultdict.py | 680 | 3.53125 | 4 | from collections import defaultdict
d = defaultdict(int)
print(d["a"]) # 0
print(d["b"]) # 0
print(d) # defaultdict(<class 'int'>, {'a': 0, 'b': 0})
d2 = defaultdict(str)
print(d2["a"]) # ''
print(d2["b"]) # ''
print(d2) # defaultdict(<class 'str'>, {'a': '', 'b': ''})
d3 = defaultdict(bool)
print(d3["a"]) # False
print(d3["b"]) # False
print(d3) # defaultdict(<class 'bool'>, {'a': False, 'b': False})
def default_factory():
return "value by default"
d4 = defaultdict(default_factory)
print(d4["a"]) # value by default
print(d4["b"]) # value by default
d4["c"] = 1
print(d4) # {'a': 'value by default', 'b': 'value by default', 'c': 1}) |
de43f1d785ce343d4c7a292ee71eb5113dd8a912 | scifi6546/glados-terminal | /python/parser.py | 4,518 | 3.734375 | 4 |
from terminal import *
def open_file():
file_string=""
file=open("../text.txt","r",1)
while(0==0):
temp_string=file.read(10)
if(temp_string!=""):
file_string=file_string + temp_string
else:
break
return file_string
class token:
type=""
content=""
def __init__(self,type,content):
self.type=type
self.content=content
def __str__(self):
return "TOKEN type: " + self.type + " content: " + str(self.content)
class string:
string=""
index=0
def __init__(self,input):
self.string = input
self.index=0
def read_char(self):
if(self.index==self.get_len()):
return None
char = self.string[self.index]
self.index=self.index+1
return char
def get_len(self):
return len(self.string)
def peak(self):
return self.string
def put_back(self):
self.index=self.index-1
class parser:
token_arr=[]
def __init__(self):
self.file=string(open_file())
self.parse_file()
def parse_file(self):
while(0==0):
char = self.file.read_char()
if(char is None):
break
if(char=='#'):
self.ignore()
if(char.isalpha()):
self.file.put_back()
self.read()
if(char=='('):
self.file.put_back()
self.parenthesis_open()
if(char==')'):
self.file.put_back()
self.parenthesis_closed()
if(char=='"'):
self.file.put_back()
self.quote()
if(char.isdigit()):
self.file.put_back()
self.num()
if(char==','):
self.file.put_back()
self.comma()
if(char==';'):
self.file.put_back()
self.semicolon()
def ignore(self):
while(0==0):
char = self.file.read_char()
if(char=='\n'):
break
print("ignored")
def read(self):
type="name"
contents=""
temp_char=""
while(0==0):
broke=False#checks if symbol has been found
temp_char=self.file.read_char()
if(temp_char=="("):
self.file.put_back()
broke=True
break
if(temp_char==")"):
self.file.put_back()
broke=True
break
if(temp_char==","):
self.file.put_back()
broke=True
break
if(broke==False):
contents+=temp_char
token_temp = token(type,contents)
self.token_arr.append(token_temp)
print(token_temp)
def quote(self):
self.file.read_char()
contents=""
type="quote"
while(0==0):
temp_char=self.file.read_char()
if(temp_char!='"'):
contents+=temp_char
else:
break
temp_token=token(type,contents)
print(temp_token)
self.token_arr.append(temp_token)
def parenthesis_open(self):
contents="("
type="("
temp_token=token(type,contents)
self.token_arr.append(temp_token)
self.file.read_char()
print(temp_token)
def parenthesis_closed(self):
contents=")"
type=")"
temp_token=token(type,contents)
self.token_arr.append(temp_token)
self.file.read_char()
print(temp_token)
def num(self):
type="number"
contents_temp=""
while(0==0):
temp_char=self.file.read_char()
if(temp_char.isdigit()):
contents_temp+=temp_char
else:
self.file.put_back()
break
contents=int(contents_temp)
temp_token=token(type,contents)
self.token_arr.append(temp_token)
print(temp_token)
def comma(self):
content=","
type=","
temp_token=token(type,content)
self.token_arr.append(temp_token)
print(temp_token)
self.file.read_char()
def semicolon(self):
content=";"
type=";"
temp_token=token(type,content)
self.token_arr.append(temp_token)
print(temp_token)
self.file.read_char()
|
83ed1a4afd57ae1d06449ba83afb2350880b1726 | Kamilla23072001/Lab1 | /5.1.py | 1,674 | 4.5 | 4 | print ("Добрый день!")
m = float (input("Введите ваш вес в кг: "))
h = float (input("Введите ваш рост в м: "))
bmi = float(m / (h*h))
if float(bmi) < 16.5:
print ("Индекс тела равен:", "%.2f" % bmi, "кг/м²,", "у Вас выраженный дефицит массы тела")
elif float(bmi) >= 16.5 and float(bmi) <= 18.49:
print ("Индекс тела равен:", "%.2f" % bmi, "кг/м²,", "у Вас Недостаточный масса тела")
elif float(bmi) >= 18.5 and float(bmi) <= 24.99:
print ("Индекс тела равен:", "%.2f" % bmi, "кг/м²,", "у Вас норма")
elif float(bmi) >= 25 and float(bmi) <= 29.99:
print ("Индекс тела равен:", "%.2f" % bmi, "кг/м²,", "у Вас избыточная масса тела")
elif float(bmi) >= 30 and float(bmi) <= 34.99:
print ("Индекс тела равен:", "%.2f" % bmi, "кг/м²,", "у Вас ожирение первой степени")
elif float(bmi) >= 35 and float(bmi) <= 39.99:
print ("Индекс тела равен:", "%.2f" % bmi, "кг/м²,", "у Ваc ожирение второй степени")
elif float(bmi) >= 40:
print ("Индекс тела равен:", "%.2f" % bmi, "кг/м²,", "у Вас ожирение третьей степени")
""" Эта программа определяет индекс массы тела по введенным значениям массы и роста и выводит результат на экран с округлением в 2 знака после запятой"""
|
2ba4d449674ab92757a42efa5d9525521db4b5d6 | guilhermebaos/Other-Programs | /Modules/my_list/__init__.py | 528 | 3.84375 | 4 | # Manter Ordem Alfabética
def join_list(lst, string=', '):
"""
:param lst: List to be joined
:param string: String that will be used to join the items in the list
:return: List after being converted into a string
"""
lst = str(string).join(str(x) for x in lst)
return lst
def unique_list(lst):
to_eliminate = []
for c, item in enumerate(lst):
if lst.index(item) != c:
to_eliminate += [c]
to_eliminate.sort(reverse=True)
for c in to_eliminate:
lst.pop(c)
return lst
|
a989a227f75186172da66b1f125f75b20e414cbc | KennethRuan/competitive-programming | /DMOJ/ccc15j4.py | 2,561 | 3.59375 | 4 | friend_total =[]
friends=[]
searching = False
location_one = -1
location_two = -1
completed = []
cycle = int(input())
person = -1
total_wait = 0
friend_num = -1
data = []
def calculate_wait(location_one,location_two):
total_wait = 0
subtract = data[location_one:location_two].count("W")
for y in range(0, location_two - location_one):
if data[y + location_one] == "W":
total_wait += data[y + location_one + 1]
elif data[y +location_one] == "R" or data[y +location_one] == "S":
total_wait += 1
return(total_wait - subtract)
for x in range(0,cycle):
data.append(input())
data = (" ".join(data).split(" "))
for i in data:
if i == " ":
data.remove(" ")
for x in range(0,len(data)):
try:
data[x] = int(data[x])
except:
pass
for x in range(0,len(data)):
if data[x] == "R" or data[x] == "S":
friends.append(data[x+1])
friends = list(set(friends))
friends = sorted(friends)
while len(completed) < len(friends):
searching = False
location_two = -1
location_one = -1
person = friends[friend_num]
friend_num += 1
above = "inactive"
for x in range(0,len(data)):
if isinstance(x,int):
if data[x] not in completed and data[x-1] == "R" and searching != True and data[x] == friends[friend_num]:
location_one = x
searching = True
above = "active"
if isinstance(x,int):
if data[x] not in completed and data[x-1] == "R" and searching != True and above != "active":
person == friends[friend_num]
if searching:
if x != location_one and data[x] == friends[friend_num] and location_two == -1 and data[x-1] == "S":
location_two = x
wait_calculate = True
if location_one != -1 and location_two != -1 and wait_calculate == True:
total_wait += calculate_wait(location_one,location_two)
searching = False
location_one = -1
location_two = -1
if total_wait > 0:
wait_calculate = False
if x == (len(data)-1):
if location_two == -1 and location_one != -1:
total_wait = -1
friend_total.append([friends[friend_num],total_wait])
completed.append(friends[friend_num])
total_wait = 0
friend_total = sorted(friend_total, key=lambda x : x[0])
for x in range(len(friend_total)):
print(str(friend_total[x][0]) +" "+ str(friend_total[x][1])) |
0546acaf3a13daf47cbe64b28f481d6b361bf58a | minMaximilian/codeforces | /StringTask.py | 173 | 3.5 | 4 | x = input().lower()
vowels = "aeiouy"
newstr = ([i for i in x if i not in vowels])
j = 0
while j != len(newstr):
newstr.insert(j, ".")
j += 2
print("".join(newstr)) |
0666e5e8021b8db9ab926725da46a056397cbc5e | jacksonludwig/CSE216 | /hw3/package/project/two_d_point.py | 1,620 | 3.921875 | 4 | from typing import List
class TwoDPoint:
def __init__(self, x, y) -> None:
self.__x = x
self.__y = y
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
def __eq__(self, other) -> bool:
# was TODO
if type(self) != type(other):
return False
if self.x != other.x or self.y != other.y:
return False
return True
def __ne__(self, other: object) -> bool:
return not self.__eq__(other)
def __str__(self) -> str:
return "(%g, %g)" % (self.__x, self.__y)
# was TODO: add magic methods such that two TwoDPoint objects can be added and subtracted coordinate-wise just by using
# syntax of the form p + q or p - q
def __add__(self, point):
if type(self) != type(point):
raise TypeError("Cannot add a point to any other type")
x_added = self.x + point.x
y_added = self.y + point.y
return TwoDPoint(x_added, y_added)
def __sub__(self, point):
if type(self) != type(point):
raise TypeError("Cannot subtract a point from any other type")
x_dif = self.x - point.x
y_dif = self.y - point.y
return TwoDPoint(x_dif, y_dif)
@staticmethod
def from_coordinates(coordinates: List[float]):
if len(coordinates) % 2 != 0:
raise Exception("Odd number of floats given to build a list of 2-d points")
points = []
it = iter(coordinates)
for x in it:
points.append(TwoDPoint(x, next(it)))
return points
|
205a94da7f2de8de304262a2930aa72822ee8689 | mkinet/SDCND | /CarND-MiniFlowLab/miniflow.py | 5,647 | 3.953125 | 4 | import numpy as np
class Node(object):
"""Base class that defines a node of a graph."""
def __init__(self, inbound_nodes=[]):
# Nodes from which this node receives values
self.inbound_nodes = inbound_nodes
# Nodes to which this node passes values
self.outbound_nodes = []
# For each node in the inbound node, add the present node as an
# outbound node.
for n in self.inbound_nodes:
n.outbound_nodes.append(self)
# Output value of the node
self.value = None
def forward(self):
"""
Forward propagation method
Compute the output value based on inbound nodes and store the output in
self.value.
This method will depend on the type of node and thus will be
implemented case-by-case in subclasses.
"""
raise NotImplemented(
'Forward method should not be called for the base class Node. This is probably due to a wrong definition of the node.')
class Input(Node):
"""Subclass specifically for input nodes. Performs no calculation and has
no input node."""
def __init__(self):
# An Input node has no inbound nodes,
# so no need to pass anything to the Node instantiator.
Node.__init__(self)
def forward(self, value=None):
# NOTE: Input node is the only node where the value
# may be passed as an argument to forward().
#
# All other node implementations should get the value
# of the previous node from self.inbound_nodes
#
# Example:
# val0 = self.inbound_nodes[0].value
# Overwrite value if one is passed in.
if value is not None:
self.value = value
class Add(Node):
"""Subclass specific for the addition of two values."""
def __init__(self, *inputs):
# there are two inbounds nodes in this case.
Node.__init__(self, inputs)
def forward(self):
# The output value is defined as the sum of the values of the inbound
# nodes
self.value = 0
for n in self.inbound_nodes:
self.value += n.value
def backward(self):
# To be implmented
# TODO : implement backward method for add node.
raise NotImplemented
class Linear(Node):
def __init__(self, inputs, weights, bias):
Node.__init__(self, [inputs, weights, bias])
# NOTE: The weights and bias properties here are not
# numbers, but rather references to other nodes.
# The weight and bias values are stored within the
# respective nodes.
def forward(self):
"""
Set self.value to the value of the linear function output.
Your code goes here!
"""
inputs = self.inbound_nodes[0]
weights = self.inbound_nodes[1]
bias = self.inbound_nodes[2]
self.value = np.dot(inputs.value, weights.value) + bias.value
class Sigmoid(Node):
"""
Method That implements a sigmoid node. Has only one inbound node
and produces the sigmoid of the input value as output.
"""
def __init__(self, node):
Node.__init__(self, [node])
def _sigmoid(self, x):
"""
This method is separate from `forward` because it
will be used later with `backward` as well.
`x`: A numpy array-like object.
Return the result of the sigmoid function.
Your code here!
"""
return 1/(1+np.exp(-x))
def forward(self):
"""
Set the value of this node to the result of the
sigmoid function, `_sigmoid`.
"""
self.value = self._sigmoid(self.inbound_nodes[0].value)
class Relu(Node):
"""
Method That implements a relu node. Has only one inbound node
and produces max(0,input) as output.
"""
def __init__(self, node):
Node.__init__(self, [node])
def forward(self):
"""
Set the value of this node to the input if it is positive, to 0 other
wise.
"""
self.value = np.max(0,self.inbound_nodes[0].value)
def topological_sort(feed_dict):
"""
Sort generic nodes in topological order using Kahn's Algorithm.
`feed_dict`: A dictionary where the key is a `Input` node and the value is the respective value feed to that node.
Returns a list of sorted nodes.
"""
input_nodes = [n for n in feed_dict.keys()]
G = {}
nodes = [n for n in input_nodes]
while len(nodes) > 0:
n = nodes.pop(0)
if n not in G:
G[n] = {'in': set(), 'out': set()}
for m in n.outbound_nodes:
if m not in G:
G[m] = {'in': set(), 'out': set()}
G[n]['out'].add(m)
G[m]['in'].add(n)
nodes.append(m)
L = []
S = set(input_nodes)
while len(S) > 0:
n = S.pop()
if isinstance(n, Input):
n.value = feed_dict[n]
L.append(n)
for m in n.outbound_nodes:
G[n]['out'].remove(m)
G[m]['in'].remove(n)
# if no other incoming edges add to S
if len(G[m]['in']) == 0:
S.add(m)
return L
def forward_pass(output_node, sorted_nodes):
"""
Performs a forward pass through a list of sorted nodes.
Arguments:
`output_node`: A node in the graph, should be the output node (have no outgoing edges).
`sorted_nodes`: A topologically sorted list of nodes.
Returns the output Node's value
"""
for n in sorted_nodes:
n.forward()
return output_node.value
|
b148fcbbff18e4eccc108c56cf893a66a0a7260f | SulJis/nix_trainee_course | /task4.py | 156 | 3.8125 | 4 | list1 = ["Oleg", "Vasya", "Anna"]
list2 = ["Ivanov", "Sidorov", "Petrova"]
full_names = list(zip(list1, list2))
for person in full_names:
print(person)
|
aeda1b9c651de34522d6dd792cbc7d3e76550387 | daniel-reich/turbo-robot | /oF8T7Apf7jfagC4fD_7.py | 1,714 | 4.3125 | 4 | """
In this challenge, you are given a list and in turn, you must obtain a smaller
list, following three steps:
* Split the list into **two parts of equal length**. If the given list has an odd length, then you have to eliminate the number in the middle of the list for obtaining two equal parts.
* Sum each number of the first part with each number of the **reversed second part** , obtaining a new single list having the same length of the previous two.
* **Divide by two** each number in the final list.
Given a list of integers `lst`, implement a function that returns a new list
applying the above algorithm.
### Examples
antipodes_average([1, 2, 3, 4]) ➞ [2.5, 2.5]
# Left part = [1, 2]
# Reversed right part = [4, 3]
# List resulting from the sum of each pair = [5, 5]
# Each number is divided by two = [2.5, 2.5]
antipodes_average([1, 2, 3, 4, 5]) ➞ [3, 3]
# The length of list is odd, number 3 (in the middle) is eliminated
# Left = [1, 2]
# Reversed right = [5, 4]
# Sum = [6, 6]
# Division by two = [3, 3]
antipodes_average([-1, -2]) ➞ [-1.5]
# (-1 + -2) / 2 = [-1.5]
### Notes
* Every given `lst` will contain at least two numbers.
* Into the given `lst`, numbers will always be whole (either positives or negatives), but the numbers into the returned final list can also be a float (either positives or negatives, see the examples #1 and #3).
* You can do three separated steps, or thinking about how the algorithm can be synthesized for obtaining the result.
"""
def antipodes_average(lst):
l1 = lst[:len(lst) // 2]
l2 = lst[-(len(lst) // 2):][::-1]
return [(i1 + i2) / 2 for i1, i2 in zip(l1, l2)]
|
7d8cd074723a2673ea1f257dc3e0fce87d3edb4d | jcliese/pdsnd_github | /bikehsare.py | 9,088 | 4.375 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
options = ('chicago', 'new york city', 'washington')
while True:
try:
city = input('Please enter the city you want to analyze. Possible options are Chicago, New York City and Washington: ').lower()
if city in options:
break
else:
raise ValueError
except ValueError:
print("That was no valid city. Try again...")
continue
# TO DO: get user input for month (all, january, february, ... , june)
yesno = ('yes', 'no')
while True:
try:
filter_month = input('Do you want to filter the Month? Type: Yes or No: ').lower()
if filter_month in yesno:
break
else:
raise ValueError
except ValueError:
print("That was no valid input. Try again...")
continue
month_options = ('jan', 'feb', 'mar', 'apr', 'may', 'jun')
if filter_month == 'yes':
while True:
try:
month = input('For which month do you want to filter. Please type the first 3 letters of the month (e.g. mar): ').lower()
if month in month_options:
break
else:
raise ValueError
except ValueError:
print("That was no valid month. Try again...")
continue
else:
month = 'all'
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
while True:
try:
filter_day = input('Do you want to filter the Day? Type: Yes or No: ').lower()
if filter_day in yesno:
break
else:
raise ValueError
except ValueError:
print("That was no valid input. Try again...")
continue
day_options = ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
if filter_day == 'yes':
while True:
try:
day = input('For which weekday do you want to filter. Please type the first three letters of the weekday (e.g. wed): ').lower()
if day in day_options:
break
else:
raise ValueError
except ValueError:
print("That was no valid weekday. Try again...")
continue
else:
day = 'all'
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
df['month'] = pd.to_datetime(df['Start Time']).dt.month
if month != 'all':
m = {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6}
month = m[month]
df = df[df['month'] == month]
df['day_of_week'] = pd.to_datetime(df['Start Time']).dt.weekday
if day != 'all':
d = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, 'sun': 6}
day = d[day]
df = df[df['day_of_week'] == day]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
df['month'] = pd.to_datetime(df['Start Time']).dt.month
m={1: 'January', 2: 'February', 3: 'March', 4: 'April', 5:'May', 6:'June'}
month = m[df['month'].mode()[0]]
print('The most common month is {}.'.format(month))
# TO DO: display the most common day of week
df['day_of_week'] = pd.to_datetime(df['Start Time']).dt.weekday
d={0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5:'Saturday', 6:'Sunday'}
day = d[df['day_of_week'].mode()[0]]
print('The most common weekday is {}.'.format(day))
# TO DO: display the most common start hour
df['hour'] = pd.to_datetime(df['Start Time']).dt.hour
hour = df['hour'].mode()[0]
print('The most common hour is {} o\'clock.'.format(hour))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
start_station = df['Start Station'].mode()[0]
print('The most commonly used start station is: {}'.format(start_station))
# TO DO: display most commonly used end station
end_station = df['End Station'].mode()[0]
print('The most commonly used end station is: {}'.format(end_station))
# TO DO: display most frequent combination of start station and end station trip
combination = df.groupby(['Start Station','End Station']).size().idxmax()
print('The most frequent combination is between start station "{}" and end station "{}".'.format(combination[0], combination[-1]))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
total_travel_time = df['Trip Duration'].sum()
print('The total travel time in minutes is {},\nin hours it is {},\nin days it would be {}\nand in years it would be {}.'.format(total_travel_time/60, total_travel_time/360, total_travel_time/8640, total_travel_time/3153600))
# TO DO: display mean travel time
avg_travel_time = df['Trip Duration'].mean()
print('\nThe average travel time in minutes is {}'.format(avg_travel_time/60))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
user_types = df.groupby('User Type')['Start Time'].nunique()
print(user_types.to_string(),'\n')
# TO DO: Display counts of gender
gender = df.groupby('Gender')['Start Time'].nunique()
print(gender.to_string(),'\n')
# TO DO: Display earliest, most recent, and most common year of birth
earliest_by = df['Birth Year'].min()
print('The earliest birth year is {}.'.format(int(earliest_by)))
recent_by = df['Birth Year'].max()
print('The most recent birth year is {}.'.format(int(recent_by)))
most_common_by = df['Birth Year'].mode()[0]
print('The most common birth year is {}.'.format(int(most_common_by)))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def print_raw(df):
while True:
try:
print_init = input('Do you want to print a sample? Yes or No: ').lower()
if print_init in ('yes', 'y'):
i = 0
while True:
print(df.iloc[i:i+5])
i += 5
more_data = input('Would you like to see more data? Please enter Yes or No: ').lower()
if more_data not in ('yes', 'y'):
break
break
elif print_init in ('no', 'n'):
break
else:
raise ValueError
except ValueError:
print("That was no valid input. Try again...")
continue
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
if city != 'washington':
user_stats(df)
print_raw(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
#Test whether the program should start again
if restart.lower() != 'yes':
break
if __name__ == "__main__":
#This part of code runes first
main()
|
761b864c75c8907abae9b68d43c3a046b59567e0 | chaovite/jupiter_notebook_tutorial | /mymodule.py | 265 | 3.859375 | 4 | """
This is a simple module where you can write your subroutines or classes
"""
def reverseList(a):
""" reverse a python list
"""
return a[::-1]
def addTwoNums(a, b = 0):
""" add two numbers and set default of b to be zero
"""
return a + b |
46abb60f70a62f14a883b10a94978db8aafcfddb | py-bootcamp/learn-python-with-tdd | /hello-world/v8/hello.py | 474 | 4 | 4 | ENGLISH_HELLO_PREFIX = "Hello"
LANGUAGES = {
"Spanish": "Hola",
"French": "Bonjour",
}
def prefix(language: str) -> str:
return LANGUAGES.get(language, ENGLISH_HELLO_PREFIX)
def hello(name: str = None, language: str = None) -> str:
"""Return a personalized greeting.
Defaulting to `Hello, World` if no name and language are passed.
"""
if not name:
name = "World"
return f"{prefix(language)}, {name}"
print(hello("world", ""))
|
56c13339c61129ace91d141309c5ec59c4dddce7 | yuki-Melody/Disparate-Codes | /read_from_inside.py | 747 | 3.765625 | 4 | class Read:
def __init__(self, test = True, s=None):
self.test = test
self.s = s
self.i = 0
if(s != None and test == True):
line = s.split('\n')
line = list(filter(lambda x:len(x)>0, line))
self.line = line
def read(self):
if(self.test == False):
return input() #从键盘输入
i = self.i
line = self.line
if i == len(line):
print('Warn: relocate i')
self.i = 0
return self.read()
self.i = i + 1
return line[i]
read = Read(True, """
3
1 2 2
2 3 1
""").read #delegate,将对象的方法委托给read
# read = input
# use read instead of input |
69188c20d261cdcb23bdf2fb3d9dc1d1a4be5004 | odiah/ktcng-py-assignments | /py.py | 605 | 4.25 | 4 | print("We're about to find the average of just three numbers")
print("This is my first official python code in up to three years, by the way")
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
avg = (num1+num2+num3)/3
print("The average of the three numbers is: ", avg)
numlist = [num3,num1,num2]
hold_large_num = 0
for num in numlist:
if(num>hold_large_num):
hold_large_num = num
print("\n BTW, the highest of the numbers you typed in is: ", hold_large_num)
#pardon my lack of use of comoments, really
|
6a178d88c2962d90e10a5635d2afebeadf85f592 | jimmy-kyalo/python_tutorials | /printing_models.py | 1,006 | 4.15625 | 4 | #modifying a list in a function
"""
unprinted_designs = ['case', 'pendant', 'sphere']
completed_models = []
while unprinted_designs:
current_design = unprinted_designs.pop()
print("\nPrinting model: " + current_design)
completed_models.append(current_design)
print("\nThe printed models are: ")
for completed_model in sorted(completed_models):
print(completed_model.title())
"""
#------------------------------------------------
# ALTERNATIVE
def print_models(unprinted_designs, completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print("\nPrinting model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
print("\nThe printed models are: ")
for completed_model in sorted(completed_models):
print(completed_model.title())
unprinted_designs = ['case', 'pendant', 'sphere']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
|
c554e0843d18a71eb594ad6f686178afcad2de79 | silvafj/BBK-MSCCS-2017-19 | /POP1/assignment-one/LunarLander.py | 5,322 | 4.53125 | 5 | """
Author: Fernando Silva <fdealm02>
Lunar Lander is a game that simulates the landing of a spacecraft on the moon.
"""
class Lander:
"""
A lunar lander is a kind of spacecraft designed for moon landing.
This class simulates the lander physical properties and behaviours, which
will be updated based on external inputs.
"""
MOON_GRAVITATIONAL_ACCELERATION = 1.6 # metres/second
# That is, velocity decreases by **some constant** times the amount of fuel.
# A constant of 0.15 makes the game fairly easy to win.
VELOCITY_FUEL_RATE = 0.15
def __init__(self):
self.altitude = 1000.0 # Altitude above the moon (metres)
self.velocity = 0.0 # Velocity toward the moon (metres/second)
self.fuel = 1000.0 # Fuel remaining (litres)
def burn_fuel(self, fuel):
"""
Burn an amount of fuel and calculate the lander new position.
:param float fuel: Amount of fuel to be burned
:return: None
"""
# Adjust the fuel to burn: (1) can't burn a negative amount of fuel,
# (2) neither can burn more fuel than what currently exists.
if fuel < 0:
fuel = 0.0
elif fuel > self.fuel:
fuel = self.fuel
# Velocity increases by 1.6 m/s due to the acceleration of gravity and
self.velocity += self.MOON_GRAVITATIONAL_ACCELERATION
# decreases by an amount proportional to the amount of fuel just burned
self.velocity -= fuel * self.VELOCITY_FUEL_RATE
# Altitude decreases by the velocity, adjustable as it can't be negative
self.altitude -= self.velocity
if self.altitude < 0:
self.altitude = 0
# Fuel decreases by the amount that was burn
self.fuel -= fuel
def has_landed(self):
""" Lander has landed if the altitude is less than or equal to 0. """
# NOTE: Checking for altitude less than or equal to 0 is to comply with
# the project specifications. In practice, the way the position is being
# calculated doesn't allow the altitude to be less 0.
return self.altitude <= 0
def has_landed_safely(self):
""" Safe landing happens if the velocity is under 10 meters/second. """
return self.has_landed() and self.velocity <= 10
def query_fuel_burn():
"""
Specialized input for how much fuel to burn.
:return: Amount of fuel to burn
:rtype: float
"""
while True:
to_burn = input("How much fuel you want to burn? ")
try:
# Avoid that the game crashes due to bad input
return float(to_burn)
except Exception:
pass
def confirm_new_game():
"""
Specialized input to ask confirmation about starting a new game.
:return: The user confirmation
:rtype: bool
"""
print("") # Empty line for aesthetical purposes
acceptable = set(["Y", "YES", "N", "NO"])
choice = ""
while choice not in acceptable:
choice = input("Do you want to play again (y/n)? ").upper()
return choice[0] == "Y"
def land_the_lander():
"""Deploy a new lander for the player to land."""
print("") # Empty line for aesthetical purposes
# Create a new lander instance. It will keep track of the current physical
# state and allows us to interact with it.
lander = Lander()
while not lander.has_landed():
print_lander_status(lander)
lander.burn_fuel(query_fuel_burn())
print_lander_status(lander)
if lander.has_landed_safely():
print("Congratulations! You have safely landed :)")
else:
print("Bummer! You have crashed into the moon!")
def print_lander_status(lander):
"""Update the screen with the current lander information."""
print("Altitude: {:.1f}m | Velocity: {:.1f}m/s | Fuel: {:.1f}l".format(
lander.altitude, lander.velocity, lander.fuel,
))
def welcome():
""" Prints the welcome screen and game instructions. """
# Lunar Lander ASCII art generated from
# http://patorjk.com/software/taag/#p=display&f=Big&t=Lunar%20Lander
print("""
_ _ _
| | | | | |
| | _ _ _ __ __ _ _ __ | | __ _ _ __ __| | ___ _ __
| | | | | | '_ \ / _` | '__| | | / _` | '_ \ / _` |/ _ \ '__|
| |___| |_| | | | | (_| | | | |___| (_| | | | | (_| | __/ |
|______\__,_|_| |_|\__,_|_| |______\__,_|_| |_|\__,_|\___|_|
by Fernando Silva <fdealm02>
You are in a lunar module, some distance above the Moon's surface.
Gravity is pulling you toward the Moon at an ever-increasing rate
of speed.
You have a limited amount of fuel to use, and each time you burn
fuel, you reduce your speed by a certain amount. If you burn the
right amount of fuel at the right time, you can land safely.
""")
# This is required so we can import this module from other scripts without
# running the game immediately (e.g, unit testing)
if __name__ == '__main__':
welcome()
keep_playing = True
while keep_playing:
land_the_lander()
keep_playing = confirm_new_game()
print("\nBye! Thank you for playing.")
|
e80478d9f38b38d978eaa37c13892ee7bf0baf37 | AaronJny/leetcode | /151-200/160.py | 1,049 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @File : do3.py
# @Author: AaronJny
# @Date : 2019/06/13
# @Desc :
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def list_len(self, head):
p = head
cnt = 0
while p:
cnt += 1
p = p.next
return cnt
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
m = self.list_len(headA)
n = self.list_len(headB)
p1 = headA
p2 = headB
if m > n:
x = m - n
while x:
p1 = p1.next
x -= 1
else:
x = n - m
while x:
p2 = p2.next
x -= 1
x = min(m, n)
while x:
if p1 is p2:
return p1
x -= 1
p1 = p1.next
p2 = p2.next
return None
|
6fdaff4c528b1915c5f4b8838b1a5fa534e4155b | ataleksandrov/Substitution-Cipher-Cracker | /n_gram.py | 501 | 3.796875 | 4 | def __n_grams(word):
N = 3 #setting N to 3
return [word[i:i+N] for i in range(0, len(word)-N+1)]
def get_n_grams(text):
res = {}
for word in text.split():
for n_gram in __n_grams(word):
res[n_gram] = text.count(n_gram)
return res
def get_n_grams_in_file(file, n_grams_dict):
res = {}
with open(file) as f:
for line in f:
for n_gram in __n_grams(line):
res[n_gram] = res.get(n_gram, 0) + 1
return res |
ac658b4c30e5baea00bf685b89b689d89ac1e86b | joaoo-vittor/estudo-python | /OrientacaoObjeto/exercicio_poo/main.py | 1,760 | 4.34375 | 4 | """
Exercício com Abstração, Herança, Encapsulamento e Polimorfismo
Criar um sistema bancário (extremamente simples) que tem clientes, contas e
um banco. A ideia é que o cliente tenha uma conta (poupança ou corrente) e que
possa sacar/depositar nessa conta. Contas corrente tem um limite extra. Banco
tem clientes e contas.
Dicas:
Criar classe Cliente que herda da classe Pessoa (Herança)
Pessoa tem nome e idade (com getters)
Cliente TEM conta (Agregação da classe ContaCorrente ou ContaPoupanca)
Criar classes ContaPoupanca e ContaCorrente que herdam de Conta
ContaCorrente deve ter um limite extra
Contas têm agência, número da conta e saldo
Contas devem ter método para depósito
Conta (super classe) deve ter o método sacar abstrato (Abstração e
polimorfismo - as subclasses que implementam o método sacar)
Criar classe Banco para AGREGAR classes de clientes e de contas (Agregação)
Banco será responsável autenticar o cliente e as contas da seguinte maneira:
Banco tem contas e clentes (Agregação)
* Checar se a agência é daquele banco
* Checar se o cliente é daquele banco
* Checar se a conta é daquele banco
Só será possível sacar se passar na autenticação do banco (descrita acima)
"""
from conta import ContaPoupanca, ContaCorrente
from cliente import Cliente
from banco import Banco
banco = Banco()
cliente1 = Cliente('joao', 22)
cliente2 = Cliente('vitor', 26)
conta1 = ContaPoupanca(1111, 2222, 0)
conta2 = ContaCorrente(2222, 3333, 0)
cliente1.inserir_cliente(conta1)
cliente2.inserir_cliente(conta2)
print(cliente1.getNome)
cliente1.conta.detalhes()
print(cliente2.getNome)
cliente2.conta.detalhes()
banco.inserir_cliente(cliente1)
banco.inserir_conta(conta1)
|
4b5188edabe61d79ee147586425cec13b220a2c7 | EgorKurito/UniverPractice | /vectorGUI.py | 5,257 | 3.515625 | 4 | from tkinter import *
import math
class Vec2D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def add(self, other):
return Vec2D(self.x + other.x, self.y + other.y, self.z + other.z)
def sub(self, other):
return Vec2D(self.x - other.x, self.y - other.y, self.z - other.z)
def mul(self, other):
return self.x*other.x + self.y*other.y + self.z*other.z
def scMul(self, scalar):
return Vec2D(scalar*self.x, scalar*self.y, scalar*self.z)
def abs(self):
return math.sqrt(self.x**2 + self.y**2 + self.z**2)
def __str__(self):
return '(%g, %g, %g)' % (self.x, self.y, self.z)
def vecMul(self, other):
return Vec2D(self.y*other.z - self.z*other.y, -1*(self.x*other.z - self.z*other.x), self.x*other.y - self.y*other.x)
class Vector(Frame):
def __init__(self, master):
super().__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self, text = 'a: ').grid(row=1, column=0, sticky=E)
Label(self, text = 'X: ').grid(row=1, column=1, sticky=W)
Label(self, text = 'Y: ').grid(row=1, column=3, sticky=W)
Label(self, text = 'Z: ').grid(row=1, column=5, sticky=W)
Label(self, text = 'b: ').grid(row=2, column=0, sticky=E)
Label(self, text = 'X: ').grid(row=2, column=1, sticky=W)
Label(self, text = 'Y: ').grid(row=2, column=3, sticky=W)
Label(self, text = 'Z: ').grid(row=2, column=5, sticky=W)
Label(self, text = 'c: ').grid(row=3, column=0, sticky=E)
Label(self, text = 'X: ').grid(row=3, column=1, sticky=W)
Label(self, text = 'Y: ').grid(row=3, column=3, sticky=W)
Label(self, text = 'Z: ').grid(row=3, column=5, sticky=W)
Label(self, text = 'd: ').grid(row=4, column=0, sticky=E)
Label(self, text = 'X: ').grid(row=4, column=1, sticky=W)
Label(self, text = 'Y: ').grid(row=4, column=3, sticky=W)
Label(self, text = 'Z: ').grid(row=4, column=5, sticky=W)
self.a_x = Entry(self, width=3)
self.a_y = Entry(self, width=3)
self.a_z = Entry(self, width=3)
self.b_x = Entry(self, width=3)
self.b_y = Entry(self, width=3)
self.b_z = Entry(self, width=3)
self.c_x = Entry(self, width=3)
self.c_y = Entry(self, width=3)
self.c_z = Entry(self, width=3)
self.d_x = Entry(self, width=3)
self.d_y = Entry(self, width=3)
self.d_z = Entry(self, width=3)
self.a_x.grid(row=1, column=2, sticky=W)
self.a_y.grid(row=1, column=4, sticky=W)
self.a_z.grid(row=1, column=6, sticky=W)
self.b_x.grid(row=2, column=2, sticky=W)
self.b_y.grid(row=2, column=4, sticky=W)
self.b_z.grid(row=2, column=6, sticky=W)
self.c_x.grid(row=3, column=2, sticky=W)
self.c_y.grid(row=3, column=4, sticky=W)
self.c_z.grid(row=3, column=6, sticky=W)
self.d_x.grid(row=4, column=2, sticky=W)
self.d_y.grid(row=4, column=4, sticky=W)
self.d_z.grid(row=4, column=6, sticky=W)
Button(self, text="Add", command=self.create, width=13).grid(row=5, column=0, pady=10, padx=10)
Button(self, text="(d,c)/(b,c)*[b,d]", command=self.multi, width=13).grid(row=6, column=0, pady=10, padx=10)
#Button(self, text='Distanse from p1 to p2',command=self.distance12, width = 16).grid(row=6, column=0, pady=10, padx=10)
#Button(self, text='Distanse from p1 to p3',command=self.distance13, width = 16).grid(row=7, column=0, pady=10, padx=10)
#Button(self, text='Distanse from p2 to p3',command=self.distance23, width = 16).grid(row=8, column=0, pady=10, padx=10)
self.answer=Text(self, width=20, height=5, wrap=WORD)
self.answer.grid(row=5, column=7, pady=10, padx=10, sticky=E)
def create(self):
try:
self.a = Vec2D(int(self.a_x.get()),int(self.a_y.get()),int(self.a_z.get()))
self.b = Vec2D(int(self.b_x.get()),int(self.b_y.get()),int(self.b_z.get()))
self.c = Vec2D(int(self.c_x.get()),int(self.c_y.get()),int(self.c_z.get()))
self.d = Vec2D(int(self.d_x.get()),int(self.d_y.get()),int(self.d_z.get()))
self.answ = 'Three Vector Added: ' + '\n' + str(self.a) + '\n' + str(self.b) + '\n' + str(self.c) + '\n' + str(self.d)
except ValueError:
self.answ = 'All three Point need added!'
self.calculate()
def multi(self):
'''(d,c)/(b,c)*[b,d]'''
t = self.b.vecMul(self.d)
solve = t.scMul(self.d.mul(self.c)/self.b.mul(self.c))
self.answ = solve
self.calculate()
def calculate(self):
self.answer.delete(0.0,END)
self.answer.insert(0.0,self.answ)
self.a_x.delete(0)
self.a_y.delete(0)
self.a_z.delete(0)
self.b_x.delete(0)
self.b_y.delete(0)
self.b_z.delete(0)
self.c_x.delete(0)
self.c_y.delete(0)
self.c_z.delete(0)
self.d_x.delete(0)
self.d_y.delete(0)
self.d_z.delete(0)
root=Tk()
root.title("Vector")
root.geometry('700x500')
calc=Vector(root)
root.mainloop()
|
20eeb53fe53b058c85d5fca151e0eb32be0588d5 | bgarrido7/AdventOfCode-2017 | /lvl1/01.py | 256 | 3.609375 | 4 | s = input()
sum=0
res = [int(x) for x in str(s)] #place the input number into an array
if res[-1]==res[0]:
sum=res[0]
for i in range(len(res)):
if i+1 < len(res):
if res[i]==res[i+1] :
sum+=res[i]
print("sum = ",sum)
|
7cc0ee3f5f318961ace74c111edc90d4227a5023 | babichevko/proga_babichev_2021 | /звёзды.py | 220 | 3.578125 | 4 | import turtle as t
t.speed(5)
def z(n):
b=(n-2)*180/n
a=180-b/3
for i in range(n):
t.forward(100)
t.left(a)
z(5)
t.penup()
t.backward(150)
t.pendown()
z(11)
|
bfaabc667cf5ef7306f437bf58266593a83cbd98 | doomnonius/codeclass | /daily-probs/powerSet.py | 215 | 3.84375 | 4 | def powerSet(arr):
L = [[]]
while len(arr) >= 0:
if arr == []:
return L
for x in range(len(L)):
L.append(L[x] + [arr[0]])
arr = arr[1:]
print(powerSet([1,2])) |
0e50692893af68701ff8750d7bb8a47316c17f51 | murphsp1/ProjectEuler_Python | /p4.py | 690 | 3.71875 | 4 |
import sys
def check_number_symmetry(n):
#assume int
n_str = str(n)
len_str = len(n_str)
str_rev = n_str[::-1]
if (len_str%2)==0: #even
mid = len_str/2+1
if n_str[0:mid]==str_rev[0:mid]:
return True
else:
mid = len_str/2
if n_str[0:mid]==str_rev[0:mid]:
return True
def main():
palindromes = []
for x in xrange(1,1000):
for y in xrange(1,1000):
prod = x*y
if check_number_symmetry(prod):
palindromes.append(prod)
print(palindromes)
print(max(palindromes))
if __name__ == '__main__':
#call function that we need
sys.exit(main())
|
b0e960ee75a69e7ecd04fe11e39b070e09a207b3 | Bit64L/LeetCode-Python- | /Lowest_Common_Ancestor_of_a_Binary_Search_Tree_235.py | 1,164 | 3.640625 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root:
return None
pPath = self.getPath(root, p)
qPath = self.getPath(root, q)
i = 0
while i < (min(len(pPath), len(qPath))) and pPath[i] == qPath[i]:
i = i + 1
return qPath[i - 1]
def getPath(self, root, node):
path = []
if root == node:
return [root]
while True:
path.append(root)
if node.val < root.val:
root = root.left
elif node.val > root.val:
root = root.right
elif node.val == root.val:
path.append(node)
break
return path
n1 = TreeNode(2)
n2 = TreeNode(1)
n3 = TreeNode(3)
n1.left = n2
n1.right = n3
solution = Solution()
lca = solution.lowestCommonAncestor(n1, n2, n2)
print(lca.val)
|
b6cb96b2b238398d1ba96ee7070627ff81d6d06e | ekjellman/interview_practice | /ctci/16_4.py | 1,502 | 3.90625 | 4 | ###
# Problem
###
# Design an algorithm to figure out if someone has won a game of tictactoe
###
# Work
###
# Questions:
# Format of the board? (Assume whatever you want)
# Do we want this to be extensible? (Assume no is fine)
# What do we mean by "won"? (Assume the current position is terminal, not
# that someone could win with best play or anything like that)
# Otherwise test for board validity? (For example, both X and O winning,
# or other invalid game states? Assume no.)
def game_won(board):
# Board is a 9 char string with X, O, or .
assert len(board) == 9
for win in ((0, 3, 6), (1, 4, 7), (2, 5, 8), # Columns
(0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
(0, 4, 8), (2, 4, 6)): # Diagonals
a, b, c = win
if (board[a] == board[b] and board[a] == board[c] and
(board[a] == "X" or board[a] == "O")):
return True
return False
print "True", game_won("XXX......")
print "True", game_won("...OOO...")
print "True", game_won("......XXX")
print "True", game_won("X..X..X..")
print "True", game_won(".X..X..X.")
print "True", game_won("..X..X..X")
print "True", game_won("O...O...O")
print "True", game_won("..O.O.O..")
print "False", game_won(".........")
print "False", game_won("OXOOXOXOX")
# Time: 9 minutes
###
# Mistakes / Bugs / Misses
###
# Got my full board test wrong
# Didn't think about caching solution
# Didn't ask what to return, just returned True or False instead of winner,
# which is probably more useful
|
a4425245074d9329a2e54fab1dd9b990a3fc6f63 | athomsen115/basic-python-scripts | /variables.py | 218 | 3.890625 | 4 | #!/usr/bin/env python3.8
first_name = "Alexa"
last_name = "Thomsen"
age = 27
birth_date = "March 3, 1992"
print(f"My name is {first_name} {last_name}")
print(f"I was born on {birth_date}, and I am {age} years old")
|
0f497da49460d95c368752b0bb942ead64bf10c4 | stelukutla/LING516 | /ExampleCodesFromClass/Week5/MultiFunctionProgram.py | 1,057 | 3.796875 | 4 | import random,math
def OddEven(n):
if n%2 == 0:
return "Even"
else:
return "Odd"
"""
Log10 of 0 is undefined. Should I be worried?
"""
def LogNum(n):
return math.log10(n)
def RandNum(n):
return random.randint(0,n)
def main():
try:
number = int(input("Enter a positive whole number: "))
if number <= 0:
print("Enter a positive whole number!")
else:
print("The number is: ", OddEven(number))
print("Log of the number is: ", str(LogNum(number)))
print("Random number between 0 and this number is: ", str(RandNum(number)))
except:
print("Something went wrong, and I don't care about giving explicit information!")
if __name__ == "__main__":
main()
"""
Ideally, if you intend to use these functions beyond this program, by importing this into other programs,
you should have these try except blocks in all functions, not just the main function.
or, you should put those checks before the functions are called in other programs
"""
|
62612ddf44677d754be0e6155fbbe64c85160a65 | cami-la/python_curso_em_video | /Mundo03:estruturas-compostas/exercicio-python#082-dividindo-valores-em-varias-listas.py | 1,211 | 4.21875 | 4 | from termcolor import cprint
'''
Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas.
'''
def play():
exercise()
numbers = []
while(True):
number = int(input("Type a number: "))
numbers.append(number)
to_continue = " "
while(to_continue not in "YN"):
to_continue = str(input("Do you want to continue? ")).upper().strip()
if (to_continue == "N"):
break
even_numbers = []
odd_numbers = []
for i in range(len(numbers)):
if (numbers[i] % 2 == 0):
even_numbers.append(numbers[i])
else:
odd_numbers.append(numbers[i])
print("-="*30)
print(f"numbers = {numbers}")
print(f"even_numbers = {even_numbers}")
print(f"odd_numbers = {odd_numbers}")
def exercise():
cprint("Create a program that will reads several numbers and put on a list. After this, create two extra list that will contain only even values and the odd values entered, respective. At the end, show the content of the three generate list.\n","green", attrs=["blink"])
|
9d1618d694403efd82b13bb9b553181f17fecd69 | MaddozS/converter | /check_number.py | 243 | 3.875 | 4 | # Esta funcion verifica que cada digito
# de nuestro numero se encuentre dentro
# de la base a converitr
def checkNumber(number, dictionary):
for digit in number:
if digit not in dictionary:
return False
return True |
0157db75da615b41010c5ea3d973c2bbb3670f71 | GustavoBragaa/PythonProject | /Python/M3-Funcao.py | 7,205 | 4.3125 | 4 | '''Para criar uma função é necessario por 'def' antes'''
# def nome(str):
# print('-' * 10)
# print(f"{str:^10}")
# print('-'*10)
# name = input(str('Insira o que vc quiser: ')).upper()
# nome(name)
# ----------------------------------------------------------
# def nome(str):
# print('-' * 10)
# print(f"{str:^10}")
# print('-' * 10)
# nome('QUALQUER COISA')
# ----------------------------------------------------------
'''Empacotar parametros'''
# def contador(*num):
# print(len(num))
# contador(1, 2, 3)
# contador(5, 8, 6, 7)
# ----------------------------------------------------------
"""print('-' * 20)
print('CALCULO DE ÁREA')
print('-' * 20)
def area(t, l):
area = t * l
print('-' * 20)
print(f'Você inseriu o tamanho {t} e largura {l}, O calculo da area é {area}m²')
tamanho = float(input('Insira o tamanho: '))
largura = float(input('Insira a largura: '))
area(tamanho, largura)"""
# ----------------------------------------------------------
"""def nome(str):
tmn = len(str) + 4
print('-' * tmn)
print(f' {str}')
print('-' * tmn)
name = input(str('Insira o que vc quiser: ')).upper()
nome(name)"""
# ----------------------------------------------------------
'''import time
def contador(i, f, p):
for c in range(i, f + 1, p):
print(c, end=' ')
time.sleep(0.5)
for c in range(1, 11):
print(c, end=' ')
time.sleep(0.5)
print()
for c in range(10, 0, -2):
print(c, end=' ')
time.sleep(0.5)
print()
i = int(input('Insira o incio: '))
f = int(input('Insira o fim: '))
p = int(input('Insira o passo: '))
contador(i, f, p)'''
# ----------------------------------------------------------
'''import time
from random import randint
cont = 0
lst = list()
vzs = randint(1, 10)
for n in range(1, vzs+1):
qtd = randint(1, 10)
if qtd not in lst:
lst.append(qtd)
lst.sort()
for i in range(1, len(lst)+1):
print(lst[cont], end=' ')
time.sleep(0.3)
cont += 1
print(f'Foram informados {len(lst)} valores')
print(f'o Maior valor informado foi {max(lst)}')'''
# ----------------------------------------------------------
'''from random import randint
def sorteio(lts):
qtd = 6
for n in range(1, 6):
sorteio = randint(1, 10)
lts.append(sorteio)
print(f'sorteando 5 valores da lista: {lts}')
def somaPar():
soma = 0
for x in lista:
if x % 2 == 0:
soma += x
lista.sort()
print(f'Somando os valores pares de {lista}, temos {soma}')
lista = list()
sorteio(lista)
somaPar()'''
# ----------------------------------------------------------
'''Aula 2'''
'''Ajuda Interativa'''
# help()
# print(input.__doc__)
'''DOCSTRINGS'''
'''Documentando sua função particular '''
'''Para documentar sua função, é ne abrir 3 aspas duplas abaixo
do inicio da função 'def', apertar enter e descrever oque seu codigo faz'''
# ----------------------------------------------------------
'''PARAMETROS OPCIONAIS'''
'''Informar na declaração do codigo o valor de 0 para a variavel
ela serviara como contingencia caso o usuario não informe valor'''
# def somar(a=0, b=0, c=0):
# s = a + b + c
# print(f'{s}')
# somar(1, 2, 3)
# somar(1, 2)
# ----------------------------------------------------------
'''ESCOPO DE VARIAVEIS'''
# Para usar uma variavel global dentro de funções, supondo que a variavel fora da funcao seja 'a'
# def funcao():
# global a
# ----------------------------------------------------------
'''RETORNO DE VARIAVEIS'''
# def somar(a=0, b=0, c=0):
# s = a + b + c
# return s
# resp = somar(1, 2, 3)
# print(somar(1, 2, 3))
# ----------------------------------------------------------
'''def fatorial(num=1):
f = 1
for c in range(num, 0, -1):
f *= c
return f'''
# ----------------------------------------------------------
'''def vota(nasc):
idade = 2021 - nasc
if idade < 16:
print(f'Com {idade}: VOTO NEGADO')
elif idade >= 16 and idade < 18 or idade > 65:
print(f'Com {idade}: VOTO OPCIONAL')
elif idade >= 18 and idade <= 65:
print(f'Com {idade}: VOTO OBRIGATORIO')
ano = int(input('Insira seu ano de nascimento: '))
vota(ano)'''
# ----------------------------------------------------------
'''def fatorial(num=1, show=False):
"""
Calcula o fatorial de um numero
:param num: o numero a ser calulado.
:param show: (opcional)Mostrar ou não a conta.
:return: O valor Fatorial de Num
"""
f = 1
for c in range(num, 0, -1):
if show:
print(c, end='')
if c > 1:
print(f' x ', end='')
else:
print(' = ', end='')
f *= c
return f
print(fatorial(5, show=True))'''
# ----------------------------------------------------------
'''def ficha(nome='<Desconhecido>', gols=0):
"""
A função mostra a ficha do jogador
:param nome: nome do jogador.
:param gols: quantos gols ele fez.
:return: print com quantidade de gols
"""
print(f'O jogador {nome}, fez {gols}(s) no campeonato.')
nome = str(input('Insira o nome do jogador: '))
gol = str(input('Insira a quantidade de gols do jogador: '))
if gol.isnumeric():
gols = int(gol)
else:
gols = 0
if nome.strip() == '':
ficha(gols=gol)
else:
ficha(nome, gol)'''
# ----------------------------------------------------------
'''def leiaInt(msg):
ok = False
valor = 0
while True:
n = str(input(msg))
if n.isnumeric():
valor = int(n)
ok = True
else:
print('\033[0;31mERRO!\033[m')
if ok:
break
return valor
n = leiaInt('Digite um numero: ')
print(f' você acabou de digitar o numero {n}')'''
# ----------------------------------------------------------
'''def notas(*notas, sit=False):
dicio = dict()
dicio['Total'] = len(notas)
dicio['Maior'] = max(notas)
dicio['Menor'] = min(notas)
dicio['Média'] = sum(notas) / len(notas)
if sit:
if dicio['Média'] >= 7.0:
dicio['Situação'] = 'BOA'
elif dicio['Média'] >= 5 and dicio['Média'] < 7:
dicio['Situação'] = 'RAZOAVEL'
else:
dicio['Situação'] = 'RUIM'
return dicio
print(notas(10, 9, 9, 8, sit=True))'''
# ----------------------------------------------------------
'''from time import sleep
c = ('\033[m',
'\033[0;30;41m', # Vermelho
'\033[0;30;42m', # Verd
'\033[0;30;43m', # Amarelo
'\033[0;30;44m', # Azul
'\033[0;30;45m', # Roxo
'\033[47m' # Branco
);
def ajuda(com):
titulo(f' Acessando o manual do comando \'{com}\'', 4)
print(c[6], end='')
help(com)
print(c[6], end='')
sleep(2)
def titulo(msg, cor=0):
tam = len(msg) + 4
print(c[cor], end='')
print('~' * tam)
print(f' {msg}')
print('~' * tam)
print(c[0], end='')
sleep(1)
comando = ''
while True:
titulo('SISTEMA DE AJUDA PyHELP', 2)
comando = str(input("Função ou Biblioteca > "))
if comando.upper() == 'FIM':
break
else:
ajuda(comando)
titulo('ATÈ LOGO!', 1)'''
|
8e9ad356b43afa00c4f571c276e2df1a0ecbfd30 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2_neat/16_0_2_jaudibert_B.py | 439 | 3.5 | 4 |
def count_flips(s):
transitions = 0
curr = s[0]
for c in s[1:]:
if c != curr:
transitions += 1
curr = c
if s[-1] == "-":
return transitions + 1
return transitions
def main():
# take in input
t = int(raw_input())
solutions = []
for i in range (t):
s = raw_input()
solutions.append("Case #" + str(i+1) + ": " + str(count_flips(s)))
for solution in solutions:
print solution
if __name__ == "__main__":
main() |
6648a0a313b020527a78bdfef00cbbcc6ffaf483 | lucasgnavarro/python-design-patterns | /structural/bridge.py | 1,997 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = "Lucas Navarro (lucasgnavarro@gmail.com)"
__copyright__ = "Copyright (C) 2018- Lucas Navarro"
# Python Version 3.6
#
# Example of bridge design pattern
#
from abc import ABC, abstractmethod
class Website(ABC):
def __init__(self, implementation):
self._implementation = implementation
def __str__(self):
return 'Interface: {}; Implementation{}: '.format(self.__class__.__name__,
self._implementation.__class__.__name__)
@abstractmethod
def show_page(self):
pass
class FreeWebsite(Website):
def show_page(self):
ads = self._implementation.get_ads()
text = self._implementation.get_excerpt()
call_to_action = self._implementation.get_call_to_action()
print(ads)
print(text)
print(call_to_action)
class PaidWebsite(Website):
def show_page(self):
text = self._implementation.get_article()
print(text)
print('')
class Implementation(ABC):
def get_excerpt(self):
return 'excerpt from the article'
def get_article(self):
return 'full article'
def get_ads(self):
return 'some ads'
@abstractmethod
def get_call_to_action(self):
pass
class ImplementationA(Implementation):
def get_call_to_action(self):
return 'Pay 10$ a month to remove ads'
class ImplementationB(Implementation):
def get_call_to_action(self):
return 'Remove Ads with just 10$ a month'
def main():
a_free = FreeWebsite(ImplementationA())
print(a_free)
a_free.show_page() # the client interacts only with the interface
b_free = FreeWebsite(ImplementationB())
print(b_free)
b_free.show_page()
a_paid = PaidWebsite(ImplementationA())
print(a_paid)
a_paid.show_page()
b_paid = PaidWebsite(ImplementationB())
print(b_paid)
b_paid.show_page()
if __name__ == '__main__':
main()
|
080ffa7a1d3bb953476cf1696238acc89c335fea | Hashnroll/prog | /py_source_code/algorithms and structures/sorts/linear time/counting_sort.py | 640 | 3.671875 | 4 | count = {}
k = 100 #max value of integer
def counting_sort(a):
for j in range(k):
count[j]=0
for j in range(len(a)):
count[a[j]]+=1
res = []
for j in range(k):
while count[j]>0:
res.append(j)
count[j]-=1
print(res)
#version different from above. it does sorting with bringing satellite data
"""L=[]
k=10 #max value of key
def counting_sort(a):
for j in range(k): #L should be a list of k empty lists
L.append([])
for j in range(len(a)):
L[key(a[j])].append(a[j])
output=[]
for i in range(k):
output.extend(L[i])"""
|
7b827fc09eb87d2a853ec0a7f0af615609801d16 | sodle/advent-of-code-2020 | /aoc2020/day02/_test.py | 372 | 3.5 | 4 | import unittest
from . import part1, part2
class Test(unittest.TestCase):
sample_input = [
"1-3 a: abcde",
"1-3 b: cdefg",
"2-9 c: ccccccccc"
]
def test_part1(self):
assert part1(self.sample_input) == 2
def test_part2(self):
assert part2(self.sample_input) == 1
if __name__ == '__main__':
unittest.main()
|
f4b660c53591169eea9cc1045be6bd9bef4eaf31 | uhhcaitie/Coding4NonCoders | /dict.py | 340 | 3.9375 | 4 | dict_example = {"A":1,"B":2,"C":3}
#print(dict_example["A"]
dict_example["D"]=4
#print(dict_example)
user_input=input("Prints all even numbers from 0 to... \nA: 10, B: 20, C:30, D:40: ")
user_input=user_input.upper()
max_number = {"A":10, "B":20, "C":30, "D":40}
for x in range(0, max_number[user_input]):
if x%2==0:
print(x)
|
a089578d15f3f37e250b78900942844d7869048e | gopikrishna-a/Python_Training_Complete_Status | /day_6/rectangle_class.py | 967 | 3.890625 | 4 | class Rectangle:
count = 0
def __init__(self,x,y) :
self.length=x
self.width=y
Rectangle.count=Rectangle.count+1
def __str__(self):
return 'Rectangle({0},{1})'.format(self.length,self.width)
def __add__(self,other):
return Rectangle(self.length+other.length,self.width+other.width)
def __eq__(self,other):
return Rectangle(self.length==other.length,self.width==other.width)
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length
def issquare(self):
if self.length == self.width:
return True
@staticmethod
def getcount():
return Rectangle.count
R=Rectangle(2,2)
print R
a=R.area()
print "Area:",a
b=R.perimeter()
print "Perimeter:",b
if R.issquare():
print "Square"
else:
print "Not Square"
R1=Rectangle(2,3)
R2=Rectangle(2,4)
R3=R1+R2
print "R3:",R3
a=R3.area()
print "Area:",a
if R1 == R2:
print "same:"
else:
print "NotSame:"
d=Rectangle.getcount()
print "Count :",d
|
04fbc7b080d2873ee027417d6f374a443e7fc6fa | MaoYuwei/leetcode | /86.py | 1,531 | 3.859375 | 4 | # Definition for singly-linked list.
# remember add a head node
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Li(object):
def __init__(self, l):
self.head = ListNode(l[0])
cur = self.head
for i in range(1, len(l)):
cur.next = ListNode(l[i])
cur = cur.next
def returnHead(self):
return self.head
def printL(self, head):
cur = head
while cur:
print cur.val,'->',
cur = cur.next
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
L = ListNode(x-1)
L.next = head
head = L
cur = head
while cur:
while cur.next and cur.next.val<x:
cur = cur.next
if cur.next == None:
return head.next
next = cur.next
while next.next and next.next.val>=x:
next = next.next
if next.next == None:
return head.next
q = next.next
next.next = next.next.next
temp = cur.next
cur.next = q
cur = cur.next
cur.next = temp
return head.next
if __name__ == '__main__':
solution = Solution()
li = Li([2,3,1])
head = li.returnHead()
print li.printL(head)
head = solution.partition(head, 2)
print li.printL(head)
|
b47ca7a1a297862ae07303ca25b9d661ba36bbbb | HenryEscobar/public-notes | /python/notes/basic/the_basics.py | 1,963 | 3.796875 | 4 | # from the_basics import *
# dir(foobar) and type(foobar) are your friends
#
# Examples of ways to print options for a class/variable
# dir(set)
# print(*dir(set), sep="\n")
# print(' '.join(str(x) for x in dir(set)))
# print(' '.join(map(str,dir(list))))
# print(('\n'.join(dir(list))))
#
# # Utilities
# help('modules')
# pydoc modules
# dir(dict)
# print("something {x} and {y}".format(x=1,y="foo"))
# print(f"{num} something {x * y}") # Not sure if fan of this format.
my_list=['a','b',1,5, True] # my_list[0] == 'a'
my_list.append("foobar")
# An array where every item is unique and no index.
my_set=set(my_list)
my_set2={'1','2',5,'bar'} # only can access elements in a set. no index. not an array!
my_set.add('foo')
my_dict = { 'key1': 'value1', 'key2': 'value2' } # print(my_dict['key1'])
def function_name(x,y="foo"):
return(x + y)
def hello_world():
print("hi")
def pass_arg_as_tuple(*arg): # unlmited args. each one is a tuple
print(type(arg))
for i in arg:
print(i)
def try_except_block(user_input):
try:
if user_input.isdigit():
foo=int(user_input) # cast the string of user_input to an int
print("User input of {} is a digit!".format(user_input))
else:
print("User input of {} is not a digit!".format(user_input))
except ValueError:
print("Input is not a valida number")
except:
print("what unkown error code did yo do")
# return(user_input)
if __name__ == "__main__":
# user_input=''
# while user_input.upper() != "Q":
while True:
user_input = input("Please enter string or list (Enter q to quit): ")
for i in user_input.split(): # split(", ") if you wnat to split on , and space
if i.upper() == "Q":
print("Exiting as {} was emtered".format(i))
exit(0)
try_except_block(i)
print("User has entered {}. exiting".format(user_input))
|
8f78586e54118446d762b192eb1bef40692e53c1 | zhiyingf/pythonMooc | /MOD_02/MOD_02_iterationChange.py | 1,239 | 3.8125 | 4 | #可变可迭代对象修改问题
'''
python中可变可迭代对象一边迭代一边修改会出现问题,remove insert对迭代器的迭代产生影响
'''
lst=[1,2,4,3,5]
for x in lst[:]:#lst的浅拷贝:lst[:]
if x%2==0:
lst.remove(x)
print(lst)
#不可变迭代器,不会修改原始迭代器中的元素
s="beautiful"
for ch in s:
if ch in "aeion":
s=s.replace(ch,'')
print(s)
#浅拷贝与深拷贝:关系到是否会修改原始对象或原始对象中的部分元素
x=[1,2,3]
y=x
y[0]=4
print(x)#x改变,说明x,y都是对同一块内存空间的引用
#为避免以上问题,可以创建对象的拷贝
z=x[:]#把x的浅拷贝赋给z
z[0]=8
print(x)#x没有改变
x=[1,2,[3,4]]
y=x.copy()#x浅拷贝
y[0],y[2][0]=9,9
print(y)
print(x)#x的一级元素没有改变,二级元素改变。
'''
说明:让一级元素有了自己独立的内存空间,二级元素仍然指向了被拷贝对象的二级元素的内存区域
即:浅拷贝只复制了父对象,就是一级元素,而不复制内部子对象
想要实现既复制父对象又复制内部子对象使用深拷贝
python默认的方式是浅拷贝
'''
import copy
z=copy.deepcopy(x)
z[0],z[2][0]=8,8
print(z)
print(x)
|
0e32ff78fed26e7258253e4baad1d6cf84499df4 | alfredoarturo/Introduction-to-computation | /Tarea07/ejercicio4.py | 392 | 3.59375 | 4 | f = [0,0,0,0,0,0,0,0,0,0]
print("Ingresa 10 numeros")
for n in range(0, 10):
f[n] = int(input())
print("Ingresa el numero de lugares desplazados")
desp = int(input())
print("Shidt a la izquierda")
for n in range(0, 10):
a = (desp + n) % 10
print("%i, "%(f[a]), end = "")
print("\nShift a la derecha\n")
for n in range(0, 10):
a = (n-desp+10) % 10
print("%i, "%(f[a]), end="")
print("\n") |
b6245cf6d2bb9a5f478ef19b48ee9376cdad2353 | alazar-des/alx-higher_level_programming | /0x00-python-hello_world/5-print_string.py | 101 | 3.65625 | 4 | #!/usr/bin/python3
str = "Holberton School"
str2 = 3 * str
print("{:s}\n{:s}".format(str2, str[:9]))
|
44e9d6830691eebe37e2b24dd73ac9fef9e0a400 | VitorSchweighofer/exertec | /Exercicio4/exercicio 4/exe4.py | 179 | 3.984375 | 4 | numero = int(input('Digite aqui seu número: '))
tabuada = numero*1
print (tabuada)
for contador in range(1,10):
number = tabuada
tabuada = number + numero
print(tabuada) |
a5aa96fa0ae1235d692bf555fafe90aefae0faf8 | mondler/leetcode | /codes_python/0875_koko_eating_bananas.py | 2,563 | 3.578125 | 4 | #
# @lc app=leetcode id=875 lang=python3
#
# [875] Koko Eating Bananas
#
# https://leetcode.com/problems/koko-eating-bananas/description/
#
# algorithms
# Medium (54.03%)
# Likes: 4482
# Dislikes: 196
# Total Accepted: 193.9K
# Total Submissions: 359.4K
# Testcase Example: '[3,6,7,11]\n8'
#
# Koko loves to eat bananas. There are n piles of bananas, the i^th pile has
# piles[i] bananas. The guards have gone and will come back in h hours.
#
# Koko can decide her bananas-per-hour eating speed of k. Each hour, she
# chooses some pile of bananas and eats k bananas from that pile. If the pile
# has less than k bananas, she eats all of them instead and will not eat any
# more bananas during this hour.
#
# Koko likes to eat slowly but still wants to finish eating all the bananas
# before the guards return.
#
# Return the minimum integer k such that she can eat all the bananas within h
# hours.
#
#
# Example 1:
#
#
# Input: piles = [3,6,7,11], h = 8
# Output: 4
#
#
# Example 2:
#
#
# Input: piles = [30,11,23,4,20], h = 5
# Output: 30
#
#
# Example 3:
#
#
# Input: piles = [30,11,23,4,20], h = 6
# Output: 23
#
#
#
# Constraints:
#
#
# 1 <= piles.length <= 10^4
# piles.length <= h <= 10^9
# 1 <= piles[i] <= 10^9
#
#
#
# @lc code=start
class Solution:
def minEatingSpeed(self, piles: list[int], h: int) -> int:
def feasible(speed):
hrs = sum([(pile - 1) // speed + 1 for pile in piles])
return hrs <= h
left = 1
right = max(piles)
while left < right:
speed = left + (right - left) // 2
if feasible(speed):
right = speed
else:
left = speed + 1
return left
def bruteForce(self, piles, h):
import math
def hrsPerPile(pile, k):
# if pile % k == 0:
# return pile // k
# else:
# return pile // k + 1
return math.ceil(pile / k)
k = 1
while True:
hrs = [hrsPerPile(pile, k) for pile in piles]
totalhrs = sum(hrs)
if totalhrs <= h:
return k
else:
k += 1
return
# @lc code=end
piles = [3, 6, 7, 11]
h = 8
print(Solution().minEatingSpeed(piles, h))
print(Solution().bruteForce(piles, h))
piles = [30, 11, 23, 4, 20]
h = 5
print(Solution().minEatingSpeed(piles, h))
print(Solution().bruteForce(piles, h))
piles = [30, 11, 23, 4, 20]
h = 6
print(Solution().minEatingSpeed(piles, h))
print(Solution().bruteForce(piles, h))
|
6c487f8f857100cd2ad84f9dc1196e00a43aa242 | elshadow11/Prog | /POO python/ejemplos/persona.py | 1,172 | 3.59375 | 4 | class Persona:
def __init__(self, sexo, nombre, estatura, peso, edad, color_de_pelo, color_de_piel, tiene_pelo, color_de_ojos,
tiene_gafas):
self.sexo = sexo
self.nombre = nombre
self.estatura = estatura
self.peso = peso
self.edad = edad
self.tiene_pelo = tiene_pelo
self.color_de_pelo = color_de_pelo
self.color_de_piel = color_de_piel
self.color_de_ojos = color_de_ojos
self.tiene_gafas = tiene_gafas
def cumple_annos(self):
self.edad = self.edad + 1
return self.edad
def comer(self, comida):
print(f"estoy comiendo {comida}")
def dormir(self):
print("Buenas noches\n ZZZZzzzzzzz")
def despertar(self):
print("Wenos dias peñita UwU")
def andar(self, direccion, tiempo=0, dist=0):
if direccion == "norte" or direccion == "sur" or direccion == "este" or direccion == "oeste":
if tiempo == 0:
print(f"Voy a andar hacia el {direccion} unos {dist} kilometros")
if dist == 0:
print(f"Voy a andar hacia el {direccion} durante {tiempo} minutos")
|
38806b775cb70f0be8f9b995dd981b049bb061e4 | Sfera-IT/adventofcode2020 | /the_maxtor/day2/puzzle3.py | 417 | 3.65625 | 4 | #!/usr/bin/python3
valid = 0
with open("input_day2.txt") as inputFile:
for row in inputFile:
policy, password = row.split(":")
min = policy.split("-")[0]
max = policy.split("-")[1].split(" ")[0]
letter = policy.split("-")[1].split(" ")[1]
occurances = password.strip().count(letter)
if int(min) <= occurances <= int(max):
valid = valid + 1
print(valid) |
1120a048179058a5edd10fb886afae2236820c56 | gustavolima007/Training_Program | /Python/1_Python Basics/15-while_loops.py | 665 | 4.28125 | 4 | # While Loops
# While Loops for complex situations, and For Loops for simple operations
# infinite loop - don't run this code
# i = 0
# while i < 50:
# print(i)
# to finish the loop, we use Break
i = 0
while i < 10:
print(i)
i += 1 # this line will stop the loop
else:
print('Done with all the work')
print('\n')
# i = index
# decrement loop with while loops
i = 5
while i > 0:
print(i)
i += -1
# Other example
my_list = [1, 2, 3]
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
print('\n')
# Question Loop
while True:
response = input('Say something: ')
if (response == 'bye'):
break
print('\n')
|
3c09fb3fd373f9e46972cec2c4ba08975955ae47 | crazcalm/Python_cookbook_favorites | /chapter3/ThreePointFour.py | 980 | 4.5625 | 5 | """
Working with Binary, Octal, and Hexadecimal
-------------------------------------------
Problem:
--------
You need to convert or output itegers represented by binary, octal, or
hexadecimal digits.
Solution:
--------
To convert an integer into a binary, octal, or hexadecimal text string, use
bin(), oct(), or hex() functions, respectively:
"""
print("Using bin(), oct(), and hex():\n\n")
x = 1234
print("number:", x)
print("bin():", bin(x))
print("oct():", oct(x))
print('hex():', hex(x))
"""
Alternatively, you can use the format() function if you don't want the 0b,
0o, or 0x prefixes to appear. For example:
"""
print("\n\nUsing format(): \n\n")
print(format(x, 'b'))
print(format(x, 'o'))
print(format(x, 'x'))
"""
To convert integer strings in different bases, simply use the int() function
with an appropriate base. For example:
"""
print("\n\nConversions using int():\n\n")
print(int('4d2', 16))
print(int('10011010010', 2))
|
1b7d4a8d417aec5aeb29cb7f42a8c80ec7ec166f | rajeshsvv/Lenovo_Back | /1 PYTHON/9 PYTHON PROGRAMS/PYTHON PROGRAMS LENOVO/1_first_notes(18 Programs)/7_randomize_content.py | 416 | 3.8125 | 4 | import random
from random import shuffle
mylist=[9,8,7,6,5,4,3,2,1]
# print(shuffle(mylist)) if u print like this u get None k
random.shuffle(mylist)
print(mylist)
# 15 generate random numbers
import random
result=random.random()
print(result)
# 20 Random the string elements
list=["Abay","Raju","Shekhar","Mallemala"]
random.shuffle(list)
print(list)
random.choice(list)
print(list) |
a8996d663e0bfac317cf5169f6213be4acbdb040 | omaralsayed/neural-networks | /autoencoder/autoencoder.py | 10,085 | 3.671875 | 4 | '''
Autoencoder network using the dataset and hyperparameters used in the MLP neural network. The task of this autoencoder
is to explore interesting features in the hidden layers and to reconstruct the input, which is a 28 x 28 pixels image.
'''
import dataset
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sn
import pandas as pd
mnist = dataset.get_sets()
class Autoencoder:
def __init__(self, layers, neurons, epoch=0, epochs=500, learning_rate=0.3, min_learning_rate=0.0025, momentum=0.9):
self.neurons = neurons # List of nerons for Autoencoder
self.epoch = epoch
self.epochs = epochs
self.alpha = learning_rate
self.min_alpha = min_learning_rate
self.momentum = momentum
self.layers = layers
self.output = []
self.hyperparameters = self.initialize_dictionary()
def initialize_dictionary(self):
hyperparameters = {}
input_layer = self.neurons[0]; output_layer = self.neurons[len(self.neurons) - 1]
layer_sizes = self.neurons[1:len(self.neurons) - 1] # Extract hidden layers
hidden = { hidden: [] for hidden in range(self.layers) }
for x in range(len(layer_sizes)):
hidden[x] = layer_sizes[x]
hyperparameters['W1'] = np.random.randn(hidden[0], input_layer) * np.sqrt(1. / hidden[0])
for x in range(self.layers-1):
hyperparameters['W' + str(x + 2)] = np.random.randn(hidden[x + 1], hidden[x]) * np.sqrt(1. / hidden[x + 1])
hyperparameters['W' + str(self.layers + 1)] = np.random.randn(output_layer, hidden[self.layers - 1]) * np.sqrt(1. / output_layer)
return hyperparameters
def forward_pass(self, x_train):
hyperparameters = self.hyperparameters
hyperparameters['A0'] = x_train
for i in range(self.layers + 1):
hyperparameters['Z' + str(i + 1)] = np.dot(hyperparameters['W' + str(i + 1)], hyperparameters['A' + str(i)])
hyperparameters['A' + str(i + 1)] = self.compute_sigmoid(hyperparameters['Z' + str(i + 1)])
return hyperparameters['A' + str(self.layers + 1)]
def backward_pass(self, y_train, output):
hyperparameters = self.hyperparameters; w = {}
error = 2 * (output - y_train) / output.shape[0] * self.compute_sigmoid(hyperparameters['Z' + str(self.layers + 1)], derivative=True)
w['W' + str(self.layers + 1)] = np.outer(error, hyperparameters['A' + str(self.layers)])
for x in range(self.layers, 0, -1):
error = np.dot(hyperparameters['W' + str(x + 1)].T, error) * self.compute_sigmoid(hyperparameters['Z' + str(x)], derivative=True)
w['W' + str(x)] = np.outer(error, hyperparameters['A' + str(x - 1)])
return w
def update_w(self, w):
for wi, wv in w.items():
if self.epoch == 0:
self.hyperparameters[wi] -= (self.alpha * wv)
else:
self.hyperparameters[wi] -= (self.momentum * self.alpha * wv)
def save_w(self):
w = open('weights.txt', 'w')
for wi in self.hyperparameters['W1']:
np.savetxt(w, wi)
w.close()
def compute_sigmoid(self, x, derivative=False):
if derivative:
return (np.exp(-x)) / ((np.exp(-x) + 1) ** 2)
return 1 / (1 + np.exp(-x))
def compute_accuracy(self, xp, output, labels):
losses = []; cumulative_losses = []
itr_loss = 0; total_loss = 0
l0 = []; l1 = []; l2 = []; l3 = []; l4 = []
l5 = []; l6 = []; l7 = []; l8 = []; l9 = []
ln = []
epoch = 0
for xp, _ in zip(xp, output):
output = self.forward_pass(xp)
if (self.epoch == self.epochs - 1):
self.output.append(output)
for i in range(self.neurons[len(self.neurons) - 1]):
itr_loss += (xp[i] - output[i]) ** 2
losses.append(0.5 * itr_loss)
if self.epoch == self.epochs:
if labels[epoch] == '0':
l0.append(0.5 * itr_loss)
elif labels[epoch] == '1':
l1.append(0.5 * itr_loss)
elif labels[epoch] == '2':
l2.append(0.5 * itr_loss)
elif labels[epoch] == '3':
l3.append(0.5 * itr_loss)
elif labels[epoch] == '4':
l4.append(0.5 * itr_loss)
elif labels[epoch] == '5':
l5.append(0.5 * itr_loss)
elif labels[epoch] == '6':
l6.append(0.5 * itr_loss)
elif labels[epoch] == '7':
l7.append(0.5 * itr_loss)
elif labels[epoch] == '8':
l8.append(0.5 * itr_loss)
else:
l9.append(0.5 * itr_loss)
ln.append(0.5 * itr_loss)
epoch += 1
if self.epoch == self.epochs:
digits = [l0, l1, l2, l3, l4, l5, l6, l7, l8, l9]
for digit in digits:
cumulative_losses.append(100 - np.mean(digit) / len(xp))
total_loss = 100 - np.mean(ln) / len(xp)
return [np.mean(losses) / len(xp), cumulative_losses, total_loss]
def train_model(self, x_train, y_train, x_test, y_test, y_train_, y_test_):
losses = []
for epoch in range(self.epochs):
for x, y in zip(x_train, y_train):
output = self.forward_pass(x)
w = self.backward_pass(y, output)
self.update_w(w)
if self.alpha > self.min_alpha:
self.alpha -= 0.0001 * self.alpha
# Save accuracy value at the beginning, and then at every tenth epoch
itr_loss = self.compute_accuracy(x_test, x_test, y_test)[0]
if (self.epoch % 10 == 0):
losses.append(itr_loss)
self.epoch += 1
print('Epoch: {0} ... Loss:'.format(epoch + 1), round(itr_loss, 2))
itr_loss, losses_test, total_loss_test = (self.compute_accuracy(x_test, x_test, y_test_)[0],
self.compute_accuracy(x_test, x_test, y_test_)[1], self.compute_accuracy(x_test, x_test, y_test_)[2])
itr_loss, losses_train, total_loss_train = (self.compute_accuracy(x_train, x_train, y_train_)[0],
self.compute_accuracy(x_train, x_train, y_train_)[1], self.compute_accuracy(x_train, x_train, y_train_)[2])
self.show_plots(losses, losses_train, losses_test, total_loss_train, total_loss_test)
def show_plots(self, accuracy, losses_train, losses_test, total_loss_train, total_loss_test):
span = np.arange(0, self.epochs, 10)
'''
Overall Accuracy Plot
'''
plt.figure(0)
plt.plot(span, accuracy)
plt.title('Overall Accuracy Over 500 Epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
'''
Accuracy Per Digit Chart
'''
plt.figure(1)
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
interval = np.arange(10)
bar_train = [x + 0.15 for x in interval]
bar_test = [x + 0.15 for x in bar_train]
plt.bar(bar_train, losses_train, width = 0.15, label='Train')
plt.bar(bar_test, losses_test, width = 0.15, label='Test')
plt.xticks([r + 0.15 for r in range(len(losses_train))], digits)
plt.legend()
plt.title('Accuracy Per Digit Over 500 Epochs')
plt.xlabel('Digits')
plt.ylabel('Accuracy')
'''
Overall Accuracy Chart
'''
plt.figure(2)
bar_train = 0.15; bar_test = 0.30
plt.bar(bar_train, total_loss_train, width = 0.15, label='Train')
plt.bar(bar_test, total_loss_test, width = 0.15, label='Test')
plt.legend()
plt.title('Train and Test Accuracy Over 500 Epochs')
plt.xlabel('Data Labels')
plt.ylabel('Accuracy')
def show_image_reconstruction(self, xp):
figure, axes = plt.subplots(nrows=2, ncols=8, sharex=True, sharey=True)
for images, rows in zip([xp, self.output[:8]], axes):
for image, row in zip(images, rows):
row.imshow(image.reshape((28, 28)), cmap='gray')
row.get_xaxis().set_visible(False)
row.get_yaxis().set_visible(False)
figure.tight_layout(pad=0.1)
def show_random_hidden_neurons(self):
neurons = self.hyperparameters['W1']
neuron = []
for i in range(len(neurons)):
neuron.append(neurons[i])
figure, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True)
for images, rows in zip([neuron[:10], neuron[20:30]], axes):
for image, row in zip(images, rows):
row.imshow(image.reshape((28, 28)), cmap='gray')
row.get_xaxis().set_visible(False)
row.get_yaxis().set_visible(False)
figure.tight_layout(pad=0.1)
def main():
'''
User can specify number of hidden layers at run-time. Input and output neurons are predetermined
since each image (input) is 24 x 24 pixels and the output layer is the reconstructed input.
Sample input:
Hidden layers: 2
Number of neurons (seperate using space): 256 128
'''
hidden_layers = int(input('Hidden layers: '))
neurons = list(map(int, input('Number of neurons (seperate using space): ').strip().split()))[:hidden_layers]
neurons_list = [784] # Input layer dimensionality
for layer in range(0, hidden_layers):
neurons_list.append(neurons[layer])
neurons_list.append(784) # Output layer dimensionality
auto = Autoencoder(layers=hidden_layers, neurons=neurons_list)
auto.train_model(mnist.x_train, mnist.x_train, mnist.x_test, mnist.x_test, mnist.y_train_, mnist.y_test_)
# Store final weights
auto.save_w()
# Generate plots
auto.show_image_reconstruction(mnist.x_test[:8])
auto.show_random_hidden_neurons()
plt.show()
if __name__ == '__main__':
main() |
15508132015724e4fc1c52bf24eca1cbab78d238 | llhyatt98/Data-Structures | /Red-Black-Tree/RBT.py | 11,746 | 3.875 | 4 |
# BinarySearchTree is a class for a binary search tree (BST)
# when called, a BST is initialized with no root and size 0.
# size keeps track of the number of nodes in the tree
from Node import RB_Node
class RedBlackTree:
# initialize root and size
def __init__(self):
self.root = None
self.size = 0
# All leaf nodes point to self.sentinel, rather than 'None'
# Parent of root should also be self.sentinel
self.sentinel = RB_Node(None, color = 'black')
self.sentinel.parent = self.sentinel
self.sentinel.leftChild = self.sentinel
self.sentinel.rightChild = self.sentinel
'''
Free Methods
'''
def sentinel(self):
return self.sentinel
def root(self):
return self.root
def __iter__(self):
# in-order iterator for your tree
return self.root.__iter__()
def getKey(self, key):
# expects a key
# returns the key if the node is found, or else raises a KeyError
if self.root:
# use helper function _get to find the node with the key
res = self._get(key, self.root)
if res: # if res is found return the key
return res.key
else:
raise KeyError('Error, key not found')
else:
raise KeyError('Error, tree has no root')
def getNode(self, key):
# expects a key
# returns the RB_Node object for the given key
if self.root:
res = self._get(key, self.root)
if res:
return res
else:
raise KeyError('Error, key not found')
else:
raise KeyError('Error, tree has no root')
# helper function _get receives a key and a node. Returns the node with
# the given key
def _get(self, key, currentNode):
if currentNode is self.sentinel: # if currentNode does not exist return None
print("couldnt find key: {}".format(key))
return None
elif currentNode.key == key:
return currentNode
elif key < currentNode.key:
# recursively call _get with key and currentNode's leftChild
return self._get( key, currentNode.leftChild )
else: # key is greater than currentNode.key
# recursively call _get with key and currentNode's rightChild
return self._get( key, currentNode.rightChild )
def __contains__(self, key):
# overloads the 'in' operator, allowing commands like
# if 22 in rb_tree:
# ... print('22 found')
if self._get(key, self.root):
return True
else:
return False
#Call this method within delete,
def __transplant(self, nodeA, nodeB):
'''
Replaces the node rooted at A with the node rooted at B.
'''
if (nodeA.parent == None):
self.root = nodeB
elif (nodeA == nodeA.parent.leftChild):
nodeA.parent.leftChild = nodeB
else:
nodeA.parent.rightChild = nodeB
if nodeB != None:
if nodeB.parent == None:
nodeB.parent = nodeA.parent
def delete(self, key):
# Same as binary tree delete, except we call rb_delete fixup at the end.
# Code goes through and checks all the testcases of RB Trees and does corresponding
# operation to maintain properties.
z = self.getNode(key)
if z.leftChild is self.sentinel or z.rightChild is self.sentinel:
y = z
else:
y = z.findSuccessor()
if y.leftChild is not self.sentinel:
x = y.leftChild
else:
x = y.rightChild
if x is not self.sentinel:
x.parent = y.parent
if y.parent is self.sentinel:
self.root = x
else:
if y == y.parent.leftChild:
y.parent.leftChild = x
else:
y.parent.rightChild = x
if y is not z:
z.key = y.key
if y.color == 'black':
if x is self.sentinel: #Fixup the other node, else fixup x
self._rb_Delete_Fixup(y)
else:
self._rb_Delete_Fixup(x)
def traverse(self, order = "in-order"):
# Same a BST traverse
self.walk(order, self.root)
'''
Required Methods Begin Here
'''
def insert(self, key):
# add a key to the tree. Don't forget to fix up the tree and balance the nodes.
#Drawn from the pseudocode in the CLRS
z = RB_Node(key)
y = self.sentinel
x = self.root
if x == None:
z.parent = self.sentinel
z.leftChild = self.sentinel
z.rightChild = self.sentinel
z.color = 'black'
self.root = z
else:
while x != self.sentinel:
y = x
if z.key < x.key:
x = x.leftChild
else:
x = x.rightChild
z.parent = y
if y == self.sentinel:
self.root = z
elif z.key < y.key:
y.leftChild = z
else:
y.rightChild = z
z.leftChild = self.sentinel
z.rightChild = self.sentinel
z.color = "red"
self._rbInsertFixup(z) #Last step is to fixup the new node, calling our insert fixup.
def _rbInsertFixup(self, z):
# write a function to balance your tree after inserting
#Drawn from the pseudocode in the CLRS
#This function is meant to be called after we insert a node into the tree.
while z.parent.color == 'red':
if z.parent == z.parent.parent.leftChild:
y = z.parent.parent.rightChild
if y.color == "red":
z.parent.color = "black"
y.color = "black"
z.parent.parent.color = "red"
z = z.parent.parent
else:
if z == z.parent.rightChild:
z = z.parent
self.leftRotate(z)
z.parent.color = "black"
z.parent.parent.color = "red"
self.rightRotate(z.parent.parent)
else:
y = z.parent.parent.leftChild
if y.color == "red":
z.parent.color = "black"
y.color = "black"
z.parent.parent.color = "red"
z = z.parent.parent
else:
if z == z.parent.leftChild:
z = z.parent
self.rightRotate(z)
z.parent.color = "black"
z.parent.parent.color = "red"
self.leftRotate(z.parent.parent)
self.root.color = "black" #Maintain this property after every insertion.
def _rb_Delete_Fixup(self, x):
# receives a node, x, and fixes up the tree, balancing from x.
#Drawn from the pseudocode in the CLRS
#Called directly after we delete.
while x != self.root and x.color == 'black':
if x == x.parent.leftChild:
w = x.parent.rightChild
if w.key == None:
break
if w.color == "red":
w.color = "black"
x.parent.color = "red"
self.leftRotate(x.parent)
w = x.parent.rightChild
if w.leftChild.color == "black" and w.rightChild.color == "black":
w.color = "red"
x = x.parent
else:
if w.rightChild.color == "black":
w.leftChild.color = "black"
w.color = "red"
self.rightRotate(w)
w = x.parent.rightChild
w.color = x.parent.color
x.parent.color = "black"
w.rightChild.color = "black"
self.leftRotate(x.parent)
x = self.root
else:
w = x.parent.leftChild
if w.key == None:
break
if w.color == "red":
w.color = "black"
x.parent.color = "red"
self.rightRotate(x.parent)
w = x.parent.leftChild
if w.rightChild.color == "black" and w.leftChild.color == "black":
w.color = "red"
x = x.parent
else:
if w.leftChild.color == "black":
w.rightChild.color = "black"
w.color = "red"
self.leftRotate(w)
w = x.parent.leftChild
w.color = x.parent.color
x.parent.color = "black"
w.leftChild.color = "black"
self.rightRotate(x.parent)
x = self.root
x.color = "black"
def leftRotate(self, currentNode):
# perform a left rotation from a given node
# Current node will be of type RB_Node
#Drawn from the pseudocode in the CLRS
y = currentNode.rightChild
currentNode.rightChild = y.leftChild
if y.leftChild != self.sentinel:
y.leftChild.parent = currentNode
y.parent = currentNode.parent
if currentNode.parent == self.sentinel:
self.root = y
elif currentNode == currentNode.parent.leftChild:
currentNode.parent.leftChild = y
else:
currentNode.parent.rightChild = y
y.leftChild = currentNode
currentNode.parent = y
def rightRotate(self, currentNode):
# perform a right rotation from a given node
# Current node will be of type RB_Node
#Drawn from the pseudocode in the CLRS
y = currentNode.leftChild
currentNode.leftChild = y.rightChild
if y.rightChild != self.sentinel:
y.rightChild.parent = currentNode
y.parent = currentNode.parent
if currentNode.parent == self.sentinel:
self.root = y
elif currentNode == currentNode.parent.rightChild:
currentNode.parent.rightChild = y
else:
currentNode.parent.leftChild = y
y.rightChild = currentNode
currentNode.parent = y
'''
Optional handy methods that you can imagine can start here
'''
#Made this to use
def walk(self, order, top):
'''
Implements recursive based calls to traverse the tree, printing the node data in the specified
depth first traversals.
This was drawn and adapted from my traversal in BST.
'''
if top != self.sentinel:
if order == "pre-order":
print(top.key),
self.walk("pre-order", top.leftChild) #Recursion used to print first, then recurse
self.walk("pre-order", top.rightChild)
elif order == "in-order":
self.walk("in-order", top.leftChild) #Here the recursion happens first, (inorder)
print(top.key),
self.walk("in-order", top.rightChild)
elif order == "post-order":
self.walk("post-order", top.leftChild) #Here we print last for postorder, after recursion
self.walk("post-order", top.rightChild)
print(top.key),
else:
print("Error, order {} undefined".format(order))
#This function is required to search the tree (called within lab4.py main())
def search(self, data):
'''
Searches the tree to see if it contains a particular value within a node. Returns true if there is an
occurence, false otherwise.
'''
tmp = self.root
while(tmp != self.sentinel):
if tmp.key == data:
return True
else:
if data < tmp.key:
tmp = tmp.leftChild
else:
tmp = tmp.rightChild
return False
|
ffc651921b8bb5666fe82004da877f78f34e63b6 | jadball/python-course | /Level 3/18 Type Hints/03_example.py | 91 | 3.53125 | 4 | def concat(x: str, y: str, z: str) -> str:
result = x + y + z
print(concat(5, 7, 9))
|
2934977fd824d10ebf0952205fc00177eb188085 | arnoldlu/pm-debug | /test/multithread/multithread.py | 820 | 3.875 | 4 | import random
import time
import os
from threading import Thread
class MyThread(Thread):
"""
A threading example
"""
#----------------------------------------------------------------------
def __init__(self, name):
"""Initialize the thread"""
Thread.__init__(self)
self.name = name
self.duration = 20
self.start()
#----------------------------------------------------------------------
def run(self):
"""Run the thread"""
time.sleep(random.uniform(10, 20))
print self.name
#----------------------------------------------------------------------
def create_threads():
"""
Create a group of threads
"""
name = "Thread trace"
for i in range(5):
MyThread(name=name+str(i))
if __name__ == "__main__":
create_threads()
|
3ee093e8ceb7ee9576a8cabf4d542d95af6b90f6 | bong-o-hari/Interview-Prep | /Arrays/min_max_array_linear_search.py | 983 | 4.15625 | 4 | # Time complexity O(n)
# Structure used to return two values from getMinMax()
class Pair:
def __init__(self):
self.min = 0
self.max = 0
def getMinMax(arr, n):
minmax = Pair()
# If there is only one element in the array then that element
# is the minimum and the maximum value
if n == 1:
minmax.min = arr[0]
minmax.max = arr[0]
return minmax
# If there is more than one element then initialize min and max
if arr[0] > arr[1]:
minmax.min = arr[1]
minmax.max = arr[0]
else:
minmax.min = arr[0]
minmax.max = arr[1]
for i in range(2, n):
if arr[i] > minmax.max:
minmax.max = arr[i]
elif arr[i] < minmax.min:
minmax.min = arr[i]
return minmax
# Driver code
if __name__ == "__main__":
arr = [999, 56, 121, 155, 984, 1]
minmax = getMinMax(arr, len(arr))
print("Maximum : ", minmax.max)
print("Minimum : ", minmax.min) |
aea9475ea3402d05f221b3e9878ac989dca69012 | mallimuondu/python-practice | /sqlite/03.py | 151 | 3.859375 | 4 |
def uppdate():
while True:
name = input("enter your name: ")
if not name.isalpha():
continue
break
uppdate() |
70540911221243f13ac28f678fcb455a604a3280 | MZhoume/IoTLabs | /Lab2/main-1.py | 770 | 3.546875 | 4 | # LED runs on duty from 0 to 200
# Piezo runs on duty from 0 to 10
# ADC output higher when there's light
from time import sleep_ms
from machine import ADC
from machine import Pin
from machine import PWM
# PWM for led outputs from Pin 12
pwm_led = PWM(Pin(12))
# PWM for led outputs from Pin 13
pwm_piezo = PWM(Pin(13))
# let's set the frequency to the highest value
pwm_led.freq(1000)
pwm_piezo.freq(1000)
# we use ADC 0
adc = ADC(0)
while True:
# read the value from ADC
adc_val = adc.read()
# calculate the duty value for led and piezo
led_val = adc_val / 20
piezo_val = adc_val / 100
# set the duty value
pwm_led.duty(int(led_val))
pwm_piezo.duty(int(piezo_val))
# wait for 50ms to sample the next value
sleep_ms(50) |
3ce87e1d32afbd208f07f686bef21ee270b86f6f | bharathprabha/data-structure-and-algorithm | /Algorithm/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 386 | 3.59375 | 4 |
# def calc_fib(n):
# golden_ratio = (1 + math.sqrt(5)) / 2
# val = (golden_ratio ** n - (1 - golden_ratio) ** n) / math.sqrt(5)
# return int(round(val))
def calc_fib(n):
if n is 0:
return 0
a = [0 for _ in range(n+1)]
a[0] = 0
a[1] = 1
for i in range(2,n+1):
a[i] = a[i-1] + a[i-2]
return a[-1]
n = int(input())
print(calc_fib(n))
|
3f541366002623253807bb58f28c63756eb7790c | lldenisll/learn_python | /Exercícios/segundos.py | 447 | 3.65625 | 4 | segundos_str=input("Por favor preencha o numero de segundos que deseja converter: ")
segundos_int=int(segundos_str)
dias=segundos_int//86400
segundosrestantesd=segundos_int%86400
horas_restantes=segundosrestantesd//3600
segundos_restantesh=segundosrestantesd%3600
minutos=segundos_restantesh//60
segundos_restantesf=segundos_restantesh%60
print(dias,"dias,",horas_restantes,"horas,", minutos, "minutos e", segundos_restantesf, "segundos.")
|
61cd2aba0d8655add20b817c174c1bde7f32f9c7 | ChennakesavaReddy123/python-assignment1 | /assignment1_temperature.py | 210 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 12:11:28 2020
@author: Administrator
"""
c=float(input("enter the temperature in celsius"))
f=1.8*c+32
print("the temperature in fahrenheit is ",f) |
ddcdc99a419aa2746f2ed54f2ffc4ca068cc6a82 | majorbriggs/python_training | /classes.py | 1,463 | 3.8125 | 4 | class MyClassWithRepr():
def __init__(self):
pass
def __repr__(self):
return "This is my class"
class MyClassWithoutRepr():
def __init__(self):
pass
x = MyClassWithoutRepr()
y = MyClassWithRepr()
print(x)
print(y)
class Vector1D():
def __init__(self, *args):
for arg in args:
if not isinstance(arg, int):
raise ValueError("Vector1D can store only integer values")
self._values = args
def __str__(self):
return self._values
def __add__(self, other):
if not isinstance(other, Vector1D):
raise ValueError('Expected Vector1D, instead got {}'.format(other.__class__))
if len(self._values) != len(other._values):
raise ValueError('Added vectors have to have the same lenght')
return [i + j for i, j in zip(self._values, other._values)]
def __eq__(self, other):
return self._values == other._values
def __ne__(self, other):
return self._values != other._values
A = Vector1D(1, 2, 3, 4)
B = Vector1D(5, 6, 7, 8)
C = A + B
print(A == B) # False
print(C)
# -> [6, 8, 10, 12]
class Animal():
def __init__(self, name, make_sound_method):
self.name = name
self.make_sound = make_sound_method
def quack():
print('Quack!')
def moo():
print('Moooo!')
def bah():
print('Bah!')
bah = Animal(name='Sheep', make_sound_method=bah)
bah.make_sound() |
ae18234bcd28fe414ef12cbae60462592ca94c60 | thiagorente/pythonchallenge | /challenge_2.py | 404 | 3.953125 | 4 | def challenge_2(hidden_text):
#the answer to this challenge is search for some alphanumeric char in the middle of the hidden string
# in the source code of the website
word = ''
for line in hidden_text:
for char in line:
word += (char if char.isalpha() else '')
print(word)
if __name__ == '__main__':
challenge_2(open('./resources/challenge_2.txt', 'r'))
|
ef54ca40acf95270488213f131ef6f6a39a54497 | youssefgorgi/atelier-1-2 | /A1Exercice2.py | 268 | 3.75 | 4 |
#defining the function
def cnv(n):
if n > 1:
cnv(n // 2) # floor division: nous permet de prendre juste la resultat sans vergule
print(n % 2, end=' ')
nbr = int(input("Veuillez entrez un nombre decimal: ")) #calling the function
cnv(nbr ) |
1aeb76d0f3d81d7f30f939b456accc550fa62b1e | RijuDasgupta9116/LintCode | /Single Number III.py | 836 | 3.890625 | 4 | """
Given 2*n + 2 numbers, every numbers occurs twice except two, find them.
Example
Given [1,2,2,3,4,4,5,3] return 1 and 5
Challenge
O(n) time, O(1) extra space.
"""
__author__ = 'Danyang'
class Solution:
def singleNumberIII(self, A):
"""
Bit manipulation
If two numbers are different, \exists 1 bit set in one while unset in the other.
To get the rightmost set bit: n&(~n+1), which is equivalent to n&-n (2's complement)
:param A: An integer array
:return: Two integer
"""
bits = 0
for a in A:
bits ^= a
rightmost_set_bit = bits&-bits
bits1 = 0
bits2 = 0
for a in A:
if a&rightmost_set_bit:
bits1 ^= a
else:
bits2 ^= a
return bits1, bits2
|
3fde71d35d4aa62a2867a6599e5f208cd0b3c55b | modcomlearning/python_oct | /Lesson2g.py | 232 | 3.84375 | 4 |
# while loop
i = 0
while i < 1000000:
print("Looping", i)
i = i + 1
# While loop can fixed or not fixed(infinite)
# while loop runs when condition is true
# while loop does not run for a condition that executes to false |
662c06274e1cb93291388f65a1d6046649e7afe8 | a1h2med/OpenCv_Projects | /Learning_Codes_and_Projects/erosing and dilation.py | 683 | 3.515625 | 4 | import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
image = cv.imread('C:/Users/LENOVO/Desktop/ME.jpg') # used to read an image
Part18 = "erosion and dilation"
###### Erosion Removes pixels at the boundaries of objects in an image
###### dilation adds pixels to the boundaries of objects in an image
###### open means to do erosion then dilation(used to remove noise) , closing is vice versa
kernel = np.ones((5,5),np.uint8)
erosion = cv.erode(image,kernel)
dilation = cv.dilate(image,kernel)
openning = cv.morphologyEx(image,cv.MORPH_OPEN,kernel)
closing = cv.morphologyEx(image,cv.MORPH_CLOSE,kernel)
#cv.imshow("erosion",erosion)
|
c73c41316b5973d58a584ee7b9d78b43426d9136 | IKnawDeWae/crypto-Eyadaabdellatif | /codage/monge2.py | 205 | 3.71875 | 4 |
def monge2():
i=0
s=input('code: ')
m = int(input('nombre de chiffrage souhaiter :'))
n=s
while i < m :
i=i+1
n=n[-2::-2]+n[1::2]#les character de pos -1 en pos -2
print(n)
monge2() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.