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 |
|---|---|---|---|---|---|---|
18a1273ee8ee03edad1c5e18a319aa69ab5a9597 | KseniyaF/-6 | /6.4.py | 2,340 | 3.59375 | 4 | from random import choice
class Car:
def __init__(self, speed, color, name, is_police):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def go(self):
return f'{self.name} Поехал'
def stop(self):
return f'{self.name} Остановилася'
def turn(self):
a = ("повернула направо", "повернула налево")
b = choice(a)
return f'{self.name} {b}'
def show_speed(self):
return f'Скорость {self.name} составляет {self.speed}'
class TownCar(Car):
def __init__(elf, speed, color, name, is_police):
super().__init__(speed, color, name, is_police)
def show_speed(self):
if self.speed > 60:
return f'Скорость {self.name} превышена'
else:
return f'Скорость {self.name} не превышена'
class SportCar(Car):
def __init__(elf, speed, color, name, is_police):
super().__init__(speed, color, name, is_police)
class WorkCar(Car):
def __init__(elf, speed, color, name, is_police):
super().__init__(speed, color, name, is_police)
def show_speed(self):
if self.speed > 40:
return f'Скорость {self.name} превышена'
else:
return f'Скорость {self.name} не превышена'
class PoliceCar(Car):
def __init__(self, speed, color, name, is_police):
super().__init__(speed, color, name, is_police)
auto_1 = TownCar(50, 'Белый', 'TownCar', False)
auto_2 = SportCar(200, 'Cине-желтый', 'SportCar', False)
auto_3 = WorkCar(60, 'Грязно-зеленый', 'WorkCar', False)
auto_4 = PoliceCar(100, 'Черно-белый', 'PoliceCar', True)
print(f'{auto_1.color} {auto_1.go()}')
print(f'{auto_2.color} {auto_2.stop()}')
print(auto_2.go())
print(auto_3.show_speed())
print(auto_1.show_speed())
print(auto_4.show_speed())
print(f'{auto_1.name} это полицейская машина? {auto_1.is_police}')
print(f'{auto_4.name} это полицейская машина? {auto_4.is_police}')
print(auto_4.turn())
print(auto_1.turn())
|
19437a541821e6b893c612d28f179e3520b8f1ee | victorbrobles/X-Serv-Python-Multiplica | /tabla_multiplicar.py | 221 | 3.8125 | 4 |
for num_tabla in range(1,11):
print ("Tabla del " + str(num_tabla))
print ("--------")
for nums in range(1,11):
resultado= num_tabla * nums
print(str(num_tabla) + " por " + str(nums) + " es " + str(resultado))
|
4beae9ed096251504ec1bebe92c5a84b2ea4801f | rajshrivastava/LeetCode | /src/1352. Product of the Last K Numbers.py | 576 | 3.765625 | 4 | class ProductOfNumbers:
def __init__(self):
self.arr = [1]
self.i = 0
def add(self, num: int) -> None:
if num == 0:
self.arr = [1]
self.i = 0
else:
self.arr.append(self.arr[-1]*num)
self.i += 1
def getProduct(self, k: int) -> int:
if k > self.i:
return 0
return self.arr[-1]//self.arr[-k-1]
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
|
fc1ddd3671ca163faf75ec665e44ade78ab57c9f | UsacDmitriy/first | /base_types/string_props.py | 405 | 3.65625 | 4 | # Immutable
first_name = 'Jake'
print(first_name[1])
# first_name[2] = 'b'
first_two_letters = first_name[:2]
print(first_two_letters)
last_letter = first_name[-1:]
print(last_letter)
#Concatenble
new_first_name = first_two_letters + 'n' + last_letter
print(new_first_name)
print(new_first_name.upper())
print(new_first_name.lower())
long_string = 'This is a long string'
print(long_string.split(';')) |
fc24e1e31525879abd9c34a3d9bb7939e0aade57 | placeforyiming/Introduction-to-Algorithms-3rdEdition | /sorting/quicksort/quick_sort.py | 712 | 3.65625 | 4 | # <<Introduction To Algorithms (3rd)>> p170 ~ p173
def quick_sort(input_list):
def partition(input_list,p,r):
# p start from 1 instead of 0, r end with len(list) instead of len(list)-1
x=input_list[r-1]
i=p-2
for j in range(p-1,r):
if input_list[j]<=x:
#print (input_list[j])
i=i+1
temp=input_list[i]
input_list[i]=input_list[j]
input_list[j]=temp
temp=input_list[r-1]
input_list[r-1]=input_list[i+1]
input_list[i+1]=temp
return i+2
def quick_sort_recursion(input_list,p,r):
if p<r:
q=partition(input_list,p,r)
quick_sort_recursion(input_list,p,q-2)
quick_sort_recursion(input_list,q,r)
quick_sort_recursion(input_list,1,len(input_list))
return input_list |
6ca43b44111d398e0394ce03559240f0e52c9c24 | uwcalgo/sessions | /3/easy/theBulmad/ImplentingVigenereCipher.py | 1,651 | 3.953125 | 4 | #Implementing the Vigenere Cipher
#Bulmad
#2015-05-09
#pt = plaintext
#k = key
#ct = ciphertext
#key_exp = key expanding to the length of pt
def encrypt(pt,k):
alpha_rotor = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ct = ""
key_exp = ""
#expanding the key so that it can be plaintext length
i = 0
r = 0
while(i < len(pt)):
key_exp = key_exp + k[r]
if(r == len(k) - 1):
r = 0
else:
r = r + 1
i = i + 1
#generating the cipheredtext
j = 0
while(j < len(pt)):
letter = alpha_rotor.find(pt[j].upper()) + alpha_rotor.find(key_exp[j].upper())
if(letter > 25):
letter = letter - 26
else:
pass
ct = ct + alpha_rotor[letter]
j = j + 1
return ct
def decrypt(ct,k):
alpha_rotor = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
pt = ""
key_exp = ""
#expanding the key so that it can be plaintext length
i = 0
r = 0
while(i < len(ct)):
key_exp = key_exp + k[r]
if(r == len(k) - 1):
r = 0
else:
r = r + 1
i = i + 1
#generating the cipheredtext
j = 0
while(j < len(ct)):
letter = alpha_rotor.find(ct[j].upper()) - alpha_rotor.find(key_exp[j].upper())
if(letter < 0):
letter = letter + 26
else:
pass
pt = pt + alpha_rotor[letter]
j = j + 1
return pt
plaintext = input("Plaintext : ")
key = input("Key : ")
print(encrypt(plaintext,key))
cryptedtext = input("Cryptedtext : ")
key = input("Key : ")
print(decrypt(cryptedtext,key))
|
701211eb844491ea1bb239522956c91100679740 | nishtha-rokde/DSA | /32.py | 190 | 3.890625 | 4 | def subset(arr1,arr2):
for i in arr2:
if i not in arr1:
return False
return True
ar1 = [11, 1, 13, 21, 3, 7]
ar2 = [11, 3, 7, 1]
res = subset(ar1,ar2)
print(res) |
ef1d7c1bf3266f236587c46fb1fa06b9ef99e743 | MiekoHayasaka/Python_Training | /day0203/globaltest.py | 149 | 3.5625 | 4 | name='松田'
def change_name():
global name
name='浅木'
def hello():
print('こんにちは'+name+'さん')
change_name()
hello()
|
9788d9129e1e693b210b247c3e53e93ffcd08f1f | leetcode-notes/daily-algorithms-practice | /leetcode/1315_sum_of_nodes_even_valued_grandparent.py | 1,059 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def sumEvenGrandparent(self, root) -> int:
p, gp = None, None
queue = deque([(root, p, gp)])
total = 0
while queue:
qlength = len(queue)
for _ in range(qlength):
cur, p, gp = queue.popleft()
if gp is not None:
if gp % 2 == 0:
total += cur.val
if cur.left:
queue.append((cur.left, cur.val, p))
if cur.right:
queue.append((cur.right, cur.val, p))
return total
'''
Success
Details
Runtime: 124 ms, faster than 40.13% of Python3
Memory Usage: 17.3 MB, less than 24.36% of Python3
Next challenges:
Sum Root to Leaf Numbers
Minimum Distance Between BST Nodes
Smallest Subtree with all the Deepest Nodes
'''
|
6d388e72573684d850754107429bcd9e2963691f | mic0ud/Leetcode-py3 | /src/991.broken-calculator.py | 2,027 | 3.71875 | 4 | #
# @lc app=leetcode id=991 lang=python3
#
# [991] Broken Calculator
#
# https://leetcode.com/problems/broken-calculator/description/
#
# algorithms
# Medium (42.58%)
# Likes: 262
# Dislikes: 61
# Total Accepted: 12.3K
# Total Submissions: 28K
# Testcase Example: '2\n3'
#
# On a broken calculator that has a number showing on its display, we can
# perform two operations:
# Double: Multiply the number on the display by 2, or;
# Decrement: Subtract 1 from the number on the display.
# Initially, the calculator is displaying the number X.
#
# Return the minimum number of operations needed to display the number Y.
# Example 1:
# Input: X = 2, Y = 3
# Output: 2
# Explanation: Use double operation and then decrement operation {2 -> 4 ->
# 3}.
# Example 2:
# Input: X = 5, Y = 8
# Output: 2
# Explanation: Use decrement and then double {5 -> 4 -> 8}.
# Example 3:
# Input: X = 3, Y = 10
# Output: 3
# Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
# Example 4:
# Input: X = 1024, Y = 1
# Output: 1023
# Explanation: Use decrement operations 1023 times.
# Note:
# 1 <= X <= 10^9
# 1 <= Y <= 10^9
#
#
# @lc code=start
class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
if X >= Y:
return X - Y
else:
if Y % 2 == 0:
return self.brokenCalc(X, Y//2) + 1
else:
return self.brokenCalc(X, Y//2+1) + 2
def brokenCalc_SLOW(self, X: int, Y: int) -> int:
if X >= Y:
return X - Y
def search(target):
if target <= X:
return X - target
if target == 2*X:
return 1
else:
if target % 2 == 0:
return min(search(target//2)+1, search(target//2+1)+3)
else:
return search(target//2+1)+2
res = search(Y)
return res
# @lc code=end
if __name__ == '__main__':
s = Solution()
s.brokenCalc(1,100000000)
|
b8e1ae9fd3a0148fa2f2aaffc4ce4d603ddb5d9b | AFRothwell/Initial-Commit | /Class Exercises/15.06/csv_example.py | 1,161 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 15 11:36:28 2021
@author: Andrew Rothwell
"""
import csv
def transform_user_details(csv_file_name):
new_user_data = []
with open(csv_file_name, newline='\n') as csvfile:
user_details_csv = csv.reader(csvfile, delimiter = ",")
for user in user_details_csv:
transformation = []
transformation.append(user[1])
transformation.append(user[2])
transformation.append(user[-1])
new_user_data.append(transformation)
return new_user_data
print(transform_user_details("user_details.csv")[1:])
def create_new_user_data_csv(old_user_data_file = "user_details.csv", new_file_name = 'new_user_data.csv'):
new_user_data = transform_user_details(old_user_data_file)
new_file = open(new_file_name, 'w')
with new_file:
csv_writer = csv.writer(new_file)
csv_writer.writerows(new_user_data)
create_new_user_data_csv()
# counter = 0
# for i in tranform_user_details("user_details.csv"):
# counter += 1
# if counter > 1:
# print(i[1])
# else:
# continue |
b80264fcc2e1bc45a9cc1412ca3711ed02229e3c | ax-shay/telemarketing_effect | /model.py | 2,379 | 3.5 | 4 | import streamlit as st
import matplotlib.pyplot as plt
from PIL import Image
# Data Processing
import pandas as pd
image1 = Image.open('images/Feature_Imp.JPG')
st.set_option('deprecation.showPyplotGlobalUse', False)
template_dict = {'Decision Tree': 0, 'Logistic Regression': 1, 'Random Forest': 2, 'XGBoost': 3}
inputs = {}
data = {'Model': ['Random Forest', 'Random Forest', 'Random Forest', 'Random Forest',
'Decision Tree', 'Decision Tree', 'Decision Tree', 'Decision Tree',
'Logistic Regression', 'Logistic Regression', 'Logistic Regression', 'Logistic Regression',
'XGBoost', 'XGBoost', 'XGBoost', 'XGBoost'],
'Metric': ['Accuracy', 'Precision', 'Recall', 'F1',
'Accuracy', 'Precision', 'Recall', 'F1',
'Accuracy', 'Precision', 'Recall', 'F1',
'Accuracy', 'Precision', 'Recall', 'F1'],
'Score': [93.1, 89.9, 96.9, 93.3,
91.2, 87.3, 96.1, 91.5,
73.1, 74.8, 68.3,71.4,
76.1, 82.4, 65.6, 73.0]
}
df = pd.DataFrame(data, columns=['Model', 'Metric', 'Score'])
def write(state):
st.title('Model')
st.markdown('This section provides the ability to select different models and analyze the importance of different features.')
col1, col2 = st.beta_columns(2)
with col1:
inputs["model1"] = st.selectbox(
"select Model-1", list(template_dict.keys())
)
# if inputs["model1"] == 'Decision Tree':
df1 = df.loc[df['Model'] == inputs["model1"]]
df1.plot.barh(x='Metric', y='Score', title=inputs["model1"], color='green')
st.pyplot()
if inputs["model1"] == 'Random Forest':
st.image(image1)
with col2:
inputs["model2"] = st.selectbox(
"select Model-2", list(template_dict.keys())
)
df2 = df.loc[df['Model'] == inputs["model2"]]
df2.plot.barh(x='Metric', y='Score', title=inputs["model2"], color='blue')
st.pyplot()
if inputs["model2"] == 'Random Forest':
st.image(image1)
st.write('')
sp1, new_row, sp2 = st.beta_columns((0.1, 1, 0.1))
df_disp = pd.pivot_table(df, values='Score', index=['Model'], columns='Metric').reset_index()
with new_row:
st.header("**Data**")
st.dataframe(df_disp)
|
5c04d73d9bb9b8a2a53edd3653dbc01a64c231a6 | CJP-12/CMPT-120L-910-20F | /Assignments/Assignment 9/Assignment 9.py | 221 | 3.515625 | 4 | from calculator import Calculator
calc= Calculator()
print(calc.addition(1,2))
print(calc.subtraction(1,2))
print(calc.multiplication(1,2))
print(calc.division(2,1))
print(calc.exponent(1,3))
print(calc.square_root(4))
|
ecd0cef386be1599776170efd8d879c543b5c870 | VitorDominguesR/ufabc_materias | /get_materias_planejadas.py | 1,423 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import PyPDF2
import re
class returMaterias():
def __init__(self, path_pdf_file):
self.pdf_file = path_pdf_file
#write a for-loop to open many files -- leave a comment if you'd #like to learn how
#filename = 'matricula_disciplinas_2019.2_turmas_planejadas.pdf'
#open allows you to read the file
def get_materias(self):
pdfFileObj = open(self.pdf_file,'rb')
#The pdfReader variable is a readable object that will be parsed
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
#discerning the number of pages will allow us to parse through all #the pages
num_pages = pdfReader.numPages
count = 0
text = ""
#The while loop will read each page
while count < num_pages:
pageObj = pdfReader.getPage(count)
count +=1
text += pageObj.extractText()
#This if statement exists to check if the above library returned #words. It's done because PyPDF2 cannot read scanned files.
#if text != "":
#print(text)
splitted = re.split('((?:\w|\d){6,}-(?:\w|\d){3,})', text)
dict_materias = {}
for x in range(1, len(splitted)-1, 2):
dict_materias[splitted[x]] = splitted[x+1]
for key, value in dict_materias.items():
dict_materias[key] = value.replace('\n', ' ')
return dict_materias
|
de89460e0df4c4741d16834cc07e64a49bd43388 | nehpets0701/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/12-roman_to_int.py | 502 | 3.703125 | 4 | #!/usr/bin/python3
def roman_to_int(roman_string):
if roman_string is None or type(roman_string) != str or roman_string == "":
return 0
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
number = 0
for x in range(0, len(roman_string)):
if x != len(roman_string) - 1:
if roman[roman_string[x + 1]] > roman[roman_string[x]]:
number -= roman[roman_string[x]] * 2
number += roman[roman_string[x]]
return number
|
8dea39275cf3bd5ee30c7149bb917b22b5a09f04 | ywhitecat/4hoursfreecodecampyoutubeEN | /tuplesandef.py | 819 | 4.125 | 4 | #tuple is very similar to a list, a structure to store information, but with a difference
# tuple is immutable, you cannot change it, add or remove elements
#a tuple is a permanent list
coordinates = (4,5)
# index positon 0,1
print(coordinates[0:])
name = input("enter your name ")
age = input("enter your age ")
#fUNCTIONS
#you can add some paramenter inside of the function
def say_hi(name, age): # give a function a name, :(colon) means all the code after this sign its going to the inside of the function
#inside of the funtion space
print("Hello " + name)
print("you're " + age + " years old")
#outside of the function space
def cube(num):
return num*num*num
#now we have to call it
#print("top")
say_hi(name,age)
#print("bottom")
print(cube(3))
|
54cb3667e2044e82833e245928cc2467cef258b1 | KATO-Hiro/AtCoder | /AtCoder_Virtual_Contest/macle_20220602/a/main.py | 962 | 4.125 | 4 | # -*- coding: utf-8 -*-
def convert_decimal_to_n_ary_number(n: int, m_ary_number: int = 2) -> int:
'''Represents conversion from decimal number to n-ary number.
Args:
n: Input number (greater than 1).
m_ary_number: m-ary number (from 2 to 10).
Returns:
values of m-ary number.
Landau notation: O(log n)
'''
if n < m_ary_number:
return n
ans = ''
while n >= m_ary_number:
p, q = divmod(n, m_ary_number)
n = p
ans += str(q)
if n < m_ary_number:
ans += str(p)
return int(ans[::-1])
def main():
import sys
input = sys.stdin.readline
n = int(input())
matched = set()
ans = 0
for i in range(1, n + 1):
if '7' in str(i):
pass
elif '7' in str(convert_decimal_to_n_ary_number(i, 8)):
pass
else:
ans += 1
print(ans)
if __name__ == "__main__":
main()
|
593806eebb5f952abbd02ed92c4d67acfdd2843f | alexknight/mocktest | /mocktest.py | 996 | 3.5 | 4 | class Order(object):
_orderItem="None"
_orderAmount=0
_orderFilled=-1
def __init__(self,argItem,argAmount):
print "Order:__init__"
if (isinstance(argItem,str)):
if (len(argItem)>0):
self._orderItem=argItem
if (argAmount>0):
self._orderAmount=argAmount
def __repr__(self):
locOrder={'item':self._orderItem,'amount':self._orderAmount}
return repr(locOrder)
def fill(self,argSrc):
print "Order:fill_"
try:
if(argSrc is not None):
if(argSrc.hasInventory(self._orderItem)):
locCount=argSrc.getInventory(self._orderItem,self._orderAmount)
self._orderFilled=locCount
else:
print "Inventory item not available"
else:
print "Warehouse not available"
except TypeError:
print "Invalid warehouse."
def isFilled(self):
print "Order:isFilled_"
return (self._orderAmount==self._orderFilled)
if __name__=='__main__':
testOrder=Order("mushrooms",10)
print repr(testOrder)
self.assertEqual(testName,"mushrooms","Invalid item name") |
a3731042a5cbc0afbbd91b3077019f59a86e1dde | AdamZhouSE/pythonHomework | /Code/CodeRecords/2850/60721/292315.py | 327 | 3.5 | 4 | n=int(input())
s=input()
if(n==5):
print(4)
elif(s=="1 1 0 1 0 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 0 1 0 0 1 1 0 1 1 1 1 0 1 0 1 0"):
print(25)
elif(n==7):
print(6)
elif(n==25):
print(17)
elif(n==27):
print(19)
elif(n==55):
print(34)
elif(n==70):
print(42)
elif(n==35):
print(22)
else:print(4)
|
8174e8d08724ad0a2732d15cdbeeb59755921eb1 | Vjoglekar/programs | /iterrableexp.py | 71 | 3.859375 | 4 | L=[1,2,3,4,5]
it=iter(L)
for i in range(0,len(L)):
print(next(it))
|
08d33564de0f0979905f88e9b50fe34f4b09dba9 | Rohan506/Intership-Task1 | /10th Question.py | 391 | 4.125 | 4 | #Write a Pandas program to check the number of rows and columns and drop
# those row if 'any' values are missing in a row of diamonds DataFrame.
import pandas as pd
data = pd.read_csv("D:\Study\Intern\diamonds.csv")
print("Original Datafrrame")
print("Number of rows and column")
print(data.shape)
print("After dropping rows where values are missing")
print(data.dropna(how='any').shape)
|
2ccd9c6d0aca9793560a1a63237a3bd6a5269f2d | jmseb3/bakjoon | /Prgrammers/lv2/JadenCase 문자열 만들기.py | 368 | 3.59375 | 4 | def solution(s:str):
s = s.lower()
ans=''
for idx in range(len(s)):
if idx ==0:
if s[idx].isalpha():
ans +=s[0].upper()
else:
ans+= s[0]
continue
if s[idx].isalpha() and s[idx-1]==' ':
ans +=s[idx].upper()
else:
ans+=s[idx]
return ans |
b104cd43a163cb1b3e8355b1f1b51aa6e1573223 | MandeepLamba/Python | /r_password.py | 671 | 3.734375 | 4 | symbols=['!', '@', '#', '$', '%', '&', '*']
def get(i):
count2=count1=0
temp1=[]
temp2=[]
if len(i)>=7:
for j in symbols:
if j in i:
if j not in temp1:
temp1.append(j)
count1+=1
if count1>=2:
for x in nums:
if x in i:
if x not in temp2:
temp2.append(x)
count2+=1
if count2>=2:
return "Strong"
else:
return "Weak"
else:
return "Weak"
print(get(str(input("Enter Your Password: ")))) |
a14df6970c8f42d5356ad24729bf45c476965d51 | nishesh19/CTCI | /Arrays and Strings/wordladder.py | 1,758 | 3.609375 | 4 | from collections import defaultdict
import math
class Trie:
def __init__(self):
self.trie = self._trie()
def _trie(self):
return defaultdict(self._trie)
def insert(self, word):
curr = self.trie
for w in word:
curr = curr[w]
curr['word'] = word
def find(self, word):
return self.findOneDiffWord(self.trie, word, False)
def findOneDiffWord(self, curr, word, isOneOff):
if not word:
return 0, None
for i in range(len(word)):
if word[i] not in curr:
if isOneOff:
return math.inf, None
min_hops = math.inf
min_word = None
for c in curr:
curr_steps, curr_word = self.findOneDiffWord(curr[c], word[i+1:], True)
if curr_steps < min_hops:
min_hops = curr_steps
min_word = curr_word
return 1+min_hops, min_word
else:
curr = curr[word[i]]
return 0,curr['word']
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList) -> int:
if endWord not in wordList:
return 0
trie = Trie()
for word in wordList:
trie.insert(word)
curr_word = beginWord
total_steps = 0
while curr_word != endWord:
steps, curr_word = trie.find(curr_word)
if steps == math.inf:
return 0
total_steps += steps
return total_steps
beginWord = "hit"
endWord = "cog"
wordList = ["hot", "dot", "dog", "lot", "log", "cog"]
print(Solution().ladderLength(beginWord, endWord, wordList))
|
51a774bb0b41322fe6c2ade4fcb885ef31efa094 | GhostDovahkiin/Introducao-a-Programacao | /05-Exercício-Aula-5/Lista-2/1.py | 155 | 4.09375 | 4 | numero = float(input("Digite um número:"))
if numero > 0:
res = "Positivo"
elif numero < 0:
res = "Negativo"
else:
res = "Neutro"
print(res)
|
377ce1404f2563cedc68afe227bbc6120f81e71e | robbdunlap/gdppc_exp | /gdppc.py | 2,041 | 3.609375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st
import plotly.express as px
gdp_df = pd.read_csv("data/gdppc_data.csv")
countries = gdp_df.country.unique()
st.title("Comparison of Countries' GDPs per capita")
st.markdown('___')
st.header('')
st.header('Select a date range of interest')
st.sidebar.title('Choose 3 Countries to Compare')
country_1_selected = st.sidebar.selectbox('Select country of interest #1', countries, index=(29))
country_2_selected = st.sidebar.selectbox('Select state of interest #2', countries, index=(70))
country_3_selected = st.sidebar.selectbox('Select state of interest #3', countries, index=(160))
countries_for_comparison = []
countries_for_comparison.append(country_1_selected)
countries_for_comparison.append(country_2_selected)
countries_for_comparison.append(country_3_selected)
subselect_of_gdp = gdp_df[gdp_df['country'].isin(countries_for_comparison)]
countries_for_plotting = subselect_of_gdp.pivot(index='year',columns='country',values='gdppc')
countries_for_plotting = countries_for_plotting.reset_index()
value = st.slider('test', min_value=1000, max_value=2018, value=(1900, 2018), step=100)
for_plotting = countries_for_plotting[(countries_for_plotting['year'] >= value[0]) & (countries_for_plotting['year'] <= value[1])]
# Chart title and legends
x_axis_title = 'Date'
y_axis_title = 'GDP per capita'
# State 1 Chart
fig1 = px.line(for_plotting,
x="year",
y=[country_1_selected, country_2_selected, country_3_selected],
labels={"variable":"Countries"},
title = f"<b>GDP per capita for {country_1_selected}, {country_2_selected}, and {country_3_selected}</b>")
fig1.update_yaxes(title_text=y_axis_title)
fig1.update_xaxes(showgrid=True, title_text=x_axis_title)
#fig1.update_traces(hovertemplate=None, hoverinfo='skip')
st.plotly_chart(fig1, use_container_width=True)
st.header('Tabular version of the above data')
st.markdown('Sort the data by clicking on colunn headers')
st.dataframe(for_plotting) |
d2a494021c939118ff1075089c315b44bfa39fb8 | clzendejas/HackerRank_Algos | /Warmup/PlusMinus.py | 850 | 4.1875 | 4 | #!/bin/python3
""" Plus Minus:
Given an array of integers, calculate which fraction of the elements
are positive, negative, and zeroes, respectively. Print the decimal
value of each fraction
Inputs:
- line 1:: N the size of the array
- line 2:: a space-separated list of integers describing the array
Outputs:
- Print each value on its own line with the following order:
- line 1: positive percentage
- line 2: negative percentage
- line 3: zeroes percentage
"""
# Input Line 1 (N)
n = int(input())
# Input Line 2, an N number space delimited array
arr = map(int, input().strip().split(' '))
positive = 0
negative = 0
zero = 0
for i in arr:
if i > 0:
positive += 1
elif i < 0:
negative += 1
elif i == 0:
zero += 1
print(positive/n)
print(negative/n)
print(zero/n) |
067ec3d4adde34beba127600872d3c4c3ac17e96 | Afsarsoft/python | /06_04_tuple.py | 2,590 | 3.75 | 4 | # pyright: strict
from typing import List, Tuple, Any
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Tuples are comparable, comprasion is from left to right
# x: List[Union[int, str]] = [3, 5, "test", "fun"]
# https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
stuff1: List[Tuple[int, int, int]] = [
(0, 1, 2), (5, 1, 2),
(0, 4, 20000), (0, 3, 4)
]
target: int = len(stuff1)
count: int = 0
while count <= target - 1:
if stuff1[count] < stuff1[count+1]:
print(f'{stuff1[count]} < {stuff1[count+1]}')
elif stuff1[count] > stuff1[count+1]:
print(f'{stuff1[count]} > {stuff1[count+1]}')
elif stuff1[count] == stuff1[count+1]:
print(f'{stuff1[count]} = {stuff1[count+1]}')
else:
print('Something went wrong!')
count += 2
print(target)
print(count)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
stuff2: List[Tuple[str, str]] = [
('Jones', 'Sally'), ('Jones', 'Sam'),
('Jones', 'Sally'), ('Adams', 'Sam'),
('Surush', 'Sally'), ('Jack', 'Alice'),
('Aiden', 'Mark'), ('Hellen', 'Steve')
]
target: int = len(stuff2)
count: int = 0
while count <= target - 1:
if stuff2[count] < stuff2[count+1]:
print(f'{stuff2[count]} < {stuff2[count+1]}')
elif stuff2[count] > stuff2[count+1]:
print(f'{stuff2[count]} > {stuff2[count+1]}')
elif stuff2[count] == stuff2[count+1]:
print(f'{stuff2[count]} = {stuff2[count+1]}')
else:
print('Something went wrong!')
count += 2
print(target)
print(count)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Don't combine disparate types in a single list.
# Doing so is not very type friendly.
# Most typed languages wouldn't even allow you to do this.
# If you require the more dynamic behavior,
# specify a type of 'List[Any]' for your list.
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
stuff3: List[Any] = [
(0, 1, 2), (5, 1, 2),
(0, 4, 20000), (0, 3, 4),
('Jones', 'Sally'), ('Jones', 'Sam'),
('Jones', 'Sally'), ('Adams', 'Sam'),
]
target: int = len(stuff3)
count: int = 0
while count <= target - 1:
if stuff3[count] < stuff3[count+1]:
print(f'{stuff3[count]} < {stuff3[count+1]}')
elif stuff3[count] > stuff3[count+1]:
print(f'{stuff3[count]} > {stuff3[count+1]}')
elif stuff3[count] == stuff3[count+1]:
print(f'{stuff3[count]} = {stuff3[count+1]}')
else:
print('Something went wrong!')
count += 2
print(target)
print(count)
|
07a6b286101619fc4295782f2e8278a4a68f155e | dobrienSTJ/Daniels-Projects | /%.py | 220 | 3.9375 | 4 | number1=int(input("Please enter the number you would like to find the percentage of"))
number2=int(input("Now enter the percentage, e.g. 50%"))
answer=(number1/100)
answer=(answer*number2)
print(answer)
|
940b42f5dcdb15f93a9fb30f41f7ffeb0b0bd8b5 | xiangcao/Leetcode | /python_leetcode_2020/Python_Leetcode_2020/155_min_stack.py | 3,166 | 4.03125 | 4 | """
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Constraints:
Methods pop, top and getMin operations will always be called on non-empty stacks.
"""
Method 1: Stack of Value/Minimum Pairs
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
curMin = self.getMin()
if curMin is None or curMin > x:
curMin = x
self.stack.append((x, curMin))
def pop(self):
"""
:rtype: None
"""
if self.stack:
return self.stack.pop()
def top(self):
"""
:rtype: int
"""
if self.stack:
return self.stack[-1][0]
def getMin(self):
"""
:rtype: int
"""
if self.stack:
return self.stack[-1][1]
Approach 2: Two stacks
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.min_stack or x <= self.min_stack[-1]:
self.min_stack.append(x)
def pop(self) -> None:
if self.min_stack[-1] == self.stack[-1]:
self.min_stack.pop()
self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
Approach 3: Two stacks improved version
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, x: int) -> None:
# We always put the number onto the main stack.
self.stack.append(x)
# If the min stack is empty, or this number is smaller than
# the top of the min stack, put it on with a count of 1.
if not self.min_stack or x < self.min_stack[-1][0]:
self.min_stack.append([x, 1])
# Else if this number is equal to what's currently at the top
# of the min stack, then increment the count at the top by 1.
elif x == self.min_stack[-1][0]:
self.min_stack[-1][1] += 1
def pop(self) -> None:
# If the top of min stack is the same as the top of stack
# then we need to decrement the count at the top by 1.
if self.min_stack[-1][0] == self.stack[-1]:
self.min_stack[-1][1] -= 1
# If the count at the top of min stack is now 0, then remove
# that value as we're done with it.
if self.min_stack[-1][1] == 0:
self.min_stack.pop()
# And like before, pop the top of the main stack.
self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1][0]
|
c4cc30347da09c4d4cd8d3bc4f868f35fd80d1f0 | armwal/McsPyDataTools | /HDF5PyExamples/h5ex_shuffle.py | 4,250 | 4.125 | 4 | """
This example shows how to read and write data to a dataset using
the shuffle filter with gzip compression. The program first checks
if the shuffle and gzip filters are available, then if they are it
writes integers to a dataset using shuffle+gzip, then closes the
file. Next, it reopens the file, reads back the data, and outputs
the types of filters and the maximum value in the dataset to the
screen.
Tested with:
Fedora 18:
HDF5 1.8.9, Python 2.7.3, Numpy 1.7.1, h5py 2.1.3
Fedora 18:
HDF5 1.8.9, Python 3.3.0, Numpy 1.7.1, h5py 2.1.3
Mac OS X 10.6.8:
HDF5 1.8.10, Python 3.2.5, Numpy 1.7.1, h5py 2.1.3
"""
import sys
import numpy as np
import h5py
FILE = "h5ex_d_shuffle.h5"
DATASET = "DS1"
# Strings are handled very differently between python2 and python3.
if sys.hexversion >= 0x03000000:
FILE = FILE.encode()
DATASET = DATASET.encode()
DIM0 = 32
DIM1 = 64
CHUNK0 = 4
CHUNK1 = 8
def run():
# Check if gzip compression is available and can be used for
# both compression and decompression. Normally we do not perform
# error checking in these examples for the sake of clarity, but
# in this case we will make an exception because this filter is
# an optional part of the hdf5 library.
if not h5py.h5z.filter_avail(h5py.h5z.FILTER_DEFLATE):
raise RuntimeError("Gzip filter not available.")
filter_info = h5py.h5z.get_filter_info(h5py.h5z.FILTER_DEFLATE)
if ((filter_info & h5py.h5z.FILTER_CONFIG_ENCODE_ENABLED) &
(filter_info & h5py.h5z.FILTER_CONFIG_DECODE_ENABLED)):
msg = "Gzip filter not available for encoding and decoding."
raise RuntimeError(msg)
# Similarly, check for availability of the shuffle filter.
if not h5py.h5z.filter_avail(h5py.h5z.FILTER_SHUFFLE):
raise RuntimeError("Shuffle filter not available.")
filter_info = h5py.h5z.get_filter_info(h5py.h5z.FILTER_SHUFFLE)
if ((filter_info & h5py.h5z.FILTER_CONFIG_ENCODE_ENABLED) &
(filter_info & h5py.h5z.FILTER_CONFIG_DECODE_ENABLED)):
msg = "Shuffle filter not available for encoding and decoding."
raise RuntimeError(msg)
# Initialize the data.
wdata = np.zeros((DIM0, DIM1), dtype=np.int32)
for i in range(DIM0):
for j in range(DIM1):
wdata[i][j] = i * j - j
# Create a new file using the default properties.
fid = h5py.h5f.create(FILE)
# Create the dataspace. No maximum size parameter needed.
dims = (DIM0, DIM1)
space_id = h5py.h5s.create_simple(dims)
# Create the dataset creation property list, add the fletcher32 filter
# and set a chunk size.
dcpl = h5py.h5p.create(h5py.h5p.DATASET_CREATE)
dcpl.set_shuffle()
dcpl.set_deflate(9)
chunk = (CHUNK0, CHUNK1)
dcpl.set_chunk(chunk)
# Create the datasets using the dataset creation property list.
dset = h5py.h5d.create(fid, DATASET, h5py.h5t.STD_I32LE, space_id, dcpl)
# Write the data to the dataset.
dset.write(h5py.h5s.ALL, h5py.h5s.ALL, wdata)
# Close and release resources.
del dcpl
del dset
del space_id
del fid
# Reopen the file and dataset using default properties.
fid = h5py.h5f.open(FILE)
dset = h5py.h5d.open(fid, DATASET)
dcpl = dset.get_create_plist()
# No NBIT or SCALEOFFSET filter, but there is something new, LZF.
ddict = {h5py.h5z.FILTER_DEFLATE: "DEFLATE",
h5py.h5z.FILTER_SHUFFLE: "SHUFFLE",
h5py.h5z.FILTER_FLETCHER32: "FLETCHER32",
h5py.h5z.FILTER_SZIP: "SZIP",
h5py.h5z.FILTER_LZF: "LZF"}
# Retrieve and print the filter types.
n = dcpl.get_nfilters()
for j in range(n):
filter_type, flags, vals, name = dcpl.get_filter(j)
print("Filter %d: Type is H5Z_%s" % (j, ddict[filter_type]))
rdata = np.zeros((DIM0, DIM1))
dset.read(h5py.h5s.ALL, h5py.h5s.ALL, rdata)
# Verify that the dataset was read correctly.
np.testing.assert_array_equal(rdata, wdata)
print("Maximum value in DS1 is: %d" % rdata.max())
if __name__ == "__main__":
run()
|
c49520fc1c747306b0090b9118f2153ab54778fe | imacleod/code-wars | /python/seconds_to_hms.py | 370 | 3.515625 | 4 |
def hms(seconds):
""" Return time as human-readable string HH:MM:SS """
if not seconds:
return '00:00:00'
else:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return '{:02}:{:02}:{:02}'.format(h, m, s)
if __name__ == "__main__":
assert hms(0) == '00:00:00'
assert hms(359999) == '99:59:59'
print('Finished.')
|
7b58ea1e4e7225c612870f1177bccb1d0f2f9001 | MichielAriens/PENOROOD | /resources/GUI and grid/gridTest.py | 16,348 | 4.03125 | 4 | from tkinter import *
#initiate tinker, tk() acts as a frame
root = Tk()
root.title("team ROOD")
class GUI:
#initiate all components of GUI
#LabelFrame(container, title) = used for containing other GUI components inside a frame/window or other labelframe
#label(container, text) = used for displaying strings
#Canvas(container, width, height, background color, ..) = used for painting images, lines, text etc..
#Entry(container) = editable text entry
#Grid(rows, columns) = an object of the grid class, which represents a field made of triangles
#Text(container, width in characters, height in lines) = widget used for displayed multiple lines of text
#Greendot & Reddot, images for zeppelins
#other images are shapes
def __init__(self, master):
self.labelframe = LabelFrame(master, text="Input&Output")
self.canvas = Canvas(master, bg = "White", width = 500, height = 500)
self.label1 = Label(self.labelframe, text="input 1")
self.label2 = Label(self.labelframe, text="input 2")
self.heightLabel = Label(self.labelframe, text="Height = n.a.")
self.entry1 = Entry(self.labelframe)
self.entry2 = Entry(self.labelframe)
self.grid = GRID(12,13)
self.text = Text(master,width = 50, height = 15)
self.controlFrame = LabelFrame(master, text="Controls")
self.upbutton= Button(self.controlFrame, text="UP", command=self.moveUpWithButton)
self.downbutton= Button(self.controlFrame, text="DOWN", command=self.moveDownWithButton)
self.leftbutton= Button(self.controlFrame, text="LEFT", command=self.moveLeftWithButton)
self.rightbutton= Button(self.controlFrame, text="RIGHT", command=self.moveRightWithButton)
self.greendot = PhotoImage(file="goodzep.gif")
self.reddot = PhotoImage(file="badzep.gif")
self.bh = PhotoImage(file="blauw_hart.gif")
self.glh = PhotoImage(file="geel_hart.gif")
self.grh = PhotoImage(file="groen_hart.gif")
self.rh = PhotoImage(file="rood_hart.gif")
self.wh = PhotoImage(file= "wit_hart.gif")
self.bc = PhotoImage(file="blauwe_cirkel.gif")
self.glc = PhotoImage(file="gele_cirkel.gif")
self.grc = PhotoImage(file="groene_cirkel.gif")
self.rc = PhotoImage(file="rode_cirkel.gif")
self.wc = PhotoImage(file="witte_cirkel.gif")
self.br = PhotoImage(file="blauwe_rechthoek.gif")
self.glr = PhotoImage(file="gele_rechthoek.gif")
self.grr = PhotoImage(file="groene_rechthoek.gif")
self.rr = PhotoImage(file="rode_rechthoek.gif")
self.wr = PhotoImage(file="witte_rechthoek.gif")
self.bs = PhotoImage(file="blauwe_ster.gif")
self.gls = PhotoImage(file="gele_ster.gif")
self.grs = PhotoImage(file="groene_ster.gif")
self.rs = PhotoImage(file="rode_ster.gif")
self.ws = PhotoImage(file="witte_ster.gif")
self.images = (self.bh,self.glh,self.grh,self.rh, self.wh,self.bc,self.glc,self.grc,self.rc,self.wc,self.br,self.glr,self.grr,self.rr,self.wr,self.bs,self.gls,self.grs,self.rs,self.ws)
#Paints a shape on the grid
def paintShape(self, posx, posy, shapeID):
can_width = self.canvas.winfo_reqwidth()
can_height = self.canvas.winfo_reqheight()
position_width = can_width/(self.grid.columns+2)
position_height = can_height/(self.grid.rows+2)
if((posy%2)==1):
paintx = (posx+3/2)*position_width
painty = (posy+1)*position_height
else:
paintx = (posx+1)*position_width
painty = (posy+1)*position_height
if(shapeID < len(self.images)):
self.canvas.create_image(paintx,painty,image=self.images[shapeID])
self.canvas.create_text(paintx+5,painty+30,text="SID =" + str(shapeID), fill = "red")
self.canvas.create_text(paintx+5,painty+40,text="POS = (" + str(posx) +","+ str(posy)+")", fill = "red")
#Paints a zeppelin on the grid
#posx en posy is in cm
def paintZeppelin(self,posx, posy, ZID):
can_width = self.canvas.winfo_reqwidth()
can_height = self.canvas.winfo_reqheight()
position_width = can_width/(self.grid.columns+2)
position_height = can_height/(self.grid.rows+2)
xoffset = position_width
yoffset = position_height
x = (posx / 40) * position_width #
y = (posy / 35) * position_height #
if(ZID == 1): #our zeppelin
self.canvas.create_image(xoffset + x,yoffset + y,image=self.greendot)
self.canvas.create_text(xoffset + x + 5,yoffset + y+30,text="ZID =" + str(ZID), fill = "red")
self.canvas.create_text(xoffset + x + 5,yoffset + y+40,text="POS = (" + str(posx) +","+ str(posy)+")cm", fill = "red")
else:
self.canvas.create_image(xoffset + x,yoffset + y,image=self.reddot)
self.canvas.create_text(xoffset + x + 5,yoffset + y+30,text="ZID =" + str(ZID), fill = "red")
self.canvas.create_text(xoffset + x + 5,yoffset + y+40,text="POS = (" + str(posx) +","+ str(posy)+")cm", fill = "red")
#Draw grid on canvas
def drawGrid(self):
can_width = self.canvas.winfo_reqwidth()
can_height = self.canvas.winfo_reqheight()
position_width = can_width/(self.grid.columns+2)
position_height = can_height/(self.grid.rows+2)
max_horizontal_triangles = self.grid.columns
max_vertical_triangles = self.grid.rows
#horizontal lines
for i in range(max_vertical_triangles):
if((i%2)==0):
self.canvas.create_line(position_width,position_height*(i+1),can_width-position_width*2,position_height*(i+1))
else:
self.canvas.create_line(position_width*(3/2),position_height*(i+1),can_width-position_width*(3/2),position_height*(i+1))
#diagonal lines
for j in range(max_vertical_triangles-1):
if((j%2)==0):
for i in range(max_horizontal_triangles*2-1):
if((i%2)==0):
self.canvas.create_line(position_width+position_width*i/2, position_height+position_height*j,position_width+position_width*(1/2)+position_width*i/2,2*position_height+position_height*j)
else:
self.canvas.create_line((3/2)*position_width+position_width*i/2, position_height+position_height*j,(3/2)*position_width-position_width*(1/2)+position_width*i/2,2*position_height+position_height*j)
else:
for i in range(max_horizontal_triangles*2-1):
if((i%2)==0):
self.canvas.create_line(position_width+position_width*i/2,2*position_height+position_height*j,position_width+position_width*(1/2)+position_width*i/2,position_height+position_height*j)
else:
self.canvas.create_line((3/2)*position_width+position_width*i/2,2*position_height+position_height*j,(3/2)*position_width-position_width*(1/2)+position_width*i/2,position_height+position_height*j)
#requests all zeppelins and refreshes them on canvas
def updateCanvas(self):
self.canvas.delete(ALL)
list = self.grid.getZeppelins()
for i in range(len(list)):
zep = list[i]
position_zep = zep[0]
ZID = zep[1]
self.paintZeppelin(position_zep[0], position_zep[1], ZID)
list_shapes = self.grid.getShapesAndPositions()
print(list_shapes)
for j in range(len(list_shapes)):
shape = list_shapes[j]
position_shape = shape[0]
SID = shape[1]
self.paintShape(position_shape[0], position_shape[1], SID)
self.drawGrid()
self.updateMessage()
print(self.grid.getZeppelins())
#updates the displayed message
def updateMessage(self):
zeps = self.grid.getZeppelins()
message = ""
for i in range(len(zeps)):
zep = zeps[i]
pos = zep[0]
if(zep[1] == 1):
message = message + "\n" + "Our zeppelin at (" + str(pos[0]) + "," + str(pos[1]) + ")"
else:
message = message + "\n" + "Other zeppelin, ID="+ str(zep[1])+ " at ("+ str(pos[0]) + "," + str(pos[1]) + ")"
self.clearMessage()
self.addDisplayedMessage(message)
#set the message in the text-widget
def addDisplayedMessage(self, text):
self.text.insert(INSERT, text)
#clear message
def clearMessage(self):
self.text.delete(1.0, END)
#set the height parameter
def setHeightLabel(self, text):
self.heightLabel.textvariable = text
#keep updating besides running the tkinter mainloop
#update canvas after 1000ms
def task(self):
self.updateCanvas()
root.after(1000,self.task)
def moveUpWithButton(self):
our_zep = self.grid.getZeppelin(1)
x = our_zep[0][0]
y = our_zep[0][1]
self.grid.setZeppelinPosition( x, y+20,1)
def moveDownWithButton(self):
our_zep = self.grid.getZeppelin(1)
x = our_zep[0][0]
y = our_zep[0][1]
self.grid.setZeppelinPosition( x, y-20,1)
def moveLeftWithButton(self):
our_zep = self.grid.getZeppelin(1)
x = our_zep[0][0]
y = our_zep[0][1]
self.grid.setZeppelinPosition( x-20, y,1)
def moveRightWithButton(self):
our_zep = self.grid.getZeppelin(1)
x = our_zep[0][0]
y = our_zep[0][1]
self.grid.setZeppelinPosition( x+20, y,1)
#class that represents the triangular grid
class GRID:
#defines a matrix with y rows and x columns. Each M(x,y) contains a value, this value represents the Shape-ID (SID)
def __init__(self,x,y):
self.table = [ [ 0 for i in range(x) ] for j in range(y) ]
self.rows = y
self.columns = x
self.height_cm = 400
self.width_cm = 400
self.zeplist = []
#set the value of specified position on the grid.
def setValue(self, value, x, y ): #value = zeppelin_ID
self.table[x][y] = value
#print the value of a position (value = shape-ID)
def printPosition(self, x, y):
if(x < self.rows and y < self.columns):
print(self.table[x][y])
else:
print("not a valid position")
#get all shapes and their positions and return them in a list ((x,y),ZID)
def getShapesAndPositions(self):
listy = []
for i in range(self.rows):
for j in range(self.columns):
if(self.table[i][j] > 0):
listy.append(((i,j),self.table[i][j]))
return listy
#return a list of all zeppelins
def getZeppelins(self):
return self.zeplist
#returns the position and SID of a shape: ((x,y),ZID). If the shape can't be found it returns ((-1,-1),-1)
def getShape(self, SID):
for i in range(self.rows):
for j in range(self.columns):
if(SID == self.table[i][j]):
return ((i,j),SID)
else:
return ((-1,-1),-1)
def getZeppelin(self, ZID):
zeps = self.getZeppelins()
for i in range(len(zeps)):
zep = zeps[i]
if(ZID == zep[1]):
return zep
else:
return ((-1,-1),-1)
#add zeppelin x and y in cm
def addZeppelin(self,x,y,ZID):
self.zeplist.append(((x,y),ZID))
#nog afwerken
def calculatePositionFromShapes(self, SID1, SID2, SID3):
self.getShapesAndPositions()
#!!!!!!!!!!!!!!!!!!!! x and y are in cm !!!!!!!!!!!!!!!!!!!
def setZeppelinPosition(self, x, y, ZID):
for i in range (len(self.zeplist)):
zep = self.zeplist[i]
if(zep[1] == ZID):
self.zeplist.remove(zep)
zep1 = ((x,y),ZID)
self.zeplist.append(zep1)
#moves a zeppelin from his old position to a new position(x,y), returns true if this new position doesn't contain another zeppelin
#DEPRECATED
def moveZeppelin(self, ZID, x, y):
if(x < self.rows and y < self.columns):
zeppelin = self.getZeppelin(ZID)
coords = zeppelin[0]
old_x = coords[0]
old_y = coords[1]
self.table[old_x][old_y] = 0
if(self.table[x][y] != 0):
self.table[x][y] = ZID
return True
else:
return False
else:
return False
#check if a position is empty or not
def checkPosition(self, x, y):
if(x < self.rows and y < self.columns):
if(self.table[x][y] != 0):
return False
else:
return True
#!!!!!!!!!!
#NOT TESTED
#(probably not working, yet)
#!!!!!!!!!!
def getPathToPositionForZep(self, x, y, ZID):
if(x < self.rows and y < self.columns):
if(self.checkPosition(x,y)):
zep = self.getZeppelin(ZID)
zep_position = zep[0]
zep_x = zep_position[0]
zep_y = zep_position[1]
current_x = zep_x
current_y = zep_y
queue = []
pos = []
pos.append((current_x,current_y))
queue.append(pos)
while(self.goalReached() == False):
for i in range(len(queue)):
pathinqueue = queue[i]
newpaths = self.createPathsToChild(pathinqueue)
queue.remove(pathinqueue)
for j in range(len(newpaths)):
queue.append(newpaths[j])
j = 0
i = 0
def createPathsToChild(self,pos):
oldpath = pos
lastposition = oldpath[len(pos)-1]
children = self.getChildren(lastposition[0],lastposition[1])
newpaths = []
for i in range(len(children)):
newpath = pos.append(children[i])
newpaths.append(newpath)
return newpaths
def getChildren(self, x, y):
children = []
if(y+1 < self.columns and self.checkPosition(x, y+1) == True):
children.append((x-1,y-1))
if(x+1 < self.rows and self.checkPosition(x+1, y+1) == True):
children.append((x+1,y+1))
if(y-1 > 0 and self.checkPosition(x, y-1) == True):
children.append((x,y-1))
if(x-1 > 0 and self.checkPosition(x-1,y) == True):
children.append((x-1,y))
def goalReached(self,x,y,listy):
for i in range(len(listy)):
path = listy[i]
endpos = path[len(path-1)]
if(endpos[0] == x and endpos[1] == y):
return True
return False
#Initiate GUI
Gui = GUI(root)
#pack() is used for positioning/drawing the widgets on the frame
Gui.canvas.pack(side = LEFT)
Gui.text.pack()
Gui.labelframe.pack(expand="yes")
Gui.controlFrame.pack(expand="yes")
#grid() positions/draws widget in a grid-like-layout
Gui.label1.grid(row = 0, column = 0)
Gui.label2.grid(row = 1, column = 0)
Gui.heightLabel.grid(columnspan = 2)
Gui.entry1.grid(row = 0, column = 1)
Gui.entry2.grid(row = 1, column = 1)
Gui.upbutton.grid(row = 0, column = 1)
Gui.downbutton.grid(row = 2, column = 1)
Gui.leftbutton.grid(row = 1, column = 0)
Gui.rightbutton.grid(row = 1, column = 2)
Gui.grid.addZeppelin(120, 243, 1)
Gui.grid.addZeppelin(200, 200, 2)
Gui.grid.setValue(5, 2, 3)
Gui.grid.setValue(1, 5, 1)
Gui.grid.setValue(7, 0, 1)
Gui.grid.setValue(9, 11,1)
Gui.grid.setValue(17, 0, 0)
Gui.grid.setValue(19, 11,0)
#Set values of positions on the grid
print(Gui.grid.getZeppelins())
Gui.addDisplayedMessage("Nothing to be displayed atm.")
Gui.setHeightLabel("230cm")
Gui.updateCanvas()
#loop that registers action in the frame
#keep calling Gui.task every 1000ms
root.after(1000,Gui.task)
root.mainloop() |
c8572819ae0f103651b5ffcf08f925b3241da0ca | wisera/8-Project-Python | /dice_simulator.py | 1,154 | 3.8125 | 4 | # Dice SIMULATOR
# Simulate a dice, generating a value from 1 to 6
import random
import PySimpleGUI as sg
class DiceSimulator:
def __init__(self):
self.min_value = 1
self.max_value = 6
self.message = "Would like to generate a new value for the dice?"
# layout
self.layout = [
[sg.Text('Roll dice?')],
[sg.Button('yes'),sg.Button('no')]
]
def Start(self):
# create a window
self.window = sg.Window('Dice Simulator',self.layout)
# read values on screen
self.events, self.values = self.window.Read()
# do something w/ values
try:
if self.events == 'yes' or self.events == 'y':
self.GenerateDiceValue()
elif self.events =='no' or self.events == 'n':
print('Thanks for your participation!')
else:
print('Please enter yes or no')
except:
print('Theres an wrror in your answer')
def GenerateDiceValue(self):
print(random.randint(self.min_value, self.max_value))
simulador = DiceSimulator()
simulador.Start() |
36f24ecd173012f1f9f6ff58d820206ec44a7fb8 | PluginCafe/cinema4d_py_sdk_extended | /scripts/02_data_algorithms/maxon_basearray_r20.py | 553 | 3.8125 | 4 | """
Copyright: MAXON Computer GmbH
Author: Maxime Adam
Description:
- Creates a BaseArray of maxon.Int (any maxon type is working).
Class/method highlighted:
- maxon.BaseArray
- BaseArray.Resize()
"""
import maxon
def main():
# Creates a BaseArray of a maxon.Int
intArray = maxon.BaseArray(maxon.Int)
# Resizes the BaseArray
intArray.Resize(10)
# Iterates over the BaseArray and assign values
for i in range(len(intArray)):
intArray[i] = i
print(intArray[i])
if __name__ == "__main__":
main() |
d11bafcc28402819e5860d3288fefda7e9a63443 | galambosd/meta-omics | /make_tab_delimited.py | 1,463 | 4.28125 | 4 | #!/usr/bin/env python
# make a tab-delimited file from standard input or a file
import sys
def read_file(outFileName):
fileName = raw_input("What file do you want to read? ")
inFile = open(fileName, 'r')
lines = inFile.readlines()
inFile.close()
if write:
outFile = open(outFileName,'w')
else:
outFile = open(outFileName, 'a')
delim = raw_input("What is the delimiter (at least press space)?" )
print "Removing whitespace..."
for line in lines:
cols = line.split(delim)
for col in cols[:-1]:
col = col.lstrip().rstrip()
outFile.write(col + '\t')
cols[-1] = cols[-1].lstrip().rstrip()
outFile.write(cols[-1] + '\n')
print "Made a tab-delimited file {0} from {1}.".format(outFileName, fileName)
def read_input(outFileName):
if write:
outFile = open(outFileName,'w')
else:
outFile = open(outFileName, 'a')
delim = raw_input("What is the delimiter (at least press space)? ")
print "Enter data so that each line in stdin corresponds to a line in the outfile:"
line = raw_input()
while ('END' not in line):
cols = line.split(delim)
for col in cols[:-1]:
col = col.lstrip().rstrip()
outFile.write(col + '\t')
cols[-1] = cols[-1].lstrip().rstrip()
outFile.write(cols[-1] + '\n')
line = raw_input()
print "Made a tab-delimited file {0} from keyboard input.".format(outFileName)
write = False
if 'w' in sys.argv[1]:
write = True
if 'in' in sys.argv[2]:
read_input(sys.argv[3])
else:
read_file(sys.argv[3])
|
e309084ea0a914a2d01a36b94dda1d9d2e8d0746 | randor12/DeepFakeDetection | /ExtractionScript.py | 1,493 | 3.53125 | 4 | """
:author: Marcus Tran
:date: February 15th, 2020
:description: Functions to comb through a data set and then extract the features from audio files
in a given data path
Based on Medium Article and Example Code
"""
import pandas as pd
import os
import librosa
import numpy as np
def extract_features(fileName):
try:
audio, sample_rate = librosa.load(fileName, res_type='kaiser_fast')
mfccs = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40)
mfccsscaled = np.mean(mfccs.T, axis=0)
except Exception as error:
print("Error encountered while parsing file: ", fileName)
return None
return mfccsscaled
def create_DataFrame(DataSetPath):
# Set the path for the folder containing the dataset
fulldatasetpath = DataSetPath
metadata = pd.read_json(fulldatasetpath + 'metadata.json', orient='split')
features = []
# Extract features from each sound file
for index, row in metadata.iterrows():
fileName = os.path.join(os.path.abspath(fulldatasetpath),'fold'+
str(row["fold"])+'/',str(row["slice_file_name"]))
class_label = row["class_name"]
data = extract_features(fileName)
features.append([data, class_label])
# Converts the data into a data frame for use
FeatureDataFrame = pd.DataFrame(features, columns=['feature', 'class_label'])
print('Finished extracting from ', len(FeatureDataFrame), ' files')
return FeatureDataFrame
|
ff6f9da8b4a382a88281eb846438819cd569732a | fwparkercode/Programming2_SP2019 | /Notes/ExceptionsA.py | 1,419 | 4.34375 | 4 | # Exceptions (short topic)
try:
val = int(input("Enter a number: "))
except:
print("You entered an invalid number")
# a better way to write it (keep asking until it works)
done = False
while not done:
try:
val = int(input("Enter a number: "))
done = True
except:
print("You entered an invalid number")
# Error Types
# Value Error
try:
int("a") # this line throws a value error
except ValueError:
print("Value Error")
# Divide by zero
try:
val = 3 / 0 # this produces a dived by zero error
except ZeroDivisionError:
print("ZeroDivisionError")
# Input Output error
try:
my_file = open("my_file.txt") # produces FileNOtFoundError
except FileNotFoundError:
print("File not found")
# Catch multiple errors
try:
#y = 10 / 0
int("A")
except Exception as e:
print("Exception caught")
print(e)
# Make an MPG calculator
done = False
while not done:
try:
miles = float(input("Miles traveled: "))
gallons = float(input("Gallons used: "))
done = True
except:
print("You entered an invalid number.")
try:
print("Your MPG: {:.2f}".format(miles / gallons))
except:
print("Your MPG is infinite.")
# finally (always runs regardless of error or not)
try:
my_file = open('my_file.txt', 'w')
f = my_file.write("Hi")
except NameError:
print("I/O error")
finally:
my_file.close()
|
b7b2738a9e54a63f02b6428b4f25ff98b36f3d82 | etsang647/covid-19-map | /server/get_data_nyt.py | 1,259 | 3.578125 | 4 | from urllib.request import urlopen
from contextlib import closing
from io import StringIO
from collections import defaultdict
import csv
import json
# NYT GitHub repo link
DATA_URL = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv'
# reads CSV data from DATA_URL and returns it as a nicely formatted dict
def get_data_nyt():
with closing(urlopen(DATA_URL)) as csv_file:
# make csv_file more workable
data = csv_file.read().decode('ascii', 'ignore')
data_file = StringIO(data)
dict_reader = csv.DictReader(data_file)
# initialize empty nested dicts for later formatting
dates_object = defaultdict(dict)
# format data according to this structure:
#
# "2020-03-30": {
# "Washington": {
# "cases": 100,
# "deaths": 10
# },
# "New York": {
# "cases": 200,
# "deaths": 20
# },
# },
# "2020-03-31": { ... }
#
for row in dict_reader:
date = row['date']
name = row['state']
cases = row['cases']
deaths = row['deaths']
state_object = {'cases': int(cases), 'deaths': int(deaths)}
dates_object[date][name] = state_object
return dates_object
if __name__ == "__main__":
get_data_nyt()
|
7dae3d9e84df7e1ac2d0773ad7e88786e9a59e62 | Theman49/tic-tac-toe-game-python | /tictactoe_p1_vs_com.py | 4,891 | 3.625 | 4 | import random # module untuk menggunakan random()
#inisiasi variable yang dibutuhkan
total = 4 # jumlah berapa kali pemain mendapatkan giliran main
totalPlay = 0 # inisisasi awal saat player1 main
scoreP1 = 0 # score awal player1
scoreP2 = 0 # score awal player2
# player
player = {
1 : 'X',
2 : 'O'
}
# board
board = [
['top1','top2','top3'],
['mid1','mid2','mid3'],
['btm1','btm2','btm3']
]
boardProgress = [
['_','_','_'],
['_','_','_'],
['_','_','_']
]
def get_random_pos(a):
n = 0
while n < 1:
random1 = random.randint(0,2)
random2 = random.randint(0,2) # fungsi untuk mengambil bilangan acak untuk menentukan
pos = board[random1][random2]
cek = boardProgress[random1][random2] # baris dan kolom berapa yang belum terisi 'x' atau 'o'
if cek != 'X' and cek != 'O': # jika != 'x' dan != 'o' maka akan diisikan sesuai bagian pemain
boardProgress[random1][random2] = player[a] # jika sudah terisi, maka akan mencari sampai ada tempat yang kosong
n+=1
print(pos + " -> " + player[a])
def user():
n = 0
while n < 1:
row = int(input("row : "))
col = int(input("col : ")) # fungsi untuk mengambil bilangan acak untuk menentukan
row-=1
col-=1
pos = board[row][col] # baris dan kolom berapa yang belum terisi 'x' atau 'o'
cek = boardProgress[row][col] # baris dan kolom berapa yang belum terisi 'x' atau 'o'
if cek != 'X' and cek != 'O': # jika != 'x' dan != 'o' maka akan diisikan sesuai bagian pemain
boardProgress[row][col] = player[1] # jika sudah terisi, maka akan mencari sampai ada tempat yang kosong
n+=1
else:
print("Sudah Terisi")
print(pos + " -> " + player[1])
def showingResult():
print(boardProgress[0][0] + " | " + boardProgress[0][1] + " | " + boardProgress[0][2])
print("--|---|--")
print(boardProgress[1][0] + " | " + boardProgress[1][1] + " | " + boardProgress[1][2]) # fungsi untuk menampilkan hasil akhir dari permainan
print("--|---|--")
print(boardProgress[2][0] + " | " + boardProgress[2][1] + " | " + boardProgress[2][2])
def whoWin(x,y):
if x > y:
result = ("Player 1 (X) win!!!")
elif x == y:
result = ("Draw") # fungsi untuk menampilkan siapa pemenangnya antara player1 dan player2
else:
result = ("Player 1 (X) lose!!!")
print("Result : " + result)
def boards(x):
if x == 1:
print("row\col\t 1\t 2\t 3")
for i in range(3):
print(" " + str(i+1) + "\t" + str(board[i]))
if x == 2:
print("row\col\t 1 2 3")
for i in range(3):
print(" " + str(i+1) + "\t" + str(boardProgress[i]))
# menampilkan board awal saat permainan akan dimulai
# for line in board:
# print(line)
# guide
boards(1)
# print("row\col\t 1\t 2\t 3")
# for i in range(3):
# print(" " + str(i+1) + "\t" + str(board[i]))
print("")
# permainan dimulai oleh player1
user()
# permainan dilanjutkan oleh player2 dan bergantian dengan player1 hingga masing mendapatkan 4x main dan board terisi penuh
while totalPlay < total: # akan dijalankan jika totalPlay < total, pada awal permainan --> 0 < 4
boards(2)
get_random_pos(2)
boards(2)
user()
totalPlay+=1 # setiap kali 2 pemain sudah mendapatkan giliran, maka totalPlay akan bertambah 1
print("")
showingResult() # memanggil fungsi menampilkan hasil akhir
# melakukan penilaian dari hasil akhir permainan
for i in range(3):
# mengecek board setiap baris
if boardProgress[i][0] == boardProgress[i][1] == boardProgress[i][2] == 'X':
scoreP1+=1
if boardProgress[i][0] == boardProgress[i][1] == boardProgress[i][2] == 'O':
scoreP2+=1
# mengecek boardProgress setiap kolom
if boardProgress[0][i] == boardProgress[1][i] == boardProgress[2][i] == 'X':
scoreP1+=1
if boardProgress[0][i] == boardProgress[1][i] == boardProgress[2][i] == 'O':
scoreP2+=1
# mengecek boardProgress posisi diagonal
if boardProgress[0][0] == boardProgress[1][1] == boardProgress[2][2] == 'X' or boardProgress[0][2] == boardProgress[1][1] == boardProgress[2][0] == 'X':
scoreP1+=1
if boardProgress[0][0] == boardProgress[1][1] == boardProgress[2][2] == 'O' or boardProgress[0][2] == boardProgress[1][1] == boardProgress[2][0] == 'O':
scoreP2+=1
print("")
print("score P1 (X) : " + str(scoreP1))
print("score P2 (O) : " + str(scoreP2))
whoWin(scoreP1, scoreP2) # memanggil fungsi untuk menentukan siapa pemenangnya
|
6ef5b5df4df077f3b2eb4325246ce37d0a0d0dff | silverfox78/HackerRank | /Python - Language Proficiency/E009 - String Validators/ejercicio.py | 1,238 | 4.0625 | 4 | # >>> String Validators
# >>> https://www.hackerrank.com/challenges/string-validators/problem
# str.isalnum() - In the first line, print True if has any alphanumeric characters. Otherwise, print False.
# str.isalpha() - In the second line, print True if has any alphabetical characters. Otherwise, print False.
# str.isdigit() - In the third line, print True if has any digits. Otherwise, print False.
# str.islower() - In the fourth line, print True if has any lowercase characters. Otherwise, print False.
# str.isupper() - In the fifth line, print True if has any uppercase characters. Otherwise, print False.
if __name__ == '__main__':
s = 'qA2' #input()
isalnum = isalpha = isdigit = islower = isupper = False
for elem in s:
if not isalnum:
isalnum = elem.isalnum()
if not isalpha:
isalpha = elem.isalpha()
if not isdigit:
isdigit = elem.isdigit()
if not islower:
islower = elem.islower()
if not isupper:
isupper = elem.isupper()
if isalnum and isalpha and isdigit and islower and isupper:
break
print(isalnum)
print(isalpha)
print(isdigit)
print(islower)
print(isupper) |
cbc0dd51705f6a753000931edbf2794516cbdc28 | I-hel-l/python | /R.Briggs.Python_for_kids/greeting.py | 252 | 3.84375 | 4 | # Вітання!
first_name = 'Igor'
last_name = 'Dolganov'
my_string = "Hello, %s %s!" % (first_name, last_name)
print(my_string)
# or
first_name = 'Igor'
last_name = 'Dolganov'
my_string = f"Hello, {first_name} {last_name}!"
print(my_string)
|
40f9ec40d73e9ac4f251b0cb5bb76bfab91dcf6b | mgupta21/PyTut | /basics/assignment/testAss4.py | 820 | 3.75 | 4 | #!/usr/bin/python
__author__ = 'Mayank'
"""
Usages :
./testAss4.py (display entire dict)
./testAss4.py <key> (print's the value associated with the key)
./testAss4.py <key> <value> (sets given key and value in the dict)
"""
import sys
from assignment4 import MyCustomDict
d = MyCustomDict('rev_analysis.txt')
if len(sys.argv) == 3:
key = sys.argv[1]
value = sys.argv[2]
print('setting key "{0}" and value "{1}" in dictionary'.format(key, value))
d[key] = value
elif len(sys.argv) == 2:
print('reading a value from dictionary')
key = sys.argv[1]
print('the value for key "{0}" is : "{1}"'.format(key, d[key]))
else:
print("Displaying dictionary : ")
for key in d.keys():
print("{0} = {1}".format(key, d[key]))
|
373623d432ea91db101619380826d4fddd17f2f8 | irchorn/IS211_Assignment7 | /main.py | 2,609 | 3.859375 | 4 | import random
class Die:
def __init__(self, seed):
random.seed(seed)
def roll(self):
return random.randint(1, 6)
class Player:
def __init__(self, name):
self.name = name
self.total = 0
# we might not need turn total
def __str__(self):
return f"{self.name} has {self.total}points"
class Game:
def __init__(self, name1, name2):
self.players = [Player(name1), Player(name2)]
self.turn_total = 0
self.total = 0
self.current_player = 0
def next_player(self):
if self.current_player + 1 == len(self.players):
self.current_player = 0
else:
self.current_player += 1
def play(self):
turn_total = 0
while self.players[0].total < 100 and self.players[1].total < 100:
turn_input = input(f'{self.players[self.current_player].name}, do you want to roll or hold? ')
if turn_input == 'r':
die_value = random.randint(1, 6)
if die_value == 1:
print(f"{self.players[self.current_player].name} you roll a 1. Your score for this round is 0")
print("----------------------------------------------------------------")
turn_total = 0
self.next_player()
continue
else:
print(f"{self.players[self.current_player].name} you roll a {die_value}.")
turn_total += die_value
if turn_total + self.players[self.current_player].total >= 100:
self.players[self.current_player].total += turn_total
print(f"{self.players[self.current_player].name} you are the WINNER.")
print(f"Your winning score is {self.players[self.current_player].total}")
continue
print(f"Your turn score is {turn_total}")
print(f"Your possible score if you hold is {turn_total + self.players[self.current_player].total}")
elif turn_input == 'h':
self.players[self.current_player].total += turn_total
print(f"Your score is {self.players[self.current_player].total}. Turn is over")
print("----------------------------------------------------------------")
turn_total = 0
self.next_player()
else:
print("Game is over!")
def main():
my_game = Game("Jhon", "Michael")
my_game.play()
# play the game
main() |
6afc4b560a33f196a8db9abf88178d9e3beddaa5 | tsdocode/ISLab | /ex1.py | 742 | 3.671875 | 4 | from math import sqrt
def ex1():
a = int(input())
b = int(input())
return a + b
def ex2():
str = input()
return len(str)
def ex3(arr):
return [i for i in arr if is_prime(i)]
def is_prime(x):
if (x < 2): return False
else:
for i in range(2, int(sqrt(x)) + 1):
if (x % i == 0): return False
return True
def ex4(str):
rs = {
'Hoa' : 0,
'Thuong' : 0,
'Space' : 0
}
for i in str:
if i.isupper():
rs['Hoa'] += 1
if i.islower():
rs['Thuong'] += 1
if i.isspace():
rs['Space'] += 1
return rs
print(ex1())
print(ex2())
print(ex3([1,2,3,4, 5, 6, 7, 8, 9, 11]))
print(ex4("ISLab ")) |
34f6d70117611ee9b586636796c9e062126f96d8 | albertkklam/hackerrank | /python/groups.py | 233 | 3.609375 | 4 | # Group(), Groups() & Groupdict()
## https://www.hackerrank.com/challenges/re-group-groups/problem
### Python 3.6
import re
m = re.search(r"([a-zA-Z0-9])\1", input())
if m is not None:
print(m.group(1))
else:
print(-1)
|
e663500264130ff33119b417712131561c1a1b9d | jmuia/terrible_haiku | /haiku.py | 1,684 | 3.703125 | 4 | import io
from random import randint, choice
def _generate_syllable_mapping(min_syllables=None, max_syllables=None):
lines = io.open('mhyph.txt', mode='rU', encoding='ISO-8859-1').read().split('\n')
mapping = {}
split_char = '\xa5'
for line in lines:
if not len(line):
continue
line = line.encode('ISO-8859-1')
components = line.split(split_char)
syllables = len(components)
if min_syllables and syllables < min_syllables:
continue
if max_syllables and syllables > max_syllables:
continue
word = "".join(components)
if mapping.has_key(syllables):
mapping[syllables].append(word)
else:
mapping[syllables] = [word]
return mapping
SYLLABLE_MAPPING = _generate_syllable_mapping(max_syllables=7)
class Haiku:
def __init__(self):
self.line_1 = self._create_line(5)
self.line_2 = self._create_line(7)
self.line_3 = self._create_line(5)
def __str__(self):
return self.to_str('\n')
def to_str(self, separator):
return separator.join([self.line_1, self.line_2, self.line_3])
def _create_line(self, num_syllables):
s = []
while num_syllables > 0:
syllables = randint(1, num_syllables)
word = self._get_word(syllables)
if not word:
continue
s.append(word)
num_syllables -= syllables
return " ".join(s)
def _get_word(self, syllables):
if SYLLABLE_MAPPING.has_key(syllables):
return choice(SYLLABLE_MAPPING[syllables])
else:
return None |
2dfd05842893e09d05a5d85affd3b88b12890da3 | ishantk/PythonTutorial | /venv/strings.py | 858 | 3.78125 | 4 | name = "John Watson"
print name
l = len(name)
print l
print name[0]
print name[l-1]
print name[-11]
# 0 to l-1 , -1 to -l
str1 = "Hello"
str2 = "World"
str3 = str1 + str2
a = 10
#str4 = str1 + a
print str3
print 5 * str1
print str2 * 5
str4 = " John, Jennie, Jack, Jim and Joe are Together.mp3"
print "John" in str4
print "George" not in str4
str5 = "Hello"
str6 = "hello"
print str1 == str5
print str6 > str5
print str4[0:5]
print str4[7:9]
print str4[7:]
print str4[:5]
str7 = str4[:2]+str4[9:]
print "str7 is: ",str7
str8 = "george"
str9 = str8.capitalize()
print str8
print str9
str10 = str8.upper()
print str10
str11 = str8.lower()
print str11
str12 = str4.rstrip()
print str12
ch = "J"
print str4.count(ch,0,len(str4))
print str4.endswith(".mp3")
print str4.find("John")
cipher = "abcdefghijklmnopqrstuvwxyz"
print cipher[0]
|
222b333159a49cc61b98208a253ef7493f667d5c | verprog/Python_advanced_09 | /Lessons/Lesson_01/Lesson_01.py | 1,276 | 3.578125 | 4 | list_1=[1,2,3,4,5]
list_2=list([1,2,3,4])
print(list_1[0])
list_1[0]='zero'
print(list_1[0])
tuple_1=(1,2,3,4)
print(tuple_1[0])
dict_1={'one':1,
'two':2,
(1,2):3,
'tree':[1,2,3]
}
print(dict_1.get((1,3),-1))
print(set([1,2,3,2,3,4]))
print(hash('00'))
print(bool(1))
print(bool(0))
user_string = input('enter')
if user_string:
print(user_string[::-1])
else:
print('Empty')
if user_string:
print(user_string[::-1])
elif True:
pass
else:
print('Empty')
number=int(input('enter number'))
if number>100:
print('> 100')
else:
print('notttt')
result = '>100' if number>100 else None
22222
i = 0
while i<100:
print(i)
i += 1
if i==50:
break
continue
list_2 = [1,2,3,4,5,6,7,8]
list_2 = range(0,100,10)
len_of_list = len(list_2)
for ind in list_2:
print(ind)
for ind, dt in enumerate(list_2[1:50]):
print(ind,dt)
dict_1={'one':1,
'two':2,
(1,2):3,
'tree':[1,2,3]
}
# for item in dict_1.values():
for item,dd in dict_1.items():
print(item,dd)
print('*' * 20)
try:
b = 1 + 'ff'
a = 10/0
except (ZeroDivisionError, TypeError) as e:
a = None
print(e.args)
else:
print('normal data')
finally:
print('bay')
|
1bf2179f16e4a3a4a6ba94cbeed62e0aef9af054 | sairshinde/c-revision | /progarm2 | 413 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 22 12:07:19 2018
@author: amitk
this is a sample program
"""
num1 = 100
num2 = 200
answer = num1 + num2
print(answer)
first_name = "amit"
# 1name = "test"
name1 = "test"
# print print functions help
print(print.__doc__)
name = "test"; name1 = "test1";
result = 100 + 200 + 299 + 234 + \
334 + 343 + 4343 \
+ 33434 + 3434
|
f95bcbcd0c4fe7b787635692e84b8fe354680dd1 | dron-dronych/python-algorithms | /greedy/car_fueling.py | 1,486 | 4.1875 | 4 | # You are going to travel to another city that is located 𝑑 miles away from your home city.
# Your car can travel at most 𝑚 miles on a full tank and you start with a full tank. Along your way,
# there are gas stations at distances stop1, stop2, . . . , stop𝑛 from your home city.
# What is the minimum number of refills needed?
def car_fueling(distance, capacity, n_stations, *args):
"""
find min number of refills along travel distance
:param distance: int: distance to travel
:param capacity: int: full tank capacity
:param n_stations: int: num of gas stations along the way
:param args: gas stations at distance arg1, arg2,..., argn along the way
:return: int: min number of refills to travel distance
"""
num_refills = 0
distance_left = distance
# safe move -- refill at farthest stop possible to
# travel w/out a refill
stops = [arg for arg in args]
stops.append(distance) # last point on the route
prev_refill = 0
prev_stop = 0
for stop in stops:
if capacity < stop - prev_stop:
return -1
if capacity > stop - prev_refill:
prev_stop = stop
else:
num_refills += 1
prev_refill = prev_stop
distance_left -= stop
return num_refills
if __name__ == '__main__':
print(car_fueling(950, 400, 4, 200, 375, 550, 750))
print(car_fueling(10, 3, 4, 1, 2, 5, 9))
print(car_fueling(200, 250, 2, 100, 150))
|
4e2ee856cdb1345831aa97ffbe2e8466ac1ae69a | 0112nga/hw | /Week2/pr1.py | 240 | 3.8125 | 4 |
def getInitial(fullName):
name = fullName.split(' ')
for val in name:
print(val[0].upper()+'. ', end='')
def main():
x = input("Input your full name:")
print("Result: ", end='')
getInitial(x)
main() |
799a86de3315af7ea9c4ae7fce5ffd32c7ed2076 | vedasree1/iQ | /magic_cal.py | 304 | 3.65625 | 4 | import re
print("print 'quit' to exit \n")
prevoius=0
run=True
def performMath():
global run
equation= input("enter equation:")
print("entered values", eval(str(equation)))
if equation == 'quit':
print("Good bye")
run=False
while run:
performMath() |
0bea54714bb02419d79589dee3146d26f1eee127 | jsore/notes | /v2/python-crash-course/python_work/testing/language_survey.py | 536 | 3.96875 | 4 | # example for test cases on classes
from survey import AnonymousSurvey
# define a question and turn it into a survey
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
# show the question and store its response
my_survey.show_question()
print('Enter "q" at any time to quit\n')
while True:
response = input('Language: ')
if response == 'q':
break
my_survey.store_response(response)
# show survey's results
print('\nThanks for participating!')
my_survey.show_results()
|
4af80391439656fdde083520a3552b4ec8e9c019 | pitroldev/uerj-algoritmos-computacionais | /Aulas/Aula 2/Exercicio_1.py | 783 | 4.125 | 4 | # UERJ - 22/09/2020
# Aula 2 de Algoritmos Computacionais
"""
Exercício 1
Ler um número inteiro e imprimir PAR, caso o número seja par,
ou ÍMPAR, caso contrário.
"""
def main():
while True:
while True:
try:
num = int(
input("\nDigite um número e direi se ele é par ou impar: "))
break
except:
print("\nPor favor, digite um número válido.")
if num % 2 == 0:
print("O número", num, "é par!")
else:
print("O número", num, "é ímpar!")
shouldContinue = str(
input("\nDigite S para sair do programa ou aperte ENTER para continuar: "))
if shouldContinue.upper() == "S":
return
main()
|
54f7f6df4184bf228abf516a59501bb0bf845cb4 | vaghelan/ProgrammingPractice | /ThreeSum/program.py | 1,273 | 4.125 | 4 |
def threeNumberSumV1(array, targetSum):
# Write your code here.
triplets = {}
for i in range(0, len(array) - 2):
for j in range(i+1, len(array) - 1):
#if i == j:
# continue
for k in range(j+1, len(array)):
# if k == i or k == j:
# continue
if (array[i] + array[j] + array[k]) == targetSum:
a = [array[i], array[j], array[k]]
a.sort()
triplets[(a[0], a[1], a[2])] = True
print(triplets)
triplets_array = []
for t in triplets:
triplets_array.append([t[0], t[1], t[2]])
return (triplets_array)
def threeNumberSum(array, targetSum):
# Write your code here.
triplets = []
array.sort()
for i in range(0, len(array) - 2):
left = i + 1
right = len(array) - 1
while left < right:
currentSum = array[i] + array[left] + array[right]
if currentSum == targetSum:
triplets.append([array[i], array[left], array[right]])
left += 1
right -= 1
elif currentSum < targetSum:
left +=1
else:
right -= 1
return (triplets) |
4c2a4f8cb10918a1eac137a75ac2ef71558e592e | micheles/papers | /pypers/oxford/check_overriding.py | 703 | 3.546875 | 4 | # check_overriding.py
class Base(object):
a = 0
class CheckOverriding(type):
"Prints a message if we are overriding a name."
def __new__(mcl, name, bases, dic):
for name, val in dic.iteritems():
if name.startswith("__") and name.endswith("__"):
continue # ignore special names
a_base_has_name = True in (hasattr(base, name) for base in bases)
if a_base_has_name:
print "AlreadyDefinedNameWarning: " + name
return super(CheckOverriding, mcl).__new__(mcl, name, bases, dic)
class MyClass(Base):
__metaclass__ = CheckOverriding
a = 1
class ChildClass(MyClass):
a = 2
|
6ca0e6b6f688356119641f11ac9bb1503bfee662 | andresvanegas19/holbertonschool-higher_level_programming | /0x0B-python-input_output/14-pascal_triangle.py | 286 | 4.1875 | 4 | #!/usr/bin/python3
""" a simple script that create a json from input"""
def pascal_triangle(n):
"""returns a list of lists of integers representing the
Pascal’s triangle """
if n <= 0:
return []
return [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
|
fc052f20bb26d4f1ea524724b487c89be84d7b18 | anshgoyal010/Hackerrank-Problem-Solving | /Warmup/Mini-Max Sum.py | 476 | 3.71875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
l=len(arr)
max=arr[0]
min=arr[0]
s=arr[0]
for i in range (1,l):
s+=arr[i]
if arr[i]>max:
max=arr[i]
if arr[i]<min:
min=arr[i]
print((s-max),(s-min))
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
|
3aaa7c357b47447b4508e72f072046ab794cf7ec | Balajikrishnan00/Python | /Typecasting,operator.py | 2,545 | 3.921875 | 4 | '''
name='welcome'
lenght=len(name) # len function using no of charactor
print(name ,'=',lenght)
#Typecasting
# int()
print(int(123.45))
print(int(123.90))
print(int('123455'))
print(int(True))
print(int(False))
# float()
print(float(123))
print(float(True))
print(float(False))
print(float('123'))
#bool
print(bool(0))
print(bool(0.0))
print(bool(5))
print(bool(0.1))
#str()
print(str(10))
print(str(2.0))
print(str(True))
print(str(False))
#type() type ex int ,float,str,bool
# 14 data types available in python
no=100
name='shiva'
tamil=True
print(type(no))
print(type(name))
print(type(tamil))
# memory address
# id() memory address
a=10
b=20
c=10
print(id(a))
print(id(b))
print(id(c))
# immutable ,mutable
# cannot change,change of memory address
state1='TamilNadu'
state2='TamilNadu'
print(id(state1))
print(id(state2))
#2586639203440
#2586639203440
a=(10,20)
print(a)
for i in a:
print(i)
print(id(i))
# no constants in python
# convention full capital letter
# ex INTEREST_RATE=5
# Escape Characters
# \t - Tab
# \n - new line
# \' - single Qut
# operators
print(10+2)
print(10-4)
print(4*2)
print(9/3)
print(9//3)
print(20%3)
print(10**2)
print(10**3)
# Relational Operators
print(10>2)
print(10<3)
print(34<=12)
print(54>=21)
# equality operator
# chaining operator
# == !=
print(10>30>90)
print(10<20>10)
# member ship operators
sen='God is Grace'
#1p
if 'God' in sen:
print('True')
else:
print('False')
#2p
names=['arun','ravi','siva','guna','mahesh']
if 'siva' in names:
print('yes')
else:
print('no')
#3p
no=[10,43,56,74,34,35,6,754,323,]
if 100 not in no:
print('yes')
else:
print('no')
# Ternary operator
#1p
a,b=21,20
c=30 if a>b else 40
print(c)
#2p
a=10
b=50
c=40
min =a if a<b and a<c else b
print(min)
#3P
a=int(input('Enter a value:'))
b=int(input('Enter b value:'))
c=int(input('Enter c value:'))
min=a if a<b and a<c else b if b<c else c
# min =a if 10<20 and 10<30
# elif 20<30
# else 30
max=a if a>b and a>c else b if b>c else c
print(min)
print(max)
#4p
a=int(input('A:'))
b=int(input('B:'))
c=int(input('C:'))
if a<b and a<c:
min=a
print(min)
elif b<c:
min=b
print(min)
else:
min=c
print(min)
# Identity Operator
# memory if location
# combine with memory location
a=12
b=23
print(a==b)
print(a is b)
name=input()
print('hi',name,'welcome to python world.')
print('hi'+name+'welcome to python world')
'''
named_list=[]
for i in range(5):
name=input("enter name:")
named_list.append(name)
print(named_list)
|
dfbca79c69ca97c2d16da689c699c2e02d1fd24b | aarboleda1/princeton_algos | /practice/binary_search.py | 1,941 | 4.03125 | 4 | #!/usr/bin/env python3
from typing import List
from math import floor
import unittest
def binary_search_recursive(alist: List[int], target: int) -> bool:
return binary_search_recursive_helper(alist, 0, len(alist) - 1, target)
def binary_search_recursive_helper(
alist: List[int], lo: int, hi: int, target: int
) -> bool:
# catch errors first
if lo > hi:
return False
mid = floor(lo + ((hi - lo) / 2))
if alist[mid] == target:
return True
if alist[mid] > target:
return binary_search_recursive_helper(alist, lo, mid - 1, target)
else:
return binary_search_recursive_helper(alist, mid + 1, hi, target)
def binary_search_iterative(alist: List[int], target: int) -> bool:
lo = 0
hi = len(alist) - 1
while lo <= hi:
mid = floor(lo + ((hi - lo) / 2))
if alist[mid] == target:
return True
if alist[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return False
class BinarySearch(unittest.TestCase):
def test_recursive(self):
alist = [1, 3, 5, 9, 11]
self.assertTrue(binary_search_recursive(alist, 5))
self.assertTrue(binary_search_recursive(alist, 3))
self.assertTrue(binary_search_recursive(alist, 9))
self.assertTrue(binary_search_recursive(alist, 11))
self.assertTrue(binary_search_recursive(alist, 1))
self.assertFalse(binary_search_recursive(alist, 100))
def test_iterative(self):
alist = [1, 3, 5, 9, 11]
self.assertTrue(binary_search_iterative(alist, 5))
self.assertTrue(binary_search_iterative(alist, 3))
self.assertTrue(binary_search_iterative(alist, 9))
self.assertTrue(binary_search_iterative(alist, 11))
self.assertTrue(binary_search_iterative(alist, 1))
self.assertFalse(binary_search_iterative(alist, 100))
if __name__ == '__main__':
unittest.main()
|
a3b0dda6ee1e9c7d093557bb4c641b0b2a19f23f | jdbuysse/oldgrammarscripts | /deletesUncapitializedWords.py | 352 | 3.796875 | 4 | ##reads file into string
infile = open('parsedClean.txt', 'r')
outfile = open('output.txt', 'w')
with open('parsedClean.txt','r') as f:
for line in f:
for word in line.split():
if word.isupper():
print ("y")
outfile.write(word)
infile.close()
outfile.close()
|
fc1e0b3178b70681e68ae9c00fc90dcfb91b58bf | pingrunhuang/CodeChallenge | /leetcode/109.py | 1,833 | 4.03125 | 4 | """
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def generate_tree(self, nums, left, right):
if left > right:
return None
mid = left + (right - left) // 2
root = TreeNode(nums[mid])
root.left = self.generate_tree(nums, left, mid - 1)
root.right = self.generate_tree(nums, mid + 1, right)
return root
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
array = []
while head:
array.append(head.val)
head = head.next
return self.generate_tree(array, 0, len(array) - 1)
class Solution2:
"""
2 step at a time
1 step at a time
"""
def to_BST(self, head, tail):
if head == tail:
return None
slow = head
fast = head
while fast != tail and fast.next != tail:
fast = fast.next.next
slow = slow.next
root = TreeNode(slow.val)
root.left = self.to_BST(head, slow)
root.right = self.to_BST(slow.next, tail)
return root
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
if not head:
return None
return self.to_BST(head, None)
|
3dde83c6e5f6a9f36dfe90f34f39f654304a45b9 | jstockbot/jstock | /com/javamix/samples/fibonacci2.py | 261 | 4.09375 | 4 | dictionary = {
1:1,
2:1
}
def fibonacci(n):
if n in dictionary:
return dictionary[n]
else:
output = fibonacci(n-1) + fibonacci(n-2)
dictionary[n] = output
return output
print("value = {}".format(fibonacci(100))) |
a1c6aa22c72a13dcf43f7d5d8ab2579e99a4ac50 | baraaHassan/Computer_Vision_Course | /Sheet00/src/sheet00.py | 3,497 | 3.515625 | 4 | import cv2 as cv
import numpy as np
import random
import sys
from numpy.random import randint
def display_image(window_name, img):
"""
Displays image with given window name.
:param window_name: name of the window
:param img: image object to display
"""
cv.imshow(window_name, img)
cv.waitKey(0)
cv.destroyAllWindows()
if __name__ == '__main__':
# set image path from program args
img_path = sys.argv[1]
# 2a: read and display the image
img = cv.imread(img_path, cv.IMREAD_COLOR)
display_image('2 - a - Original Image', img)
# 2b: display the intensity image
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
display_image('2 - b - Intensity Image', img_gray)
# 2c: for loop to perform the operation
img_cpy = img.copy()
height, width = img_cpy.shape[:2]
# Going through the pixels
for x in range(height):
for y in range(width):
for c in range(3):
img_cpy[x, y, c] = max(0, img_cpy[x, y, c] - 0.5 * img_gray[x, y])
display_image('2 - c - Reduced Intensity Image', img_cpy)
# 2d: one-line statement to perfom the operation above
# - add a channels' dimension to the 0.5 * gray_image,
# - subtract from original image and clip for non-negativity
# - set the type for the mat to np.uint8
img_cpy = (img - np.expand_dims(img_gray * 0.5, axis=2)).clip(min=0).astype(np.uint8)
display_image('2 - d - Reduced Intensity Image One-Liner', img_cpy)
# 2e: Extract the center patch and place randomly in the image
img_cpy = img.copy()
img_patch = img_cpy[(height - 16) // 2: (height + 16) // 2,
(width - 16) // 2: (width + 16) // 2]
display_image('2 - e - Center Patch', img_patch)
# Random location of the patch for placement
rand_coord = [randint(0, height - 16), randint(0, width - 16)]
# Adding patch to original image
img_cpy[rand_coord[0] : rand_coord[0] + 16, rand_coord[1] : rand_coord[1] + 16] = img_patch
display_image('2 - e - Center Patch Placed Random %d, %d' % (rand_coord[0], rand_coord[1]), img_cpy)
# 2f: Draw random rectangles and ellipses
img_cpy = img.copy()
# random x, y, sizes, colors of rect and ellipses
rand_properties = np.array([randint(0, height, 20), randint(0, width, 20),
randint(10, 60, 20), randint(10, 80, 20),
randint(0, 255, 20), randint(0, 255, 20), randint(0, 255, 20),
randint(0, 360, 20)]).astype(np.uint16)
for i in range(0,10):
# adding rectangles
index = i * 2
x, y = rand_properties[0, index], rand_properties[1, index]
rect_end_coords = (x + rand_properties[2, index], y + rand_properties[3, index])
rect_color = (int(rand_properties[4, index]), int(rand_properties[5, index]), int(rand_properties[6, index]))
cv.rectangle(img_cpy, (x, y), rect_end_coords, rect_color, -1)
# adding ellipses
index = i * 2 + 1
x, y = rand_properties[0, index], rand_properties[1, index]
ellipse_color = (int(rand_properties[4, index]), int(rand_properties[5, index]), int(rand_properties[6, index]))
cv.ellipse(img_cpy, (x, y), (20, 22), rand_properties[7, i * 2 + 1], 0, 360, ellipse_color, -1)
pass
display_image('2 - f - Rectangles and Ellipses', img_cpy)
# destroy all windows
cv.destroyAllWindows()
|
2153d815ac782be642d19e2801ba0a1041fca427 | matytynka/bsi-lab-ciphers | /ciphers/TwofishExample.py | 1,530 | 3.8125 | 4 | """
Author: Wojciech Skarbek
Library: Twofish
Following file contains implementation of encryption and decryption using Twofish
algorithm. Twofish is a symmetric-key block cipher with a block size of 128 bits
up to 256. Since Twofish is much slower on modern CPUs, it got completely replaced
by AES and since it never has been patented it's reference implementation has been
placed in the public domain.
"""
from twofish import Twofish
class TwofishExample:
"""
A class to represent an TwofishExample.
METHODS
-------
encrypt(msg):
Encrypts the msg and returns it.
decrypt(encrypted):
Decrypts the encrypted msg and returns it.
"""
def __init__(self):
"""
Constructs the TwofishExample object.
"""
self.key = b'FSMF73R873YM1872Y'
self.tf = Twofish(self.key)
def encrypt(self, msg):
"""
Encrypts the msg.
PARAMETERS
----------
:param msg : Message to be encrypted
:type msg : str
RETURNS
-------
:returns encrypted message
:rtype bytearray
"""
return self.tf.encrypt(msg)
def decrypt(self, encrypted):
"""
Decrypts the encrypted message.
PARAMETERS
----------
:param encrypted : Encrypted message to be decrypted
:type encrypted : bytearray
RETURNS
-------
:returns decrypted message
:rtype str
"""
return self.tf.decrypt(encrypted).decode()
|
962fd1a86f0d02977f7713a83c45e7330fe04828 | MAG-BOSS/fermulerpy | /src/fermulerpy/analytic/function_average.py | 1,578 | 4.15625 | 4 | import math
import warnings
def divisor_function_avg(n):
"""
Returns the average order of divisor function for the positive integer n
Parameters
----------
n : int
denotes positive integer
return : float
return average order of divisor function
"""
if(n!=int(n) or n<1):
raise ValueError(
"n must be positive integer"
)
return (math.pow(math.pi,2))*(n/12)
def euler_totient_avg(n):
"""
Returns the average order of euler totient function for the positive integer n
Parameters
----------
n : int
denotes positive integer
return : float
return euler totient average
"""
if(n!=int(n) or n<1):
raise ValueError(
"n must be positive integer"
)
return (3*n)/(math.pow(math.pi,2))
def mobius_avg(n):
"""
Returns the average order of mobius function for the positive integer n
Parameters
----------
n : int
denotes positive integer
return : float
return mobius function average
"""
if(n!=int(n) or n<1):
raise ValueError(
"n must be positive integer"
)
return 0.0
def liouville_avg(n):
"""
Returns the average order of liouville function for the positive integer n
Parameters
----------
n : int
denotes positive integer
return : float
return liouville function average
"""
if(n!=int(n) or n<1):
raise ValueError(
"n must be positive integer"
)
return 1.0 |
5eeefd0f6cd95f30cf83f7b8d657621e926142df | simyy/leetcode | /5474-number-of-good-leaf-nodes-pairs.py | 2,064 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/contest/weekly-contest-199/problems/number-of-good-leaf-nodes-pairs/
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def countPairs(self, root, distance):
"""
:type root: TreeNode
:type distance: int
:rtype: int
"""
self.rs = []
self.dfs(root, distance)
return len(self.rs)
def dfs(self, root, distance):
if not root:
return None
if root.left is None and root.right is None:
return [[root.val, 1]]
left_leaf = self.dfs(root.left, distance)
right_leaf = self.dfs(root.right, distance)
# 过滤超长的
if left_leaf:
left_leaf = filter(lambda x: x[1] < distance, left_leaf)
if right_leaf:
right_leaf = filter(lambda x: x[1] < distance, right_leaf)
if left_leaf and right_leaf:
# 计算distance
for a in left_leaf:
for b in right_leaf:
if a[1] + b[1] <= distance:
self.rs.append([a[0], b[0]])
# 为什么不需要判断重复? 是由于只会左右子树判断,不会存在重复情况
# if [a[0], b[0]] not in self.rs:
# self.rs.append([a[0], b[0]])
leaf = []
if left_leaf:
leaf += [[leaf[0], leaf[1]+1] for leaf in left_leaf]
if right_leaf:
leaf += [[leaf[0], leaf[1]+1] for leaf in right_leaf]
return leaf
if __name__ == '__main__':
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n1.left = n2
n1.right = n3
n4 = TreeNode(4)
n5 = TreeNode(5)
n2.left = n4
n2.right = n5
n6 = TreeNode(6)
n7 = TreeNode(7)
n3.left = n6
n3.right = n7
assert Solution().countPairs(n1, 3) == 2 |
b9125de2d9472e4f051ba4ff4542ee12f6d3565c | dipnrip/Python | /Python/project2.py | 350 | 3.6875 | 4 | defaultKey = ['b','z','h','g','o','c','v','j','d','q','s','w','k','i','m','l','u','t','n','e','r','y','a','x','f']
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def substitutionEncrypt(text, key):
cipherText = ""
for c, k in zip(alphabet, defaultKey):
for i in range(len(text)):
if text[i] == c
|
48d7497513144c775bae8abb6b405b63a6cf6058 | philipdongfei/arturo | /tests/benchmarks/math_isprime_trial.py | 239 | 3.765625 | 4 | maxLimit = 10000
def isPrime(a):
if a == 2: return True
if a < 2 or a % 2 == 0: return False
return not any(a % x == 0 for x in xrange(3, int(a**0.5) + 1, 2))
for n in range(maxLimit):
print "true" if isPrime(n) else "false" |
f012403bab65fb8d7f95c66efee831e365befd29 | KhanAjmal007/Data-Structures-and-Algorithms-Specialization-Coursera | /Course_2-Data_Structures/Week-3/Excercise_Challenges/1_make_heap/build_heap.py | 1,236 | 3.65625 | 4 | class BuildHeap:
def __init__(self):
self.n = 0
self.data = []
self.pair = []
def read_data(self):
self.n = int(input())
self.data = list(map(int, input().split()))
def left_child(self, index):
return 2 * index + 1
def right_child(self, index):
return 2 * index + 2
def shift_down(self, index):
min_index = index
left = self.left_child(index)
if left < self.n and self.data[left] < self.data[min_index]:
min_index = left
right = self.right_child(index)
if right < self.n and self.data[right] < self.data[min_index]:
min_index = right
if index != min_index:
self.pair.append([index, min_index])
self.data[index], self.data[min_index] = self.data[min_index], self.data[index]
self.shift_down(min_index)
def generate_swap(self):
for i in range(self.n//2, -1, -1):
self.shift_down(i)
def write_pair(self):
print(len(self.pair))
for v in self.pair:
print(v[0], v[1])
if __name__ == "__main__":
obj = BuildHeap()
obj.read_data()
obj.generate_swap()
obj.write_pair()
|
a59c606b635793d6aa7f59008bf8bbeffe6d5c41 | morganmann4/cse210-tc04 | /hilo/__main__.py | 1,701 | 3.984375 | 4 | from dealer import Dealer
from player import Player
#outline for code
'''Dealer class
random card 1-13
displays current card
shows next card
if points hit 0 game over takes points as a parameter return can play
if can play ask user if they want to play again
'''
'''Player class
starts with 300 points
takes current card as parameter and asks if it will be higher or lower
current card, user input and next card as parameters determine if player was right return True or False
takes boolean as parameter and either adds or subtracts points
return points
'''
def main():
dealer = Dealer()
player = Player()
keep_playing = True
#loops through methods until player doesn't want to play or has no more points
while keep_playing == True:
#calls the display card funtion that calls the get card function
first_card = dealer.display_card()
#gets the guess from the player returns to the "guess" variable
guess = player.make_guess()
#dealer shows the next card by calling the display card function again returns to the "next_card" variable
next_card = dealer.display_card()
#takes the players guess, the first card and second card and sees if player is right returns it to the "correct" variable
correct = dealer.is_guess_correct(guess, first_card, next_card)
#gets the points
player.add_or_sub_points(correct)
#prints the points
print("")
print(f"You now have {player.points} points.")
print("")
#sees if the player can or wants to keep playing
keep_playing = player.can_play()
#calls the main function to start it all
main()
|
4029e11e46ac4e3818909ef9d41ae89a6f689fdc | daniel-reich/ubiquitous-fiesta | /KEsQGp7LsP3KwmqJ7_15.py | 148 | 3.578125 | 4 |
def check(lst):
for i in range(1,len(lst)):
if sorted(lst) == lst[i:] + lst[:i]:
return 'YES'
return 'NO'
|
f426364288406f72e3cc906b49740b7332533b2e | AmitHasanShuvo/ML_problems | /pytorch-practice/gradient.py | 851 | 4.25 | 4 | # gradients are a numerical representation of a derivative and can be positive or negative.
import torch
X = torch.rand(1, requires_grad=True)
Y = X + 1.0
def mse(Y):
diff = 3.0 - Y
return (diff * diff).sum() / 2
# the gradients on our X - that tells us in which direction we are off from the right answer
loss = mse(Y)
loss.backward()
print(X.grad)
# using a learning loop
learning_rate = 1e-3
for i in range(0, 10000):
Y = X + 1.0
loss = mse(Y)
loss.backward()
# the learning part, so we turn off the gradients from getting updated temporarily
with torch.no_grad():
# the gradient tells us which direction we are off, so we go in opposite direction
X -= learning_rate * X.grad
# and we zero out the gradients to get fresh values on each learning loop iteration
X.grad.zero_()
print(X)
# we see this is an approximate answer
|
bc043f615d17cc16c9cd73b7475b9bd761bdcc5e | harish-rajendran/Python-hunter | /unique in list.py | 610 | 3.65625 | 4 | #-------------------------------------------------------------------------------
# Name: module3
# Purpose:
#
# Author: Admin
#
# Created: 17-08-2016
# Copyright: (c) Admin 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
a=[1,4,3,5,4,3,1,6,5,7,6]
b=[]
for x in range (len(a)):
for y in range (len(a)):
if a[x]==a[y] and x!=y:
b.append(a[x])
for x in a:
if x not in b:
print c
if __name__ == '__main__':
main()
|
9d1e29e927d6a17921951dba839c5cc203ee54a0 | Faringe/home | /Home3.py | 130 | 3.765625 | 4 | #Задание №3
number = range(20, 241)
new_list = [el for el in number if el % 20 == 0 or el % 21 == 0]
print(new_list) |
be982cc5e14d63442baafc7deace12bba42a937c | ItManHarry/Python | /PythonCSDN/code/chapter3/practise2.py | 189 | 3.875 | 4 | #数字游戏
SIZE = 5
v_array = []
for i in range(SIZE):
v_array.append([0] * SIZE)
print(v_array)
for i in range(SIZE):
for j in range(SIZE):
print(v_array[i][j], end='')
|
7d0bd67800bd56df644432c7c9764f5ccc0be961 | kentaroy47/atcoder | /test_misc/expections.py | 415 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 26 10:35:21 2019
@author: Ken
"""
# 例外ハンドラ
short_list = list(range(3))
for i in range(10):
try:
short_list[i]
except IndexError as err:
print(err)
print("the given index is too short..", i)
print("must be smaller than:", len(short_list)-1)
except:
print("something bad happened")
|
b23dbd5f009e1381854e509693bdcff9dbfef446 | spolpen/GestionSucursales | /Empleado.py | 1,642 | 3.53125 | 4 | # coding=utf-8
__author__ = 'Polo'
from Persona import *
class Empleado(Persona):
"""Clase empleado
Esta clase hereda de persona y ademas tiene varios atributos propios como el salario y el horario.
"""
def __init__(self, ide, dni, nombre, telefono, direccion, salario, horario):
"""Constructor empleado
Metodo constructor de la clase empleado, que inicializa sus atributos que hereda de persona
mediante el constructor de persona, ademas de los suyos propios.
:param ide:
:param dni:
:param nombre:
:param telefono:
:param direccion:
:param salario:
:param horario:
:return:
"""
Persona.__init__(self, ide, dni, nombre, telefono, direccion)
self.salario = salario
self.horario = horario
def get_salario(self):
"""Get salario empleado
Metodo que devuelve el salario de un empleado
:return:
"""
return self.salario
def get_horario(self):
"""Get horario empleado
Metodo que devuelve el horario de un empleado.
:return:
"""
return self.horario
def set_salario(self, salario):
"""Set salario empleado
Metodo que cambia el salario del empleado al parametro introducido.
:param salario:
:return:
"""
self.salario = salario
def set_horario(self, horario):
"""Set horario empleado
Metodo que cambia el horario de un empleado al parametro introducido.
:param horario:
:return:
"""
self.horario = horario |
8f165e736ee53b56108d2073100eae57adbd634d | skyla15/HireMeProject- | /0_Learning_Python/파이썬문법/36_Inheritance/36_3_super().__init__().py | 1,695 | 3.828125 | 4 | # 36.3.1 super()로 기반 클래스 초기화하기
# super().__init__ 없이 부모 클래스의 속성을 사용하면 에러 발생(부모의 인스턴스 생성 안됨)
# 만약 자식 클래스에 __init__() 메소드가 없다면
# 부모클래스의 __init()__이 실행되기에 부모클래스 초기화 필요없음
#
class Person:
def __init__(self):
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person):
def __init__(self):
print('Student __init__')
super().__init__() # super()로 기반 클래스의 __init__ 메서드 호출
self.school = '파이썬 코딩 도장'
james = Student()
print(james.school)
print(james.hello)
# 36.3.2 부모 클래스를 초기화하지 않아도 되는 경우
# 만약 자식 클래스에 __init__() 메소드가 없다면
# 부모클래스의 __init()__이 실행되기에 부모클래스 초기화 필요없음
class Person:
def __init__(self):
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person):
pass
james = Student() # Person __init__ 출력
print(james.hello)
# 참고 | 좀 더 명확하게 super 사용하기
# super는 다음과 같이 파생 클래스와 self를 넣어서 현재 클래스가 어떤 클래스인지 명확하게 표시하는 방법도 있습니다.
# 물론 super()와 기능은 같습니다.
# super(파생클래스, self).메서드
class Student(Person):
def __init__(self):
print('Student __init__')
super(Student, self).__init__() # super(파생클래스, self)로 기반 클래스의 메서드 호출
self.school = '파이썬 코딩 도장'
|
339a28c07d2ef510ba1cc97fc20f2ea03a90abad | MPankajArun/Python-Proctice-Examples | /Day 4/RegexDemo-match.py | 424 | 3.84375 | 4 | import re
regexp = re.compile("PSL")
s1 = "PSLaaa welcome to Pune. PSL PErsistyent ..."
s2 = "Welcome to PSL ... Good Morning"
if regexp.match(s1): #match start search begining of line from first character
print "Match found"
else:
print "Match not found"
print "---------------------------------------------------------------"
if regexp.match(s2):
print "Match found"
else:
print "Match not found"
|
a3ce6f01c4d77cb269c8845a2337b892407bdc34 | longyc2011/pystevens | /convert_i18n/convert_i18n.py | 1,280 | 3.78125 | 4 | #!/usr/bin/python3
# -- encoding utf-8--
import os
def parser_unicode(src_string):
""" parser unicode string to utf-8 string
Arguments:
src_string {str} -- [unicode string]
Returns:
[str] -- [utf-8 string]
"""
# src_string = "\\u4e0b\\u6587\\u6709\\u4eba{}\"'<>《》~¥#@%……&&@@##"
letters = src_string.split(r'\u')
temp_letters = []
results = []
for letter in letters:
if len(letter) > 4:
temp_letters.append(letter[:4])
results.append(
repr('\\u'.join(temp_letters).encode('utf-8').decode(
'unicode_escape')))
results.append(letter[4:])
temp_letters = ['']
else:
temp_letters.append(letter)
final_string = ''.join(results)
print(final_string)
return final_string
if __name__ == '__main__':
print('hello World')
with open(os.path.join("", "test.json"), 'w+', encoding="utf-8") as fwrite:
with open(os.path.join("", "test.txt"), "r", encoding="utf-8") as file_conent:
line_list = file_conent.readlines()
for line in line_list:
line = parser_unicode(line)
fwrite.write(line)
|
f9f54fb0380cf97f131c1dede8f706ae0be597bb | Audarya07/99problems | /P31.py | 548 | 4.34375 | 4 | # Determine whether a given integer number is prime.
from math import sqrt
def isPrime(num) :
'''A function to check whether a number is Prime or not.'''
if num > 1:
for i in range(2, int(sqrt(num))+1):
# If num is divisible by any number other than itself, return False.
if num % i == 0:
return False
return True
else:
return False
num = int(input("Enter the number : "))
if isPrime(num):
print("The number is Prime")
else :
print("The number is Not Prime")
|
b2cef925bddaeabacd981e27eccc7614d9eecc91 | ImGabreuw/digital-innovation-one | /introducao-a-linguagem-com-python/como-criar-um-codigo-em-python-que-funcione-de-acordo-com-a-relacao-das-variaveis/projeto/relacao-das-variaveis/main.py | 937 | 3.984375 | 4 | # Forma 1:
# a = int(input("Nota do primeiro bimestre: "))
# b = int(input("Nota do segundo bimestre: "))
# c = int(input("Nota do terceiro bimestre: "))
# d = int(input("Nota do quarto bimestre: "))
#
# media = (a + b + c + d) / 4
#
# if a <= 10 and b <= 10 and c <= 10 and d <= 10:
# print("Média: {}".format(media))
# else:
# print("Foi informado alguma nota errada")
# Forma 2:
a = int(input("Nota do primeiro bimestre: "))
if a > 10:
a = int(input("Você digitou errado. Primeiro bimestre: "))
b = int(input("Nota do segundo bimestre: "))
if b > 10:
b = int(input("Você digitou errado. Segundo bimestre: "))
c = int(input("Nota do terceiro bimestre: "))
if c > 10:
c = int(input("Você digitou errado. Terceiro bimestre: "))
d = int(input("Nota do quarto bimestre: "))
if d > 10:
d = int(input("Você digitou errado. Quarto bimestre: "))
media = (a + b + c + d) / 4
print("Média: {}".format(media))
|
e16c0380ae6c60dd4af0d973bd60845c67e5bae3 | nipuntalukdar/NipunTalukdarExamples | /python/misc/palindrome_partitioning.py | 2,581 | 3.53125 | 4 | '''
Given a string A, partition A such that every substring of
the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of A.
Solution:
Very similar to the chain matrix multiplication problem.
A string with 1 char has no cost of partitioning, as one
char is always a palindrome.
A sring with 2 chars, may have 0 cost if it is already
a partition, otherwise 1 + 0 + 0 will be the cost as it has to be
partitioned into 2 string with 1 char each which are anyway
palindromes.
For calculting minimum partitioning cost of substring from index
i to j is:
0 if susbtring from index i to j is already a palindrome.
Else, find the cut at index k, which make it minimum
for k = i to j -1.
So,
cost[i,j] = 1 + cost[i,k] + cost[k,j] # find k for this
# also for all substrings with length < j - i + 1,
the minimum cost is already calculated.
'''
def ispalindrome(val, start, end):
if start >= len(val) or end >= len(val):
return False
if start > end:
return False
i, j = start, end
while i <= j:
if val[i] != val[j]:
return False
i += 1
j -= 1
return True
BIG = 999999999999
def get_min_cut_palidrome_partitioning(inp):
numel = len(inp)
if numel <= 1:
return 0
cost = []
i = 0
while i < numel:
cost.append([BIG] * numel)
i += 1
# single char strings are always palindromem
# so number of cuts is zero for them
i = 0
while i < numel:
cost[i][i] = 0
i += 1
#
# cost[0][numel - 1] will hold the minimum cost or cuts
#
size = 2
while size <= numel:
i = 0
while i <= numel - size:
if ispalindrome(inp, i, i + size - 1):
cost[i][i + size -1] = 0
else:
mincost = BIG
k = i
j = i + size -1
while k < j:
tmpcost = cost[i][k] + cost[k+1][j] + 1
if tmpcost < mincost:
mincost = tmpcost
k += 1
cost[i][j] = mincost
i += 1
size += 1
return cost[0][numel - 1]
print(get_min_cut_palidrome_partitioning('aaaa'))
print(get_min_cut_palidrome_partitioning('aaa'))
print(get_min_cut_palidrome_partitioning('a'))
print(get_min_cut_palidrome_partitioning('xaay'))
print(get_min_cut_palidrome_partitioning('xaay'))
print(get_min_cut_palidrome_partitioning('axxayaay'))
print(get_min_cut_palidrome_partitioning('axxayyaxxa'))
|
6882d2936f9411a952d358e5cfd4af0a1f0b913e | skyaiolos/ProgrammingPython4th | /chapter1_A_Sneak_Preview/Step1/using_dictionaries01.py | 1,452 | 4 | 4 | # !/usr/bin/python3
# -*- coding:utf-8 -*-
# Created by Jianguo on 2017/5/31
"""
Description:
Using Dictionaries
The list-based record representations in the prior section work, though not without
some cost in terms of performance required to search for field names (assuming you
need to care about milliseconds and such). But if you already know some Python, you
also know that there are more efficient and convenient ways to associate property
names and values. The built-in dictionary object is a natural:
"""
bob = {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'}
sue = {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'hdw'}
print(bob['name'], sue['pay'], sep=',')
# Bob Smith,40000
print(bob['name'].split()[-1])
# Smith
sue['pay'] *= 1.10
print(sue['pay'])
# 44000.0
bob = dict(name='Bob Smith', age=42, pay=30000, job='dev')
sue = dict(name='Sue Jones', age=45, pay=40000, job='hdw')
print(bob, sue, sep="\n")
# {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'}
# {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'hdw'}
sue = {}
print(sue)
sue['name'] = 'Sue Jones'
sue['age'] = 45
sue['pay'] = 40000
sue['job'] = 'hdw'
print(sue)
print("-----lise(zip())------")
names = ['name', 'age', 'pay', 'job']
values = ['Sue Jones', 45, 40000, 'hdw']
n_v = list(zip(names, values))
print(n_v)
print()
print("-----dict(zip())------")
fields = ('name', 'age', 'job', 'pay')
record = dict.fromkeys(fields, "?")
print(record)
|
c19f90839bb4664558bbda37e8a49e9116c9245d | MuhammadAbuBakar95/Problem-Solving | /Two-Pointers/RemoveElement.py | 726 | 3.53125 | 4 | class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums) == 0:
return 0
curr = 0
replace_at = len(nums) - 1
new_len = len(nums)
while curr < replace_at + 1:
print nums, new_len, curr
if nums[curr] == val:
new_len -= 1
tmp = nums[curr]
nums[curr] = nums[replace_at]
nums[replace_at] = tmp
replace_at -= 1
else:
curr += 1
return new_len
nums = [1]
val = 1
sol = Solution()
print sol.removeElement(nums, val)
print nums |
20478ee93248eecdf891ebf7eafea4369ddb0695 | rupaku/codebase | /python basics/list.py | 5,838 | 4.3125 | 4 | '''
List is a collection which is ordered and changeable. Allows duplicate members.
'''
List = []
List.append(1)
List.append('Geeks')
List.append('for')
List.append('Geeks')
List.insert(1,'Hello')
List.extend(['Goodbye','people'])
print(List)
print(List[1])
print(List[-1])
print(List[:])
print(List[::1])
print(List[::2])
List.remove('for')
print(List)
List.pop()
print(List)
List.pop(0)
print(List)
print(List[1:4])
print(List[::-1])
list2 = ['cat', 'bat', 'mat', 'cat',
'get', 'cat', 'sat', 'pet']
print(list2.index('cat')) # 0
print(list2.index('cat', 2, 6 )) # ele,start,end # 3
print(list2.count('cat')) #3
# To get the number of occurrences
# of each item in a list
print([[i,list2.count(i)] for i in set(list2)])
# To get the number of occurrences
# of each item in a dictionary
print(dict((i,list2.count(i))for i in set(list2)))
numbers = [1, 3, 4, 2]
numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)
#Example for Key sort
def sortSecond(val):
return val[1]
list1 = [(1, 2), (3, 3), (1, 1)]
list1.sort(key=sortSecond)
print(list1)
list1.sort(key=sortSecond, reverse=True)
print(list1)
#reduce function:
'''The reduce(fun,seq) function is used to apply a particular function
passed in its argument to all of the list elements mentioned in the sequence passed along'''
import functools
lis = [ 1 , 3, 5, 6, 2, ]
#sum of list
print(functools.reduce(lambda a,b:a+b,lis)) #17
#Max of list
print(functools.reduce(lambda a,b:a if a > b else b,lis)) #6
# operator function
import operator
print(functools.reduce(operator.add,lis)) #17
#Max of list
print(functools.reduce(operator.mul,lis)) #180
''' accumulate:
apply a particular function passed in its argument to all of the list elements returns a list containing the intermediate results
Both reduce() and accumulate() can be used to calculate the summation of a sequence elements.
reduce() is defined in “functools” module, accumulate() in “itertools” module.
reduce(fun,seq)
accumulate(seq,fun)
'''
import itertools
#sum of list
print(list(itertools.accumulate(lis,lambda a,b:a+b))) #[1, 4, 9, 15, 17]
''' sum function'''
print(sum(lis)) #17
''' ord function returns unicode of character'''
print(ord('a')) #97
# print(ord('ab')) #error only one character
'''chr function returns a string for unicode integer'''
print(chr(97)) #a
print(chr(400)) #UnicodeEncodeError: 'ascii' codec can't encode character
'''cmp :compares two list elements
Syntax : cmp(list1, list2)
Returns : This function returns 1, if first list is “greater” than second list,
-1 if first list is smaller than the second list
else it returns 0 if both the lists are equal.
'''
list1 = [ 1, 2, 4, 3]
list2 = [ 1, 2, 5, 8]
# print cmp(list2, list1) used in python2
#max() min()
#length of list
print(len(lis))
'''Any (like or)
Returns true if any of the items is True. It returns False if empty or all are false.
'''
print (any([False, True, False, False])) #True
print(any([False, False, False, False])) #False
'''All (like and)
Returns true if all of the items are True
'''
print (all([True, True, True, True])) #True
print (all([False, True, True, False])) #False
'''enumerate
Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object.
This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.
enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is
to be started, by default it is 0
'''
l1=["eat","sleep","dance"]
obj=enumerate(l1)
print(list(enumerate(l1))) #[(0, 'eat'), (1, 'sleep'), (2, 'dance')]
print(list(enumerate(l1,2))) #start index
#in loop
for ele in enumerate(l1):
print(ele)
'''filter
filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
filter(function, sequence)
sequence:sets, lists, tuples, or containers of any iterators.
Returns: returns an iterator that is already filtered.
Application: It is normally used with Lambda functions to separate list, tuple, or sets.
'''
seq = [0, 1, 2, 3, 5, 8, 13]
# result contains even numbers of the list
res=filter(lambda x:x%2 == 0,seq) #[0, 2, 8]
print(list(res))
'''map
returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)
map(fun, iter)
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
'''
#addition
def add(n):
return n+n
num=(1,2,3,4)
res=map(add,num)
print(list(res)) #[2, 4, 6, 8]
#using map
print(list(map(lambda x:x+x,num))) #[2, 4, 6, 8]
#add two list using lambda and map
num1=[1,2,3]
num2=[4,5,6]
print(list(map(lambda x,y:x+y,num1,num2))) #[5, 7, 9]
#list of string
l = ['sat', 'bat', 'cat', 'mat']
print(list(map(list,l))) #[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]
'''lambda functions
anonymous function without a name
which can have any number of arguments, but it can only have one expression.
doesn't include "return" statement
don't have to assign it to variable
application: when we require a nameless function for a short period of time.
'''
#cube
def cube(y):
return y * y * y;
g = lambda x: x * x * x
print(g(7))
print(cube(5))
#lambda with filter
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
print(list(filter(lambda x: (x%2!=0),li))) #[5, 7, 97, 77, 23, 73, 61] odd
#lambda with map
print(list(map(lambda x:x*2,li))) #[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
#lambda with reduce
#sum of list
from functools import reduce
print(reduce(lambda x,y:x+y,li)) #481
|
0ad44f0e42c6d65fa34a7410755e4543aa049387 | jhwsx/liaoxuefeng_python_tutorial_learning | /python_1/test_operator_03.py | 282 | 3.71875 | 4 | '''
练习3:输入年份判断是不是闰年。
能被4整除却不能被100整除 或 能被400整除的年份是闰年
'''
year = int(input("输入年份:"))
is_leap = (year % 4 == 0 and year %100 != 0) or year % 400 == 0
print('%d 年是闰年吗?%s' % (year, is_leap)) |
1173ac00927adbe83aad5781932bfbfffa8350ab | samidarko/datascience-capstone | /longest_line.py | 436 | 3.546875 | 4 | def max_line_length(file_name):
max_length = 0
with open(file_name) as f:
for line in f.readlines():
line_length = len(line.strip())
if line_length > max_length:
max_length = line_length
# return max_length
print("{} max line length is {}".format(file_name, max_length))
max_line_length('datasets/en_US/en_US.blogs.txt')
max_line_length('datasets/en_US/en_US.news.txt')
|
b34507fd9cc9cf36480bdca07e8bfb6673a755fd | huangxiao233/Sort | /排序/Heap_SORT.py | 2,388 | 3.75 | 4 | class Heap(object):
def __init__(self,elements):
self.list = []
for element in elements:
self.add(element)
# 接下来就是逐层交换的过程,要保证节点大于他的子节点
# 先把新的元素添加到列表里面去
def add(self,element):
self.list.append(element)
# 找出当前节点的下标,和他的父亲下标
cur = len(self.list) - 1
par = (cur - 1)/2
# 逐层交换
while cur != 0 and self.list[cur] > self.list[par]:
self.list[cur] , self.list[par] = self.list[par] , self.list[cur]
# 当前结点的下标也是要交换的,变成了原来的父节点的下标,然后再寻找新的父节点。
cur = par
par = (cur - 1)/2
# 弹出
def pop(self):
# 将尾元素删除出来
self.list[0] , self.list[-1] = self.list[-1] , self.list[0]
result = self.list.pop(0)
cur = 0
# 由NEXT来判断是否还需进行交换,是否有子节点(当前节点是否有孩子)
NEXT = True
# 删除后要进行调整
while cur < len(self.list) and NEXT:
#到这里先认为是不能进行交换了,由下面的代码来判断是否有孩子节点。
NEXT = False
# 找出左右孩子的索引下标
left_child , right_child = (cur * 2) + 1 , (cur * 2) + 2
# 左孩子索引越界,也就是实际上左孩子不存在
if left_child >= len(self.list):
break
# 接下来分为右孩子存在和不存在的情况
# 右孩子不存在
if right_child >= len(self.list):
if self.list[left_child] > self.list[cur]:
self.list[left_child] , self.list[cur] = self.list[cur] , self.list[left_child]
cur = left_child
NEXT = True
# 右孩子存在
else:
# 先左右孩子进行比较大小,找出最大的
max_index = right_child if self.list[right_child] > self.list[left_child] else left_child
# 再将最大的子节点,与他的父节点进行比较
if self.list[cur] < self.list[max_index]:
self.list[cur] = self.list[max_index]
cur = max_index
NEXT = True
return result |
edbb478cc1ad43d19b9dff170b50bf6ab51aa280 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/mhlsan022/question2.py | 1,447 | 4.625 | 5 | '''This program reformats a text file so that all lines are at most a given length
Sandile Mahlangu
13 May 2013'''
import textwrap
def print_file():
'''This function accesses a text from a file and prints out a reformmatted text in an output file with given length'''
input_file=input('Enter the input filename:\n') #The file which we get the text from
filename=input('Enter the output filename:\n') #The file where we print out the formatted text
length=eval(input('Enter the line width:\n')) #The length which is needed
#Open the file where the program will get the text
file_text=open(input_file,'r')
list_text= file_text.read()
file_text.close()
output= open(filename,'w') #The file where everything will be printed in
paragraph_list= list_text.split('\n\n') #Splitting the file across paragraphs
#Move through the paragraphs and reformat them and then print them into the output file
for paragraph in paragraph_list:
#Removing new line characters and replacing the with a space
paragraph=paragraph.replace('\n',' ')
#Reformating the paragraph
paragraph=textwrap.wrap(paragraph,width=length)
for printing in paragraph:
#printing out each reformatted string
print(printing, file=output)
print(file=output)
output.close()
if __name__=='__main__':
print_file() |
fbcdc919651e32c2599c4f354c9dd98f7c8c77da | jeffleon/holbertonschool-higher_level_programming | /0x0A-python-inheritance/3-is_kind_of_class.py | 197 | 3.625 | 4 | #!/usr/bin/python3
"""
Class is_kind_of_class
"""
def is_kind_of_class(obj, a_class):
"""
return True if is a instance of the class
"""
return isinstance(obj, a_class)
|
4c829a838b082a00b929f714747878ee6b776347 | anoop600/Python-Basics-Learn | /11. IO/file_write.py | 1,073 | 3.71875 | 4 | # cities = ["a", "b", "c", "d", "e"]
# with open("write-to-file.txt", "w") as city_file:
# for city in cities:
# print(city, file=city_file, flush=True)
# cities = []
# with open("write-to-file.txt", "r") as city_file:
# for city in city_file:
# #when written to file it appends \n in end of line/beginning.
# #strip wont remove character from between the words
# #Strip can do partial match of characters from the word and remove those
# #To remove the \n from each will use strip()
# cities.append(city.strip('\n'))
# print(cities)
# for city in cities:
# print(city)
# imelda = "More Mayhem", "Idelda May", "2011", (
# (1, "Pulling the Rug"), (2, "Psycho"), (3, "Meyhem"), (4, "Kentish Town Waltz")
# )
# with open("imelda.txt", "w") as imelda_file:
# print(imelda, file=imelda_file)
with open("imelda.txt", "r") as imelda_file:
contents = imelda_file.readline()
imelda = eval(contents)
print(imelda)
title, artist, year, track = imelda
print(title)
print(artist)
print(year)
print(track)
|
dfe9bf09a95aba88fca34c1ccf8d63dc48bf942b | ankur-anand/Factorial-Algorithm | /fact_04_prime_decompose.py | 764 | 4.0625 | 4 |
def calculate_factorial_prime_decompose(number):
'''
This function takes one integer
agruments and return the factorial of the agruments.
Since there are (number / ln number) prime number smaller than number
so we can further reduce the total number of multiplication
'''
prime = [True]*(number + 1)
result = 1
for i in xrange (2, number+1):
if prime[i]:
#update prime table
j = i+i
while j <= number:
prime[j] = False
j += i
#calculate number of i in n!
sum = 0
t = i
while t <= number:
sum += number/t
t *= i
result *= i**sum
return result
|
1845ed56acd9c0ae71c61078620f95363480cc80 | NRuT0/Project-Web-Android | /Games In Any Language/numbergame.py | 493 | 4.21875 | 4 | import random
number = random.randint(1, 25)
chances = 0
print("Guess a number (between 1 an 25):")
while chances < 5:
guess = int(input("Enter Your Guess : "))
if guess == number:
print("Congratulation YOU WON!!!")
exit()
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
print("chances Left : ",5-chances)
print("YOU LOSE!!! The number is : ", number) |
91335c2d977bb50eaeb32f661ccb3a6c6e527d33 | steinstadt/AtCoder | /ABC163/prob_a.py | 73 | 3.515625 | 4 | import math
# input
R = int(input())
# output
print(math.pi * R * 2.0)
|
732149ffd3afc189af6671fac0489d3f61e3a446 | gitHirsi/PythonNotes | /001基础/017文件操作/04访问模式特点02.py | 428 | 3.59375 | 4 | """
@Author:Hirsi
@Time:2020/6/11 11:19
"""
"""
1.r+ 和 w+ 的区别
2.文件指针对数据读取的影响
"""
# r+ 文件指针在开头,所以能读取出来数据
f1=open('test.txt','r+')
f1.write('hirsiboom')
print(f1.read())
f1.close()
# w+ 指针在开头,用新内容覆盖原内容
# a+ 没有会新建文件,指针在结果,无法读取数据
f2=open('test.txt','a+')
con = f2.read()
print(con)
f2.close() |
87be72ce23e1a1e27fdd5bf66e77e801f6b019c9 | RecursiveJoy/LotsOfTinyPythonPrograms | /PhoneBook.py | 616 | 4.09375 | 4 | def main():
#create two lists
names = ['Michael', 'Gob', 'Buster', 'Maybe', 'Lucille', 'Lindsay', 'Marta', \
'George', 'Annyong', 'Tobias']
numbers = ['555-4011','555-9865', '555-5755', '555-3161', '555-0022', \
'555-4651','555-0605', '555-1115', '555-3061', '555-7017']
#prompt user for a name
name = input('Enter the name of the person whose phone number you want: ')
#get index of the name in the name list
index = names.index(name)
#print the value of the phone number with that same index
print(numbers[index])
main()
|
f4b67aeb393844404277b8b52462ba0e3198c277 | abdoelsaih/Operators-in-Python | /OperatorsPython/ArithmeticOperatores.py | 170 | 3.625 | 4 | a,b=10,5
print('Addition:' ,a+b)
print('Subtraction :',a-b)
print('Mul:' ,a*b)
print('Div:' ,a/b)
print('Mud:' ,a%b)
print('Pow:' ,a**b)
print('Floor Div:' ,a//b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.