blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
ea98e09a847e3342735e6be680f6b30f70ea82bc | nownabe/competitive_programming | /AtCoder/JOI2008YOA_Otsuri.py | 314 | 3.671875 | 4 | # https://atcoder.jp/contests/joi2008yo/tasks/joi2008yo_a
def search(amount):
otsuri = 1000 - amount
count = 0
for coin in [500, 100, 50, 10, 5]:
if otsuri >= coin:
count += otsuri // coin
otsuri = otsuri % coin
return count + otsuri
print(search(int(input())))
|
3d4f45c674aa87192d2e5516f93ad657ed354a5c | paul-schwendenman/advent-of-code | /2015/day05/day5.py | 1,291 | 4 | 4 | import fileinput
import re
def has_three_vowels(word):
vowels = "aeiou"
count = 0
for letter in word:
if letter in vowels:
count += 1
return count >= 3
def has_double_letter(word):
for num, letter in enumerate(word[:-1]):
if letter == word[num+1]:
return True
return False
def has_restricted_pairs(word):
bad_substrings = ["ab", "cd", "pq", "xy"]
return any(substring in word for substring in bad_substrings)
def is_nice_string(word):
return has_three_vowels(word) and has_double_letter(word) and not has_restricted_pairs(word)
def part1(filename = "input"):
count = 0
for line in fileinput.input(filename):
if is_nice_string(line):
count += 1
return count
def has_repeated_pair(word):
return re.search(r'(..).*\1', word) is not None
def has_letter_sandwich(word):
return re.search(r'(.).\1', word) is not None
def is_nice_string2(word):
return has_repeated_pair(word) and has_letter_sandwich(word)
def part2(filename = "input"):
count = 0
for line in fileinput.input(filename):
if is_nice_string2(line):
count += 1
return count
def main():
print(part1())
print(part2())
if __name__ == '__main__':
main() |
c5d02c80368ae7e0de9aa47cef9ace451fe89428 | den01-python-programming-exercises/exercise-1-32-inheritance-tax-MrFathed | /src/exercise.py | 541 | 3.8125 | 4 | def main():
#write your code below this line
inheritance = int(input("Inheritance:"))
years = int(input("Years since death:"))
taxable = inheritance - 325000
tax = 0.0
if years < 3:
tax_rate = 0.40
elif years < 4:
tax_rate = 0.32
elif years < 5:
tax_rate = 0.24
elif years < 6:
tax_rate = 0.16
elif years < 7:
tax_rate = 0.08
else:
tax_rate = 0.0
tax = taxable * tax_rate
print("Tax: " + str(tax))
if __name__ == '__main__':
main()
|
28cc129160bdae17315f3c21132cfc5ff9b60d25 | rheehot/baekjun | /1_dimention/3052.py | 160 | 3.59375 | 4 | arr = [0] * 10
num_arr = []
for i in range(10):
arr[i] = int(input())
for j in arr:
num_arr.append(j % 42)
num_arr = set(num_arr)
print(len(num_arr)) |
a7dea7b5a6491e851e01ae68c80ece489b789a92 | mepujan/IWAssignment_1_python | /data_types/data_type_40.py | 185 | 4 | 4 | # Write a Python program to add an item in a tuple.
def main():
sample_tuple=(1,2,3)
new_tuple= sample_tuple + (5,)
print(new_tuple)
if __name__ == "__main__":
main() |
8c7df9386326069d7af8d47fc5f443245ac61c9e | Gendo90/topCoder | /0-300 pts/topcoderMagicSquare.py | 1,452 | 4.25 | 4 | # Problem Statement
#
# A magic square is a 3x3 array of numbers, such that the sum of each row, column, and diagonal are all the same. For example:
#
# 8 1 6
# 3 5 7
# 4 9 2
# In this example, all rows, columns, and diagonals sum to 15.
# You will be given a tuple (integer) representing the nine numbers of a magic square, listed left-to-right, top-to-bottom. However, one of these numbers will be replaced by a -1. Write a method to determine which number was removed. For example, if the 7 was removed from the magic square above, you would be given { 8, 1, 6, 3, 5, -1, 4, 9, 2 }, and your program should return 7.
# The completed magic square will consist of exactly 9 distinct positive integers.
# Definition
#
# Class:
# MagicSquare
# Method:
# missing
# Parameters:
# tuple (integer)
# Returns:
# integer
# Method signature:
# def missing(self, square):
#Gendo90 has submitted the 250-point problem for 230.40 points
#Successful on first try!
class MagicSquare(object):
def missing(self, square):
reshaped = [square[0:3], square[3:6], square[6:9]]
target_num = 0
replaced_val = 0
for item in reshaped:
if(-1 not in item):
target_num = sum(item)
break
for item in reshaped:
if(-1 in item):
replaced_val = target_num-(sum(item)+1)
return replaced_val
test = MagicSquare()
print(test.missing(()))
|
042580e404aa4082d010372ac2239bde1a7e7893 | 4RCAN3/D-Crypter | /D-Crypter/Beaufort.py | 3,196 | 4.375 | 4 | '''Taking the input of CIPHERTEXT from the user and removing UNWANTED CHARACTERS and/or WHITESPACES'''
Input = input("Enter ciphertext:")
Input = Input.upper()
NotRecog = '''`~1234567890!@#$%^&*()-_=+[{]}\|'";:.>/?,< '''
for i in Input:
if i in NotRecog:
Input = Input.replace(i,'')
'''Taking the input of KEY from the user and removing UNWANTED CHARACTERS and/or WHITESPACES'''
Key = input("Enter key:")
Key = Key.upper()
NotRecog = '''`~1234567890!@#$%^&*()-_=+[{]}\|'";:.>/?,< '''
for i in Key:
if i in NotRecog:
Key = Key.replace(i,'')
'''Making the KEYWORD which will be used to decipher the ciphertext
Keyword is made on the basis of two things:
1) LENGTH of the Ciphertext = Keyword
2) The KEY is REPEATED again and again till the length is statisfied
Ex: Ciphertext: Aeeealuyel
Key: Hippo
Keyword:HippoHippo'''
Keyword = ''
for i in range(0,len(Input)):
if len(Keyword)<=len(Input):
if len(Input)==len(Key):
n = len(Input)
Keyword += Key[0:n]
elif len(Input)-len(Key)<=len(Input)-len(Keyword):
n = len(Input)-len(Key)
Keyword += Key[0:n]
else:
n = len(Input)-len(Keyword)
Keyword += Key[0:n]
if len(Keyword)==len(Input):
break
'''Deciphering the Ciphertext using the Keyword and TempLists
The AlphaList and TempLists are reversed,i.e.,A will be Z, B will be Y and so on, This is the main difference between
Vigenere and Beaufort Cipher'''
AlphaList = ['Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A']
Result = ''
'''Creation of TempLists:
TempLists(Required row of letters from vigenere grid) is made on the basis of Caesar shift.
A Beaufort Square has 26 Rows & Columns each labeled as a LETTER of the ALPHABET in ORDER.
Each row is shifted(Caesar Shift) according to the formula: Index/Number of Label Letter-1
Ex: Let the row be Z
Number of Label Letter: 26
Shift: 26-1=25
After Shifting the List is reversed on the basis explained above.
Deciphering:
Deciphering is done in 3 steps:
1) A letter of the Keyword is taken
2) Corresponding(Same index/number) Letter of Ciphertext is searched in the row of TempLists
3) After finding the Ciphertext Letter the Column Letter/Index(Check the letter at same index in original AlphaList) is
the Deciphered Letter
Ex: Ciphertext: Aeeealuyel
Key: Hippo
Keyword: Hippohippo
Let letter be H
Corresponding Letter in Ciphertext: A
TempList: ['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A', 'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K', 'J', 'I']
Location of A in TempList: Index 7
In AlphaList at Index 7 is H
ColumnName/Index: H
Deciphered Letter: H'''
for i in range(0,len(Keyword)):
TempLi = ['Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A']
if Keyword[i]=='A':
Result += Input[i]
else:
for j in range(0,AlphaList.index(Keyword[i])):
TempLi+=[TempLi.pop(0)]
L = Input[i]
n = TempLi.index(L)
Result += AlphaList[25-n]
print("Deciphered text:",Result) |
6eb78f742fe36d3460c58d6947f5ba03bb180fd8 | moon0331/baekjoon_solution | /programmers/고득점 Kit/위장.py | 530 | 3.71875 | 4 | from collections import defaultdict
def solution(clothes):
clothes_dict = defaultdict(int)
for x, y in clothes:
clothes_dict[y] += 1
answer = 1
for x in clothes_dict.values():
answer *= (x+1)
return answer - 1
clothes_list = [
[["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]],
[["crowmask", "face"], ["bluesunglasses", "face"], ["smoky_makeup", "face"]]
]
returns = [5, 3]
for c, r in zip(clothes_list, returns):
print(solution(c) == r) |
3e8368833319e2d6d6d5fb552e803d346dec720b | vector5891/Perceptrons | /test-demos/stringops.py | 2,635 | 3.78125 | 4 | # stringops.py
# String processing functions
# Test-Driven Development (TDD): write failing tests FIRST, then write
# code to make tests pass.
from hypothesis import given, assume
from hypothesis.strategies import text
def capitalizeWord(word):
"""Make the first character of word uppercase. If first character is
not a letter, or the word is the empty string, just return the
word as-is.
>>> capitalizeWord('Chris')
'Chris'
>>> capitalizeWord('chris')
'Chris'
>>> capitalizeWord('42')
'42'
>>> capitalizeWord('-6')
'-6'
>>> capitalizeWord(' ')
' '
>>> capitalizeWord(' hello')
' hello'
>>> capitalizeWord('étienne')
'Étienne'
>>> capitalizeWord('δx')
'Δx'
>>> capitalizeWord('')
''
"""
if len(word) == 0:
return word
else:
return word[0].upper() + word[1:]
def trimSpaces(s):
"""Remove trailing and leading spaces, but leave interior spaces alone.
>>> trimSpaces(' yes ')
'yes'
>>> trimSpaces(' not here ')
'not here'
"""
return s.strip()
# Example of using unittest module
# Often, unittest code is put into a *separate* file.
import unittest
class StringOpsTests(unittest.TestCase):
# Each test is written as a separate method in this class.
def test_trim_spaces(self):
self.assertEqual('hello world',
trimSpaces(' hello world '))
def test_trim_preserves_interior_spaces(self):
self.assertEqual(trimSpaces('wow! it works. '),
'wow! it works.')
# Can specify some initialization code that runs before/after each
# test.
def setUp(self):
print("BEFORE")
def tearDown(self):
print("AFTER")
# We're still within the unittest-derived class, but we're going
# to use hypothesis for specifying properties.
@given(s=text())
def test_first_char_is_capital(self, s):
assume(len(s) > 0) # if false, this test case won't count
lc_latin_b_curls = [0x221, 0x234, 0x235, 0x236]
assume(s[0].isalpha() and ord(s[0]) < 128) # ascii only
assert capitalizeWord(s)[0].isupper()
@given(s=text())
def test_rest_of_string_unchanged(self, s):
assume(len(s) > 0)
assert capitalizeWord(s)[1:] == s[1:]
if __name__ == "__main__":
# This block runs only if this script is being run directly, not
# if it's being imported into another module.
import doctest
fails, tests = doctest.testmod()
assert fails == 0 and tests > 0
print("Passed", tests, "doc tests.")
unittest.main()
|
4628aec6692f05704bd74d799a40d08f34ae0502 | marekbrzo/PythonDataAnalysisNotes | /5-1_OutlierAnalysisExtremeUnivariateMethods.py | 3,601 | 3.828125 | 4 | # OUTLIER ANALYSIS
# Outlier detection is useful for the following: Preprocessing task for analysis or machine learning. Analytical
# methods of its own.
# Three main types of outliers:
# Point outliers: observations anomalous with respect to the majority of observation in a feature( univariate outlier)
# Contextual outliers: observations considered anomalous give a specific context. (E.g., Warm day, but where and when)
# Collective outliers: a collection of observations anomalous but appear to close to one another because they all have
# a similar anomalous value.
# Methods for Outlier Detection
# Extreme value analysis with the Tukey methods.
# Multivariate analysis with boxplots and scatterplot matrices.
# Machine learning - density-based spatial clustering of applications with noise (DBSCAN) and PCA.
# Outlier Analysis can be used for: Discovering anomalies such as, Equipment failure, Fraud, Cybersecurity event.
# In this section we will be using the Tukey method. They can be used to find extreme values outside the interquartile
# range.
# When looking at boxplots, the whiskers are set at 1.5 the interquartile range. Most likely data points outside the
# whiskers are outliers. The most top whisker to the most top box bar represents the UPPER QUARTILE, here 25% of the
# data points are higher then the box bar value. Analogues with the UPPER QUARTILE, is the LOWER QUARTILE, where the
# extreme lows are.
# Instead of using the BOXPLOT we can determine the TUKEY Outlier Label mathematically.
# Interquartile Range (Spread: IQR) = Distance between the Lower Quartile (@25% [1st:Q1]) and the Upper Quartile(@75% [3rd:Q3])
# a = Q1 - 1.5(IQR)
# b = Q3 + 1.5(IQR)
# Mins below a or maxs above b, then the variable is suspect for outliers.
#%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from matplotlib.pylab import rcParams
#%%
rcParams['figure.figsize'] = 5,4
sb.set_style('whitegrid')
#%%
address = "C:/Users/Marek/Desktop/Python/Ex_Files_Python_Data_Science_EssT/Ex_Files_Python_Data_Science_EssT/Exercise Files/Ch05/05_01/iris.data.csv"
# Indication that comma seperates data
flower_data = pd.read_csv(address,
header = None,
sep = ',')
flower_data.columns=['Sepal Length','Sepal Width', 'Petal Lenght','Petal Width', 'Species']
# X and Y values of the data
flower_data_x = flower_data.iloc[:,0:4].values
flower_data_y = flower_data.iloc[:,4].values
flower_data[:5]
#%%
# Lets make a BoxPlot
flower_data.boxplot(return_type = 'dict')
plt.plot()
#%%
# Notice in the Sepal width plot, values above 4 and below 2.05 are great outlier candidates. The lie outside the whiskers.
# Let us deal with this outliers. First we need to filter out the data.
sepal_width =flower_data.iloc[:,1]
iris_outliers = (sepal_width > 4)
flower_data[iris_outliers]
#%%
# Now values of sepal width less than 2.05
sepal_width =flower_data.iloc[:,1]
iris_outliers = (sepal_width < 2.05)
flower_data[iris_outliers]
# This is how visually we determine outliers
#%%
# Applying the Tukey outlier method.
pd.options.display.float_format = '{:.1f}'.format
x_flower_data = pd.DataFrame(flower_data_x)
print (x_flower_data.describe())
#%%
# We can determine the IQR mathematically.
# IQR = 3.3 - 2.8 = 0.5
# Tukey = (1.5)*IQR = 0.75
# Outliers in the first quartile = 2.8 - 0.75 = 2.05
# Our min values is less than that.
# Outliers in the third quartile = 3.3 + 0.75 = 4.05
# Our max value is more than that. |
4d7da82ee3cb1c2ad364b70070013da79fb7b618 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week_11/Dynamic Programming/Longest Increasing Subsequence.py | 2,516 | 4.09375 | 4 | Longest Increasing Subsequence
Given an array of integers, find the length of the longest (strictly) increasing subsequence from the given array.
Example 1:
Input:
N = 16
A[]={0,8,4,12,2,10,6,14,1,9,5
13,3,11,7,15}
Output: 6
Explanation:Longest increasing subsequence
0 2 6 9 13 15, which has length 6
Example 2:
Input:
N = 6
A[] = {5,8,3,7,9,1}
Output: 3
Explanation:Longest increasing subsequence
5 7 9, with length 3
Your Task:
Complete the function longestSubsequence() which takes the input array and its size as input parameters and returns the length of the longest increasing subsequence.
Expected Time Complexity : O( N*log(N) )
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 105
0 ≤ A[i] ≤ 106
Solution
class Solution:
#binary search function finds the position of the first integer
#in arr[] which is greater than or equal to 'value'.
def binarySearch(self,lst, l, h, value):
#if new value is greater than all array values,
#then it is placed at the end.
if value > lst[h]:
return h+1
#binary search algorithm.
while h>l:
middle = (h+l)//2
if lst[middle] == value:
return middle
if lst[middle] > value:
h = middle
else:
l = middle + 1
return h
#Function to find length of longest increasing subsequence.
def longestSubsequence(self,a,n):
#tail[i] holds the last value in a subsequence of length i+1.
tail = [0 for _ in range(n)]
tail[0] = a[0]
#the position of last filled index in tail[].
lastIndex = 0
for i in range(1,n):
#getting the furthest possible index for a[i].
index = self.binarySearch( tail, 0, lastIndex, a[i] )
tail[index] = a[i]
#updating lastIndex.
lastIndex = max( lastIndex, index )
#returning the result.
return lastIndex+1
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
for _ in range(int(input())):
n = int(input())
a = [ int(x) for x in input().split() ]
ob=Solution()
print(ob.longestSubsequence(a,n))
# } Driver Code Ends |
4baf97aeec02c5cfd6bb230125e43d7ecedfeae9 | davidnge/euler | /prob-7.py | 520 | 4.03125 | 4 | #What is the 10 001st prime number?
import math
def isPrime(number):
if number == 2:
return True
if number % 2 == 0:
return False
i = 3
sqrtOfNumber = math.sqrt(number)
while i <= sqrtOfNumber:
if number % i == 0:
return False
i = i+2
return True
def main():
n = 2
count = 0
while n > 0:
if isPrime(n):
count+=1
if count == 10001:
print n
break
n+=1
main() |
f47622994a626386f0e8861c2c60561e3337b37e | juliodparedes/python_para_dioses | /ejercicios/08MayorNumero.py | 293 | 3.96875 | 4 | print("Humano vas a ingresar dos números:")
n1=int(input("Numero 1: "))
n2=int(input("Numero 2: "))
if n1==n2:
print("Humano los 2 numeros son iguales")
elif n1>n2:
print(f"Humano el número {n1} es mayor que {n2}")
else:
print(f"Humano el número {n2} es mayor que {n1}") |
631270d081b572d6901a8147220cd8e434ee705a | camelct/python-study | /5-6.如何在环状数据结构中管理内存.py | 1,521 | 3.875 | 4 | '''
问题:如何在环状数据结构中管理内存?
实际案例
在python中,垃圾回收器通过引用计数来回收垃圾对象,但某些环状数据结构(树,图...)存在对象间的循环引用,
比如树的父节点引用子节点子节点也同时引用父节点.此时同时del掉引用父子节点两个对象不能被立即回收.
如何解决此类的内存管理问题?
解决方案
使用标准库weakref,它可以创建一种能访问对象但不增加引用计数的对象,
'''
# import weakref
# class A(object):
# # 析构函数 在回收的时候,会被调用
# def __del__(self):
# print('in A.__del__')
# a = A()
# import sys
# print(sys.getrefcount(a) - 1)
# a2 = a
# print(sys.getrefcount(a) - 1)
# del a2
# print(sys.getrefcount(a) - 1)
# # a = '79'
# # print(sys.getrefcount(a) - 1)
# a_wref = weakref.ref(a)
# a2 = a_wref()
# print(a is a2)
import weakref
class Data(object):
def __init__(self, value, owner):
self.owner = weakref.ref(owner)
self.value = value
def __str__(self):
return '%s"s data, value is %s' % (self.owner(), self.value)
def __del__(self):
print('in Data.__del__')
class Node(object):
def __init__(self, value):
self.data = Data(value, self)
def __del__(self):
print('in Node.__del__')
node = Node(100)
del node
input('wait...')
# 强制回收 也不能进行回收
# import gc
# gc.collect()
|
530fcc088b054e1d293e498e7b4b72a82942d94a | deadbok/eal_programming | /Assignment 2A/prog4.py | 4,985 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
"""
Name: Program 4
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (13/11-2016)
Asks the user to enter the monthly costs for expenses incurred from operating
and owning an automobile. Print out the total cost of the expenses for a month
and a year.
"""
class Car(object):
"""
Class to calculate the expenses incurred from operating and owning an
automobile.
"""
# Loan payment per month.
loan_payment = 0
# Insurance payment per month.
insurance = 0
# Expenses on gas per month.
gas = 0
# Expenses on oil per month.
oil = 0
# Expences on tires per month.
tires = 0
# Expenses on maintenance per moth.
maintenance = 0
def __init__(self):
"""
Ask for values from the user, for expenses, when instantiating this
object.
"""
print('Enter the monthly payment for each of these expenses:')
try:
self.loan_payment = float(input('\tLoan payment: '))
self.insurance = float(input('\tInsurance: '))
self.gas = float(input('\tGas: '))
self.oil = float(input('\tOil: '))
self.tires = float(input('\tTires: '))
self.maintenance = float(input('\tMaintainance: '))
except ValueError:
# Complain when something unexpected was entered.
print('\nPlease use only numbers.')
exit(1)
def calc_expenses_for_months(self, current_expenses=None, months=1):
"""
Calculate the expenses for an span of months.
:param current_expenses: Tuple of the current expenses incurred up until
the current call of the function.
:param months: Span of months to calculate expenses for.
:return: A dictionary with the total cost for each expense.
"""
# If there are still more month to go.
if months != 0:
# If this is not the first call to this function.
if current_expenses is not None:
# Add monthly expenses to the current expenses.
current_expenses['Loan payment'] += self.loan_payment
current_expenses['Insurance'] += self.insurance
current_expenses['Gas'] += self.gas
current_expenses['Oil'] += self.oil
current_expenses['Tires'] += self.tires
current_expenses['Maintenance'] += self.maintenance
else:
# If this is the first call create a dictionary for the
# expenses and add them for the current month.
current_expenses = dict()
current_expenses['Loan payment'] = self.loan_payment
current_expenses['Insurance'] = self.insurance
current_expenses['Gas'] = self.gas
current_expenses['Oil'] = self.oil
current_expenses['Tires'] = self.tires
current_expenses['Maintenance'] = self.maintenance
# Make the function recursive, to shoot myself in the foot when
# I have to create the hierarchy diagram.
# The function calls itself until month is 0.
return(self.calc_expenses_for_months(current_expenses, months - 1))
else:
# If this is the final call, return a dictionary of the acumulated
# expenses.
return(current_expenses)
def expenses_for_months(self, months=1):
"""
Calculate and output the expenses for a span of months.
:param months: Span of months to calculate expenses for.
"""
# Print a header for the expenses output.
print('\nExpenses for {} months: '.format(months))
# Get a dictionary with the total expenses as values and expense name
# as key.
expenses = self.calc_expenses_for_months(None, months)
# Variable to keep the total cost of all expenses.
total_cost = 0
# Run through all expenses in the dictionary printing their key
# as description and value as result.
for key, value in expenses.items():
# Align both the description and the result using new style string
# formatting.
print('\t{:<12}: {:12.2f}'.format(key, value))
total_cost += value
#Print the total cost
print('\t{:<12}: {:12.2f}'.format('Total cost', total_cost))
def main():
"""
Program main entry point.
"""
#Create the Car instance
car = Car()
# Calculate and print the expenses for one month.
car.expenses_for_months(1)
# Calcualte and print the expenses for a year.
car.expenses_for_months(12)
# Run this when invoked directly
if __name__ == '__main__':
main()
|
a8c93cc0bdf7455e1873d157ab4abab0ffbaa51a | Gavinzqk/python-1 | /python实战一期/python基础篇/1.python基础/流程控制-for/for.py | 2,131 | 3.578125 | 4 | #! /usr/bin/env python
# encoding: utf-8
'''
@author:Gavin
@contact: [email protected]
@file: for.py
@time: 2019/1/7 15:38
'''
# dic = dict.fromkeys("abcde",100)
# for i in dic:
# print(i)
# dic = dict(name='gavin',age=29)
# for k in dic:
# print("%s: %s" % (k,dic[k]))
# dic = dict(name='gavin',age=29)
# for k in dic:
# print("%s--->%s" % (k,dic[k]),end=' ')
# dic = dict(name='gavin',age=29)
# for k in dic.items():
# print(k)
# dic = dict(name='gavin',age=29)
# for x,y in dic.items():
# print("%s: %s" % (x,y))
# for x in range(1,10):
# for y in range(1,x+1):
# print("%s*%s=%s" % (y,x,y*x),end=' ')
# print()
# sum = 0
# for i in range(1,101):
# sum = sum + i
# print(sum)
# import random
# ran = random.randint(1,20)
# for i in range(1,7):
# num = int(input("please input a number: "))
# if num == ran:
# print('你赢了')
# break
# else:
# if num >ran:
# if 6-i != 0: print("太大了")
# elif num <ran:
# if 6-i != 0: print("太小了")
# else:
# print('你输了')
# import random
# ran = random.randint(1,20)
# for i in range(1,7):
# while True:
# num = input("please input a number: ")
# if num.isdigit():
# break
# else:
# continue
# num = int(num)
# if num == ran:
# print("you win")
# break
# else:
# if num > ran:
# if 6-i !=0 :print('too large')
# if 6 - i != 0: print('you have '+ str(6-i) + ' test')
# elif num < ran:
# if 6 - i != 0: print('too small')
# if 6 - i != 0: print('you have ' + str(6-i) + ' test')
# else:
# print('you lose')
# for i in range(1,5):
# if i == 3:
# continue
# if i == 4:
# break
# print(i)
# else:
# print('main end')
# import sys
# for i in range(1,11):
# if i == 3:
# continue
# if i == 8:
# sys.exit()
# print(i)
# else:
# print('end')
# import time
# for i in range(1,10):
# print(i)
# time.sleep(1)
# else:
# print('main end')
|
c8770b7c4d94c9e49c015f200aff5e285d35ee7c | MonoNazar/MyPy | /0.7/Rank.py | 998 | 3.859375 | 4 | n = [1, 2, 3, 8, 5, 3, 6]
l = 1
n.append(l)
n.sort()
print(len(n) - n.index(l))
#Петя перешёл в другую школу. На уроке физкультуры ему понадобилось определить своё место в строю. Помогите ему это сделать.
# Программа получает на вход невозрастающую последовательность натуральных чисел, означающих рост каждого человека в строю.
# После этого вводится число X – рост Пети. Все числа во входных данных натуральные и не превышают 200.
# Выведите номер, под которым Петя должен встать в строй.
# Если в строю есть люди с одинаковым ростом, таким же, как у Пети, то он должен встать после них. |
982a248377910a3d5d546421742f87f7a24ec9d2 | Aasthaengg/IBMdataset | /Python_codes/p02262/s935999369.py | 715 | 3.625 | 4 | n = input()
A = [input() for i in range(n)]
def insertionSort(A,n,g):
cnt = 0
for i in range(g,n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j -= g
cnt += 1
A[j+g] = v
return cnt
def shellSort(A,n):
cnt = 0
m = int((n-1)/3)
G = [1]
for i in range(1,n):
gn = G[i-1]+3**i
if gn > n:
break
G.append(gn)
m = len(G)
for i in range(m):
j = (m-1) - i
cnt += insertionSort(A,n,G[j])
return m, G, cnt
m, G, cnt = shellSort(A,n)
print m
for i in range(1,m):
j = m - i
print G[j],
print G[0]
print cnt
for item in A:
print item |
e54877eca7323d768536d1cb303ab395f0fc778e | innovatorved/BasicPython | /x33- if element in list.py | 225 | 3.875 | 4 | fruits=('apple','bannana','pine apple','guava')
a=input('Enter the fruit name: ')
if a in fruits:
print('fruit is already available-@',fruits.index(a))
print(fruits.index(a))
else:
print('fruit is not available')
|
c2a24a42c40b748b0b81c7dc84d5985081af0832 | martinegeli/TDT4110 | /øving5/øving5-8.py | 1,000 | 3.65625 | 4 | def gcd(a,b):
while b!=0:
gammel_b=b #i løkken setter vi gammel_b til å være b
b=a%b #finner b ved å ta a modulo b, som gir rest etter at a er delt på b
a=gammel_b #setter a til å være gammel_b, slik at fra øverst så vil nå resten fra a%b bli til a, som vil brukes til å finne ny rest i neste runde hvor løkken kjører. Dette kjører helt til b blir 0, som da har funnet minste felles divisor. Løkken returnerer a som blir minste felles divisor.
return a
print(gcd(100, 8))
def reduce_fraction(a,b):
d = gcd(a, b) #setter variabelen d til å være gcd mellom a og b fra gcd-funksjonen.
a2=int(a/d) #d som er et heltall fra gcd mellom a og b, vil gi et heltall når a deles med d. Dette settes til variabelen a2 som returneres.
b2=int(b/d)
return [a2,b2]
a=int(input('a: '))
b=int(input('b: '))
ab=reduce_fraction(a, b) #fordi jeg returnerte som en liste så vil ab[0] høre til a2
print('brøken a = ', a, '; b = ', b, 'skriver programmet ut "',ab[0], '/',ab[1], '"') |
ea3c26852f08784c46fe4538b4d184e173941145 | AlanMorningLight/GAN_work_internship | /python_training/p11.py | 342 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 14 18:59:19 2019
@author: sarfaraz
"""
class employee:
def __init__(self, id1, name):
self.id1 = id1
self.name = name
def display(self):
print(self.id1, self.name)
obj = employee(17103078, "Sarfaraz");
obj.display() |
42730e22946b8a4adf78b9a36ee27902dacc3ce5 | xiaogy0318/coding-exercises | /python/PythonTreeTest/PythonTreeTest.py | 5,097 | 3.53125 | 4 |
treedata = '425a68393141592653599f22b34c00003edd80001040047ff00002bf209a00500507800001a00004aa7a69a9ea35334c937aa69e81aa7a6a327b48d4680029a3401a0000a68d00680000aaa9e099302152834f5371f4758d491b5e50959d6b4854861548a73b519ee445ad39276874864a9fda586cf19f1f3810ece4b1b98071c83f0e6a744c62e4164d77f8a986547dfd8b6d32d2cee6ff1474ffdfdfeb4fef10fdd2785143d61441a51551fc6974167f1059879fc434eda55a9b492e82c78617614d9a748b4b2ae96a21a8a041232cbd727b830a2ee3b49076824d41749b2cb9b3a69749a74a26db0f7dc36fe4aef10befdb49c47f7ce956d259145c48b26ea88a304544d541c5932b755641e27e24a13fd74d35cb3bca69f649277ebefd0612c2cd32db2f5174d3083b209a1dba6d95dd2cd9461b77044f7dda6f5969551679ce8e20da8bb4b9245e31c841ef5f791fd241daafd2e3083e79e55936abecd527af59f9f32f9a789bf6de395bcde34dbef3d876f2eabe7105d94d58206a7d2f7ab8c71555db8e977a8a7dee774289be4d874f914dc73925db6d045b59051f63d7a8b8e30aace927ab49545debcd26da2979a6544f884eaf5046a8a2bf906de38baa9308acbb8820822d34da5743f45ef957155117af11c4fdda6e3a4e4f5ae3d5d359359e3cf34e32869ea2d36e3d4c9b3e42f7938da282abba78edeacf58e9da2ca0e918b28f6e915905137e8ab671061c74c2cbbef6bc5dd6d6692414ed0bba4df5f2abe5515de3b2d6f967ce964585d07104d069c55b7adb0f1674a26cbb5bb7bc951c71eb6ce90baaca6d2654fa687ee24e206587aa20d341038c811790299d432519d685614b63687a83a4e2e1d64c263538e2cfbed36f5c34bb28bb55b4517aa22c63e49cd21a6d75174507a933ada28b8cbb4ddb8f0da892486d0fd84def9c49769bcbe674e9441e27341475a43b3b4dc5986dc74aa2e9e14554744966177de7157b2f165139d0e26f9ebed3a749b6f1abf4f1e28f565d741eb2aa4f57599cc2184b2e9c4166596dc76f5545274e3082b845d28ba6d6a10a32c30f17419edd36e9e3a79543a3493c2cf136512acb5996abdacc2584d1b30bcfc511509f6d27743f57a434eff4d976945869445674b3b753cdb3a6996db49f32eda554536db29a8a51069759541d2abfcb22c2acbefbcaa0a3b61369c7ac22f1a48bb49be7af976925d793e74ba4aa8c20b28e8dbb69343efd069f7df3b2af1841359961751345478e26edeac824ed651671661759876a25daacbe7a932dacd30b36cbb7c9a4e32b2aedf7efdffc5dc914e142427c8acd30'
import binascii
import os
import bz2
from os import listdir
import shutil
class Node:
text = ""# For holding the file name as key
nodes = []# For the children
value = "" # the leaf's value. Only when nodes is empty
def printNode(self):
#print "text: ", self.text
#print "value: ", self.value
if (len(self.value) > 0):
print self.value,
#print "nodes: ",
counter = 0
for i in self.nodes:
#print "child #", counter, ": ", i
counter = counter + 1
#print
def printTreeNode(node):
# print node itself
node.printNode()
# print children from left to right
for childKey in node.nodes:
#print "Found child: ", childKey
#printTreeNode(child)
# Now I have child's text, Now find it in the dict
childNode = filedict[childKey]
printTreeNode(childNode);
'''
# Test a simple tree
node1 = Node()
node1.text = "node1"
node2 = Node()
node2.text = "node2"
node1.nodes.append(node2);
print node1.text
print node1.nodes
print node2.text
'''
shutil.rmtree("tree")
#os.rmdir("tree")
os.mkdir('tree')
for f in bz2.decompress(binascii.unhexlify(treedata)).split(','):
arr = f.split(':')
fid = open('tree/'+arr[0], 'w')
fid.write(arr[1])
fid.close()
# Interviewee starts below here. You can look at the above if you like but it won't help.
# The above code created a directory called 'tree' with ~ 30 files in it.
# Each file defines a node in the tree and contains either:
# - A single character. This is a leaf node of the tree; or
# - A list of space separated file names. These nodes are the children of the node associated with the file name.
# The children are listed as nodes left-to-right.
# Your job is to:
# A) Find the root node.
# B) Traverse the tree using a left first traversal and print the characters in each leaf node. This should produce
# English text.
#
#print("Here's a list of files in the 'tree' directory: %s" % '\n'.join(sorted(os.listdir('tree'))))
# Construct the tree
# Read from files and put them into Node class, and then the nodes into an array
filelist = []
# Read the file names from directory "tree" and put into the Node class
for f in listdir('tree'):
node = Node()
node.text = f
filelist.append(node)
# Now open the file and read the content
fid = open('tree/' + f, 'r')
#print node.text, "has: ", fid.read()
# either a single character (leaf), or a space delimetered string of file names
content = fid.read()
# Now parse the content
if (len(content) == 1): # leaf
node.value = content
else:
# Now just need to convert to array and put in nodes
node.nodes = str.strip(content).split(" ")
#node.printNode()
#for i in filelist:
# print i.printNode()
# Now scan the filelist, and construct the tree
# Find root first, then from root, just scan the rest and link to all childrens, recursively
# Use dict instead of list of better in searching... Now try to convert list to dict
'''
filedict = {}
#print filedict["af30f30738b20428a2dd39df98e93e97"];
'''
# Find root now...
# Root is the node whose text never appears in its any other nodes' children list
filedict = {}
for i in filelist:
filedict[i.text] = i
filedict = dict(filedict)
root = Node()
for i in filelist:
nodeText = i.text # This is the node's text for the test
# Now scan all nodes in the dict (for simplicity, including itself, which doesn't matter)
isRoot = True
for key in filedict:
# Check if nodes contains the text
nodes = filedict[key].nodes
for temp in nodes:
if nodeText in temp:
# this node is not root
isRoot = False
else:
# Should continue the test until exhausted
continue
# Now we know if it's a root or not
if(isRoot):
# Now we know i is the root, stop
#print "Found root:"
root = i;
break
else:
continue
# Now print the root
#root.printNode()
printTreeNode(root)
'''
# print children from left to right
for childKey in root.nodes:
print "Found child: ", childKey
#printTreeNode(child)
# Now I have child's text, Now find it in the dict
childNode = filedict[child]
childNode.printNode()
'''
# Now we build up the tree by truely linking to each other (previously the link is by text, now update the nodes with actual nodes...)
# Oh, actually, no need to if the job is to print out the stuff.
'''
fid = open('tree/'+arr[0], 'w')
fid.write(arr[1])
fid.close()
'''
|
e9c8db28d30cb6c5a70114107e249aeb8cc524f4 | dailycode4u/python4u | /Topics/functions.py | 157 | 3.890625 | 4 | def scan_letter(word:str,letters:str='aeiou') ->set:
"""returns a set of letters found in a phrase"""
return set(letters).intersection(set(word))
|
e9e52334d88294ffaf39fb3f8f33e39e5d7b2047 | IsinghGitHub/advanced_python | /adv_py_1_try_accept_raise/assert_example.py | 279 | 4.1875 | 4 | raw_a = raw_input("Enter a positive number: ")
try:
a = float(raw_a)
except ValueError:
print('You must enter a number')
raw_a = raw_input("Enter a positive number: ")
a = float(raw_a)
assert (a > 0), "A is not positive"
b = 7.0
c = a + b
print('c = %s' % c)
|
0077e236869fbf5ee9f76e06a89827c2626cfa8b | alexyi822/122bprog2 | /findkthlargest.py | 908 | 3.96875 | 4 | #sort an array and return kth element
#take input file as command line argument and k value as command line argument
# http://interactivepython.org/runestone/static/pythonds/SortSearch/TheInsertionSort.html
import time
import sys
comp = 0 # number of comparisons
def insertion_sort(arr):
global comp
for index in range(1, len(arr)):
currentValue = arr[index]
pos = index
while pos > 0 and arr[pos-1] > currentValue:
comp = comp+1
arr[pos]=arr[pos-1]
pos=pos-1
arr[pos] = currentValue
def main():
start = time.clock()
# k = 5
k = int(sys.argv[2])
nums = []
with open(sys.argv[1]) as f:
for line in f:
nums.append(int(line))
# nums.sort()
insertion_sort(nums)
end = time.clock()
print("kth element:\t %d" % (nums[k-1]))
print("Comparisons:\t %d" % (comp))
print("Time:\t %f" % (end-start))
if __name__ == "__main__":
main() |
26bdc8888a13d9ad20e5587818cde136804e18c3 | supremeKAI40/NumericalMethods | /Root Finding Mehtod/BisectionMethod.py | 749 | 3.84375 | 4 | import math
def f(x):
return x**(3)+x**-100
x0= float(input('enter first guess: '))
x1= float(input('enter second guess: '))
question=float(input ('question number: '))
error= 0.0001
def bisection(x0,x1,x2):
step=1
print('\n\n solution to question %0.2f \n****Bisection Method Implementing***\n'%(question))
print('\n Iteration \t a \t\t b \t\t xn \t\t f(xn)\n')
condition= True
while condition :
x2= (x0+x1)/2
print('Iteration -%d, \t %0.6f, \t %0.6f, \t %0.6f, \t %0.6f' % (step,x0,x1,x2,f(x2)))
i=f(x0)/f(x2)
if i<0:
x1=x2
else:
x0=x2
step+=1
condition = abs(f(x2))>error
print('\nRequired root is : %0.8f' % x2)
if f(x0)/f(x1)>0:
print("The guess value don't bracket a root")
else:
bisection(x0,x1,error)
|
8ea7b827ab9753dbd47f3e74c589dd9f52b1bb90 | Bloodielie/tg_contrallers_bot | /utils/utils.py | 1,736 | 3.671875 | 4 | from configuration.message import MESSAGE_KEYBOARD
def converting_time(sec_time: int):
""" Добавления правильного окончания для времени """
hours = sec_time // 3600
minutes = None
if sec_time % 3600 == 0.0:
pass
else:
minutes = int((sec_time - hours * 3600) / 60)
if hours == 1:
hours_prefix = "час"
else:
hours_prefix = "часа"
min_prefix = "минут"
if hours == 0:
return f'{minutes} {min_prefix}'
elif minutes:
return f'{hours} {hours_prefix} {minutes} {min_prefix}'
else:
return f'{hours} {hours_prefix}'
def deconverting_time(time: str):
""" Декодирование окончания в секунды """
_str = time.split()
sec = 0
if len(_str) == 2:
if _str[1] == "час":
sec += 3600
elif _str[1] == "часа":
if len(_str) == 2:
sec += int(_str[0]) * 3600
elif _str[1] == "мин":
sec = 1800
else:
sec += (int(_str[0]) * 3600) + 1800
return sec
def text_display(data: list):
""" Представление словаря в тексте """
text = '\n'.join([f'{stop[0]}, {stop[1][0]}, {stop[1][1]}' for stop in data])
if text:
return text
else:
return 'Остутствуют сообщения людей.'
def get_data_from_list(data_list: list) -> list:
text_city = []
for _ in data_list:
for text_keyb in _:
if text_keyb == MESSAGE_KEYBOARD['back_keyb'] or text_keyb == MESSAGE_KEYBOARD['menu_keyb']:
continue
text_city.append(text_keyb)
return text_city
|
b279a10910865ed288d9e6a51ec599605154ce89 | navy-xin/Python | /Python 100例/Python 练习实例9.py | 261 | 3.65625 | 4 | #!/usr/bin/python
# -*- codeing = utf-8 -*-
# @Time : 2020/12/11 16:47
# @Author : navy
# @File : Python 练习实例9.py
# @Software: PyCharm
import time
myD = {1: 'a', 2: 'b', 3: 'c'}
for key, value in dict.items(myD):
print(key,value)
# time.sleep(1) |
c3d3ee3946922d95da53def8c724dd0acda226f6 | causeyo/udemy_modern_bootcamp | /csv/12_delete_users.py | 1,211 | 3.65625 | 4 | """
delete_users("Grace", "Hopper") # Users deleted: 1.
delete_users("Colt", "Steele") # Users deleted: 2.
delete_users("Not", "Here") # Users deleted: 0.
"""
from csv import reader, writer
def delete_users(first, last):
with open('users.csv') as file:
user_list = list(reader(file))
users_matched = sum([1 for user in user_list if user == [first, last]])
new_user_list = [elem for elem in user_list if elem != [first, last]]
if users_matched:
with open('users.csv', "w") as file:
csv_writer = writer(file)
for user in new_user_list:
csv_writer.writerow(user)
return "Users deleted: {}.".format(users_matched)
"""
udemy solution
import csv
def delete_users(first_name, last_name):
with open("users.csv") as csvfile:
csv_reader = csv.reader(csvfile)
rows = list(csv_reader)
count = 0
with open("users.csv", "w") as csvfile:
csv_writer = csv.writer(csvfile)
for row in rows:
if row[0] == first_name and row[1] == last_name:
count += 1
else:
csv_writer.writerow(row)
return "Users deleted: {}.".format(count)
""" |
2024ce51873d26eae12c3fd122e404fb5192bd9b | nupur24/python- | /nupur_gupta_16.py | 433 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 16 11:40:34 2018
@author: HP
"""
s=raw_input("enter string:")
def translate():
str2 = ''
x=['a','e','i','o','u',' ']
for i in s:
if i in x:
str2 = str2 + i
else:
str2 = str2 + (i+'o'+i)
print str2
translate()
|
0cd79e483c0ece6b4c48777f6b88a998f662dd12 | noahmelngailis/business-resources | /webscraping_dynamic_webpages_for_boa.py | 3,534 | 3.6875 | 4 | import pandas as pd
# for running selenium
from time import sleep
import selenium
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
def find_nearest_bank_of_america(df):
"""This function pulls in data from a csv and returns a dataframe with the additional columns of address
and distance of the closest bank locations"""
rank_list = []
location_name = []
bank_location_address = []
bank_location_name = []
distance_to_bank = []
text = 'This Financial Center has been temporarily closed. Please visit one of our neighboring ATMs or utilize Online and Mobile Banking, all of which are available 24 hours a day, 7 days a week. To make an appointment to access your safe deposit box during regular business hours, email us your full name, address and phone number at:[email protected] .'
browser = webdriver.Chrome(ChromeDriverManager().install())
sleep(1)
for i in df.index:
# get url from dataframe
url = f'https://locators.bankofamerica.com/?lat={df.Latitude[i]}&lng={df.Longitude[i]}'
# let selenium do its magic
browser.get(url)
sleep(2)
location = browser.find_elements_by_class_name("map-list-item")
# debugging
print(i)
#number of inputs returned: this returns top five closest locations, unless it has less than 5 locations then it returns that number of locations.
if len(location) >= 5:
z = 5
else:
z = len(location)
#build out lists of responses from webscrape
for x in range(z):
if location[x].text.split('\n')[6] == text:
continue
else:
location_id = df.location_id[i]
address = location[x].text.split('\n')[5]
distance = location[x].text.split('\n')[3]
name = location[x].text.split('\n')[1]
# create lists from data
rank_list.append(x)
location_name.append(location_id)
bank_location_name.append(name)
bank_location_address.append(address)
distance_to_bank.append(distance)
return df, rank_list, location_name, bank_location_name, bank_location_address, distance_to_bank
def create_bank_df(location_name, rank_list, bank_location_name, bank_location_address, distance_to_bank):
"""This function takes in a series of lists and turns them into a data frame.
Then pivots the data frame by location id to return a usable df for locating nearest banks"""
data = {'location_id': location_name,
'distance_rank': rank_list,
f'name_of_bank_location': bank_location_name,
f'address_of_bank': bank_location_address,
f'distance_to_bank': distance_to_bank}
locations = pd.DataFrame(data)
locations['for_operators'] = (locations.name_of_bank_location +
" Bank of America Location is at " +
locations.address_of_bank +
". This is " +
locations.distance_to_bank +
" miles from your retail location"
)
for_export = locations.pivot(index='location_id', columns='distance_rank', values='for_operators').fillna('location closed')
return for_export
|
e7376b92e6eeefdf3048e70557eab438eebe4d91 | hooj0/python-examples | /17_examples_object/init.py | 827 | 3.625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
# @author: hoojo
# @email: [email protected]
# @github: https://github.com/hooj0
# @create date: 2018-04-01 18:09:37
# @copyright by hoojo@2018
# @changelog Added python3 `object -> init` example
class Student:
name = 'jack'
age = 22
''' 初始化方法,构造方法 ,在实例化创建'''
def __init__(self):
self.name = 'jason'
self.age = 33
# 创建实例化,init方法被执行
stu = Student()
print('name: %s, age: %s' % (stu.name, stu.age))
class Class:
name = 'calss 1'
# 有参构造函数
def __init__(self, no, author):
self.Num = no
self.Author = author
cla = Class('453122645', 'tom')
print('name: %s' % cla.name)
print('Num: %s, Author: %s' % (cla.Num, cla.Author)) |
ff74b24b9d57ba80b7b9a7e53ed675e96aa899b5 | aysla001/ExploreDataScience | /Ch1 Fundamentals/Ex 1.4.1 SciKit.py | 744 | 3.59375 | 4 | #scikit-learn, scikit imported as sklearn is a machine learning library that is built on top of NumPy, SciPy, and matplotlib.
#scaling data
import numpy as np
import sklearn as sk
from sklearn import preprocessing
data = np.genfromtxt('sample.data', delimiter=',', dtype='f8,f8,f8,f8',names='a,b,c,d')
#this method of import creates a flexible type which does not allow `mean.()` to be called
X = np.array([data[x] for x in data.dtype.names])
mean = X.mean(axis=0)
stdev = X.std(axis=0)
mean
#will return the mean of each column
#preprocessing subtracts the mean and divides by the standard deviation
scaledData = preprocessing.scale(X)
# mean of scaledData
scaledData.mean(axis=0)
# standard deviation of scaledData
scaledData.std(axis=0) |
10f78fc10279b209766cdaf22309e3b4a13e7a8a | presscad/Some_codes | /aboutPython/DATAstructure By Python/arraylist_1.py | 1,505 | 4.21875 | 4 | """
File:arraylist_1.py
Date:Sep 14 2018 20:29
Description:重构后的ArrayList类的代码
"""
from arrays import Array
from abstractlist import AbstractList
from arraysortedlist import ArraySoredList
from arraylistiterator import ArrayListIterator
class ArrayList(ArraySoredList):
"""An array-based list implementation"""
def __init__(self,soureCollection = None):
"""Set the initial atate of selt ,which include the cntent of soureCollection
if it's present."""
ArraySoredList.__init__(self,soureCollection)
# Accessor methods
def index(self,item):
"""Precondition: item is in the list.Return the position of the item ,
Raise: ValueError if the item is not in the list """
return AbstractList.index(self,item)
# Mutator methods
def __setitem__(self,i,item):
"""Preconditon 0<=i<len(self),
Replace the item at position i
Raise: indexError if i is out of the range """
if i<0 or i>=len(self):
raise IndexError("List index out of range")
self._items[i] =item
def insert(self,i,item):
"""Insert the item at position i"""
#Resize the array here if necessary
if i<0:
i=0
elif i>len(self):
i=len(self)
if i<len(self):
for j in range(len(self),i,-1):
self._items[j] = self._items[j-1]
self._items[i] = item
self._size +=1
self.incModCount()
def add(self,item):
""" Add item to self."""
AbstractList.add(self,item)
def listIterator(self):
"""return a list iterator """
return ArrayListIterator(self)
|
ba34e6c97dab49313d2ad1883013aa73b5e99a42 | MichSzczep/PythonLab | /zad7b2.py | 2,817 | 3.59375 | 4 | import threading
import time
from threading import Lock
class Lokaj:
def __init__(self):
self.mutex = Lock()
def licz_paleczki (self):
zajete = 0
for palka in paleczki:
if palka.zajety:
zajete += 1
return zajete
def zapytaj_kelnera(self, lpaleczka, ppaleczka, pesel):
if self.mutex.acquire():
if self.licz_paleczki() >= 4:
res = False
else:
if (lpaleczka.zajety==False and ppaleczka.zajety==False):
res = lpaleczka.wez_paleczke(pesel) and ppaleczka.wez_paleczke(pesel)
else:
res = False
self.mutex.release()
return res
else:
return False
class Filozof:
def __init__(self, pesel, lewaPaleczka, prawaPaleczka):
self.pesel = pesel
self.lewaPaleczka = lewaPaleczka
self.prawaPaleczka = prawaPaleczka
def posilek(self): #process
for i in range(10):
while not lokaj.zapytaj_kelnera(self.lewaPaleczka, self.prawaPaleczka, self.pesel):
pass
print("Filozof %s rozpoczyna posiłek" %self.pesel)
time.sleep(1) # eat
print("Filozof %s skończył posiłek" %self.pesel)
self.lewaPaleczka.oddaj_paleczke(self.pesel)
self.prawaPaleczka.oddaj_paleczke(self.pesel)
print("Posilek numer: ", i)
class Paleczka:
def __init__(self, numer):
self.numer = numer
self.zajety = False
self.semafor = threading.Semaphore()
def wez_paleczke (self, pesel):
zz= []
for j in paleczki:
if j.zajety:
zz.append(j.numer)
print(zz)
if self.zajety:
return False
self.semafor.acquire()
self.zajety = True
print("Paleczka o numerze %s jest wlasnie zabierana przez Filozofa %s" %(self.numer, pesel))
return True
def oddaj_paleczke (self, pesel):
self.semafor.release()
self.zajety = False
print("Paleczka o numerze %s została właśnie oddana przez Filozofa %s" %(self.numer, pesel))
paleczki = []
for i in range(5):
paleczki.append(Paleczka(i))
lokaj = Lokaj()
filozofowie = []
for i in range(5):
if i==4:
filozofowie.append(Filozof(i, paleczki[i], paleczki[0]))
print("Filozof %s dostal paleczki %s, %s" %(i, i, 0))
else:
filozofowie.append(Filozof(i, paleczki[i], paleczki[i+1]))
print("Filozof %s dostal paleczki %s, %s" %(i, i, i+1))
watki = []
for i in range(5):
watki.append(threading.Thread(target=filozofowie[i].posilek))
watki[i].start()
|
43796025fe8d1342758176901e91b5fbd0d91630 | PashaKlybik/Python | /lab2/z6.py | 597 | 3.6875 | 4 | __author__ = 'pasha'
class Defaultdict():
def __init__(self):
self.dic = dict()
def __get__(self, instance, owner):
return self.dic
def __setitem__(self, key, value):
self.dic[key]=value
def __getitem__(self, item):
return Defaultdict.getitem(self,item,0)
def getitem(self, item,point):
if not self.dic.get(item):
self.dic[item]=Defaultdict()
return self.dic[item]
def __str__(self):
a = '{'
for key in self.dic:
a+=str(key)+": "+str(self.dic[key])+", "
return a[:-2]+"}"
|
bb2ef09c654edf48e8c42eb9c281d5e180340a48 | MayankHirani/Spring-Internship-2020 | /realsimulator.py | 6,993 | 3.515625 | 4 | """
Spring Internship with Prof. Sinha
Mayank Hirani 2020
[email protected]
"""
# Import everything from simulator for the class
import simulator
from importlib import reload
reload(simulator)
from simulator import *
# Import random for probabilities
import random
# Import matplotlib for graphing
import matplotlib.pyplot as plt
# Import pandas dataframe for plotting heatmap
from pandas import DataFrame
# Import numpy for making DataFrame
import numpy as np
# Main simulator class
class RealSimulator():
# Get the values needed, generate the sequences, insert the patterns
def __init__(self):
# ----- Stats -----
# Chance of pattern appearing in a sequence
self.p = 1
# Chance for error in pattern
self.e = 0
# Number of sequences
self.num_of_sequences = 100
# Length of Pattern
self.patlen = 10
# ----- Data ------
# This will be dictionary of accuracy
self.p_data = {}
self.e_data = {}
self.vary_stats()
print('P Results:', self.p_data)
print('E Results:', self.e_data)
# ----- Data Plotting -----
self.plot_data(self.p_data, 'P Data')
self.plot_data(self.e_data, 'E Data')
# General run, create pattern, create sequences, insert pattern
def run(self):
self.create_pattern()
self.sequences_pattern = 'sequences_pattern.txt'
self.create_sequences()
return self.determine_accuracy(self.run_pattern_finder())
# Specific run, for each stat it will be varied and use the run() command
def vary_stats(self):
# Number of times run for each variable
num = 1
# For whatever variable is being tested, a list of all successful/unsuccessful runs
self.general_data = []
'''
# P
for p in range(0, 101): # Default (90, 101)
self.general_data = []
self.p = p / 100
# How many times you want to run with same stat value
for x in range(num):
self.general_data.append(self.run())
self.p_data[self.p] = self.general_data.count(1)
self.p = 1 # Reset value for p to default (1)
# E
for e in range(0, 101): # Default (10, 61)
self.general_data = []
self.e = e / 100
for x in range(num):
self.general_data.append(self.run())
self.e_data[self.e] = self.general_data.count(1)
self.e = 0 # Reset value for e to default (0)
'''
# Pattern Length
# Removed because the pattern length does not affect the accuracy (except for values 1-6)
# Number of Sequences
# Removed because the number of sequences does not affect the accuracy (except for values 1-10)
# Varying two variables (p and e) at once and recording data in heat map
self.plot_heatmap(num)
# Create normal sequences and sequences with patterns and write them to designated files
def create_sequences(self):
f = open(self.sequences_pattern, 'w+')
for sequence_counter in range(self.num_of_sequences):
sequence = ""
for x in range(1000):
sequence += random.choice(['T', 'C', 'G', 'A'])
# Only insert for chance p
prob = random.random()
if prob <= self.p:
sequence = self.insert_pattern(sequence)
f.write(sequence + '\n')
f.close()
# Input a sequence and output a sequence with the pattern inserted
def insert_pattern(self, sequence):
# Starting index of the patter
pat_start = random.randint(0, len(sequence) - self.patlen + 1)
# With chance e, alter the pattern
prob = random.random()
if prob < self.e:
sequence = sequence[0:pat_start] + self.alter_pattern() + sequence[pat_start+self.patlen:]
else:
# Before pattern + Pattern + Ending part
sequence = sequence[0:pat_start] + self.pattern + sequence[pat_start+self.patlen:]
return sequence
# Function to create the pattern
def create_pattern(self):
self.pattern = ''
for x in range(self.patlen):
self.pattern += random.choice(['T', 'C', 'G', 'A'])
self.pattern_file = open('pattern.txt', 'w+')
self.pattern_file.write(self.pattern)
self.pattern_file.close()
# Used to alter the pattern by 1 letter for chance e
def alter_pattern(self):
altered_pattern = list(self.pattern)
index = random.randint(0, self.patlen - 1)
# Choose a random letter that is not its own
letter = self.pattern[index]
while letter == self.pattern[index]:
letter = random.choice(['T', 'C', 'G', 'A'])
altered_pattern[index] = letter
altered_pattern = ''.join(altered_pattern)
return altered_pattern
# Determine the accuracy by comparing the pattern found to right pattern (exact match)
def determine_accuracy(self, pattern_found):
if pattern_found == self.pattern:
return 1
else:
return 0
# -----------------------------------------------------------------------------
# Pattern Finder Section
# Generate a dictionary of the frequency of all potential patterns present
# in all the sequences
def run_pattern_finder(self):
self.pattern_counts = {}
for sequence in open(self.sequences_pattern):
for index in range(0, 1000 - self.patlen + 1):
pat = sequence[ index : index + self.patlen ]
if pat in self.pattern_counts:
self.pattern_counts[pat] += 1
else:
self.pattern_counts[pat] = 1
return max(self.pattern_counts, key=self.pattern_counts.get)
# -----------------------------------------------------------------------------
# Plotting Section
# Function for plotting the data from dictionary form
def plot_data(self, data, type):
# Convert the dictionary to usable form
lists = sorted(data.items())
x, y = zip(*lists)
# Plot the data
plt.plot(x, y)
plt.xlabel(type)
plt.ylabel('Accuracy out of 100')
plt.show()
# Function for plotting the data into a heatmap
def plot_heatmap(self, num):
# Each row is a value of p, each column is a value of e
rows = []; col = []
self.heatmap_data = np.zeros((101, 101))
for indexp, p in enumerate(range(0, 101, 1)):
self.p = p / 100
# Add the values for the x axis labels and y axis labels
rows.append(str(self.p))
col.append(str(self.p))
for indexe, e in enumerate(range(0, 101, 1)):
self.e = e / 100
print(self.p, self.e)
self.general_data = []
for x in range(num):
self.general_data.append(self.run())
self.heatmap_data[indexp][indexe] = self.general_data.count(1)
# Create a DataFrame of the results
self.heatmap_data = DataFrame(self.heatmap_data, index=rows, columns=col)
# Plot the DataFrame as a heatmap
plt.pcolor(self.heatmap_data)
# Set intervals for x and y axis
plt.yticks(np.arange(0.5, len(self.heatmap_data.index), 1), self.heatmap_data.index)
plt.xticks(np.arange(0.5, len(self.heatmap_data.columns), 1), self.heatmap_data.columns, rotation=90)
# Set labels
plt.xlabel('E Value')
plt.ylabel('P Value')
# The colorbar on the side showing what colors mean what
colorbar = plt.colorbar()
colorbar.ax.set_ylabel('Accuracy out of ' + str(num))
# Save the plot file as PNG type
plt.savefig('heatmap')
# Final Plot
plt.show()
if __name__ == '__main__':
simulator = RealSimulator()
|
cdba980ce7c54174714288ba192ff62275e5209c | Ethan30749/monthy-python-and-the-holy-grail | /Creador de matrices.py | 592 | 4.15625 | 4 | def crear_matriz(M,N):
matriz= []
#atribuye al valor "matriz" una lista vacía
for i in range(M):
matriz.append([])
#agrega listas vacías a la matriz equivalente al valor M
for j in range (N):
value=int(input("ingrese valores: "))
matriz[i].append(value)
#agrega N valores a cada lista de la matriz
return matriz
#devuelve la matriz completa
M=int(input("ingrese cantidad de filas: "))
N=int(input("ingrese cantidad de columnas: "))
#solicita los valores M y N para construir la matriz
print(crear_matriz(M,N))
|
3fe9b0c225fc5ad42891692f2f5e0461f99bc01e | mdjglover/hotmail-eml-to-text-converter | /hotmail_eml_to_txt_converter/parser/Email.py | 782 | 3.875 | 4 | class Email():
# Simple object to hold email data
def __init__(self):
self.sender_name = ""
self.sender_email = ""
self.receiver_name = ""
self.receiver_email = ""
self.date = ""
self.time = ""
self.datetime_hotmail_format = ""
self.subject = ""
self.body = ""
def __str__(self):
output = f"From: {self.sender_name} <{self.sender_email}>\n"
output += f"To: {self.receiver_name} <{self.receiver_email}>\n"
output += f"Subject: {self.subject}\n"
output += f"Date: {self.datetime_hotmail_format}\n"
output += f"-------------------------------------------------------------\n"
output += f"\n"
output += f"{self.body}"
return output |
9515194406010ebd924b2632fd5c22d5df6b1383 | ivan-ops/progAvanzada | /Ejercicio25.py | 780 | 3.765625 | 4 | # Ejercicio 25
# En este ejercicio usted revertira el proceso descrito en el ejercicio previo.
# Desarrolle un programa que comnienze por leer una cantidad en segundos introducidos por el usuario.
# Su programa debe desplegar la cantidad equivlente en forma de D:HH:NN:SS,
# Donde D son los dias, HH las horas, MM los minutos y SS los segundos.
# Las horas, minutos y segundos deben estar en formato de 2 digitos, con un 0 al inicio, si es necesario.
d = 86400
h = 3600
m = 60
segundos = int(input('Introduce los segundos: '))
dias = segundos / d
segundos = segundos % d
horas = segundos / h
segundos = segundos % h
minutos = segundos / m
segundos = segundos % m
print('\n %d:%02d:%02d:%02d.' %(dias, horas, minutos, segundos)) |
c955d3ba563542bc0a7e780f885133898e341b46 | 2020marion/jtc_class_code | /challenges/03_primitive_data_types_part_1/temperature.py | 657 | 4.25 | 4 | #question 1 formula for converting F to C
x = 100
celsius_100 = (x-32)*(5/9)
print(celsius_100)
#the resulting temp is a float (it has a decimal)
#question 2 convert temp of 0 degrees F to C
x = 0
celsius_0 = (x-32)*(5/9)
print(celsius_0)
#question 3 convert temp os 34.2 F to celsius
print((34.2-32)*(5/9))
#question 4 convert BACK. 5 degrees C to F
x = 5
farenheit_5 = ((9/5)*x)+32
print(farenheit_5)
#question 5 first convert 85.1 F to celsius,
f = 85.1
celsius = (f-32)*(5/9)
print(celsius)
#question 5 second - if they are both now celsius i can make the comparison which is hotter
print("30.2 degrees celsius is hotter than 85.1 degrees farenheit") |
c77b2cea6019b312c771aaaac3d75db9eba1d004 | here0009/LeetCode | /Python/1774_ClosestDessertCost.py | 3,557 | 4.28125 | 4 | """
You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert:
There must be exactly one ice cream base.
You can add one or more types of topping or have no toppings at all.
There are at most two of each type of topping.
You are given three inputs:
baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor.
toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping.
target, an integer representing your target price for dessert.
You want to make a dessert with a total cost as close to target as possible.
Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
Example 1:
Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10
Output: 10
Explanation: Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
Total: 7 + 3 + 0 = 10.
Example 2:
Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
Output: 17
Explanation: Consider the following combination (all 0-indexed):
- Choose base 1: cost 3
- Take 1 of topping 0: cost 1 x 4 = 4
- Take 2 of topping 1: cost 2 x 5 = 10
- Take 0 of topping 2: cost 0 x 100 = 0
Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.
Example 3:
Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9
Output: 8
Explanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.
Example 4:
Input: baseCosts = [10], toppingCosts = [1], target = 1
Output: 10
Explanation: Notice that you don't have to have any toppings, but you must have exactly one base.
Constraints:
n == baseCosts.length
m == toppingCosts.length
1 <= n, m <= 10
1 <= baseCosts[i], toppingCosts[i] <= 104
1 <= target <= 104
"""
from bisect import bisect_left
from typing import List
class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
t_cost = [0]
for _curr in toppingCosts:
tmp = t_cost[:]
t_cost.extend([_t + _curr for _t in tmp])
t_cost.extend([_t + _curr * 2 for _t in tmp])
t_cost.extend([-float('inf'), float('inf')])
t_cost.sort()
res = float('inf')
gap = float('inf')
# print(t_cost)
for _b in baseCosts:
tmp_target = target - _b
idx = bisect_left(t_cost, tmp_target)
tmp_gap = abs(t_cost[idx] - tmp_target)
tmp_res = t_cost[idx] + _b
if tmp_gap < gap or (tmp_gap == gap and tmp_res < res):
gap = tmp_gap
res = tmp_res
tmp_gap = abs(t_cost[idx - 1] - tmp_target)
tmp_res = t_cost[idx - 1] + _b
if tmp_gap < gap or (tmp_gap == gap and tmp_res < res):
gap = tmp_gap
res = tmp_res
return res
S = Solution()
baseCosts = [1,7]
toppingCosts = [3,4]
target = 10
print(S.closestCost(baseCosts, toppingCosts, target))
baseCosts = [2,3]
toppingCosts = [4,5,100]
target = 18
print(S.closestCost(baseCosts, toppingCosts, target))
baseCosts = [3,10]
toppingCosts = [2,5]
target = 9
print(S.closestCost(baseCosts, toppingCosts, target))
baseCosts = [10]
toppingCosts = [1]
target = 1
print(S.closestCost(baseCosts, toppingCosts, target))
|
da7c096ef3b6ed7c6e517d3472b4480535635e89 | CSPInstructions/HR-1819-Analysis-6 | /Unit Test/Test.py | 1,098 | 3.78125 | 4 | # We import the unittest library and the content of the Fac file
import unittest
import Fac
# We create a class that will contain or tests
class TestFactional( unittest.TestCase ):
# We define a test case for the fac function
def test_factional(self):
# We wanna check whether we receive a value error
with self.assertRaises( ValueError ):
# We run the fac function with 0 as argument
Fac.fac( 0 )
# We wanna check whether we receive a value error
with self.assertRaises( ValueError ):
# We run the fac function with -1 as argument
Fac.fac( -1 )
# We wanna check whether we receive a value error
with self.assertRaises( ValueError ):
# We run the fac function with 'hi' as argument
Fac.fac( "Hi" )
# We wanna check whether we receive the right result for arguments 5 and 1
self.assertEqual(Fac.fac(5), 120)
self.assertEqual(Fac.fac(1), 1)
###############
# Python Crap #
###############
if __name__ == '__main__':
unittest.main() |
4e4179abf3ed2cfe4df7672045284426dc01fdf4 | jingtaisong/LeetCodePython | /CountSmallerNumbersAfter.py | 4,059 | 3.71875 | 4 | from unittest import (TestCase, main)
class CountSmallerToTheRight(object):
def mergeSortWithInverseOrderCount(self, nums, low, high, counts):
"""
mergeSort an array nums on [low, high), adjust counts[i] by the number of elements from the right of nums[i] to the left of nums[i]
"""
if low >= high:
raise ValueError(
'low index {lowIndex} cannot be higher than or equal to the high index {highIndex}'.format(lowIndex=low,
highIndex=high))
elif low == high - 1:
return [nums[low]] # no need to do anything if low == high - 1
else:
mid = (low + high) // 2 # guaranteed that low < mid < high
sortedLowToMid = self.mergeSortWithInverseOrderCount(nums, low, mid, counts)
sortedMidToHigh = self.mergeSortWithInverseOrderCount(nums, mid, high, counts)
# mergeSort:
sortedLowToHigh = []
lowInd = low
highInd = mid
while lowInd < mid and highInd < high:
if sortedLowToMid[lowInd - low]['value'] > sortedMidToHigh[highInd - mid]['value']:
sortedLowToHigh.append(sortedMidToHigh[highInd - mid])
highInd += 1
else:
sortedLowToHigh.append(sortedLowToMid[lowInd - low])
# when we decide to add an element in LowToMid,
# we count how many elements have been added from MidToHigh,
# and that is the number of elements that have been moved to the left of this element in LowToMid
counts[sortedLowToMid[lowInd - low]['index']] += highInd - mid
lowInd += 1
if highInd < high:
while highInd < high: # trailing elements in MidToHigh
sortedLowToHigh.append(sortedMidToHigh[highInd - mid])
highInd += 1
elif lowInd < mid:
while lowInd < mid: # trailing elements in LowToMid
sortedLowToHigh.append(sortedLowToMid[lowInd - low])
counts[sortedLowToMid[lowInd - low]['index']] += highInd - mid # also do this for the trailing elements in LowToMid
lowInd += 1
ind = len(sortedLowToHigh)
if ind != high - low:
raise ValueError(
'ind {indVal} must be equal to high {highVal} minus low {lowVal}'.format(indVal=ind, highVal=high,
lowVal=low))
return sortedLowToHigh
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not len(nums):
return []
else:
augmentedNums = []
augmentedNumsIndex = 0
for x in nums:
# index will keep track the original position of an element
# this is important because we need to keep track the number of elements moved to the left of each original position
# during the mergeSort procedure
augmentedNums.append({'index': augmentedNumsIndex, 'value': x})
augmentedNumsIndex += 1
counts = [0] * len(nums)
self.mergeSortWithInverseOrderCount(augmentedNums, 0, len(nums), counts)
return counts
class TestCountSmallerToTheRight(TestCase):
"""
Regtest
"""
def setUp(self):
self.test_object = [{
'test_nums': [21, 84,66,65,36,100,41],
'test_output': [0, 4,3,2,0,1,0],
}]
def test_result(self):
obj = CountSmallerToTheRight()
for test_case in self.test_object:
result = obj.countSmaller(test_case['test_nums'])
self.assertEqual(test_case['test_output'], result)
if __name__ == '__main__':
main()
|
8261fb4e4e1d46da4c52ef27ffd7522815e7e3c8 | turb0bur/tsp-heuristics | /heuristics.py | 2,153 | 3.625 | 4 | from random import randrange
def nearest_neighbour_algorithm(graph):
if graph.size == 0:
return -1, []
points = [i for i in range(graph.size())]
current = randrange(0, graph.size())
tour = [current]
points.remove(current)
while len(points) > 0:
next = points[0]
for point in points:
if graph.get_distance(current, point) < graph.get_distance(current, next):
next = point
tour.append(next)
points.remove(next)
current = next
tour.append(tour[0])
length = graph.get_tour_length(points=tour)
return length, tour
def nearest_insertion_algorithm(graph):
if graph.size == 0:
return -1, []
points = [i for i in range(graph.size())]
current = randrange(0, graph.size())
points.remove(current)
i = current
j = points[0]
cij = graph.get_distance(i, j)
for point in points:
if graph.get_distance(i, point) < cij:
cij = graph.get_distance(i, point)
j = point
points.remove(j)
edges = [(i, j)]
visited = []
visited.append(i)
visited.append(j)
while len(points) > 0:
i = visited[0]
k = points[0]
crj = graph.get_distance(k, i)
for point in points:
for c in visited:
dist = graph.get_distance(point, c)
if dist < crj:
k = point
i = edges[0][0]
j = edges[0][1]
c_min = graph.get_distance(i, k) + graph.get_distance(k, j) - graph.get_distance(i, j)
for e in edges:
aux_i = e[0]
aux_j = e[1]
dist = graph.get_distance(aux_i, k) + graph.get_distance(k, aux_j) - graph.get_distance(aux_i, aux_j)
if dist < c_min:
c_min = dist
i = aux_i
j = aux_j
if len(edges) == 1:
edges.append((j, i))
edges.remove((i, j))
edges.append((i, k))
edges.append((k, j))
visited.append(k)
points.remove(k)
length = graph.get_tour_length(edges=edges)
return length, edges
|
3e60333d8041939881ad52eabe9c7324b62f31f5 | lekshmijraj/PythonPrograms | /loops/ifpass.py | 134 | 4.03125 | 4 | a=35
b=36
if b>a:
print("a <b")
elif a==b:
print("a and b are equal")
else:
print(" a > b")
print("hello, the checks are done!")
|
17d71e890229021008aa3036692544e9dc6abb04 | thatislav/flightscraper | /parsing_machine_4.1_task.py | 16,926 | 3.6875 | 4 | """
This module parse information about flight tickets from http://www.flybulgarien.dk/en/
with parameters taken from user
"""
from datetime import datetime, timedelta
import re
import requests
from lxml import html
from texttable import Texttable
# 1. Параметры юзера принимаем функцией, полёты обрабатываем классом
DATA = dict()
def check_dep_city(city_from_user):
"""Check for input accuracy of departure city"""
response = requests.get('http://www.flybulgarien.dk/en/')
parsed = html.fromstring(response.text)
cities_from_html = parsed.xpath('//*[@id="departure-city"]/option[@value]/text()')
cities_for_dep = [re.search('[A-Z]{3}', city).group() for city in cities_from_html]
while city_from_user.upper() not in cities_for_dep:
city_from_user = input(
' - город введён неверно. Введите код города из списка: {}\n'.format(cities_for_dep))
DATA['dep_city'] = city_from_user.upper()
r_new = requests.get('http://www.flybulgarien.dk/script/getcity/2-{}'.
format(DATA['dep_city']))
cities_for_arr = [city for city in r_new.json()]
if not cities_for_arr:
print('\n..самолёты из {}, к сожалению, никуда не летают..'.
format(DATA['dep_city']))
# take_data_from_user()
check_dep_city(input('введите другой город: '))
elif len(cities_for_arr) == 1:
DATA['arr_city'] = cities_for_arr[0]
print('\nПрекрасно! Самолётом из {0} можно добраться только до {1}.'
'\n2) город прибытия: {1}'.
format(DATA['dep_city'], DATA['arr_city']))
check_arr_city(DATA['arr_city'])
else:
text = ' или '.join(cities_for_arr)
print('\nПрекрасно! Самолётом из {} можно добраться до {}. Куда направляетесь?'.
format(DATA['dep_city'], text))
check_arr_city(input('\n2) город прибытия: '))
def check_arr_city(city_from_user):
"""Check for input accuracy of arrival city"""
r_new = requests.get('http://www.flybulgarien.dk/script/getcity/2-{}'.
format(DATA['dep_city']))
cities_for_arr = [code for code in r_new.json()]
while city_from_user.upper() not in cities_for_arr:
city_from_user = input(
' - город введён неверно. Введите код города из списка: {}\n'.format(cities_for_arr)
)
DATA['arr_city'] = city_from_user.upper()
def available_dates(for_depart=True):
"""Pull out available dates"""
if for_depart: # Runs scenario for getting dates for departure
body = 'code1={0}&code2={1}'.format(DATA['dep_city'], DATA['arr_city'])
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# make POST-request to site with selected cities, to know available dates
r_new = requests.post('http://www.flybulgarien.dk/script/getdates/2-departure',
data=body, headers=headers)
raw_dates_from_html = set(re.findall(r'(\d{4},\d{1,2},\d{1,2})', r_new.text))
dates_for_dep = \
[datetime.strptime(raw_date, '%Y,%m,%d') for raw_date in raw_dates_from_html]
dates_for_dep = sorted(dates_for_dep)
DATA['dates_for_dep'] = dates_for_dep
return dates_for_dep
# Runs scenario for getting dates for arrive
dates_for_arr = [i for i in DATA['dates_for_dep'] if i >= DATA['dep_date']]
DATA['dates_for_arr'] = dates_for_arr
return dates_for_arr
def get_date_in_format(date_from_user):
"""Check for date input accuracy, and convert date into Datetime format"""
# проверяем, совпадает ли введенная дата с форматом
res = re.search(r'\d{1,2}\.\d{1,2}\.\d{4}', date_from_user)
if not res:
return get_date_in_format(input(' - формат даты: "ДД.ММ.ГГГГ". Повторите ввод:\n'))
try:
return datetime.strptime(date_from_user, '%d.%m.%Y')
except ValueError:
return get_date_in_format(input(
'Дата введена некорректно. Формат даты: "ДД.ММ.ГГГГ". Повторите ввод:\n'))
def check_dep_date(date_from_user):
"""Check if user's date suitable for choice for departure date"""
verified_dep_date = get_date_in_format(date_from_user)
dates_for_dep = available_dates()
if verified_dep_date not in dates_for_dep:
check_dep_date(input(
' - для выбора доступна любая из этих дат:\n{}\nКакую выберЕте?\n'.
format([datetime.strftime(date, '%d.%m.%Y') for date in dates_for_dep]))
)
else:
DATA['dep_date'] = verified_dep_date
DATA['dep_date_for_url'] = datetime.strftime(DATA['dep_date'], '%d.%m.%Y')
print('\nСупер! Почти всё готово. Обратный билет будем брать?'
'\nЕсли да - введите дату, если нет - нажмите Enter')
def check_arr_date(date_from_user):
"""Check for the presence of the input of arrival date"""
if not date_from_user:
print('Ок! One-way ticket!\nИтак, что мы имеем...')
check_if_oneway_flight()
else:
verified_arr_date = get_date_in_format(date_from_user)
dates_for_arr = available_dates(for_depart=False)
if verified_arr_date not in dates_for_arr:
check_arr_date(input(
' - выберите любую из этих дат:\n{}\n'.
format([datetime.strftime(date, '%d.%m.%Y') for date in dates_for_arr])))
else:
DATA['arr_date'] = verified_arr_date
check_if_oneway_flight(one_way=False)
def check_if_oneway_flight(one_way=True):
"""Check return flight"""
print('\n===============..Минутчку, пожалст..====================')
if one_way:
DATA['arr_date_for_url'] = ''
DATA['flag'] = 'ow'
DATA['arr_date'] = ''
else:
DATA['arr_date_for_url'] = '&rtdate=' + datetime.strftime(DATA['arr_date'], '%d.%m.%Y')
DATA['flag'] = 'rt'
# FIXME Program starts here
print('\nСалют! Билеты на самолёт??\nПроще простого! Введите:\n')
check_dep_city(input('1)город отправления: '))
check_dep_date(input('\n3) дата вылета (ДД.ММ.ГГГГ): '))
check_arr_date(input('\n4) дата возврата (необязательно) (ДД.ММ.ГГГГ): '))
URL = 'https://apps.penguin.bg/fly/quote3.aspx?{4}=&lang=en&depdate={2}' \
'&aptcode1={0}{3}&aptcode2={1}&paxcount=1&infcount='.\
format(DATA['dep_city'], DATA['arr_city'], DATA['dep_date_for_url'],
DATA['arr_date_for_url'], DATA['flag'])
R_FINAL = requests.get(URL)
TREE = html.fromstring(R_FINAL.text)
INFO_DEP = TREE.xpath('//tr[starts-with(@id, "flywiz_rinf")]')
PRICE_DEP = TREE.xpath('//tr[starts-with(@id, "flywiz_rprc")]')
INFO_ARR = TREE.xpath('//tr[starts-with(@id, "flywiz_irinf")]')
PRICE_ARR = TREE.xpath('//tr[starts-with(@id, "flywiz_irprc")]')
# список (словарей) релевантных вылетов ТУДА
DEPARTURE_LIST_RELEVANT = []
# список (словарей) всех вылетов ТУДА, выданных сайтом
DEPARTURE_LIST_ALL = []
# список (словарей) релевантных вылетов ОБРАТНО
ARRIVAL_LIST_RELEVANT = []
# список (словарей) всех вылетов ОБРАТНО, выданных сайтом
ARRIVAL_LIST_ALL = []
def change_data_dict():
"""Меняем главный словарь с параметрами от юзера
для использования при поиске обратного полёта"""
data_reverse = DATA.copy()
DATA['dep_city'] = data_reverse['arr_city']
DATA['arr_city'] = data_reverse['dep_city']
DATA['dep_date'] = data_reverse['arr_date']
DATA['arr_date'] = data_reverse['dep_date']
def prepare_finishing_flight_info(flight):
"""Проверяем подходят ли данные о вылете под параметры юзера"""
finished_flight_info = dict()
# время взлета в формате datetime
finished_flight_info['dep_time'] = \
datetime.strptime(flight[0] + ' ' + flight[1], '%a, %d %b %y %H:%M')
# время посадки в формате datetime
finished_flight_info['arr_time'] = \
datetime.strptime(flight[0] + ' ' + flight[2], '%a, %d %b %y %H:%M')
# к дате посадки +1 день, если время взлёта позднее времени посадки
if finished_flight_info['dep_time'] > finished_flight_info['arr_time']:
finished_flight_info['arr_time'] += timedelta(days=1)
finished_flight_info['duration'] = \
finished_flight_info['arr_time'] - finished_flight_info['dep_time']
finished_flight_info['price'] = float(flight[5].split()[1])
finished_flight_info['currency'] = flight[5].split()[2]
finished_flight_info['from'] = re.search('[A-Z]{3}', flight[3]).group()
finished_flight_info['to'] = re.search('[A-Z]{3}', flight[4]).group()
return finished_flight_info
def check_site_info(flight_info, price_info, relevant_list, all_list, return_flight=False):
"""Получаем 1 из 2 списков:
1) подходящих под параметры вылетов - relevant_list
2) и всех вылетов, прежложенных сайтом - all_list"""
# необработанные данные с сайта о вылетах в списке
prepared_flights_info = []
i = 0
# наполняем необрабортанными данными список prepared_flights_info
for flight_variant in [full_info for full_info in zip(flight_info, price_info)]:
prepared_flights_info.append([])
for element in flight_variant:
for piece in element.xpath('./td/text()'):
prepared_flights_info[i].append(piece)
i += 1
# если функция используется для проверки вылетов в обратном направлении (direction == 2),
# то правим словарь с параметрами вылета, чтобы по-прежнему можно пользоваться этой функцией
if return_flight:
change_data_dict()
# теперь отбираем из выдачи сайта (prepared_flights_info) -
# все подходящие под запрос юзера вылеты ТУДА в список словарей site_info_finished
for flight in prepared_flights_info:
# если вылет подходит под запрос юзера,
# сохраняем его в соотв-щий список relevant_list
if (re.search('[A-Z]{3}', flight[3]).group() == DATA['dep_city']) \
and (re.search('[A-Z]{3}', flight[4]).group() == DATA['arr_city'])\
and (datetime.strptime(flight[0], '%a, %d %b %y') == DATA['dep_date']):
relevant_list.append(prepare_finishing_flight_info(flight))
# если вылет не подходит под запрос юзера,
# тоже сохраняем его, но уже в список всех вылетов all_list
else:
all_list.append(prepare_finishing_flight_info(flight))
def print_flights_table(flights_list, header, list_is_relevant=True):
table_for_suitable_flights = Texttable(max_width=100)
table_for_suitable_flights.header(header)
for flight in flights_list:
table_for_suitable_flights.add_row(flight)
# FIXME можно попробовать table_for_suitable_flights.add_rows(flights_list)
print(table_for_suitable_flights.draw())
def pretty_time(time):
return datetime.strftime(time, '%H:%M %d.%m.%Y')
def show_suitable_flights(list_relevant, list_all, return_flight=False):
"""Проверяем, есть ли подходящие вылеты"""
# если подходящие вылеты были, выводим их на экран
list_filtered = list()
if list_relevant:
print('\nДля маршрута из {} в {} нашлось следующее:'.
format(DATA['dep_city'], DATA['arr_city']))
header = 'Взлёт в:\tПосадка в:\tДлительность перелёта:\tЦена билета:'.split('\t')
for flight in list_relevant:
flight_restruct = [pretty_time(flight['dep_time']),
pretty_time(flight['arr_time']),
flight['arr_time'] - flight['dep_time'],
str(flight['price']) + ' ' + flight['currency']]
list_filtered.append(flight_restruct)
print_flights_table(list_filtered, header)
# иначе выводим сообщение, что подходящих вылетов нет,
# и на всякий выдаём инфу о всех предложенных сайтом вылетах
else:
print('\nК сожалению, вылетов из {} в {} не нашлось.'
'\nНо это только пока, не отчаивайтесь ;)'
'\nЗато есть вот такие варианты:\n'.
format(DATA['dep_city'], DATA['arr_city']))
header = \
'Откуда:\tВзлёт в:\tКуда:\tПосадка в:\tДлительность перелёта:\tЦена билета:'.split('\t')
for flight in list_all:
flight_restruct = [flight['from'],
pretty_time(flight['dep_time']),
flight['to'],
pretty_time(flight['arr_time']),
flight['arr_time'] - flight['dep_time'],
str(flight['price']) + ' ' + flight['currency']]
list_filtered.append(flight_restruct)
print_flights_table(list_filtered, header, list_is_relevant=False)
check_site_info(INFO_DEP, PRICE_DEP, DEPARTURE_LIST_RELEVANT, DEPARTURE_LIST_ALL)
show_suitable_flights(DEPARTURE_LIST_RELEVANT, DEPARTURE_LIST_ALL)
if DATA['arr_date']:
check_site_info(INFO_ARR, PRICE_ARR, ARRIVAL_LIST_RELEVANT, ARRIVAL_LIST_ALL,
return_flight=True)
show_suitable_flights(ARRIVAL_LIST_RELEVANT, ARRIVAL_LIST_ALL, return_flight=True)
# если нашлись подходящие вылеты и ТУДА, и ОБРАТНО,
# то считаем все возможные варианты пар ТУДА-ОБРАТНО,
# сортируем по общей стоимости, выводим на экран
if DEPARTURE_LIST_RELEVANT and ARRIVAL_LIST_RELEVANT:
print('\n' + (36 * '=') + ' ИТОГО ' + (36 * '=') + '\n')
FLIGHT_LIST_OF_DICTS = []
for dep_flight in DEPARTURE_LIST_RELEVANT:
for arr_flight in ARRIVAL_LIST_RELEVANT:
if dep_flight['arr_time'] > arr_flight['dep_time']:
print('После посадки в {0} в {1} обратным рейсом в {2} улететь уже не успеете.'.
format(DATA['dep_city'],
pretty_time(dep_flight['arr_time']),
pretty_time(arr_flight['dep_time'])))
continue
flight_dict = dict()
flight_dict['dep_time_tuda'] = pretty_time(dep_flight['dep_time'])
flight_dict['dep_time_obratno'] = pretty_time(arr_flight['dep_time'])
flight_dict['v_polete'] = \
(dep_flight['arr_time'] - dep_flight['dep_time']) \
+ (arr_flight['arr_time'] - arr_flight['dep_time'])
flight_dict['itog_price'] = \
str(dep_flight['price'] + arr_flight['price']) + ' ' + dep_flight['currency']
FLIGHT_LIST_OF_DICTS.append(flight_dict)
if FLIGHT_LIST_OF_DICTS:
SORTED_FLIGHT_LIST_OF_DICTS = sorted(FLIGHT_LIST_OF_DICTS, key=lambda k: k['itog_price'])
SORTED_FLIGHT_LIST_OF_LISTS = \
[[v for v in flight_d.values()] for flight_d in SORTED_FLIGHT_LIST_OF_DICTS]
header = 'Из {} в {}:\tНазад:\tИтого в полёте(ЧЧ:ММ):\tИтого цена:'.\
format(DATA['arr_city'], DATA['dep_city']).split('\t')
print_flights_table(SORTED_FLIGHT_LIST_OF_LISTS, header)
# input('\n\n\nWait a minute...\n')
|
b36169cf1712dca276d8bc33bca89412500342d1 | Bngzifei/PythonNotes | /学习路线/1.python基础/day04/09-切片.py | 834 | 4.1875 | 4 | """
切片:取出字符串的一部分字符
字符串[开始索引:结束索引:步长] 步长不写,默认为1
下一个取得索引的字符 = 当前正在取得字符索引 + 步长
其他语言叫截取
步长:1.步长的正负控制字符串截取的方向 2.截取的跨度
"""
str1 = "hello python"
# print(str1[0:5])
# print(str1[:5]) # 如果开始索引为0,可以省略
# str2 = str1[6:12]
# str2 = str1[6:] # 如果结束索引最后,可以省略
# print(str2)
# list1 = [11, 12, 14]
# print(list1[-1]) # 负索引,倒着数,比较方便
#
# str2 = str1[-1:]
# print(str2)
# str2 = str1[::-1] # 倒置,翻转
# str2 = str1[4::-1] # 步长是-1,方向:右->左,跨度1
str2 = str1[4::-2] # 步长为-2,隔一个取一个
print(str2)
# 在列表,元组,字符串中都可以使用
# 可变参数.预习到这里
|
13c7f87d5affd2f7f3ca396f27141cc4e6ae9a39 | zainabkhosravi/runge_kutta_lane_emden | /runge_kutta.py | 823 | 3.546875 | 4 | from __future__ import division, print_function
# define functions used in integrate
def f(x, y, z):
return z
def g(x, y, z, n):
return -y**n-2/x*z
# integrate
def integrate(x_0, y_0, z_0, n, t_step):
'''Integrates one time step'''
k_0 = t_step * f(x_0, y_0, z_0)
l_0 = t_step * g(x_0, y_0, z_0, n)
k_1 = t_step * f(x_0+1/2*t_step, y_0+1/2*k_0, z_0+1/2*l_0)
l_1 = t_step * g(x_0+1/2*t_step, y_0+1/2*k_0, z_0+1/2*l_0, n)
k_2 = t_step * f(x_0+1/2*t_step, y_0+1/2*k_1, z_0+1/2*l_1)
l_2 = t_step * g(x_0+1/2*t_step, y_0+1/2*k_1, z_0+1/2*l_1, n)
k_3 = t_step * f(x_0+t_step, y_0+k_2, z_0+l_2)
l_3 = t_step * g(x_0+t_step, y_0+k_2, z_0+l_2, n)
x_1 = x_0 + t_step
y_1 = y_0 + 1/6 * (k_0+2*k_1+2*k_2+k_3)
z_1 = z_0 + 1/6 * (l_0+2*l_1+2*l_2+l_3)
return (x_1, y_1, z_1)
|
6134642fe17bd1a09d8e5390bec89671fdf73b42 | XenyLet/hse-percollation | /modules/utils.py | 350 | 3.578125 | 4 | # https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
def flatten(L):
if L is None:
return None
for item in L:
try:
if type(item) is not tuple:
yield from flatten(item)
else:
yield item
except TypeError:
yield item |
88dce776aefea393eba3246af3f4fb8af4793062 | Elonet/python3_formation_1 | /mymath/geom.py | 258 | 3.765625 | 4 | def perimeter(length, width):
"""
Return perimeter of square or rect
:param length:
:type length: float|int
:param width:
:type width: float|int
:return: Perimeter
:rtype: float|int
"""
return 2 * length + 2 * width
|
859b114f5f2589434dea429a16b6a1abb4b8a558 | JackM15/Python-Basics | /random_number_game.py | 1,862 | 4.0625 | 4 | import random
# generate a random number between 1 and 10
secretNumber = random.randint(1,10)
def game():
guesses = 0
while True:
# get a number guess from the player, if it's not a number, tell them and ask again.
while True:
try:
guess = int(input("Guess a number between 1 and 10 \n"))
break
except ValueError:
print("You didn't enter a number!")
guesses += 1
print("You have used {}/5 guesses.".format(guesses))
#Give the user 5 guesses to do it!
if guesses < 5:
# compare guess to secret number, if it matches then break, if not tell them they're wrong.
if guess == secretNumber:
guesses += 1
print("-" * 30)
print("You got it, my number was {}.".format(secretNumber))
print("It took you: {} tries to guess.".format(guesses))
print("-" * 30)
#reset guesses to 0
guesses = 0
break
#print hit or miss
elif guess <= 0:
print("That number is less than 1, try again!")
guesses += 1
print("You have used {}/5 guesses.".format(guesses))
elif guess >= 11:
print("That number is higher than 10, please try again!")
guesses += 1
print("You have used {}/5 guesses.".format(guesses))
else:
print("That's not it!")
print("Try guessing again!")
guesses += 1
print("You have used {}/5 guesses.".format(guesses))
#Break out of the loop if they took too long.
else:
print("You took too many times to guess, my number was: {}.".format(secretNumber))
break
#ask user if they want to play again
playAgain = input("Do you want to play again? - Y/n \n > ")
#if its not n, play again.
if playAgain.lower() != 'n':
game()
#Run game
game() |
807c2620cfec3e4e92a84dd0be270732ff16a5fd | daniel-reich/ubiquitous-fiesta | /7kZhB4FpJfYHnQYBq_16.py | 214 | 3.84375 | 4 |
def gcd(a, b):
if a < b: a, b = b, a
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
g = gcd(a, b)
return a * b // g
def lcm_three(num):
a, b, c = num
return lcm(lcm(a,b), lcm(b,c))
|
180ad11db84200995b6010d38f0537349b63c4ff | mshellik/automate_the_boring_stuff | /if_spam.py | 202 | 3.9375 | 4 | spam=0
if spam<5:
print("hello world")
spam=spam+1
print(spam)
#This will only print Hello World once, as once the condition is evalutes to True. it will print .. while new vaule spam will be 1
|
c5e7fe15e87cf568da5e33233cd38d6ef6938fb4 | yangzongwu/leetcode | /20200215Python-China/0166. Fraction to Recurring Decimal.py | 1,232 | 4.15625 | 4 | '''
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 2, denominator = 3
Output: "0.(6)"
'''
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator%denominator==0:
return str(numerator//denominator)
flag=''
if numerator*denominator<0:
flag='-'
numerator=abs(numerator)
denominator=abs(denominator)
first_part=str(numerator//denominator)+'.'
cur=numerator%denominator
rep=[]
second_part=''
while cur not in rep:
rep.append(cur)
if 10*cur%denominator==0:
return flag+first_part+second_part+str(10*cur//denominator)
second_part+=str(10*cur//denominator)
cur=10*cur%denominator
k=0
while rep[k]!=cur:
k+=1
return flag+first_part+second_part[:k]+'('+second_part[k:]+')'
|
72fd4e3f392e88ed6ff37886fa022d9ae182f05c | marinov98/fall-127-proof-of-work | /Python_127_proof_winter/applesnoranges07.py | 2,260 | 4.15625 | 4 | #When a fruit falls from its tree, it lands units of distance from its tree of origin along the -axis.
# A negative value of means the fruit fell units to the tree's left, and
#a positive value of means it falls units to the tree's right.
#Given the value of for apples and oranges,
#can you determine how many apples and oranges will fall on Sam's house (i.e., in the inclusive range )?
#Print the number of apples that fall on Sam's house as your first line of output,
#then print the number of oranges that fall on Sam's house as your second line of output.
#Input Format
#The first line contains two space-separated integers denoting the respective values of and .
#The second line contains two space-separated integers denoting the respective values of and .
#The third line contains two space-separated integers denoting the respective values of and .
#The fourth line contains space-separated integers denoting the respective distances that each apple falls from point .
#The fifth line contains space-separated integers denoting the respective distances that each orange falls from point .
#Constraints
#Output Format
#Print two lines of output:
#On the first line, print the number of apples that fall on Sam's house.
#On the second line, print the number of oranges that fall on Sam's house.
#Sample Input 0
#7 11
#5 15
#3 2
#-2 2 1
#5 -6
#Sample Output
#1
#1
def fruitree():
totalapple=0
totalorange=0
print("mark the start and end points of Sam's house")
s,t=input().split(' ')
s=int(s)
t=int(t)
print('what are the endpoints of the apple tree located?')
a,b=input().split(' ')
a=int(a)
b=int(b)
print('Almost there. Write the number of apples and oranges')
m,n=input().split(' ')
m=int(m)
n=int(n)
print('Final steps. write the position of the apples')
arange=[int(arange) for arange in input().split(' ')]
print('Now write the position of the oranges')
orrange=[int(orrange) for orrange in input().split(' ')]
for i in arange:
if s<=i+a<=t:
totalapple+=1
for z in orrange:
if s<=z+b<=t:
totalorange+=1
print(totalapple)
print(totalorange)
fruitree()
|
30a3a62c28e99cef20246e4a709f1d0b7cd729a2 | itsme-vivek/Akash-Technolabs-Internship | /Day-3/leapyear.py | 300 | 4.25 | 4 | print("Check Weather Year Is Leap Year Or Not")
year = int(input("Enter A Year:"))
if (year%4) == 0:
print("This Is Leap Year")
elif (year%400) == 0:
print("This Is Leap Year")
elif (year%100) != 0:
print("This Is Leap Year")
else :
print("This Is Not Leap Year") |
f83c22e67fda404820934542e16e8dc3be77312f | zaur557/python.zzz | /taack 1/Автопробег.py | 100 | 3.546875 | 4 | N = int(input())
K = int(input())
if K % N > 0:
print(K // N + 1)
else:
print(K // N)
|
5541272eb9eb2fc1cd69242c7e93045400c41983 | matthewnorman/testscore_extractor | /extractor.py | 922 | 3.53125 | 4 | import shutil
import urllib
import pandas
import os.path
import zipfile
import tempfile
DATA_URL = 'http://www5.cde.ca.gov/caasppresearchfiles/2015/ca2015_all_csv_v1.zip'
FILE_NAME = 'ca2015_all_csv_v1.txt'
def download_data(target_dir):
"""
Get the file from the internet
:param target_path: Local path for storing the file.
:return:
"""
download_file = os.path.join(target_dir, 'download.zip')
urllib.urlretrieve(DATA_URL, download_file)
zip_handler = zipfile.ZipFile(download_file)
zip_handler.extractall(path=target_dir)
def run():
"""
Run the entire process
:return:
"""
try:
target_dir = tempfile.mkdtemp()
download_data(target_dir=target_dir)
csv_file = os.path.join(target_dir, FILE_NAME)
df = pandas.DataFrame.from_csv(path=csv_file)
finally:
shutil.rmtree(target_dir)
if __name__=='__main__':
run() |
0463496bf5c0ccc9bbb7ca151a2fe2351b69fdfa | AmaralScientist/CourseworkCode | /KNN_Classifier.py | 52,326 | 3.8125 | 4 | ##
# This program uses the k nearest neighbors (KNN) algorithm, the condensed KNN
# algorithm, and the edited KNN algorithm to train and test machine learning
# classifiers. Five-fold cross-validation is performed and a KNN, condensed KNN,
# and edited KNN classifier are each tuned to determine the optimal value of k
# between k = 1 to k = 12. Summary statistics are output to separate files. The
# data set is again split for five-fold cross validation and the optimal value
# of k for each respective algorithm is used to train and test a classifier. The
# summary statistics for these experiments are output to separate files.
# The input is a pre-processed data set organized in a pandas dataframe such that
# the target class is located in the first column and the attributes in the
# remaining columns.
# @author Michelle Amaral
# @version 1.0
##
import sys,re,os
# Load pandas
import pandas as pd
# Load numpy
import numpy as np
import random
from collections import Counter
import math
# Receive the name of input file from the command line
input_file_name = sys.argv[1]
# This method accesses a data frame and splits its row numbers into k
# lists of row numbers, each corresponding to k unique test folds
# for use with k fold cross-validation
def split_for_cross_validation(data_frame, number_of_folds):
# Create empty list to hold the final row numbers for each test fold
list_of_row_numbers_for_test_folds = []
# Calculate the number of data instances per fold
number_instances_per_fold = math.floor(data_frame.shape[0] / number_of_folds)
# Create empty list to hold k number of test data sets
list_of_data_sets = []
# Create empty list to hold row numbers corresponding to each class
list_of_class_row_numbers = []
# Create empty list to hold proportion of each class
number_instances_of_each_class = []
# Determine the number of instances of each class
class_breakdown = data_frame.groupby(["Class"])["Class"].count()
# Determine the row numbers in data frame that correspond to each class
for class_index in range(0, len(class_breakdown)):
# Create a temporary data frame containing instances from a given class
temp_data_frame = data_frame.loc[data_frame['Class'] ==
class_breakdown.index.values[class_index]]
# Determine the actual row numbers of those instances
row_numbers_for_class = list(temp_data_frame.index.values.astype(int))
# Append these row numbers to list
list_of_class_row_numbers.append(row_numbers_for_class)
# Calculate the ratio class instances:number total instancess in big data set
composition_ratio = len(row_numbers_for_class) / data_frame.shape[0]
# Calculate the number of instances needed for each fold
number_instances_of_this_class_needed =
number_instances_per_fold * composition_ratio
rounded_number_instances_of_this_class_needed =
round(number_instances_of_this_class_needed, 0)
number_instances_of_each_class.append( rounded_number_instances_of_this_class_needed)
# In each fold, maintain the same ratio of the classes as in the full data set
for k_index in range(0, number_of_folds):
# Create empty list to store the row numbers for current fold
temp_row_numbers_for_this_fold = []
# Grab the row numbers needed for each class to be represented
for class_index in range(0, len(list_of_class_row_numbers)):
# The number of instances needed from given class
number_instances_needed = number_instances_of_each_class[class_index]
# Access eligible row numbers from given class
row_numbers_of_interest = list_of_class_row_numbers[class_index]
# Initialize counter variable
counter = 0
while counter < number_instances_needed:
# Randomly select the index of the eligible row number for given class
index_of_row_number_to_grab = random.randrange(len(row_numbers_of_interest))
# Access the actual row number from original data frame
row_number_to_grab = row_numbers_of_interest[index_of_row_number_to_grab]
# Append this row number to list
temp_row_numbers_for_this_fold.append(row_number_to_grab)
# Remove this row number from list of eligible row numbers
row_numbers_of_interest.pop(index_of_row_number_to_grab)
# Increment counter variable by 1
counter = counter + 1
# Append all row numbers to final list
list_of_row_numbers_for_test_folds.append( temp_row_numbers_for_this_fold )
# Return the unique row numbers for all 5 test sets
return( list_of_row_numbers_for_test_folds )
# This method implements the KNN algorithm by calculating Euclidean distances,
# identifying the k nearest neighbors, predicting a class based on the classes
# of the nearest neighbors, evaluates the accuracy of the predictions, and
# returns that measure.
def knn_algorithm_for_tuning( temp_test_data_frame, temp_train_data_frame, k_index ):
# Determine the number of rows in the test data frame
number_test_instances = temp_test_data_frame.shape[0]
# Determine the number of rows in the train data frame
number_train_instances = temp_train_data_frame.shape[0]
# Create temporary numpy array to store results
temp_df_for_test_results = np.zeros( shape=( number_test_instances, 5 ) )
# Create dataframe only consisting of attributes for test data
temp_test_df_attributes_only = temp_test_data_frame.drop(["Class"], axis=1)
# Initialize a variable to count the correctly classified instances
correct_class_counter = 0
# Initialize a variable to count the incorrectly classified instances
incorrect_class_counter = 0
for test_row_index in range( 0, number_test_instances ):
# Create temporary numpy array to store euclidean distances
temp_df_for_distances = np.zeros( shape=( number_train_instances, 2 ) )
# Create dataframe only consisting of attributes for train data
temp_train_df_attributes_only = temp_train_data_frame.drop(["Class"], axis=1)
temp_train_class_column = temp_train_data_frame["Class"]
number_train_columns = temp_test_df_attributes_only.shape[1]
# Calculate Euclidean distance between test instance and training instances
for train_row_index in range( 0, number_train_instances ):
# Initialize a variable to sum the squared distance of each feature
squared_distance = 0
# Increment over each feature to obtain the difference between
# each test and train instance
for feature_index in range( 0, number_train_columns ):
squared_distance = squared_distance +
( temp_test_df_attributes_only.iloc[test_row_index, feature_index] -
temp_train_df_attributes_only.iloc[train_row_index, feature_index] )** 2
# Calculate the square root of the sum of the differences
euclidean_distance = np.sqrt( squared_distance )
# Store the Euclidean distances and the location of that training instance
temp_df_for_distances[train_row_index, 0] = euclidean_distance
temp_df_for_distances[train_row_index, 1] = train_row_index
# Sort the numpy array containing the distances
sorted_temp_df_for_distances =
temp_df_for_distances[temp_df_for_distances[:,0].argsort()]
# Grab the k neighbors that are closest to the training instance
k_nearest_neighbors = sorted_temp_df_for_distances[0:k_index,]
# Store the classes of these neighbors
correct_class = []
for j in range(0, k_index):
class_row_number = int(k_nearest_neighbors[j, 1])
correct_class.append(temp_train_data_frame.iloc[class_row_number, 0])
# Count the number of each class from the neighbors
k_classes = Counter(correct_class)
# If all neighbors are of the same class, call the prediction
if len(k_classes) == 1:
for key in k_classes:
this_class_predicted = key
# If the neighbors represent more than one class, find most frequent
else:
# Create empty list to hold the number of each class
counts_of_neighbors = []
# Create empty list to hold the names of each class
class_name_of_neighbors = []
# Append counter output to lists
for thing in k_classes:
counts_of_neighbors.append(k_classes[thing])
class_name_of_neighbors.append(thing)
# Initialize variable to track the most frequent class
largest_count = 0
# Empty list to hold class counts in case there is a tie
tied_neighbor_counts = []
# Empty list to hold class names in case there is a tie
tied_neighbor_names = []
# Iterate over the counts of the classes to find the largest
for j in range(0, len(counts_of_neighbors)):
if counts_of_neighbors[j] > largest_count:
largest_count = counts_of_neighbors[j]
name_of_class = class_name_of_neighbors[j]
# If there is a tie, store name and count of the class
elif counts_of_neighbors[j] == largest_count:
tied_neighbor_counts.append(counts_of_neighbors[j])
tied_neighbor_names.append(class_name_of_neighbors[j])
# If there was not a tie call the predicted class
if len(counts_of_neighbors) == 0:
this_class_predicted = name_of_class
# There was a tie, break it randomly
else:
tied_neighbor_counts.append(largest_count)
tied_neighbor_names.append(name_of_class)
select_one_class_index = random.randrange(len(tied_neighbor_names))
this_class_predicted = tied_neighbor_names[select_one_class_index]
# Compare predicted to actual
correct_class = temp_test_data_frame.iloc[test_row_index, 0]
if this_class_predicted == correct_class:
correct_class_counter = correct_class_counter + 1
else:
incorrect_class_counter = incorrect_class_counter + 1
#print("\tCorrectly classified instances: ", correct_class_counter)
#print("\tIncorrectly classified instances: ", incorrect_class_counter)
# Calculate the accuracy for this data subset
performance = correct_class_counter / (correct_class_counter + incorrect_class_counter)
# Return the performance value
return( performance )
# This method accepts a training data set and implements the condensed nearest
# neighbors algorithm to produce a smaller training data set
def condensed_nearest_neighbor( temp_train_data_frame ):
# Determine the number of rows in the train data frame
number_train_instances = temp_train_data_frame.shape[0]
# Create empty list to hold row numbers of the original training data set (X)
original_training_set = []
# Append the row numbers to the list, then randomly shuffle
for k in range(0, number_train_instances):
original_training_set.append ( k )
random.shuffle( original_training_set )
# Create empty list to hold row numbers that will be contained in
# the condensed training set (Z)
condensed_training_set = []
# Move row number of the first instance to the condensed training set
remove_one_training_example = original_training_set.pop( 0 )
condensed_training_set.append( remove_one_training_example )
# Perform 1NN until a full pass is made over the original training data set
for p in range(0, len(original_training_set)):
# Grab next training example from original training data set
remove_one_training_example = original_training_set.pop( 0 )
# Create a temporary array to hold the Euclidean distances and the row number
temp_df_for_distances = np.zeros( shape=( len( condensed_training_set ), 2 ) )
# Create dataframe only consisting of attributes for train data
temp_train_df_attributes_only = temp_train_data_frame.drop(["Class"], axis=1)
number_train_columns = temp_train_df_attributes_only.shape[1]
# Calculate the Euclidean distances between the example and the instances
# contained in the condensed training data set (Z)
for m in range(0, len(condensed_training_set)):
squared_distance = 0
for feature_index in range( 0, number_train_columns ):
squared_distance = squared_distance +
( temp_train_df_attributes_only.iloc[remove_one_training_example, feature_index] -
temp_train_df_attributes_only.iloc[condensed_training_set[m], feature_index] ) ** 2
euclidean_distance = np.sqrt( squared_distance )
temp_df_for_distances[m, 0] = euclidean_distance
temp_df_for_distances[m, 1] = condensed_training_set[m]
# Sort the array by distance
sorted_temp_df_for_distances =
temp_df_for_distances[temp_df_for_distances[:,0].argsort()]
# k = 1 so remove the row of the array with the smallest distance
k_nearest_neighbors = sorted_temp_df_for_distances[0,]
# Extract the row number corresponding to that instance in the data frame
class_row_number = int(k_nearest_neighbors[1,])
# Extract the class of that instance
predicted_class = temp_train_data_frame.iloc[class_row_number, 0]
# Compare predicted class to actual class of the instance in question
correct_class = temp_train_data_frame.iloc[remove_one_training_example, 0]
# If the predicted and correct classes are not equal, append the
# row number of that instance to the condensed training set.
# Otherwise, add it back to the original training data set
if predicted_class != correct_class:
condensed_training_set.append(remove_one_training_example)
else:
original_training_set.append(remove_one_training_example)
# Initialize a variable to track the point at which no more instances
# are being added to the condensed training data set
instance_not_added_to_Z = 0
# Continue performing 1NN until a complete pass is made over the
# original training data and no instances are added to the condensed set
while ( len(original_training_set) != 0 ) and
instance_not_added_to_Z < len(original_training_set):
# Grab next training example from original training data set
remove_one_training_example = original_training_set.pop( 0 )
# Create a temporary array to hold the Euclidean distances and the row number
temp_df_for_distances = np.zeros( shape=( len( condensed_training_set ), 2 ) )
# Create dataframe only consisting of attributes for train data
temp_train_df_attributes_only = temp_train_data_frame.drop(["Class"], axis=1)
# Calculate the Euclidean distances between the example and the instances
# contained in the condensed training data set (Z)
for m in range(0, len(condensed_training_set)):
squared_distance = 0
for feature_index in range( 0, number_train_columns ):
squared_distance = squared_distance +
( temp_train_df_attributes_only.iloc[remove_one_training_example, feature_index] -
temp_train_df_attributes_only.iloc[condensed_training_set[m], feature_index] ) ** 2
euclidean_distance = np.sqrt( squared_distance )
temp_df_for_distances[m, 0] = euclidean_distance
temp_df_for_distances[m, 1] = condensed_training_set[m]
# Sort the array by distance
sorted_temp_df_for_distances =
temp_df_for_distances[temp_df_for_distances[:,0].argsort()]
# k = 1 so remove the row of the array with the smallest distance
k_nearest_neighbors = sorted_temp_df_for_distances[0,]
# Extract the row number corresponding to that instance in the data frame
class_row_number = int(k_nearest_neighbors[1,])
# Extract the class of that instance
predicted_class = temp_train_data_frame.iloc[class_row_number, 0]
# Compare predicted class to actual class of the instance in question
correct_class = temp_train_data_frame.iloc[remove_one_training_example, 0]
# If the predicted and correct classes are not equal, append the
# row number of that instance to the condensed training set.
# Otherwise, add it back to the original training data set
if predicted_class != correct_class:
condensed_training_set.append(remove_one_training_example)
# Reset indicator variable to 0 since the instance was added
instance_not_added_to_Z = 0
else:
original_training_set.append(remove_one_training_example)
# Instance was not added so increment by 1
instance_not_added_to_Z = instance_not_added_to_Z + 1
# Evaluate differences between original and condensed training data sets
print("\tInstances before condensing: ", number_train_instances)
print("\tInstances after condensing: ", len(condensed_training_set))
reduction_in_number_of_instances = ( ( number_train_instances -
len(condensed_training_set) ) / number_train_instances )
percent_reduction = reduction_in_number_of_instances * 100
print("\tPercent reduction: ", round( percent_reduction, 2 ), "%\n")
condensed_training_data_set = temp_train_data_frame.iloc[condensed_training_set,]
return( condensed_training_data_set, reduction_in_number_of_instances )
# This method accepts a training data set and implements the edited
# nearest neighbors algorithm to produce a smaller training data set
def edited_nearest_neighbor( temp_train_data_frame ):
# Determine the number of rows in the train data frame
number_train_instances = temp_train_data_frame.shape[0]
# Create empty list to hold row numbers of the original training data set
original_training_set = []
# Append the row numbers to the list, then randomly shuffle
for k in range(0, number_train_instances):
original_training_set.append ( k )
random.shuffle( original_training_set )
number_train_columns = temp_train_data_frame.shape[1]
# Perform k=3 nearest neighbors until a full pass
# is made over the original training data set
for p in range(0, number_train_instances):
# Grab one training example from original training data set
remove_one_training_example = original_training_set.pop( 0 )
# Create a temporary array to hold the Euclidean distances and the row number
temp_df_for_distances = np.zeros( shape=( len( original_training_set ), 2 ) )
# Create dataframe only consisting of attributes for train data
temp_train_df_attributes_only = temp_train_data_frame.drop(["Class"], axis=1)
number_train_columns = temp_train_df_attributes_only.shape[1]
# Calculate the Euclidean distances between the example instance and
# the remaining instances contained in the original training data set
for m in range(0, len(original_training_set)):
squared_distance = 0
for feature_index in range( 0, number_train_columns ):
squared_distance = squared_distance +
( temp_train_df_attributes_only.iloc[remove_one_training_example, feature_index] -
temp_train_df_attributes_only.iloc[original_training_set[m], feature_index] ) ** 2
euclidean_distance = np.sqrt( squared_distance )
temp_df_for_distances[m, 0] = euclidean_distance
temp_df_for_distances[m, 1] = original_training_set[m]
# Sort the temporary array by distance
sorted_temp_df_for_distances =
temp_df_for_distances[temp_df_for_distances[:,0].argsort()]
# Take the three instances with the smallest distance
k_nearest_neighbors = sorted_temp_df_for_distances[0:3,]
# Obtain the class for these instances
correct_class = []
for j in range(0, 3):
class_row_number = int(k_nearest_neighbors[j, 1])
correct_class.append(temp_train_data_frame.iloc[class_row_number, 0])
k_classes = Counter(correct_class)
predicted_class = max(k_classes, key=lambda key: k_classes[key])
# Compare predicted class to actual class of the instance in question
correct_class = temp_train_data_frame.iloc[remove_one_training_example, 0]
# If the predicted and correct classes are equal, append the
# row number of that instance back to the original training set.
# Otherwise, remove instance
if predicted_class == correct_class:
original_training_set.append(remove_one_training_example)
else:
remove_one_training_example = None
# Initialize a variable to track the point at which no more
# instances are being added back to the original training data set
instance_not_removed = 0
while ( instance_not_removed < len(original_training_set) ):
# Grab next training example from original training data set
remove_one_training_example = original_training_set.pop( 0 )
# Create a temporary array to hold the Euclidean distances and the row number
temp_df_for_distances = np.zeros( shape=( len( original_training_set ), 2 ) )
# Create dataframe only consisting of attributes for train data
temp_train_df_attributes_only = temp_train_data_frame.drop(["Class"], axis=1)
# Calculate the Euclidean distances between the example
# and the instances contained in the condensed training data set
for m in range(0, len(original_training_set)):
squared_distance = 0
for feature_index in range( 0, number_train_columns ):
squared_distance = squared_distance +
( temp_train_df_attributes_only.iloc[remove_one_training_example, feature_index] -
temp_train_df_attributes_only.iloc[original_training_set[m], feature_index] ) ** 2
euclidean_distance = np.sqrt( squared_distance )
temp_df_for_distances[m, 0] = euclidean_distance
temp_df_for_distances[m, 1] = original_training_set[m]
# Sort the array by distance
sorted_temp_df_for_distances =
temp_df_for_distances[temp_df_for_distances[:,0].argsort()]
# Take the three instances with the smallest distance
k_nearest_neighbors = sorted_temp_df_for_distances[0:3,]
# Obtain the class for these instances
correct_class = []
for j in range(0, 3):
class_row_number = int(k_nearest_neighbors[j, 1])
correct_class.append(temp_train_data_frame.iloc[class_row_number, 0])
k_classes = Counter(correct_class)
predicted_class = max(k_classes, key=lambda key: k_classes[key])
# Compare predicted class to actual class of the instance in question
correct_class = temp_train_data_frame.iloc[remove_one_training_example, 0]
# If the predicted and correct classes are equal, append the
# row number of that instance back to the original training set.
# Otherwise, remove instance
if predicted_class == correct_class:
original_training_set.append(remove_one_training_example)
instance_not_removed = instance_not_removed + 1
else:
remove_one_training_example = None
instance_not_removed = 0
# Evaluate differences between original and condensed training data sets
print("\tInstances before editing: ", number_train_instances)
print("\tInstances after editing: ", len(original_training_set))
reduction_in_number_of_instances = ( number_train_instances -
len(original_training_set) ) / number_train_instances
percent_reduction = reduction_in_number_of_instances * 100
print("\tPercent reduction: ", round(percent_reduction, 2), "%\n")
edited_train_data_frame = temp_train_data_frame.iloc[original_training_set,]
return( edited_train_data_frame, reduction_in_number_of_instances )
################################################
############## Main Driver #####################
################################################
# Load input file
temp_df = pd.read_csv(input_file_name, header=[0], sep='\t')
# Parse input file name for output file
split_input_path = input_file_name.strip().split("/")
split_input_file_name = split_input_path[7].split("_")
output_file_name_list = []
words_to_drop_from_name = ['clean']
for split_index in range(0, len(split_input_file_name)):
if words_to_drop_from_name[0] not in split_input_file_name[split_index]:
output_file_name_list.append(split_input_file_name[split_index])
output_file_name_final = '_'.join(output_file_name_list)
################################################
# Perform KNN, tuning for the k parameter
################################################
# Write results to an output file
with open ("/Users/michelleamaral/Desktop/Intro_to_Machine_Learning/Programming_Project_2/Outputs/" +
output_file_name_final + "_output_KNN_Classifier_Tune_K", 'w') as tuneOutputFile:
tuneOutputFile.write( "\nData set: " + output_file_name_final + "\n" )
tuneOutputFile.write( "\nType of problem: Classification\n" )
# Split data set into 5 folds
test_folds_row_numbers = split_for_cross_validation(temp_df, 5)
# Tune the nearest neighbors parameter k
tuneOutputFile.write( "\n************************\n" )
tuneOutputFile.write( "\nTuning the parameter k\n" )
tuneOutputFile.write( "\n************************\n" )
# Create an empty list to store accuracy measure for each k
performance_for_this_k = []
# Create an empty list to track the values of k
list_of_k_values = []
for k_index in range(1, 13):
# Store the value of k for this run
list_of_k_values.append( k_index )
# Output value of k for this run
tuneOutputFile.write( "\nFor k = " + str(k_index) + ":\n" )
# Create empty list to store accuracy measure for each of the 5 folds
list_of_performances = []
for index_lists in range(0, len(test_folds_row_numbers)):
tuneOutputFile.write( " When fold "+str(index_lists)+" is the test set:\n" )
# Obtain row numbers for test fold
temp_df_row_list = test_folds_row_numbers[index_lists]
# Obtain test data frame using row numbers for test fold
temp_test_data_frame = temp_df.iloc[temp_df_row_list,]
temp_test_data_frame = temp_test_data_frame.reset_index( drop=True )
# Obtain train data frame by dropping row numbers for test fold
temp_train_data_frame = temp_df.drop( temp_df.index[temp_df_row_list] )
temp_train_data_frame = temp_train_data_frame.reset_index( drop=True )
# Perform the knn algorithm
this_fold_performance = knn_algorithm_for_tuning( temp_test_data_frame,
temp_train_data_frame, k_index )
# Store the accuracy measure
list_of_performances.append( this_fold_performance )
# Express the accuracy as a percentage
this_fold_percent_accuracy = this_fold_performance * 100
tuneOutputFile.write( "\tClassification accuracy: " +
str(round( this_fold_percent_accuracy, 2 )) + "%\n" )
# Calculate the average of the 5 accuracy performances
average_of_5_performances = np.mean( list_of_performances )
performance_for_this_k.append( average_of_5_performances )
# Express the average accuracy as a percentage
percent_accuracy = average_of_5_performances * 100
# Calculate the standard deviation for the 5 accuracy measures
stdev_accuracy = np.std( list_of_performances )
stdev_accuracy_as_percent = stdev_accuracy * 100
tuneOutputFile.write( "\nAverage classification accuracy: " +
str(round( percent_accuracy, 2 )) + "% for k equals " + str(k_index) + "\n" )
tuneOutputFile.write( "Standard deviation: " +
str(round( stdev_accuracy_as_percent, 2 )) + "%\n" )
# Write the raw average accuracy measures for each k
tuneOutputFile.write( "\nSummary of raw average accuracy over all k: " +
str(performance_for_this_k) + "\n" )
# Determine k value associated with highest accuracy
max_accuracy = 0
optimal_k_for_knn = 0
for accuracy_index in range( 0, len(performance_for_this_k) ):
if performance_for_this_k[ accuracy_index ] > max_accuracy:
max_accuracy = performance_for_this_k[ accuracy_index ]
optimal_k_for_knn = list_of_k_values[ accuracy_index ]
tuneOutputFile.write( "\nHighest accuracy over all k: " + str(max_accuracy) + "\n" )
tuneOutputFile.write( "Optimal value of k parameter: " + str(optimal_k_for_knn)+"\n")
# Close this output file
tuneOutputFile.close()
####################################################
# Perform Condensed KNN, tuning for the k parameter
####################################################
# Write condensed nearest neighbors results to an output file
with open ("/Users/michelleamaral/Desktop/Intro_to_Machine_Learning/Programming_Project_2/Outputs/" +
output_file_name_final + "_output_Condensed_KNN_Classifier_Tune_K", 'w') as condensedOutputFile:
condensedOutputFile.write( "\nData set: " + output_file_name_final + "\n" )
condensedOutputFile.write( "\nType of problem: Classification\n" )
condensedOutputFile.write( "\n****************************\n" )
condensedOutputFile.write( "\nCondensed Nearest Neighbors\n" )
condensedOutputFile.write( "\n Tuning the parameter k\n" )
condensedOutputFile.write( "\n****************************\n" )
# Create empty list to store accuracy measure for each k
condensed_performance_for_this_k = []
# Create an empty list to track the values of k
list_of_k_values = []
for k_index in range(1, 13):
# Track the value of k for this run
list_of_k_values.append( k_index )
# Write this value of k to the output file
condensedOutputFile.write( "\nFor k = " + str(k_index) + ":\n" )
# Create empty list to store the reduction in size between original
# data set and condensed data set
list_of_reduction_in_data_size = []
# Create empty list to store accuracy measure for each of the 5 folds
condensed_list_of_performances = []
for index_lists in range( 0, len(test_folds_row_numbers) ):
condensedOutputFile.write( " When fold " + str(index_lists) +
" is the test set:\n" )
# Obtain row numbers for test fold
temp_df_row_list = test_folds_row_numbers[index_lists]
# Obtain test data frame using row numbers for test fold
temp_test_data_frame = temp_df.iloc[temp_df_row_list,]
temp_test_data_frame = temp_test_data_frame.reset_index( drop=True )
# Obtain train data frame by dropping row numbers for test fold
temp_train_data_frame = temp_df.drop( temp_df.index[temp_df_row_list] )
temp_train_data_frame = temp_train_data_frame.reset_index( drop=True )
# Call the condensed nearest neighbors method in an attempt to reduce the data size
condensed_train_data_frame, instance_reduction =
condensed_nearest_neighbor( temp_train_data_frame )
list_of_reduction_in_data_size.append( instance_reduction )
# Call the knn algorithm to determine the nearest neighbors
this_fold_performance = knn_algorithm_for_tuning( temp_test_data_frame,
condensed_train_data_frame, k_index )
condensed_list_of_performances.append( this_fold_performance )
# Express the accuracy measure as a percentage
this_fold_percent_accuracy = this_fold_performance * 100
condensedOutputFile.write( "\tClassification accuracy: " +
str(round( this_fold_percent_accuracy, 2 )) + "%\n" )
condensedOutputFile.write( "\tPercent reduction in number of instances: " +
str(round( this_fold_percent_accuracy, 2 )) + "%\n" )
# Calculate the average reduction in the size of the data set
average_of_5_instance_reductions = np.mean(list_of_reduction_in_data_size)
percent_reduction_of_instances = average_of_5_instance_reductions * 100
# Calculate the standard deviation of the reduction in the size of the data set
stdev_reduction_of_instances = np.std( list_of_reduction_in_data_size )
stdev_reduction_as_percent = stdev_reduction_of_instances * 100
condensedOutputFile.write( "\nAverage reduction in number of instances: " +
str(round( percent_reduction_of_instances, 2 )) + "%\n" )
condensedOutputFile.write( "Standard deviation: " +
str(round( stdev_reduction_as_percent, 2 )) + "%\n" )
# Calculate the average accuracy of the classifier
average_of_5_performances = np.mean( condensed_list_of_performances )
condensed_performance_for_this_k.append( average_of_5_performances )
percent_accuracy = average_of_5_performances * 100
# Calculate the standard deviation of the average accuracy
stdev_accuracy = np.std( condensed_list_of_performances )
stdev_accuracy_as_percent = stdev_accuracy * 100
condensedOutputFile.write( "\nAverage classification accuracy: " +
str(round( percent_accuracy, 2 )) + "%\n" )
condensedOutputFile.write( "Standard deviation: " +
str(round( stdev_accuracy_as_percent, 2 )) + "%\n" )
# Write the raw average accuracy measures for each k
condensedOutputFile.write( "\nSummary of raw average accuracy over all k: " +
str(condensed_performance_for_this_k) + "\n" )
# Determine k value associated with highest accuracy
max_accuracy = 0
condensed_optimal_k = 0
for accuracy_index in range( 0, len(condensed_performance_for_this_k) ):
if condensed_performance_for_this_k[ accuracy_index ] > max_accuracy:
max_accuracy = condensed_performance_for_this_k[ accuracy_index ]
condensed_optimal_k = list_of_k_values[ accuracy_index ]
condensedOutputFile.write( "\nHighest accuracy over all k: " +
str(max_accuracy) + "\n" )
condensedOutputFile.write( "Optimal value of k parameter: " +
str(condensed_optimal_k) + "\n" )
# Close this output file
condensedOutputFile.close()
################################################
# Perform Edited KNN, tuning for the k parameter
################################################
# Write condensed nearest neighbors results to an output file
with open ("/Users/michelleamaral/Desktop/Intro_to_Machine_Learning/Programming_Project_2/Outputs/" +
output_file_name_final + "_output_Edited_KNN_Classifier_Tune_K", 'w') as editedOutputFile:
editedOutputFile.write( "\nData set: " + output_file_name_final + "\n" )
editedOutputFile.write( "\nType of problem: Classification\n" )
editedOutputFile.write( "\n************************\n" )
editedOutputFile.write( "\nEdited Nearest Neighbors\n" )
editedOutputFile.write( "\n Tuning the parameter k\n" )
editedOutputFile.write( "\n************************\n" )
# Create empty list to store accuracy measure for each k
edited_performance_for_this_k = []
for k_index in range(1, 13):
editedOutputFile.write( "\nFor k = " + str(k_index) + ":\n" )
# Create empty list to store the reduction in size between original
# data set and edited data set
list_of_reduction_in_data_size = []
# Create empty list to store accuracy measure for each of the 5 folds
edited_list_of_performances = []
for index_lists in range( 0, len(test_folds_row_numbers) ):
editedOutputFile.write( " When fold " + str(index_lists) +
" is the test set:\n" )
# Obtain row numbers for test fold
temp_df_row_list = test_folds_row_numbers[index_lists]
# Obtain test data frame using row numbers for test fold
temp_test_data_frame = temp_df.iloc[temp_df_row_list,]
temp_test_data_frame = temp_test_data_frame.reset_index( drop=True )
# Obtain train data frame by dropping row numbers for test fold
temp_train_data_frame = temp_df.drop( temp_df.index[temp_df_row_list] )
temp_train_data_frame = temp_train_data_frame.reset_index( drop=True )
# Call the edited nearest neighbors method in an attempt to
# reduce the data set size
edited_train_data_frame, instance_reduction =
edited_nearest_neighbor( temp_train_data_frame )
list_of_reduction_in_data_size.append( instance_reduction )
# Call the knn algorithm; accuracy of the classifier will be returned
this_fold_performance = knn_algorithm_for_tuning( temp_test_data_frame,
edited_train_data_frame, k_index )
edited_list_of_performances.append( this_fold_performance )
this_fold_percent_accuracy = this_fold_performance * 100
editedOutputFile.write( "\tClassification accuracy: " +
str(round( this_fold_percent_accuracy, 2 )) + "%\n" )
editedOutputFile.write( "\tPercent reduction in number of instances: " +
str(round( this_fold_percent_accuracy, 2 )) + "%\n" )
# Calculate the average reduction in size of the data set
average_of_5_instance_reductions = np.mean( list_of_reduction_in_data_size )
percent_reduction_of_instances = average_of_5_instance_reductions * 100
# Calculate the standard deviation of the data size reductions
stdev_reduction_of_instances = np.std( list_of_reduction_in_data_size )
stdev_reduction_as_percent = stdev_reduction_of_instances * 100
editedOutputFile.write( "\nAverage reduction in number of instances: " +
str(round( percent_reduction_of_instances, 2 )) + "%\n" )
editedOutputFile.write( "Standard deviation: " +
str(round( stdev_reduction_as_percent, 2 )) + "%\n" )
# Calculate the average accuracy of the classifier
average_of_5_performances = np.mean( edited_list_of_performances )
edited_performance_for_this_k.append( average_of_5_performances )
percent_accuracy = average_of_5_performances * 100
# Calculate the standard deviation of the accuracy measures
stdev_accuracy = np.std( edited_list_of_performances )
stdev_accuracy_as_percent = stdev_accuracy * 100
editedOutputFile.write( "\nAverage classification accuracy: " +
str(round( percent_accuracy, 2 )) + "%\n" )
editedOutputFile.write( "Standard deviation: " +
str(round( stdev_accuracy_as_percent, 2 )) + "%\n" )
# Write the raw average accuracy measures for each k
editedOutputFile.write( "\nSummary of raw average accuracy over all k: " +
str(edited_performance_for_this_k) + "\n" )
# Determine k value associated with highest accuracy
max_accuracy = 0
edited_optimal_k = 0
for accuracy_index in range( 0, len(edited_performance_for_this_k) ):
if edited_performance_for_this_k[ accuracy_index ] > max_accuracy:
max_accuracy = edited_performance_for_this_k[ accuracy_index ]
edited_optimal_k = list_of_k_values[ accuracy_index ]
editedOutputFile.write( "\nHighest accuracy over all k: " + str(max_accuracy) + "\n" )
editedOutputFile.write( "Optimal value of k parameter: " + str(edited_optimal_k) + "\n" )
# Close this output file
editedOutputFile.close()
####################################################
# Perform KNN using optimal k parameter from tuning
####################################################
# Split data set into 5 folds
optimal_k_test_folds_row_numbers = split_for_cross_validation(temp_df, 5)
# Prepare output file
with open ("/Users/michelleamaral/Desktop/Intro_to_Machine_Learning/Programming_Project_2/Outputs/" +
output_file_name_final + "_output_KNN_Classifier_Optimal_K", 'w') as tunedKOutputFile:
tunedKOutputFile.write( "\nData set: " + output_file_name_final + "\n" )
tunedKOutputFile.write( "\nType of problem: Classification\n" )
tunedKOutputFile.write( "\n************************\n" )
tunedKOutputFile.write( "\nKNN with optimal k = " + str( optimal_k_for_knn ) + "\n" )
tunedKOutputFile.write( "\n************************\n" )
# Create empty list to store accuracy measure for each of the 5 folds
optimal_k_list_of_performances = []
for index_lists in range(0, len(optimal_k_test_folds_row_numbers)):
tunedKOutputFile.write( " When fold " + str(index_lists) + " is the test set:\n")
# Obtain row numbers for test fold
temp_df_row_list = optimal_k_test_folds_row_numbers[index_lists]
# Obtain test data frame using row numbers for test fold
temp_test_data_frame = temp_df.iloc[temp_df_row_list,]
temp_test_data_frame = temp_test_data_frame.reset_index( drop=True )
# Obtain train data frame by dropping row numbers for test fold
temp_train_data_frame = temp_df.drop( temp_df.index[temp_df_row_list] )
temp_train_data_frame = temp_train_data_frame.reset_index( drop=True )
# Perform the knn algorithm with optimal k parameter
this_fold_performance = knn_algorithm_for_tuning( temp_test_data_frame,
temp_train_data_frame, optimal_k_for_knn )
optimal_k_list_of_performances.append( this_fold_performance )
this_fold_percent_accuracy = this_fold_performance * 100
tunedKOutputFile.write( "\tClassification accuracy: " +
str(round( this_fold_percent_accuracy, 2 )) + "%\n" )
# Calculate average accuracy from the five folds
average_of_5_performances = np.mean( optimal_k_list_of_performances )
percent_accuracy = average_of_5_performances * 100
# Calculate standard deviation for the average accuracy measure
stdev_accuracy = np.std( optimal_k_list_of_performances )
stdev_accuracy_as_percent = stdev_accuracy * 100
tunedKOutputFile.write( "\nAverage classification accuracy: " +
str(round( percent_accuracy, 2 )) + "% for k equals " +
str(optimal_k_for_knn) + "\n" )
tunedKOutputFile.write( "Standard deviation: " +
str(round( stdev_accuracy_as_percent, 2 )) + "%\n" )
# Close this output file
tunedKOutputFile.close()
##############################################################
# Perform Condensed KNN using optimal k parameter from tuning
##############################################################
# Write condensed nearest neighbors results to an output file
with open ("/Users/michelleamaral/Desktop/Intro_to_Machine_Learning/Programming_Project_2/Outputs/" +
output_file_name_final + "_output_Condensed_KNN_Classifier_Optimal_K", 'w') as optimalKCondensedOutputFile:
optimalKCondensedOutputFile.write( "\nData set: " + output_file_name_final + "\n" )
optimalKCondensedOutputFile.write( "\nType of problem: Classification\n" )
optimalKCondensedOutputFile.write( "\n********************************\n" )
optimalKCondensedOutputFile.write( "\nCondensed KNN with optimal k = " +
str( condensed_optimal_k ) + "\n" )
optimalKCondensedOutputFile.write( "\n********************************\n" )
# Create empty list to store the reduction in size between original
# data set and condensed data set
list_of_reduction_in_data_size_optimal_k = []
# Create empty list to store accuracy measure for each of the 5 folds
condensed_list_of_performances_optimal_k = []
for index_lists in range( 0, len(optimal_k_test_folds_row_numbers) ):
optimalKCondensedOutputFile.write( " When fold " + str(index_lists) +
" is the test set:\n" )
# Obtain row numbers for test fold
temp_df_row_list = optimal_k_test_folds_row_numbers[index_lists]
# Obtain test data frame using row numbers for test fold
temp_test_data_frame = temp_df.iloc[temp_df_row_list,]
temp_test_data_frame = temp_test_data_frame.reset_index( drop=True )
# Obtain train data frame by dropping row numbers for test fold
temp_train_data_frame = temp_df.drop( temp_df.index[temp_df_row_list] )
temp_train_data_frame = temp_train_data_frame.reset_index( drop=True )
condensed_train_data_frame, instance_reduction =
condensed_nearest_neighbor( temp_train_data_frame )
list_of_reduction_in_data_size_optimal_k.append( instance_reduction )
percent_reduction_in_data_set_size = instance_reduction * 100
this_fold_performance = knn_algorithm_for_tuning( temp_test_data_frame,
condensed_train_data_frame, condensed_optimal_k )
condensed_list_of_performances_optimal_k.append( this_fold_performance )
this_fold_percent_accuracy = this_fold_performance * 100
optimalKCondensedOutputFile.write( "\tClassification accuracy: " +
str(round( this_fold_percent_accuracy, 2 )) + "%\n" )
optimalKCondensedOutputFile.write( "\tPercent reduction in number of instances: " +
str(round( percent_reduction_in_data_set_size, 2 )) + "%\n" )
# Calculate the average reduction in the size of the data set
average_of_5_instance_reductions = np.mean(list_of_reduction_in_data_size_optimal_k)
percent_reduction_of_instances = average_of_5_instance_reductions * 100
# Calculate the standard deviation for the reduction in the data set size
stdev_reduction_of_instances = np.std( list_of_reduction_in_data_size_optimal_k )
stdev_reduction_as_percent = stdev_reduction_of_instances * 100
optimalKCondensedOutputFile.write( "\nAverage reduction in number of instances: " +
str(round( percent_reduction_of_instances, 2 )) + "%\n" )
optimalKCondensedOutputFile.write( "Standard deviation: " +
str(round( stdev_reduction_as_percent, 2 )) + "%\n" )
# Calculate the average accuracy of the classifier
average_of_5_performances = np.mean( condensed_list_of_performances_optimal_k )
percent_accuracy = average_of_5_performances * 100
# Calculate the standard deviation of the accuracy measures
stdev_accuracy = np.std( condensed_list_of_performances )
stdev_accuracy_as_percent = stdev_accuracy * 100
optimalKCondensedOutputFile.write( "\nAverage classification accuracy: " +
str(round( percent_accuracy, 2 )) + "%\n" )
optimalKCondensedOutputFile.write( "Standard deviation: " +
str(round( stdev_accuracy_as_percent, 2 )) + "%\n" )
# Close this output file
optimalKCondensedOutputFile.close()
###########################################################
# Perform Edited KNN using optimal k parameter from tuning
###########################################################
# Write edited nearest neighbors results to an output file
with open ("/Users/michelleamaral/Desktop/Intro_to_Machine_Learning/Programming_Project_2/Outputs/" +
output_file_name_final + "_output_Edited_KNN_Classifier_Optimal_K", 'w') as optimalKEditedOutputFile:
optimalKEditedOutputFile.write( "\nData set: " + output_file_name_final + "\n" )
optimalKEditedOutputFile.write( "\nType of problem: Classification\n" )
optimalKEditedOutputFile.write( "\n************************\n" )
optimalKEditedOutputFile.write( "\nEdited KNN with optimal k = " +
str( edited_optimal_k ) + "\n" )
optimalKEditedOutputFile.write( "\n************************\n" )
# Create empty list to store the reduction in size between original
# data set and edited data set
list_of_reduction_in_data_size = []
# Create empty list to store accuracy measure for each of the 5 folds
edited_list_of_performances = []
for index_lists in range( 0, len(test_folds_row_numbers) ):
optimalKEditedOutputFile.write( " When fold " + str(index_lists) +
" is the test set:\n" )
# Obtain row numbers for test fold
temp_df_row_list = test_folds_row_numbers[index_lists]
# Obtain test data frame using row numbers for test fold
temp_test_data_frame = temp_df.iloc[temp_df_row_list,]
temp_test_data_frame = temp_test_data_frame.reset_index( drop=True )
# Obtain train data frame by dropping row numbers for test fold
temp_train_data_frame = temp_df.drop( temp_df.index[temp_df_row_list] )
temp_train_data_frame = temp_train_data_frame.reset_index( drop=True )
# Call the edited nearest neighbor method in an attempt to reduce the data set size
edited_train_data_frame, instance_reduction =
edited_nearest_neighbor( temp_train_data_frame )
list_of_reduction_in_data_size.append( instance_reduction )
percent_reduction_in_data_set_size = instance_reduction * 100
# Call the knn method; will return the accuracy of the classifier
this_fold_performance = knn_algorithm_for_tuning( temp_test_data_frame,
edited_train_data_frame, edited_optimal_k )
edited_list_of_performances.append( this_fold_performance )
this_fold_percent_accuracy = this_fold_performance * 100
optimalKEditedOutputFile.write( "\tClassification accuracy: " +
str(round( this_fold_percent_accuracy, 2 )) + "%\n" )
optimalKEditedOutputFile.write( "\tPercent reduction in number of instances: " +
str(round( percent_reduction_in_data_set_size, 2 )) + "%\n" )
# Calculate the average reduction in the size of the data set
average_of_5_instance_reductions = np.mean( list_of_reduction_in_data_size )
percent_reduction_of_instances = average_of_5_instance_reductions * 100
# Calculate the standard deviation of the reduction in data set size
stdev_reduction_of_instances = np.std( list_of_reduction_in_data_size )
stdev_reduction_as_percent = stdev_reduction_of_instances * 100
optimalKEditedOutputFile.write( "\nAverage reduction in number of instances: " +
str(round( percent_reduction_of_instances, 2 )) + "%\n" )
optimalKEditedOutputFile.write( "Standard deviation: " +
str(round( stdev_reduction_as_percent, 2 )) + "%\n" )
# Calculate the average accuracy of the classifier
average_of_5_performances = np.mean( edited_list_of_performances )
edited_performance_for_this_k.append( average_of_5_performances )
percent_accuracy = average_of_5_performances * 100
# Calculate the standard deviation of the accuracy measures
stdev_accuracy = np.std( edited_list_of_performances )
stdev_accuracy_as_percent = stdev_accuracy * 100
optimalKEditedOutputFile.write( "\nAverage classification accuracy: " +
str(round( percent_accuracy, 2 )) + "%\n" )
optimalKEditedOutputFile.write( "Standard deviation: " +
str(round( stdev_accuracy_as_percent, 2 )) + "%\n" )
# Close this output file
optimalKEditedOutputFile.close()
|
571ceab172ce97ac5e0ec54ec22fdebe886cf18a | teacherzhu/Physics-Olimpiad-Problems-Database | /arabic2rom.py | 2,672 | 3.609375 | 4 | #!/usr/bin/env python2
# Por Luis Mex
# funciones sencillas para numeros arabicos a romanos y viceversa
import sys
def arab2rom(val):
rabc=['I','II','III','IV','V','VI','VII','VIII','IX',
'X','XX','XXX','XL','L','XC','C','CC','CCC'
,'CD','D','CM','M','MM','MMM','MV_','V_']
abc=[1,2,3,4,5,6,7,8,9,10,20,30,40,50,90,100,200,300,400,
500,900,1000,2000,3000,4000,5000]
string=''
i=0
val_act=val
if val_act > 5000 :
print " el valor supera la gramtica"
exit()
while True:
if (val_act == 0):
break
else:
for j in range(0,len(abc)):
if (val_act < abc[j]):
val_tmp=-abc[j-1]+val_act
val_act=val_tmp
i=j
string+=rabc[j-1]
break
elif (val_act >= abc[len(abc)-1]):
#print "True"
val_tmp=-abc[j-1]+val_act
val_act=val_tmp
i=j
string+=rabc[j-1]
break
return string
def rom2arab(string):
rabc=['I','II','III','IV','V','VI','VII','VIII','IX',
'X','XX','XXX','XL','L','XC','C','CC','CCC'
,'CD','D','CM','M','MM','MMM','MV_','V_']
abc=[1,2,3,4,5,6,7,8,9,10,20,30,40,50,90,100,200,300,400,
500,900,1000,2000,3000,4000,5000]
num=[]
for i in range(0,len(string)):
for j in range(0,len(abc)):
if string[i]==rabc[j]:
num.append(abc[j])
for j in range(0,len(num)-1):
for i in range(j,j+1):
if num[i] < num[i+1]:
num[i]=-num[i]
return sum(num)
for val in sys.argv[1:]:
if val.isalpha ():
print rom2arab (val.upper())
elif val.isdigit ():
print arab2rom (int(val))
else:
print val + " doesn't look like a roman nor arabic numeral!"
#val=45
#val_r='XLV'
#f=arab2rom(val)
#g=rom2arab(val_r)
#print f,g
|
b85eb8cdfb85573ef679ccde0177019e7740315f | Aninhacgs/Programando_com_Python | /Condicionais-Python/CondicionalExercicio07.py | 878 | 3.96875 | 4 | #Criar um algoritmo em PYTHON que leia o valor da compra e imprima o valor da venda.
#Entrada de dados
compra = float(input("Digite o valor da compra: "))
while(compra == 0 or compra < 0):
print("Digite um valor válido para compra: ")
compra = float(input("Digite o valor da compra: "))
#processamento e impressão
if(compra < 10):
venda = compra + compra *(70 / 100)
conversao = round(venda,2)
print("Valor da venda R$:",conversao)
elif(compra < 30):
venda = compra + compra * (50 / 100)
conversao = round(venda,2)
print("Valor da venda R$:",conversao)
elif(compra < 50):
venda = compra + compra * (40 / 100)
conversao = round(venda,2)
print("Valor da compra R$:",conversao)
else:
venda = compra + compra * (30 / 100)
conversao = round(venda,2)
print("Valor da compra R$:",conversao)
|
df8466854b643478c0cebd984ad86d09de01cc9b | yrto/python-coding-tank | /aula-14-fixacao/aula-14-fix-04.py | 381 | 3.9375 | 4 | # Faça um script que recebe um texto da entrada
# e exibe a maior palavra contida nesse texto.
texto = input("Digite algo: ")
texto_lista = texto.split(" ")
maior_palavra = ''
contador = 0
for i in texto_lista:
qtd_caracteres = len(i)
if qtd_caracteres > contador:
contador = qtd_caracteres
maior_palavra = i
print(maior_palavra, "é a maior palavra")
|
27a520d8939037a2438566bf5f4e2e3d40959dce | KSDN-05/pythonassignment | /f4.py | 243 | 4.3125 | 4 | def reversed(name,length):
reverse=""
while(length>0):
reverse+=name[length-1]
length-=1
return(reverse)
a=input("enter string to be reversed:")
lengt=len(a)
reversed_string=reversed(a,lengt)
print(reversed_string) |
01cdbc166a6360ad6ab758275426f045c600b4aa | gary-gggggg/gary | /1-mouth01/day15/exe02.py | 520 | 4.03125 | 4 | """练习 1:创建列表,使用迭代思想,打印每个元素. 练习
2:创建字典,使用迭代思想,打印每个键值对"""
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
iterator = list1.__iter__()
while 1:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
dic = {"giao": "giao1", "fiao": "fiao1", "xiao": "xiao1"}
iterator1 = dic.__iter__()
while 1:
try:
key1 = iterator1.__next__()
print(key1,dic[key1])
except StopIteration:
break
|
b447c18c80e2c6a3456a480a29d131bb9c341fdb | Minu94/PythonWorkBook1 | /luminar_for_python/language_fundamentals/collections/word_count.py | 433 | 3.78125 | 4 | line="hello hai how are you"
words=line.split(" ") #split by space to get word seperatele
dict={}
for word in words:
if(word not in dict):
dict{word}=1 #word:1 # supposed to make the form {"hello":1,"hai":2
else:
dict[word]+=1
#create list [1,2,3,4,5,6]
find square of each element then from result even even listodd odd list
[10,20,30,40,50]=50 count of 50
[2,4,8]=ouput to be [12,10,6]
[3,2,5]=ouput [7,8,5] |
d42a8783db2610030a9efdbd17d119bee245b4c4 | sea-lab-wm/burt | /crashscope/lib/python-scripts/ApkParsing/check_aapt.py | 1,582 | 3.703125 | 4 | """
Last Edited by Richard Bonett: 3/25/2017
This program counts the apks from a json file of ApkInfos,
outputting a table of each discovered API level and the
number of apks having that API level.
Usage:
python3 check_aapt.py INPUT_JSON_FILE
"""
import json
import sys
from prettytable import PrettyTable
apks = []
for i in range(1, len(sys.argv)) :
apks += json.load(open(sys.argv[i]))
print("From %d apks..." % (len(apks)))
targets = {-1: 0}
versions = {-1: 0}
for apk in apks :
if 'targetSdkVersion' in apk :
if int(apk['targetSdkVersion']) in targets :
targets[int(apk['targetSdkVersion'])] += 1
else :
targets[int(apk['targetSdkVersion'])] = 1
if 'sdkVersion' in apk :
sdk = apk['sdkVersion']
if int(sdk) in versions :
versions[int(sdk)] += 1
else :
versions[int(sdk)] = 1
table = PrettyTable()
table.field_names = ["API Level", "sdkVersion", "targetSdkVersion"]
table.align = "r"
for v in sorted(list(set(list(versions.keys()) + list(targets.keys())))) :
if v in versions and v in targets :
table.add_row([v, versions[v], targets[v]])
elif v in versions :
table.add_row([v, versions[v], 0])
else :
table.add_row([v, 0, targets[v]])
print("Counts of sdkVersion and targetSdkVersion for each API level")
print(table)
"""
print("Sdk Versions:")
for v in sorted(versions.keys()) :
print(str(v) + " -- " + str(versions[v]))
print("Target Sdk Versions:")
for v in sorted(targets.keys()) :
print(str(v) + " -- " + str(targets[v]))
"""
|
7eb277b5d534bcb8013c3a488af29bc1878908e7 | siddiqsy/Handwritten-Digits-CelebFaces-Attributes-Classification | /nnScript.py | 13,908 | 3.734375 | 4 | import numpy as np
from scipy.optimize import minimize
from scipy.io import loadmat
from math import sqrt
import pandas as pd
import time
import matplotlib.pyplot as plt
def initializeWeights(n_in, n_out):
"""
# initializeWeights return the random weights for Neural Network given the
# number of node in the input layer and output layer
# Input:
# n_in: number of nodes of the input layer
# n_out: number of nodes of the output layer
# Output:
# W: matrix of random initial weights with size (n_out x (n_in + 1))"""
epsilon = sqrt(6) / sqrt(n_in + n_out + 1)
W = (np.random.rand(n_out, n_in + 1) * 2 * epsilon) - epsilon
return W
def sigmoid(z):
"""# Notice that z can be a scalar, a vector or a matrix
# return the sigmoid of input z"""
return 1.0/(1.0 + np.exp(-1.0*z))# your code here
def preprocess():
""" Input:
Although this function doesn't have any input, you are required to load
the MNIST data set from file 'mnist_all.mat'.
Output:
train_data: matrix of training set. Each row of train_data contains
feature vector of a image
train_label: vector of label corresponding to each image in the training
set
validation_data: matrix of training set. Each row of validation_data
contains feature vector of a image
validation_label: vector of label corresponding to each image in the
training set
test_data: matrix of training set. Each row of test_data contains
feature vector of a image
test_label: vector of label corresponding to each image in the testing
set
Some suggestions for preprocessing step:
- feature selection"""
mat = loadmat('mnist_all.mat') # loads the MAT object as a Dictionary
train = []
test = []
train_data = np.zeros((50000,np.shape(mat["train0"])[1]))
validation_data = np.zeros((10000,np.shape(mat["train0"])[1]))
test_data = np.zeros((10000,np.shape(mat["test0"])[1]))
train_label = np.zeros((50000,))
validation_label = np.zeros((10000,))
test_label = np.zeros((10000,))
train_len=0
validation_len=0
test_len=0
train_len_l=0
validation_len_l=0
for key in mat:
if("train" in key):
train = mat[key]#np.zeros(np.shape(mat.get(key)))
shuffle = np.random.permutation(range(train.shape[0]))
train_data[train_len:train_len+len(train)-1000] = train[shuffle[0:len(train)-1000],:]
train_label[train_len_l:train_len_l+len(train)] = int(key[-1])
validation_data[validation_len:validation_len+1000]=train[shuffle[len(train)-1000:len(train)],:]
validation_len=validation_len+1000
validation_label[validation_len_l:validation_len_l+1000] = int(key[-1])
validation_len_l=validation_len_l+1000
train_len=train_len+len(train)-1000
train_len_l=train_len_l+len(train)-1000
elif("test" in key):
test = mat[key]#np.zeros(np.shape(mat.get(key)))
test_data[test_len:test_len+len(test)] = test[np.random.permutation(range(test.shape[0])),:]
test_label[test_len:test_len+len(test)] = key[-1]
test_len=test_len+len(test)
train_shuffle = np.random.permutation(range(train_data.shape[0]))
train_data = train_data[train_shuffle]
validate_shuffle = np.random.permutation(range(validation_data.shape[0]))
validation_data = validation_data[validate_shuffle]
test_shuffle = np.random.permutation(range(test_data.shape[0]))
test_data = test_data[test_shuffle]
train_data=(train_data)/255
test_data=(test_data)/255
validation_data=np.double(validation_data)/255
train_label=train_label[train_shuffle]
validation_label=validation_label[validate_shuffle]
test_label = test_label[test_shuffle]
# Split the training sets into two sets of 50000 randomly sampled training examples and 10000 validation examples.
# Your code here.
# Feature selection
# Your code here.
data = np.array(np.vstack((train_data,validation_data,test_data)))
features_count = np.shape(data)[1]
#col_index = np.arange(features_count)
count = np.all(data == data[0,:],axis=0)
data = data[:,~count]
train_data=data[0:len(train_data),:]
validation_data=data[len(train_data):len(train_data)+len(validation_data),:]
test_data=data[len(train_data)+len(validation_data):len(train_data)+len(validation_data)+len(test_data),:]
print('preprocess done')
return train_data, train_label, validation_data, validation_label, test_data, test_label
tracker = 0
def nnObjFunction(params, *args):
"""% nnObjFunction computes the value of objective function (negative log
% likelihood error function with regularization) given the parameters
% of Neural Networks, thetraining data, their corresponding training
% labels and lambda - regularization hyper-parameter.
% Input:
% params: vector of weights of 2 matrices w1 (weights of connections from
% input layer to hidden layer) and w2 (weights of connections from
% hidden layer to output layer) where all of the weights are contained
% in a single vector.
% n_input: number of node in input layer (not include the bias node)
% n_hidden: number of node in hidden layer (not include the bias node)
% n_class: number of node in output layer (number of classes in
% classification problem
% training_data: matrix of training data. Each row of this matrix
% represents the feature vector of a particular image
% training_label: the vector of truth label of training images. Each entry
% in the vector represents the truth label of its corresponding image.
% lambda: regularization hyper-parameter. This value is used for fixing the
% overfitting problem.
% Output:
% obj_val: a scalar value representing value of error function
% obj_grad: a SINGLE vector of gradient value of error function
% NOTE: how to compute obj_grad
% Use backpropagation algorithm to compute the gradient of error function
% for each weights in weight matrices.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% reshape 'params' vector into 2 matrices of weight w1 and w2
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit j in input
% layer to unit i in hidden layer.
% w2: matrix of weights of connections from hidden layer to output layers.
% w2(i, j) represents the weight of connection from unit j in hidden
% layer to unit i in output layer."""
n_input, n_hidden, n_class, training_data, training_label, lambdaval = args
training_data = np.concatenate((np.ones((np.shape(training_data)[0],1)),training_data),1)
w1 = params[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))
w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))
obj_val = 0
aj = np.dot(w1,np.transpose(training_data))
zj=sigmoid(aj)
zj = np.concatenate((np.ones((np.shape(np.transpose(zj))[0],1)),np.transpose(zj)),1)
bj = np.dot(w2,np.transpose(zj))
ol=sigmoid(bj)
outputclass = np.zeros((n_class,training_label.shape[0])) #initialize all output class to 0
i=0
for i in range(len(training_label)):
label=0
label= int(training_label[i])
outputclass[label,i] = 1
error = -(np.sum((outputclass*np.log(ol)) + ((1-outputclass)*np.log(1-ol))))
delta = ol - outputclass
delta_new = (delta*(ol*(1-ol)))
gradient_w2 = np.dot(delta_new,zj)
product = ((1 - zj) * zj)*(np.dot(delta_new.T,w2))
gradient_w1 = np.dot(np.transpose(product),training_data)
error = error/np.shape(training_data)[0]
sqr_weights = np.sum(w1**2) + np.sum(w2**2)
grad = lambdaval * sqr_weights/(2*np.shape(training_data)[0])
obj_val = error + grad
gradient_w1 = (gradient_w1[1:n_hidden+1,] + (lambdaval*w1))/np.shape(training_data)[0]
gradient_w2 = (gradient_w2 + lambdaval*w2)/np.shape(training_data)[0]
obj_grad = np.concatenate((gradient_w1.flatten(),gradient_w2.flatten()),0)
# Make sure you reshape the gradient matrices to a 1D array. for instance if your gradient matrices are grad_w1 and grad_w2
# you would use code similar to the one below to create a flat array
# obj_grad = np.concatenate((grad_w1.flatten(), grad_w2.flatten()),0)
#obj_grad = np.array([])
return (obj_val, obj_grad)
def nnPredict(w1, w2, data):
"""% nnPredict predicts the label of data given the parameter w1, w2 of Neural
% Network.
% Input:
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit i in input
% layer to unit j in hidden layer.
% w2: matrix of weights of connections from hidden layer to output layers.
% w2(i, j) represents the weight of connection from unit i in input
% layer to unit j in hidden layer.
% data: matrix of data. Each row of this matrix represents the feature
% vector of a particular image
% Output:
% label: a column vector of predicted labels"""
labels = np.array([])
# Your code here
# dataWithBias = np.concatenate(( np.ones((data.shape[0], 1)),data),1)
# hiddenLayerSigma = np.dot(dataWithBias, np.transpose(w1))
# hiddenLayerOp = sigmoid(hiddenLayerSigma)
# hiddenLayerOp = np.concatenate(( np.ones((hiddenLayerOp.shape[0],1)),hiddenLayerOp),1)
# opLayerSigma = np.dot(hiddenLayerOp, np.transpose(w2))
# finalOp = sigmoid(opLayerSigma)
# global tracker
# tracker = finalOp
# labels = np.argmax(finalOp,axis=1)
data = np.concatenate((np.ones((np.shape(data)[0],1)),data),1)
aj = np.dot(w1,np.transpose(data))
zj=sigmoid(aj)
zj = np.concatenate((np.ones((np.shape(np.transpose(zj))[0],1)),np.transpose(zj)),1)
bj = np.dot(w2,np.transpose(zj))
ol=sigmoid(bj)
labels = np.argmax(ol.T,axis=1)
return labels
"""**************Neural Network Script Starts here********************************"""
colNames = ['Lambda','No_Hidden_Nodes','Train_Accuracy','Validation_Accuracy','Test_Accuracy','Time']
obs = pd.DataFrame(columns = colNames)
train_data, train_label, validation_data, validation_label, test_data, test_label = preprocess()
noOfHiddenNodes = np.arange(0,100,5)
#lambas = np.arange(0,60,10)
#noOfHiddenNodes = [50]
lambas = [0]
count = 0
# Train Neural Network
for l in lambas:
for hns in noOfHiddenNodes:
# set the number of nodes in input unit (not including bias unit)
startTime = time.time()
n_input = train_data.shape[1]
# set the number of nodes in hidden unit (not including bias unit)
n_hidden = hns
# set the number of nodes in output unit
n_class = 10
# initialize the weights into some random matrices
initial_w1 = initializeWeights(n_input, n_hidden)
initial_w2 = initializeWeights(n_hidden, n_class)
# unroll 2 weight matrices into single column vector
initialWeights = np.concatenate((initial_w1.flatten(), initial_w2.flatten()), 0)
# set the regularization hyper-parameter
lambdaval = l
args = (n_input, n_hidden, n_class, train_data, train_label, lambdaval)
# Train Neural Network using fmin_cg or minimize from scipy,optimize module. Check documentation for a working example
opts = {'maxiter': 50} # Preferred value.
nn_params = minimize(nnObjFunction, initialWeights, jac=True, args=args, method='CG', options=opts)
# In Case you want to use fmin_cg, you may have to split the nnObjectFunction to two functions nnObjFunctionVal
# and nnObjGradient. Check documentation for this function before you proceed.
# nn_params, cost = fmin_cg(nnObjFunctionVal, initialWeights, nnObjGradient,args = args, maxiter = 50)
# Reshape nnParams from 1D vector into w1 and w2 matrices
w1 = nn_params.x[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))
w2 = nn_params.x[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))
# Test the computed parameters
predicted_label_train = nnPredict(w1, w2, train_data)
# find the accuracy on Training Dataset
print('\n For Number of Nodes and Lambda ' +str(hns) +'and '+str(l))
print('\n Training set Accuracy:' + str(100 * np.mean((predicted_label_train == train_label).astype(float))) + '%')
train_acc = str(100 * np.mean((predicted_label_train == train_label).astype(float)))
predicted_label_validate = nnPredict(w1, w2, validation_data)
# find the accuracy on Validation Dataset
print('\n Validation set Accuracy:' + str(100 * np.mean((predicted_label_validate == validation_label).astype(float))) + '%')
val_acc = str(100 * np.mean((predicted_label_validate == validation_label).astype(float)))
predicted_label_test = nnPredict(w1, w2, test_data)
# find the accuracy on Validation Dataset
print('\n Testing set Accuracy:' + str(100 * np.mean((predicted_label_test == test_label).astype(float))) + '%')
#collections.Counter(predicted_label)
test_acc = str(100 * np.mean((predicted_label_test == test_label).astype(float)))
endTime = time.time()
runtime = endTime-startTime
obs.loc[count] = [l,hns,train_acc,val_acc,test_acc,runtime]
count += 1 |
ca3368a6105513bf6a8e6f8a9525a64857a0bfd0 | PauloVilarinho/algoritmos | /problemas uri/Problema1159.py | 160 | 3.703125 | 4 | x = 1
while x!= 0 :
total = 0
x = int(input())
y = x
if x%2 == 1:
x += 1
if y!= 0 :
for i in range(5):
total += x
x += 2
print ("%d" %total)
|
35561ff018c91efd6e5bb8489486cace89941086 | jiadaizhao/LeetCode | /1001-1100/1047-Remove All Adjacent Duplicates In String/1047-Remove All Adjacent Duplicates In String.py | 233 | 3.5625 | 4 | class Solution:
def removeDuplicates(self, S: str) -> str:
St = []
for c in S:
if St and c == St[-1]:
St.pop()
else:
St.append(c)
return ''.join(St)
|
1ec58889352e8919c1614492b40921b29b0f4ff8 | vvalcristina/exercicios-python | /curso_em_video/09_guanabara.py | 568 | 4.21875 | 4 | #Tabuada v.01
num = int(input("Digite um numero para ver sua tabuada: "))
print("-"*15)
print("TABUADA DE {}".format(num))
print("-"*15)
print("{} * {} = {}".format(num,1,num*1))
print("{} * {} = {}".format(num,2,num*2))
print("{} * {} = {}".format(num,3,num*3))
print("{} * {} = {}".format(num,4,num*4))
print("{} * {} = {}".format(num,5,num*5))
print("{} * {} = {}".format(num,6,num*6))
print("{} * {} = {}".format(num,7,num*7))
print("{} * {} = {}".format(num,8,num*8))
print("{} * {} = {}".format(num,9,num*9))
print("{} * {} = {}".format(num,10,num*10))
|
aa848492ce5486bb8dc72104a6434c05fbd829fc | Alexanderklau/Start_again-python- | /Loop_and_condition/_list_comprehensions.py | 344 | 3.75 | 4 | # -*-coding:utf-8 -*-
__author__ = 'Yemilice_lau'
print map(lambda x:x ** 2 ,range(6))
def odd(n):
return n % 2
print odd(125)
seq = [1,2,3,4,5,6,7,8,9]
# filter判断是否是奇数
print filter(lambda x :x % 2,seq)
print [x for x in seq if x % 2]
print [(x+1,y+1) for x in range(10) for y in range(10)]
# if __name__ == '__main__': |
947c6159e35a3a2de0a7179f3e3e205e50b9a403 | darthsuogles/phissenschaft | /algo/leetcode_64.py | 622 | 3.65625 | 4 | ''' Min path sum in a matrix
'''
def minPathSum(grid):
if not grid: return -1
m = len(grid)
n = len(grid[0])
if 0 == n: return -1
path_sum = []
for i in range(m):
path_sum.append([None] * n)
path_sum[0][0] = grid[0][0]
for j in range(1, n):
path_sum[0][j] = path_sum[0][j-1] + grid[0][j]
for i in range(1, m):
path_sum[i][0] = path_sum[i-1][0] + grid[i][0]
for i in range(1, m):
for j in range(1, n):
prev = min(path_sum[i-1][j], path_sum[i][j-1])
path_sum[i][j] = prev + grid[i][j]
return path_sum[m-1][n-1]
|
f8295dc2bb7764c798edc06212eca7587a1ad841 | devipriyak/IICSEA_Chapter2 | /SubsetandSuperSet_symmetricsDifference.py | 548 | 3.875 | 4 |
set1={1,2,3,4,5,6,7,24,25,26}
set2={1,2,3,4,5,6,7,8,9,10,11,12,13,14}
'''#Subset or not verification
print "Is the set1 is sub set of Set2:%s" %set1.issubset(set2)
print "set1<set2 %s" %(set1<set2)
#SuperSet Verification
print "Is the set1 is super set of Set2:" ,set1.issuperset(set2)
print "set1>set2 %s" %(set1>set2)
#Symmetric Differenece
'''
res=set1.symmetric_difference(set2)
print("Symmetric Difference two sets are %s" %res)
print("Set1^Set2 %s" %(set1^set2))
'''
set([8, 9, 10, 11, 12, 13, 14, 24, 25, 26])
'''
|
04c90bb532a41bb17a47c5ba903d38f4992d150e | artisodua/Hillel | /2_5.py | 1,531 | 3.890625 | 4 | # 5) Есть строка со словами и числами, разделенными пробелами (один пробел между словами и/или числами).
# Слова состоят только из букв. Вам нужно проверить есть ли в исходной строке три слова подряд.
# Для примера, в строке "hello 1 one two three 15 world" есть три слова подряд.
pline = 'hello 1 one two three 15 world'
def finde_three_word(line):
flist = line.split()
fx = 0
flist2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20']
flist3 = []
for i in range(len(flist)):
if fx < 3:
for j in flist:
if j not in flist2:
flist3.append(j)
fx += 1
else:
fx -= 1
flist3.pop()
return flist3
print(finde_three_word(pline))
# Строка 10 Не смог добиться что бы задать диапазон чисел от 0 до ~ например в массиве с 'кавычками'! Что бы руками не вводить
# Если есть возможность подскажи как это реализовать!
# Или может есть какой то другой способ проверить в данном массиве являются ли данные цифрами или буквами |
d0732314423fe814587702e80a6802c7eaf3860f | WarMasterGenral/OPS435-Rep | /Practices/Collatz.py | 177 | 4.21875 | 4 | def collatz(number):
if number %2 ==0:
return number // 2
elif number %2 == 1:
return 3 * number + 1
user_input = int(input('Enter number: '))
|
652784e8ff6b5140b16fb59e441d568f829f4b6c | arturchesnokov/hillel_pyton_intro | /luhn.py | 1,123 | 3.796875 | 4 | def luhn_check(card_number: str) -> bool:
"""
Validate card number
:param card_number: credit card number
:returns: True if number is valid
"""
card_number = card_number.replace(' ', '') # удаляем пробелы
if card_number.isdigit(): # если в строке остались только цифры
numbers = list(int(n) for n in card_number) # получаем список из цифр
for i in range(0, len(numbers), 2): # удваиваем значения чисел с четных индексов
numbers[i] = numbers[i] * 2 if numbers[i] * 2 < 10 else numbers[i] * 2 - 9
return sum(numbers) % 10 == 0
else:
return False
if __name__ == '__main__':
assert luhn_check('4532 3455 1540 6633') is True
assert luhn_check('3528 5070 9380 0507') is True
assert luhn_check('5106330611011704') is True
assert luhn_check('36813670686745') is False
assert luhn_check('4532 3455 154O 6633') is False
assert luhn_check('1122 3344 5566 7788') is False
assert luhn_check('11_2 3344 5566 7788') is False
|
0564dd5f5acca737aaf09afbc9358a2e2f8a9605 | Harshin1/Python-and-DL | /Labs/Lab 1/hospital admission system/patient.py | 1,153 | 3.96875 | 4 | class Patient(object):
def __init__(self, name, age, disease):
self.set_Patient_Details(name,age,disease)
# set Patient Details
def set_Patient_Details(self,name,age,disease):
self.name = name
self.age = age
self.disease = disease
print('The patient details are: ')
print(self.get_Patient_Details())
# Get Patient Name
def get_Patient_Name(self):
return self.name
# Get Patient Age
def get_Patient_Age(self):
return self.age
# Get Patient Disease
def get_Patient_Disease(self):
return self.disease
# Get Patient Details
def get_Patient_Details(self):
return self.get_Patient_Name() + " " + str(self.get_Patient_Age()) + " " + self.get_Patient_Disease()
class VisitingPatient(Patient):
#assigning patient type
def __init__(self):
Patient.__init__(self)
self.patientType = 'Visiting'
class InHousePatient(Patient):
# assigning patient type
def __init__(self):
Patient.__init__(self)
self.patientType = 'InHouse'
if __name__ == "__main__":
x = Patient("ABC",22,"fever") |
d5c4d2b5edbcc2a6a5c9fccd7991be29caa1a496 | shellcreasy/python_study | /loop.py | 1,518 | 4.09375 | 4 | #遍历列表
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician.title() + ",that was a great trick!")
print("i can't wait to see your next trick," + magician.title() + "\n")
print("Thank you,everyone,that was a wonderful magic show")
#range函数生成数字
for value in range(1,5):
print(value)
#使用range()创建数字列表
numbers = list(range(1,6))
print(numbers)
#range函数指定步长
numbers1 = list(range(2,11,2))
print(numbers1)
#range函数生成1-10的平方数字列表
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
#数字列表统计函数
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
#列表解析
squares1 = [value**2 for value in range(1,11)]
print(squares1)
#列表切片
players = ['charles','martina','michael','florence','eli']
print(players[0:3])
#没有开始索引
print(players[:4])
#没有结束索引
print(players[2:])
#遍历切片
for player in players[:3]:
print(player.title())
#复制列表
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods)
print(friend_foods)
#元组:不可变的列表
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
#遍历元组
for dimension in dimensions:
print(dimension)
#修改元组
dimensions = (250,50)
for dimension in dimensions:
print(dimension)
|
51a6a482914d388151f33f764f8e0812d1338f3d | Jonathan-aguilar/DAS_Sistemas | /Ene-Jun-2020/sanchez-niño-angela-gabriela/Practicas1.0/practica1.py | 329 | 3.671875 | 4 | resultado=1
i=0
n=int(input('Ingrese un numero base:'))
m=int(input('Ingrese numero de potencia:'))
if m!=0:
print("1")
while True:
resultado=n*resultado
print(resultado)
i=i+1
if i>= abs(m):
if m<0:
resultado=1/resultado
print(resultado)
break
|
99215cc96054e2bf665b6cde703c4d82e9a54d5d | jonataseo/PythonStudys | /chapter12/ch2.py | 239 | 3.90625 | 4 | import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * (self.radius * self.radius)
if __name__ == "__main__":
circle = Circle(3)
print(circle.area()) |
930f6bc6704cbbbcfaf811d4f931d111637fd118 | mlratj/Python-Scripts | /Short_exercises/fibonacci_sequence.py | 337 | 4.03125 | 4 | t=int(input("Place a number of terms: "))
print()
n1=0
n2=1
counter=0
if t<=0:
print("Invalid value.")
elif t==1:
print("1")
else:
print("Fibonacci sequence up to ", t, ": ")
while counter<t:
print(n1, end=" ,")
x=n1+n2
n1=n2
n2=x
counter+=1
print("\n Have a nice day!")
input() |
f6cda72eec2c67d3f3d22ce7492cb450649ba58b | marcoportela/python | /exercicio04_marco_02.py | 564 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 18 14:24:51 2014
2. Sorteie 20 inteiros entre 1 e 100 numa lista. Armazene os números pares na lista PAR e os
números ímpares na lista IMPAR. Imprima as três listas.
@author: [email protected]
"""
import random
lista = []
listaPar = []
listaImpar = []
for i in range(20):
lista.append(random.randint(1,100))
if (lista[i] % 2) == 0:
listaPar.append(lista[i])
else:
listaImpar.append(lista[i])
print('Lista')
print(lista)
print('Lista par')
print(listaPar)
print('Lista impar')
print(listaImpar)
|
27cfbebbd04ad72a63cb7bd2c9538d76e402a79c | ziweifan177/Data-Science-Knowledge-Base | /DataScience/python/PythonThread.py | 3,488 | 4.125 | 4 | import threading
#1. threading foundation:
def test():
print('threading.active_count():',threading.active_count()) # Current threading number.
print('threading.enumerate():',threading.enumerate())#What the specific thread?
print('threading.current_thread():',threading.current_thread()) #Current threading.
print('1. threading foundation:')
test()
#Output: 1
#Output: [<_MainThread(MainThread, started 7488)>]
#Output: <_MainThread(MainThread, started 7808)>
#2. threading: Add new thread:
def thread_job():
print('This is added thread: num is %s' % threading.current_thread()) #OUTPUT:<Thread(Thread-1, started 1772)>
def AddNewThread():
added_thread=threading.Thread(target=thread_job)#Add new thread.
added_thread.start()#Start this new thread.
print('threading.active_count():', threading.active_count()) #OUTPUT: 2
print('threading.enumerate():', threading.enumerate()) #OUTPUT: [<_MainThread(MainThread, started 20092)>]
print('threading.current_thread():', threading.current_thread()) # OUTPUT:<_MainThread(MainThread, started 20092)>
print('\n2. threading-Add new thread:')
AddNewThread()
#3.Thread_join():
import time
def addThread1():
print('Thread 1 start! number is %s' % threading.current_thread())
for i in range(10):
time.sleep(0.1)
print('Thread 1 done.')
def addThread2():
print('Thread 2 start! Number is %s' % threading.current_thread())
print('Thread 2 done.')
def threadsWork():
thread_1=threading.Thread(target=addThread1, name='thread1')
thread_1.start()
thread_1.join() #Wait for Thread1 done! then go ahead.
thread_2=threading.Thread(target=addThread2(),name='thread2')
thread_2.start()
print('main done.')
print('\n3.Thread_join():')
threadsWork()
#4. Threading-queue: No return in thread, just queue!
from queue import Queue
def thread_job(list,queue):
for i in range(len(list)):
list[i]=list[i]**2
queue.put(list) #No return here! just queue.
def createMultiThread(data):
q=Queue() #Queue: Store the result of every queue.
threadList=[] #List: Store threads.
for i in range(4):
thread=threading.Thread(target=thread_job, args=(data[i],q))
thread.start()
threadList.append(thread)
for thread in threadList:
thread.join()
return q
def getResult(queue):
results=[]
for _ in range(4):
results.append(queue.get())
print(results)
print('\n4. Threading-queue:')
list=[[1,2,3],[3,4,5],[5,2,6],[7,4,2]]
q=createMultiThread(list)
getResult(q)
#5. Thread-Lock:线程不仅仅可以是一个短function,也可是是一个长的,
# 而在执行长功能的时候,可以对长功能中的一小部分实现lock,这样只有那一小部分不会互相影响。
#Compare with join(): lock 是锁住变量的更新, join 是不让主线程比某个 thread 先结束
def job1():
global A,lock
lock.acquire()
for i in range(10):
A+=10
print('Job1:',A)
lock.release()
def job2():
global A,lock
lock.acquire()
for i in range(10):
A+=10
print('Job2:',A)
lock.release()
print("\n5. Thread-Lock:")
lock=threading.Lock()
A=0
thread1=threading.Thread(target=job1)
thread2=threading.Thread(target=job2)
thread1.start()
thread1.join()
thread2.start()
thread2.join()
|
4dbb7e7f9ebaa73dfafc11dbfdc3b7624a0872e2 | kf2312/kelaskita | /kelas_kita/api/question3.py | 201 | 3.765625 | 4 | number = [0, 1]
i = 2
while i <= 8:
number.append(number[i-1] + number[i-2])
i += 1
print(str(number))
# numberStr = []
# for x in number:
# numberStr.append(str(x) + ', ')
# print(number) |
b3cf30aee08935244c9e20aa49bbbc83568d7a04 | Nora-Wang/Leetcode_python3 | /Trie/212. Word Search II.py | 3,529 | 3.921875 | 4 | Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input:
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Note:
All inputs are consist of lowercase letters a-z.
The values of words are distinct.
这里用Trie + DFS
还有DFS的方法,直接看DFS中的212
****************************************
result要设置为set避免重复
Input
[["a","a"]]
["a"]
Output
["a","a"]
Expected
["a"]
****************************************
code:
DIRECTIONS = [(1,0),(-1,0),(0,1),(0,-1)]
class TrieNode(object):
def __init__(self):
self.children = {}
self.word = None
self.is_word = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def add(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
node.word = word
def find(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node
class Solution(object):
def wordSearchII(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
if not len(board) or not len(board[0]):
return []
#设为set,避免重复
#eg: [['a'], ['a']], ['a']
result = set()
#初始化trie
trie = Trie()
for word in words:
trie.add(word)
#以board的每个char开头,判断是否能在trie中找到word
for i in range(len(board)):
for j in range(len(board[0])):
char = board[i][j]
self.search(board, i, j, trie.root.children.get(char), set([(i,j)]), result)
#结果为list
return list(result)
def search(self, board, x, y, node, visited, result):
#node.children中不存在char,则说明node的剩下路都不用走了
if not node:
return
#递归出口
if node.is_word:
result.add(node.word)
#dfs向4个方向扩散
for direct in DIRECTIONS:
new_x = x + direct[0]
new_y = y + direct[1]
#判断新的点是否在board的范围内,并且不在visited里
if self.is_valid(board, new_x, new_y, visited):
visited.add((new_x, new_y))
char = board[new_x][new_y]
self.search(board, new_x, new_y, node.children.get(char), visited, result)
#set的删除是remove
visited.remove((new_x, new_y))
def is_valid(self, board, x, y, visited):
if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]):
return False
if (x,y) in visited:
return False
return True
|
fb0f19ef2d30eb5c7694c574d253fca28e5bbbd7 | gdh756462786/Leetcode_by_python | /Bit Manipulation/Single Number II.py | 1,252 | 3.6875 | 4 | # coding: utf-8
'''
Given an array of integers,
every element appears three times except for one. Find that single one.
'''
'''
如果我们把 第 ith 个位置上所有数字的和对3取余,
那么只会有两个结果 0 或 1 (根据题意,3个0或3个1相加余数都为0).
因此取余的结果就是那个 “Single Number”。
'''
# public class Solution {
# public int singleNumber(int[] nums) {
# int cnt[] = new int[32];
# int single = 0;
# for (int i = 0; i < 32; i++) {
# for (int j = 0; j < nums.length; j++) {
# cnt[i] += (nums[j] >> i) & 0x1;
# }
# single |= cnt[i] % 3 << i;
# }
#
# return single;
# }
# }
'''
ones 代表第ith 位只出现一次的掩码变量
twos 代表第ith 位只出现两次次的掩码变量
threes 代表第ith 位只出现三次的掩码变量
'''
class Solution:
def singleNumber(self, A):
one = 0; two = 0; three = 0
for i in range(len(A)):
two |= A[i] & one
one = A[i] ^ one
three = ~(one & two)
one &= three
two &= three
return one
solution = Solution()
print solution.singleNumber([-2,-2,-3,-3,-3,-4,-2]) |
eea2bc4392abe06f2a0da15b1f22440784df0461 | yeshwanthmoota/Physics_Pong_Singleplayer | /Ball_class_file.py | 2,292 | 3.859375 | 4 | import pygame
import random
import math
from universal_constants_file import *
from ball_collision import *
class Ball:
def __init__(self, x, y):
self.x = x
self.y = y
self.current_ball_speed = BALL_SPEED
self.current_theta = 0
def ball_movement(self):
# points scored
# for restricting position left and right
if self.x <= RESTRIANT - BALL_SIDE: # off left side of screen
return 1
elif self.x >= WIDTH - RESTRIANT + BALL_SIDE: #off right side of screen
return -1
# wall collisions
# for restricting position up and down
if(self.y < 0 + UP_DOWN_BORDER_HEIGHT): # UP_WALL
self.y = UP_DOWN_BORDER_HEIGHT
code = wall_ball_collision(self)
return code
elif(self.y + BALL_SIDE > HEIGHT -UP_DOWN_BORDER_HEIGHT): #DOWN_WALL
self.y = HEIGHT - UP_DOWN_BORDER_HEIGHT - BALL_SIDE
code = wall_ball_collision(self)
return code
self.x += self.current_ball_speed * round(math.cos(self.current_theta),1)
self.y += self.current_ball_speed * round(math.sin(self.current_theta),1)
return 0
def draw_ball(self, gameDisplay):
if (self.x <= RESTRIANT - BALL_SIDE) and (self.x >= WIDTH - RESTRIANT + BALL_SIDE): # off left side of screen
pass # Making Ball dissappear off the screen
else:
pygame.draw.rect(gameDisplay, WHITE, pygame.Rect(self.x, self.y, BALL_SIDE, BALL_SIDE))
# r = (BALL_SIDE) / 2
# g = math.sqrt(2)
# pygame.draw.circle(gameDisplay, WHITE, (int(self.x + r*g), int(self.y + r*g)), int(r)) # To print out a circle ball.
def initial_ball_movement(self): # To provide the initial push to the ball just after a point scored or at the beginning
self.x = WIDTH/2 - BALL_SIDE/2 # x - position reset
self.y = HEIGHT/2 - BALL_SIDE/2 # y - position reset
degrees_1 = random.randrange(60, 121, 20)
degrees_2 = random.randrange(240, 301, 20)
degrees = random.choice([degrees_1, degrees_2])
theta = math.radians(degrees)
self.current_ball_speed = BALL_SPEED
self.current_theta = theta
self.ball_movement() |
8e7b9d96cf69f7ec34ccc9df090ff3c0544be01b | bigeyesung/Leetcode | /863. All Nodes Distance K in Binary Tree.py | 1,411 | 3.796875 | 4 | import collections
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def distanceK(self, root, target, K):
#find target node
#find distance below node
#find distance above node
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and child:
conn[parent.val].append(child.val)
conn[child.val].append(parent.val)
if child.left: connect(child, child.left)
if child.right: connect(child, child.right)
connect(None, root)
bfs = [target.val]
seen = set(bfs)
for i in range(K):
# bfs = [y for x in bfs for y in conn[x] if y not in seen]
new_level = []
for x in bfs:
for y in conn[x]:
if y not in seen:
new_level.append(y)
bfs = new_level
# add all the values in bfs into seen
seen = seen | set(bfs)
return bfs
node3 = TreeNode(3)
node5 = TreeNode(5)
node1 = TreeNode(1)
node2 = TreeNode(2)
node7 = TreeNode(7)
node4 = TreeNode(4)
node3.left = node5
node3.right = node1
node5.right = node2
node2.left = node7
node2.right = node4
sol = Solution()
res = sol.distanceK(node3, node5, 2)
print(res) |
b994b81d6b5d53eb76d4d82422e2a0068cd43033 | TanveerAhmed98/Full-Stack-Programming | /Programming Concepts/loops.py | 460 | 3.78125 | 4 | # while loop
a = 0
while a < 11:
print("a = "+str(a))
a = a+1
while True:
print("Loop ends here")
break
# for loop
for b in range(1,12,2):
print(b)
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for c in numbers:
print(c)
d = 0
while d < len(numbers):
print(numbers[d])
d = d +1
dictionary = {
"name" : "jacky",
"state" : "stable",
"performance" : .89
}
for e in dictionary:
print(dictionary[e])
|
1ac4cf6cb17a0236e35616f1324c69a5f5f6f59f | ivangrebeniuk/weather-forecast-parser | /weather_forecast.py | 1,541 | 3.625 | 4 | #! Python 3.7
# Script to parse data from weather forecast web site
import requests
from bs4 import BeautifulSoup
# Download web page
page = requests.get('https://forecast.weather.gov/MapClick.php?lat=40.7146&lon=-74.0071#.X0IsJS2w3q0')
# Create a BeautifulSoup class to parse the page
soup = BeautifulSoup(page.content, 'html.parser')
# Find the div with id seven-day-forecast, and assign to seven_day
seven_day = soup.find(id='seven-day-forecast')
# Inside seven_day, find each individual forecast item.
forecast_items = seven_day.find_all(class_='forecast-tombstone')
tonight = forecast_items[0]
# TODO Extract and print it
# print(tonight.prettify())
city = seven_day.find(class_='panel-title').get_text()
period = tonight.find(class_='period-name').get_text()
short_desc = tonight.find(class_='short-desc').get_text()
temp = tonight.find(class_='temp').get_text()
img = tonight.find('img')
desc = img['title']
periods = [i.get_text() for i in seven_day.select('.tombstone-container .period-name')]
short_descs = [i.get_text() for i in seven_day.select('.tombstone-container .short-desc')]
temps = [i.get_text() for i in seven_day.select('.tombstone-container .temp')]
descs = [i['title'] for i in seven_day.select('.tombstone-container img')]
# print(periods)
# print(short_descs)
# print(temps)
# print(descs)
with open('./forecast.txt', 'w') as f:
f.write(f'Weather forecast in {city.strip()}:\n')
ls = list(zip(periods, short_descs, temps, descs))
for i in ls:
s = " | ".join(i)
f.write(s + '\n')
|
5bcb38572bd60c6783dbacd4725aec0488b65438 | arodan10/ejercicios | /5Ejercicio.py | 758 | 3.859375 | 4 | #Se tiene el nombre y la edad de tres personas. Se desea saber el nombre y la edad de la persona de menor edad. Realice el algoritmo correspondiente y represéntelo con un diagrama de flujo, pseudocodigo y diagrama N/S.
def estCondicional01():
#Definir variable
regaloP=0
#Datos de entrada
cantidadX=int(input("De que persona desea saber su edad y su nombre del de -Mayor edad(opcion 1) -Media edad(opcion 2) -Menor edad(opcion 3):"))
#Proceso
if cantidadX==1:
nombreP="Bryan"
edadP=17
elif cantidadX==2:
nombreP="Josue"
edadP=12
elif cantidadX==3:
nombreP="Matius"
edadP=10
else:
nombreP="-----"
edadP="--"
#Datos de salida
print("NOMBRE:",nombreP," ","EDAD:",edadP)
estCondicional01() |
1b25e77239d3c462f34470b22af52fa564b07ac8 | Unidade/GCC218-Algoritmos-em-Grafos | /0 - Introdução a Python/Exemplos/Classes e objetos/bancos.py | 426 | 3.640625 | 4 | # Classe Banco (bancos.py)
class Banco:
def __init__(self, nome):
self.nome = nome
self.clientes = []
self.contas = []
def abre_conta(self, conta):
self.contas.append(conta)
def lista_contas(self):
for c in self.contas:
c.resumo
# Fonte: Introdução à programação com Python : algoritmos e lógica de programação para iniciantes / Nilo Ney Coutinho Menezes. |
0581aa9a35ffbe2abc43d1cb45d1bb122706f253 | AlexGCPrint/HW_P | /hw4/2task.py | 244 | 3.609375 | 4 | li = [300, 564, 334, 338, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
li2 = []
for i in range(1, len(li)):
if li[i] > li[i-1]:
li2.append(li[i])
print(li2)
li3 = [li[i] for i in range(1, len(li)) if li[i] > li[i-1]]
print(li3)
|
e3f63e9c747426fb666931e283838915a496eb2e | karsonk09/CMSC-150 | /Sample Programs/test4.py | 4,523 | 3.96875 | 4 | import arcade
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 600
SQUARE_LENGTH = 35
SQUARE_HEIGHT = 35
TRIANGLE_COORDINATES = []
SQUARE_MOVE_SPEED = 3
class Square:
def __init__(self, position_x, position_y, change_x, change_y, side_length, side_height, color):
self.position_x = position_x
self.position_y = position_y
self.change_x = change_x
self.change_y = change_y
self.side_length = side_length
self.side_height = side_height
self.color = color
class MyApplication(arcade.Window):
"""
Main application class.
NOTE: Go ahead and delete the methods you don't need.
If you do need a method, delete the 'pass' and replace it
with your own code. Don't leave 'pass' in this program.
"""
def __init__(self, width, height):
super().__init__(width, height)
# Draw the Square
self.square_x_position = 150
self.square_y_position = 300
self.square_change_x = 3
self.square_change_y = 3
# Draw the Triangle
self.triangle_x1_y1 = [100, 50]
TRIANGLE_COORDINATES.append(self.triangle_x1_y1)
self.triangle_x2_y2 = [50, 50]
TRIANGLE_COORDINATES.append(self.triangle_x2_y2)
self.triangle_x3_y3 = [75, 100]
TRIANGLE_COORDINATES.append(self.triangle_x3_y3)
self.triangle_movement = 1
arcade.set_background_color(arcade.color.BLACK)
# Note:
# You can change how often the animate() method is called by using the
# set_update_rate() method in the parent class.
# The default is once every 1/80 of a second.
# self.set_update_rate(1/80)
def on_draw(self):
"""
Render the screen.
"""
# This command should happen before we start drawing. It will clear
# the screen to the background color, and erase what we drew last frame.
arcade.start_render()
arcade.set_background_color(arcade.color.BLACK)
arcade.draw_triangle_filled(TRIANGLE_COORDINATES[0][0], TRIANGLE_COORDINATES[0][1], TRIANGLE_COORDINATES[1][0],
TRIANGLE_COORDINATES[1][1], TRIANGLE_COORDINATES[2][0], TRIANGLE_COORDINATES[2][1],
arcade.color.RED_DEVIL)
arcade.draw_rectangle_filled(self.square_x_position, SCREEN_HEIGHT // 2, SQUARE_LENGTH, SQUARE_HEIGHT,
arcade.color.ALLOY_ORANGE)
def animate(self, delta_time):
"""
All the logic to move, and the game logic goes here.
"""
# Move the ball
# self.ball_x_position += self.ball_x_pixels_per_second * delta_time
# Did the ball hit the right side of the screen while moving right?
"""
if self.ball_x_position > SCREEN_WIDTH - BALL_RADIUS \
and self.ball_x_pixels_per_second > 0:
self.ball_x_pixels_per_second *= -1
# Did the ball hit the left side of the screen while moving left?
if self.ball_x_position < BALL_RADIUS \
and self.ball_x_pixels_per_second < 0:
self.ball_x_pixels_per_second *= -1
"""
self.square_x_position += self.square_change_x * delta_time
self.square_y_position += self.square_change_y * delta_time
def on_key_press(self, key, key_modifiers):
"""
Called whenever a key on the keyboard is pressed.
For a full list of keys, see:
http://pythonhosted.org/arcade/arcade.key.html
"""
# See if the user hit Shift-Space
# (Key modifiers are in powers of two, so you can detect multiple
# modifiers by using a bit-wise 'and'.)
if key == arcade.key.SPACE and key_modifiers == arcade.key.MOD_SHIFT:
print("You pressed shift-space")
# See if the user just hit space.
elif key == arcade.key.SPACE:
print("You pressed the space bar.")
if key == arcade.key.RIGHT:
print("Right pressed")
self.square_change_x = SQUARE_MOVE_SPEED
def on_key_release(self, key, key_modifiers):
"""
Called whenever the user lets off a previously pressed key.
"""
if key == arcade.key.SPACE:
print("You stopped pressing the space bar.")
def on_mouse_motion(self, x, y, delta_x, delta_y):
"""
Called whenever the mouse moves.
"""
pass
window = MyApplication(SCREEN_WIDTH, SCREEN_HEIGHT)
arcade.run()
|
a77a44250ff16b2c16d6161624e3c8e23d024e60 | suh-fee/nyuCoursework | /Intro to Python Labs/lab9.py | 1,804 | 3.75 | 4 | # pen and paper 1
# a: ['hi', 'mom', 'dad', 1, 57, 25]
# b: ['hi', 25]
# c: ['hi', 'mom', 'dad', [1, 57, 25]]
# d: ['hi', 'mom', 'dad', [1, 57, 25]]
# pen and paper 2
# a: 5
# b: 3
# c: [3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]
#programming
# q 1
def staircase(myint, n):
num_list = []
for i in range(n):
num_list.append(myint+i)
return num_list
# q 2
def count(lst, item):
length = len(lst)
counter = 0
for i in range(length):
if lst[i] == item:
counter += 1
return counter
# q 3
def two_powers():
n = int(input("Please input an n: "))
num_list = []
for i in range(n):
num_list.append(2**(i+1))
return num_list
# q 4
def find_max_even_index(lst):
length = len(lst)
last_even_place = -1
last_even = 0
for i in range(length):
if (lst[i] % 2) == 0:
if lst[i] > last_even:
last_even_place = i
last_even = lst[last_even_place]
return last_even_place
# q 5
def get_common_element(lst1, lst2):
fin_list = []
for i in range(len(lst1)):
for j in range(len(lst2)):
if lst1[i] == lst2[j]:
fin_list.append(lst1[i])
lst2.pop(j)
break
return fin_list
# q 6
def squared(lst):
sum = 0
for i in range(len(lst)):
sum += lst[i] ** 2
return sum
# q 7
def remove_below_average(lst):
sum = 0
for i in range(len(lst)):
sum += lst[i]
average = sum / len(lst)
difference = 0
for i in range(len(lst)):
if lst[i-difference] < average:
lst.pop(i - difference)
difference += 1
return lst
# q 8
def circular_shift_list(lst, k):
for i in range(k):
lst.insert(0, lst.pop())
return lst
|
6827701372de8eddb41d575c7cb0dee8f32435b1 | OleksandrMakeiev/python_hw | /random digit.py | 540 | 3.9375 | 4 | # 23
import random
print("Программа загадывает целое число от 1 до 10, Ваша задача отдгадать его, следуя подсказкам программы. Для выхода нажми q ")
number = random.randint(1, 11)
while True:
choice = int(input("Сделай свой выбор [1-10]: "))
if choice > number:
print("Меньше")
elif choice < number:
print("Больше")
elif choice == number:
print("Угадал")
break
|
14c5f7bba90b9f6f64f30a4dfb323db91e3a0aff | BruceHi/leetcode | /String/1reverseString.py | 793 | 4.125 | 4 | # 使用递归
# def reverseString(s):
# def helper(left, right):
# if left < right:
# s[left], s[right] = s[right], s[left]
# helper(left + 1, right - 1)
#
# helper(0, len(s) - 1)
# 双指针
# def reverse_string(s) -> None:
# left, right = 0, len(s) - 1
# while left < right:
# s[left], s[right] = s[right], s[left]
# left, right = left + 1, right - 1
# def reverse_string(s) -> None:
# left, right = 0, len(s) - 1
# while left < right:
# s[left], s[right] = s[right], s[left]
# left, right = left+1, right-1
def reverse_string(s) -> None:
s.reverse()
string = ["h","e","l","l","o"]
reverse_string(string)
print(string)
string = ["H","a","n","n","a","h"]
reverse_string(string)
print(string)
|
df7ea5c9baf77fd97baef3414bbea65013be23e5 | jasch-shah/python_codes | /countdown.py | 710 | 4 | 4 | import time
from datetime import datetime, timedelta
def setcount():
global hrs
global mins
global secs
global totalsecs
print('#### enter the requested values of the countdown timer #')
hrs = int(input('hrs: ' ))
mins = int(input('minutes: '))
secs = int(input('seconds: '))
totalsecs = 3600 * hrs + 60 * mins + secs
def countdown():
run = str(raw_input('Start? (y/n) >'))
if run == "y":
ltotalsecs = totalsecs
while ltotalsecs != 0:
sec = timedelta(seconds=int(ltotalsecs))
d = datetime(1, 1, 1) + sec
print("%d hr %d minutes %d seconds over"% (d.hour, d.minute, d.second))
time.sleep(1)
ltotalsecs -= 1
if ltotalsecs == 0:
print("Time is Up")
setcount()
countdown() |
2d0291af4a8e7a6a9fe3e9399d9383471d7ce144 | Yunzhe-Yu/products | /products.py | 2,055 | 3.984375 | 4 | # check the file if it is exist
import os # operating system
products = []
if os.path.isfile('products_price.csv'): # check the file if is existent isfile()
print('The file is existent!')
# products = [] # create a new list
with open('products_price.csv', 'r', encoding = 'utf-8') as f:
for line in f:
if 'Items, Price' in line:
continue # jump to next loop
name, price = line.strip().split(',') # split to cut the line use everything
# use strip to remove '\n'
# From left to right
# After split will generate a list []
# name = s[0]
# price = s[1]
products.append([name, price])
print(products)
else:
print('The file is nonexistent!')
# read file
# products = [] # create a new list
# with open('products_price.csv', 'r', encoding = 'utf-8') as f:
# for line in f:
# if 'Items, Price' in line:
# continue # jump to next loop
# name, price = line.strip().split(',') # split to cut the line use everything
# use strip to remove '\n'
# From left to right
# After split will generate a list []
# name = s[0]
# price = s[1]
# products.append([name, price])
#print(products)
# 2-D list
# insert a list into the first list
# input import
while True:
name = input('Please enter the name of the item: ')
if name == 'q': # quit
break
price = input('Please enter the price of this item: ')
price = int(price)
product = [] # new list
product.append(name)
product.append(price)
# product = [name, price]
products.append(product)
# products.append([name, price])
print(products)
# print each record
for p in products:
print('The price of', p[0], 'is', p[1], 'dollar!')
# 'abc' + '123' = 'abc123'
# 'abc' * 3 = 'abcabcabc'
# write in csv file
# with open('products_price.txt', 'w') as f:
with open('products_price.csv', 'w', encoding = 'utf-8') as f:
f.write('Items, Price\n')
for p in products:
f.write(p[0] + ',' + str(p[1]) + '\n') # f.write: write function
# Can not plus integer to string use str() and int()
# use encoding = utf - 8 can write chinese *****
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.