blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
2c24e00b6719c991c02ec9cee0a44ef096057e87 | AnthonyGKruger/edX-MITx-comp-science-work | /edx/MITX 6.00.1x/bisection.edpy | 1,912 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 15:19:39 2018
@author: anthony
"""
print('Please think of a number between 0 and 100!')
low = 0
max = 100
too_high = 'h'
too_low = 'l'
correct = 'c'
guess = (low + max)// 2
iterations = 0
guessed = False
while not guessed:
guess = (low + max)//2
iterations += 1
print('Is your secret number ', str(guess), '?', end = '')
question = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly." )
if question == correct.lower():
guessed = True
print('Game over. Your secret number was: ', str(guess))
elif question == too_low.lower():
low = guess
elif question == too_high.lower():
max = guess
else:
print('Sorry, I did not understand your input.')
balance = 5000
int_rate = 0.18
monthly_rate = 0.18/12
min_pay = balance * monthly_rate
unpaid_bal = balance - min_pay
interest = monthly_rate * unpaid_bal
due = unpaid_bal + interest
month = 0
for month in range(0,12):
balance = 5000
int_rate = 0.18
monthly_rate = 0.18/12
min_pay = balance * monthly_rate
balance = balance - min_pay
interest = monthly_rate * balance
due = balance + interest
month += 1
balance = due
print(balance)
balance = 42
month = 0
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
while month < 12:
int_rate = annualInterestRate
monthly_rate = annualInterestRate/12
min_pay = balance * monthly_rate
balance = balance - min_pay
interest = monthly_rate * balance
due = round(balance + interest, 2)
month += 1
balance = due
print(balance)
|
fa09f40a0bad7b4ac96fb932bcfa734a4fb940d1 | tanucdi/dailycodingproblem | /CP/Arithmetic Problem/SexyPrimes.py | 568 | 3.78125 | 4 | '''
GIVEN A RANGE OF THE FORM [L,R]. THE TASK IS TO PRINT ALL THE SEXY PRIME PAIRS IN THE RANGE.
Examples:
Input = L=1 R=19
Output = (5,11) (7,13) (11,17) (13,19)
'''
from math import sqrt
def check(n):
l=[True]*(n+1)
l[0]=False
l[1]=False
for i in range(2,int(sqrt(n))+1):
if l[i]==True:
for j in range(i*i,n+1,i):
l[j]=False
return l
L=6
R=59
myprime=check(R)
for i in range(L,len(myprime)-6):
if myprime[i]==True:
x=i
y=x+6
if myprime[y]==True:
print(f'({x},{y})') |
b64eeaed3ca6f55c4be3e8dc7a5dd54bb7d68f04 | Manjuphoenix/Algorithms | /ad_company.py | 1,015 | 4.21875 | 4 | # The media company "GlobalAd" has received a
# batch of advertisements from different product
# brands. The batch of advertisements is a
# numeric value where each digit represents the
# number of advertisements the media company
# has received from different product brands.
# Since the company banners permit only even
# numbers of advertisements to be displayed, the
# media company needs to know the total
# number of advertisements it will be able to
# display from the given batch.
# Write an algorithm to calculate the total
# number of advertisements that will be
# displayed from the batch.
# Input
# The input consists of an integer batch,
# representing the batch of advertisements
# Output
# Print an integer representing the total number
# of advertisements that will be displayed by the
# media company
# Constraints
# 0 < batchs 109
Solution:
my_list = [int(x) for x in input().split()]
total = 0
for i in my_list:
if i % 2 == 0:
total = total+i
else:
continue
print(total)
|
26a0ce539d103756b36cfce087f0c03aec93be3e | soonki-98/hyunjoon-soonki | /두_개_뽑아서_더하기.py | 382 | 3.71875 | 4 | def solution(numbers):
a = []
#모든 수 더함
for i in range(len(numbers)-1):
for j in range(1,len(numbers)):
if(i != j):
print("index :",i,"+",j,"=",numbers[i] + numbers[j])
a.append(numbers[i] + numbers[j])
print(a)
#중복된 수 삭제
print(list(set(a)))
a = list(set(a))
return a |
9a2b4edec7d93da7ae90ee0863285ea7e2fbacd9 | stat17-hb/algorithm | /geeksforgeeks/Finding Position.py | 316 | 3.53125 | 4 | # https://practice.geeksforgeeks.org/problems/finding-position/0
#%%
import sys
T = int(sys.stdin.readline())
for _ in range(T):
N = int(sys.stdin.readline())
queue = [i+1 for i in range(N)]
while len(queue)!=1:
queue = [queue[i] for i in range(len(queue)) if (i+1) % 2 ==0]
print(queue[0]) |
66e0d16f5976d8347f2fad794107aa71a99e2e41 | cjoyce333/CompPhys | /src/decay.py | 688 | 3.59375 | 4 | #-------------------------------------------------------------------------------
# Name: decay
# Purpose:
#
# Author: Claire JOyce
#
# Created: 25/09/2014
#-------------------------------------------------------------------------------
#!/usr/bin/env python
from numpy import *
from math import *
import matplotlib.pyplot as plt
import numpy as np
k=input("enter decay constant k= ")
N=1000
t=0
t_stop=100
h= input("val of time step,h")
plt.title("Euler method of solution")
plt.xlabel("time t")
fig = plt.figure()
ax=fig.add_subplot(2,1,1)
while t<t_stop:
plt.plot(t,N,"bo")
N=N-k*N*h
t=t+h
ax.set_xscale('log')
plt.show() |
3d88eb876eaa79166556db976e217d25133aa886 | A11en0/algorithms | /trick/trick_zip.py | 572 | 3.765625 | 4 | import random
X = [1, 2, 3, 4, 5, 6]
y = [0, 1, 0, 0, 1, 1]
zipped_data = list(zip(X, y))
# 将样本和标签一 一对应组合起来,并转换成list类型方便后续打乱操作random.shuffle(zipped_data)
# 使用random模块中的shuffle函数打乱列表,原地操作,没有返回值
new_zipped_data = list(map(list, zip(*zipped_data)))
# zip(*)反向解压,map()逐项转换类型,list()做最后转换
new_X, new_y = new_zipped_data[0], new_zipped_data[1]
# 返回打乱后的新数据
print('X:',X,'\n','y:',y)
print('new_X:',new_X, '\n', 'new_y:',new_y) |
95b542db9ebe2989409118998bab20ef824680ec | rbixby/python_the_hard_way | /exercises_31_40/ex40.py | 659 | 3.78125 | 4 | """
Exercise 40 Modules, Classes, and Objects
In which our intrepit instructor explains how to get things done in Python
and along the way exposes his anti-OO biases.
"""
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
hb_lyrics = ["Happy birthday to you"
, "I don't want to get sued"
, "So I will stop right there"]
happy_bday = Song(hb_lyrics)
bop_lyrics = ["They rally around the family"
, "With pockets full of shells"]
bulls_on_parade = Song(bop_lyrics)
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song() |
bb582f63949e398c03d3e17f2a85b6d0ff42d6fd | ferreret/python-bootcamp-udemy | /36-challenges/ex133.py | 564 | 3.703125 | 4 | '''
counter = letter_counter('Amazing')
counter('a') # 2
counter('m') # 1
counter2 = letter_counter('This Is Really Fun!')
counter2('i') # 2
counter2('t') # 1
'''
def letter_counter(input_string):
reference_string = input_string.lower()
def inner(letter):
nonlocal reference_string
return reference_string.count(letter.lower())
return inner
counter = letter_counter('Amazing')
print(counter('a')) # 2
print(counter('m')) # 1
counter2 = letter_counter('This Is Really Fun!')
print(counter2('i')) # 2
print(counter2('t')) # 1
|
7b48a522f9dda9f6b4c52e50f978d33dd9ac2d09 | peterlulu666/PythonProgrammingTutorial | /Chapter04/Homework04.py | 713 | 3.953125 | 4 | months = ["January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
for month in months:
if month[0] == "J":
print(month)
# months_count = 0
# while months_count < 12:
# if months[months_count][0] == "J":
# print(months[months_count])
# months_count = months_count + 1
for number in range(0, 100):
if number % 2 == 0 and number % 5 == 0:
print(number)
horton = "A person's a person, no matter how small."
vowels = "aeiouAEIOU"
for letter in horton:
if letter in vowels:
print(letter)
|
60ac53baab25ff646bb12727d2aa2d5a98aa5087 | Anthony-69/cp1404practicals | /prac_06/languages.py | 835 | 3.921875 | 4 | """
CP1404/CP5632 Practical
"""
from prac_06.programming_language import ProgrammingLanguage
def run_main():
java = ProgrammingLanguage("Java", "Static", True, 1995)
c = ProgrammingLanguage("C++", "Static", False, 1983)
# c is the programming language C++
# THe "++" is not added due to it causing errors
python = ProgrammingLanguage("Python", "Dynamic", True, 1991)
visual_basic = ProgrammingLanguage("Visual Basic", "Static", False, 1991)
ruby = ProgrammingLanguage("Ruby", "Dynamic", True, 1995)
languages = [java, c, python, visual_basic, ruby]
for language in languages:
print(language)
print("The dynamically typed languages include:")
for language in languages:
if language.is_dynamic():
print(language.name)
if __name__ == "__main__":
run_main()
|
26d76fe8af433aaebf16cc4b5ff9d54ee8a41e35 | arnab0000/CodingNinjas-DS | /1_numpy/terrorism/terrorCasultyAttack.py | 639 | 3.625 | 4 | import pandas as pd
import numpy as np
terrorism = pd.read_csv("terrorismData.csv")
df = terrorism.copy()
df.Killed.fillna(0, inplace=True)
df.Wounded.fillna(0, inplace=True)
df["Casualty"] = df['Killed'] + df["Wounded"]
df = df[df.State == "Jammu and Kashmir"]
df = df[df.Year == 1999]
df = df[df.Month >= 5]
df = df[df.Month <= 7]
# print(df)
# numbers = df["Casualty"].value_counts()
df = df[["City", "Casualty", "Group"]]
required = df[df["Casualty"] == max(df["Casualty"])]
x = required.values[0]
print(x[1], x[0], x[2])
# index = max(df["Casualty"])
# print(index)
# numbers = max(df["Casualty"])
# print(numbers) |
c9cbaae3b7a42ad8c082d9e9f9a03926ea485491 | strange-hawk/data_structure_algorithms | /bit/power_set.py | 181 | 3.546875 | 4 | #find the power set
name=input()
count=1<<len(name)
for i in range(count):
for j in range(len(name)):
if((i & (1<<j))>0):
print(name[j],end="")
print("") |
fe8fd878cc238a84b9ab49f9910501375677a1a4 | vitzwitz/school_projects | /lab-mobiles/mobiles.py | 10,330 | 3.796875 | 4 | """
file: mobiles.py
language: python3
author: ben k steele, bks@cs.rit.edu
author: Bri Miskovitz
description: Build mobiles using a tree data structure.
date: 04/2017
purpose: starter code for the tree mobiles lab
"""
from rit_lib import *
from math import floor
############################################################
# structure definitions
############################################################
class Ball(struct):
"""
class Ball represents a ball of some weight hanging from a cord.
field description:
cord: length of the hanging cord in inches
weight: weight of the ball in ounces (diameter of ball in a drawing)
# Add size?
"""
_slots = ((float, 'cord'), (float, 'weight'))
class Rod(struct):
"""
class Rod represents a horizontal rod part of a mobile with
a left-side mobile on the end of a left arm of some length,
and a right-side mobile on the end of a right arm of some length.
In the middle between the two arms is a cord of some length
from which the rod instance hangs.
field description:
leftmobile: subordinate mobile is a mobile type.
leftarm: length of the right arm in inches
cord: length of the hanging cord in inches
rightarm: length of the right arm in inches
rightmobile: subordinate mobile is a mobile type.
An assembled mobile has valid left and right subordinate mobiles;
an unassembled mobile does not have valid subordinate mobiles.
# Add size?
"""
_slots = ((object, 'leftmobile'), (float, 'leftarm'), (float, 'cord'), \
(float, 'rightarm'), (object, 'rightmobile'))
#########################################################
# Create mobiles from mobile files
#########################################################
def readMobile(file):
"""
readMobile : OpenFileObject -> Map( Ball | Rod )
readMobile reads the open file's content and
builds a mobile 'parts map' from the specification in the file.
The parts map returned has components for assembling the mobile.
If the mobile is a simple mobile, the returned value is
a parts map containing a Ball instance.
If the mobile is complex, the returned value is a parts list of
the Rod instance representing the top-most mobile component and
the other parts.
The connection point for each part is a string that identifies
the key name of the part to be attached at that point.
If there is an error in the mobile specification, then
return an empty parts map.
# an example of the file format. 'B10' is key for the 10 oz ball.
# blank lines and '#' comment lines are permitted.
B10 40 10
top B10 240 66 80 B30
B30 55 30
"""
partsMap = {}
for line in file:
if line.strip() == '' or line[0] == '#':
pass
else:
line = line.split()
if line[0][0] == 'B':
partsMap[line[0]] = Ball(float(line[1]), float(line[2]))
elif line[0][0] == 'R':
partsMap[line[0]] = Rod(line[1], float(line[2]), float(line[3]), float(line[4]), line[5])
elif line[0] == "top":
if line[1][0] == 'R' or line[1][0] == 'B':
partsMap[line[0]] = Rod(str(line[1]), float(line[2]), float(line[3]), float(line[4]), str(line[5]))
else:
partsMap[line[0]] = Ball(float(line[1]), float(line[2]))
else:
partsMap = {}
return partsMap
return partsMap
def constructMobile(partsmap):
"""
constructMobile : Map( Rod | Ball ) -> Ball | Rod | NoneType
constructMobile reads the partsmap to put together the
mobile's components and return a completed mobile object.
The constructMobile operation 'patches entries' in the partsmap.
The parts map has the components for assembling the mobile.
Each Rod in partsmap has a key name of its left and right
subordinate mobiles. constructMobile reads the key to
get the subordinate part and attach it at the slot where
the key was located within the component.
The top mounting point of the mobile has key 'top' in partsmap.
If the completed mobile object is a simple mobile, then
the top returned value is a Ball instance.
If the completed mobile is a complex mobile, then
the top returned value is a Rod instance.
If the parts map contains no recognizable mobile specification,
or there is an error in the mobile specification, then
return None.
"""
if len(partsmap) == 0:
return None
else:
if isinstance(partsmap['top'], Ball):
return partsmap['top']
else:
lst = partsmap.keys()
for part in lst:
if part[0] == 'R' or part == 'top':
tempLEFT = partsmap[part].leftmobile
tempRIGHT = partsmap[part].rightmobile
if isinstance(tempLEFT, str):
partsmap[part].leftmobile = partsmap[tempLEFT]
if isinstance(tempRIGHT, str):
partsmap[part].rightmobile = partsmap[tempRIGHT]
return partsmap["top"]
############################################################
# mobile analysis functions
############################################################
def is_balanced(theMobile):
"""
is_balanced : theMobile -> Boolean
is_balanced is trivially True if theMobile is a simple ball.
Otherwise theMobile is balanced if the product of the left side
arm length and the left side is approximately equal to the
product of the right side arm length and the right side, AND
both the right and left subordinate mobiles are also balanced.
The approximation of balance is measured by checking
that the absolute value of the difference between
the two products is less than 1.0.
If theMobile is not valid, then produce an exception
with the message 'Error: Not a valid mobile\n\t{mobile}',
pre-conditions: theMobile is a proper mobile instance.
"""
if isinstance(theMobile, Ball):
return True
if isinstance(theMobile.leftmobile, Ball):
if isinstance(theMobile.rightmobile, Ball):
return floor(theMobile.leftarm * theMobile.leftmobile.weight) \
== floor(theMobile.rightarm * theMobile.rightmobile.weight)
else:
print(theMobile.leftarm * theMobile.leftmobile.weight)
print(theMobile.rightarm * weight(theMobile.rightmobile))
return is_balanced(theMobile.rightmobile) and \
floor(theMobile.leftarm * theMobile.leftmobile.weight) \
== floor(theMobile.rightarm * weight(theMobile.rightmobile))
elif isinstance(theMobile.leftmobile, Rod):
if isinstance(theMobile.rightmobile, Ball):
return is_balanced(theMobile.leftmobile) and \
floor(theMobile.rightarm * theMobile.rightmobile.weight) \
== floor(theMobile.leftarm * weight(theMobile.leftmobile))
else:
return is_balanced(theMobile.leftmobile) and \
is_balanced(theMobile.rightmobile) and \
floor(theMobile.leftarm * weight(theMobile.leftmobile))\
== floor(theMobile.rightarm * weight(theMobile.rightmobile))
else:
raise Exception("Error: Not a valid mobile\n\t" + str(theMobile))
def weight(theMobile):
"""
weight : theMobile -> Number
weight of the theMobile is the total weight of all its Balls.
If theMobile is not valid, then produce an exception
with the message 'Error: Not a valid mobile\n\t{mobile}',
pre-conditions: theMobile is a proper mobile instance.
"""
if isinstance(theMobile, Ball):
return theMobile.weight
elif isinstance(theMobile, Rod):
if isinstance(theMobile.leftmobile, Ball):
if isinstance(theMobile.rightmobile, Ball):
return theMobile.leftmobile.weight + theMobile.rightmobile.weight
else:
return theMobile.leftmobile.weight + weight(theMobile.rightmobile)
else:
if isinstance(theMobile.rightmobile, Ball):
return weight(theMobile.leftmobile) + theMobile.rightmobile.weight
else:
return weight(theMobile.leftmobile) * weight(theMobile.rightmobile)
else:
raise Exception("Error: Not a valid mobile\n\t" + str(theMobile))
def height(theMobile):
"""
height : theMobile -> Number
height of the theMobile is the height of all tallest side.
If theMobile is not valid, then produce an exception
with the message 'Error: Not a valid mobile\n\t{mobile}',
pre-conditions: theMobile is a proper mobile instance.
"""
if isinstance(theMobile, Ball):
return theMobile.cord
elif isinstance(theMobile, Rod):
if isinstance(theMobile.leftmobile, Ball):
if isinstance(theMobile.rightmobile, Ball):
if theMobile.leftmobile.cord < theMobile.rightmobile.cord:
return theMobile.cord + theMobile.rightmobile.cord + theMobile.rightmobile.weight
else:
return theMobile.cord + theMobile.leftmobile.cord + theMobile.leftmobile.weight
else:
if theMobile.leftmobile.cord < height(theMobile.rightmobile):
return height(theMobile.rightmobile) + theMobile.cord
else:
return theMobile.leftmobile.cord + theMobile.leftmobile.weight
else:
if isinstance(theMobile.rightmobile, Ball):
if theMobile.rightmobile.cord < height(theMobile.leftmobile):
return height(theMobile.leftmobile) + theMobile.cord
else:
return theMobile.rightmobile.cord + theMobile.rightmobile.weight
else:
if height(theMobile.leftmobile) < height(theMobile.rightmobile):
return height(theMobile.rightmobile) + theMobile.cord
else:
return height(theMobile.leftmobile) + theMobile.cord
else:
raise Exception("Error: Not a valid mobile\n\t" + str(theMobile))
|
b8e4c539253013d499cfc9a0037987a42e752ff0 | mikehung/competitive-programming | /leetcode/python-sol/693.Binary_Number_with_Alternating_Bits.py | 391 | 3.546875 | 4 | class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
prev_char = None
for char in format(n, 'b'):
if prev_char and prev_char == char:
return False
prev_char = char
return True
for _ in range(12):
print(_, format(_, 'b'), Solution().hasAlternatingBits(_))
|
624d8c1c1afd6c8efd318d2492dc40e67b190ec6 | xavierloos/python3-course | /Basic/Control Flow/boolean_operator:_and.py | 759 | 4.1875 | 4 | # 1. Set the variables statement_one and statement_two equal to the results of the following boolean expressions:
# Statement one: (2 + 2 + 2 >= 6) and (-1 * -1 < 0)
# Statement two: (4 * 2 <= 8) and (7 - 1 == 6)
# 2. Let’s return to Calvin Coolidge’s Cool College. 120 credits aren’t the only graduation requirement, you also need to have a GPA of 2.0 or higher.
# Rewrite the if statement so that it checks to see if a student meets both requirements using an and statement.
# If they do, return the string: "You meet the requirements to graduate!"
statement_one = (2 + 2 + 2 >= 6) and (-1 * -1 < 0)
statement_two = (4 * 2 <= 8) and (7 - 1 == 6)
credits = 120
gpa = 3.4
if credits >= 120 and gpa >= 2.0:
print("You meet the requirements to graduate!") |
2f824fea53be4fbb7cbb341e30b4eb69d2669da5 | LuisFMendez/Lesson-2 | /Excersize 5.py | 330 | 4 | 4 | #Luis Mendez - Chapter 2 and Variables - 02052018
'''
Write a program which prompts the user for a Celsius temperature,
convert the temperature to Fahrenheit, and print out the converted temperature.
'''
Celsius = int(input('Whats the temperature in celcius: '))
Fahrenheit = (Celsius * 1.8) + 32
print (Fahrenheit)
|
2ba233fbfb78d150f2ee23ee9b7ac4dad47576e0 | choongin/leetcode | /python/1431_Kids_With_the_Greatest_Number_of_Candies/Kids_With_the_Greatest_Number_of_Candies.py | 2,151 | 4.125 | 4 | # 1431. Kids With the Greatest Number of Candies
# Link : https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
# Given the array candies and the integer extraCandies,
# where candies[i] represents the number of candies that the ith kid has.
# For each kid check if there is a way to distribute extraCandies
# among the kids such that he or she can have the greatest number of candies
# among them. Notice that multiple kids can have the greatest number of candies.
# Example 1:
# Input: candies = [2,3,5,1,3], extraCandies = 3
# Output: [true,true,true,false,true]
# Explanation:
# Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids.
# Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
# Kid 3 has 5 candies and this is already the greatest number of candies among the kids.
# Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies.
# Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
# Result : Success
# Runtime: 28 ms, faster than 66.20% of Python online submissions for Kids With the Greatest Number of Candies.
# Memory Usage: 12.7 MB, less than 59.99% of Python online submissions for Kids With the Greatest Number of Candies.
class Solution(object):
def kidsWithCandies(self, candies, extraCandies):
"""
:type candies: List[int]
:type extraCandies: int
:rtype: List[bool]
"""
max_candy = max(candies)
results = [0]*len(candies)
for i in range(len(candies)):
candy_with_extra = candies[i] + extraCandies
if candy_with_extra >= max_candy:
results[i] = True
else:
results[i] = False
return results
if __name__ == '__main__':
# begin
candies = [4,2,1,1,2]
extraCandies = 1
s = Solution()
value = s.kidsWithCandies(candies, extraCandies)
print(value)
|
677afa13514f68cf1aaf6504b075df8192d96fad | OliverVuong/Python-Chess | /ConsoleIOManager.py | 1,617 | 3.890625 | 4 | from Command import Command
from Square import Square
from Validation import isValidSelection, isValidDestination
def getSelection(data, side):
"""Queries user to select a piece"""
while True:
try:
row = int(input("Select Row: "))
column = int((input("Select Column: ")))
selection = Square(row, column)
if(isValidSelection(selection, data, side)):
break
except ValueError:
print("Invalid Input.")
return selection
def getDestination(selection, data, side):
"""Queries user where to put a selected piece
a -1, -1 destination lets the user make a new selection"""
while True:
try:
row = int(input("Destination Row: "))
column = int((input("Destination Column: ")))
destination = Square(row, column)
if(isValidDestination(selection, destination, data, side)):
break
except ValueError:
print("Invalid Input.")
return destination
def getCommand(side, data):
"""Queries user to select a piece and where to place the piece"""
if(side == "white"):
print("White's turn:")
else:
print("Black's turn:")
while True:
selection = getSelection(data, side)
destination = getDestination(selection, data, side)
if(not isResetCode(destination)):
break
return Command(selection, destination)
def isResetCode(destination):
if(destination.row == -1 and destination.column == -1):
return True
else:
return False |
b73f0e5444efc90e0870ce4c0e8fa8c8e310e52b | Louvani/holbertonschool-higher_level_programming | /0x0B-python-input_output/10-student.py | 812 | 3.84375 | 4 | #!/usr/bin/python3
"""9. Student to JSON """
class Student:
"""a class Student that defines a student by"""
def __init__(self, first_name, last_name, age):
"""Instantiation with first_name, last_name and age"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""retrieves a dictionary representation
of a Student instance (same as 8-class_to_json.py)"""
if attrs is None:
return vars(self)
if all(isinstance(args, str) for args in attrs):
new_dict = {}
for args in attrs:
if args in self.__dict__:
new_dict[args] = self.__dict__[args]
return new_dict
else:
return vars(self)
|
1feb46f2c0feb5481d7a4d2e97ceb60c29771182 | Polovnevya/python_core | /Lessons/Lesson 1/homework_4.py | 678 | 4.1875 | 4 | # Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
number = int(input("Введите целое положительное число "))
max_digit = 0
digit_counter = number
while digit_counter:
if max_digit == 9:
break
elif max_digit <= (digit_counter % 10):
max_digit = digit_counter % 10
digit_counter = digit_counter // 10
print(f"Самой большой цифрой в числе {number} является {max_digit}")
|
f5a0faab640a0153ddc6cee30ee67df1662c2c3e | FSwordArt/python-learn | /python_learn/协程_迭代器.py | 1,151 | 4 | 4 | from collections.abc import Iterable
from collections.abc import Iterator
import time
class Classmate(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
def __iter__(self):
#要实现for功能,必须实现__iter__功能,函数必须返回一个迭代器的对象
return classmateiterator(self)
class classmateiterator(object):
def __init__(self, obj):
self.obj = obj
self.index = 0
#只要类中有下面两个方法,就称这个类为迭代器
def __iter__(self):
pass
def __next__(self):
if self.index < len(self.obj.names):
set = self.obj.names[self.index]
self.index += 1
return set
else:
raise StopIteration
classmate = Classmate()
classmate.add("11")
classmate.add("22")
classmate.add("33")
print("是否为迭代对象:", isinstance(classmate, Iterable))
classmate_iterator = iter(classmate)
print("判断是否为迭代器:", isinstance(classmate_iterator, Iterator))
for name in classmate:
print(name)
time.sleep(1)
|
fe2350b30043a66394eaf820af68e4fa88a9541d | DanielOjo/Selection | /Selection glass exercise (exam mark).py | 537 | 4.03125 | 4 | #Daniel Ogunlana
#09-10-2014
#Selection glass exercise (exam mark)
exam_mark = int(input("Please enter your exam mark?:"))
if exam_mark <0 or exam_mark <=40:
print("Your grade is U")
elif exam_mark ==41 or exam_mark <=50:
print("Your grade is E")
elif exam_mark ==51 or exam_mark <=60:
print("Your grade is D")
elif exam_mark ==61 or exam_mark <=70:
print("Your grade is C")
elif exam_mark ==71 or exam_mark <=80:
print("Your grade is B")
elif exam_mark ==81 or exam_mark <=100:
print("Your grade is A")
|
89795f03a23b0ace546346fcdfdbef18906d31b8 | brandtnet1/BFS_DFS | /word_ladder.py | 1,360 | 4.03125 | 4 | def word_ladder(start, end):
file = open('words.txt')
word_list = {}
for word in file:
if len(start) + 1 == len(word):
word.replace('\n', '')
word.replace(' ', '')
word_list[word[:len(start)]] = start # Stores all words with same length as start word
queue = [start]
alphabet = 'abcdefghijklmnopqrstuvwxyz' # Alphabet to replace a single letter of each word
while len(queue): # BFS
cur = queue[0]
queue.pop(0)
if cur == end: # We got to the end word
return word_list[cur]
for i in range(len(start)):
for char in alphabet:
if cur[i] != char: # Go until you find a word that replaces a single letter
next = list(cur) # of the current word that is in the word list and add that
next[i] = char # to the queue. Append the current path of getting to that word
new = str(''.join(next)) # to the current word for printing out once you find the end.
if new in word_list and word_list[new] == start:
queue.append(new)
word_list[new] = word_list[cur] + ' ' + new
#print word_ladder('dog', 'cat')
print word_ladder('snakes', 'brains') |
81a03205fac4c38e483bcf13ef2a23e08f1e0d39 | jalongod/LeetCode | /108.py | 714 | 3.703125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums) == 0:
return
# 取nums列表的中间下标值
mid_index = len(nums)//2
pNode = TreeNode(nums[mid_index])
pNode.left = self.sortedArrayToBST(nums[:mid_index])
pNode.right = self.sortedArrayToBST(nums[mid_index+1:])
return pNode
if __name__ == '__main__':
sol = Solution()
max = sol.sortedArrayToBST([0,1,2,3,4,5,6,7,8,9])
print(max) |
d8a230f48b0d4ba259d17e6045c24c97f5e9f41f | pmontesd/katando_python | /20180915/02_enclavedeJa/03/enclavedeja.py | 949 | 3.609375 | 4 | def add_to_discount_list(season, discount_lists):
for discount_list in discount_lists:
if season not in discount_list:
discount_list.append(season)
return
discount_lists.append([season])
return
def get_series_price(seasons):
prices = {
"0": 2.5,
"1": 3,
"2": 3.5,
"3": 4,
"4": 4.5,
"5": 5
}
discount = {
"1": 1,
"2": 1,
"3": .9,
"4": .8,
"5": .7,
"6": .7
}
curr_discount = discount[str(len(seasons))]
return curr_discount * sum([prices[str(season)] for season in seasons if season != 5]) + seasons.count(5) * prices["5"]
def get_price(seasons):
discount_lists = []
for season in seasons:
add_to_discount_list(season, discount_lists)
print(discount_lists)
return round(sum([get_series_price(discount_list) for discount_list in discount_lists]), 2)
|
cff549d0b75f0c4c89963bac18ac44e670831753 | nikoGao/Leetcode | /371. Sum of Two Intergers/Answer.py | 1,078 | 3.875 | 4 | #Of course, Python doesn't use 8-bit numbers. It USED to use however many bits were native to your machine, but since that was non-portable, it has recently switched to using an INFINITE number of bits. Thus the number -5 is treated by bitwise operators as if it were written "...1111111111111111111011".
#int的0和正整数范围为0~0x7FFFFFFF,int负数的范围为-0x80000000~-1,因此,大于0x7FFFFFFF的其实是最高位为1(这是符号位)。这样算出来是把最高位不当成符号位,我们还需要对负数的情况进行修正。
#在具体实现上,我们可以先 &0x7FFFFFFF 然后取反,这样,-1变为-0x80000000(-2147483648) -2变为了-0x7FFFFFFF(-2147483647) ,因此,在^0x7FFFFFFF即可
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MAX_INT = 0x7FFFFFFF
MASK = 0x100000000
while b:
a, b = (a ^ b) % MASK, ((a & b) << 1) % MASK
return a if a <= MAX_INT else ~((a & MAX_INT) ^ MAX_INT)
|
1b3569b61139479fa81f30cfb0aed92285fe38fe | hzqfxx/python | /project/mydemo/oop/StudentTest.py | 1,313 | 4.09375 | 4 | #!C:/Users/xiaox/Anaconda3 python
# -*- coding: utf-8 -*-
' what? '
__author__ = 'xiaox'
class Student(object):
#属性加上__表示private
def __init__(self,name,age):
self.__name=name
self.age=age
def print2(self):
print("name=",self.__name,"age=",self.age)
def get_name(self):
return self.__name
def set_name(self, names):
self.__name = names
s1=Student("张三",18)
#实例可以添加属性,所以一个类的不同对象可以拥有不同的属性
s1.set_name("123")
s1.get_name()
print(s1.get_name())
#请把下面的Student对象的gender字段对外隐藏起来,用get_gender()和set_gender()代替,并检查参数有效性:
class Student(object):
def __init__(self, name, gender):
if isinstance(name,str) and isinstance(gender,str):
self.name = name
self.__gender = gender
else:
raise TypeError("参数类型错误")
def get_gender(self):
return self.__gender
def set_gender(self,gender):
self.__gender=gender
bart = Student('Bart', 'male')
if bart.get_gender() != 'male':
print('测试失败!')
else:
bart.set_gender('female')
if bart.get_gender() != 'female':
print('测试失败!')
else:
print('测试成功!')
|
13702c44995cf9906859770e45fb42e2b4f72f61 | imchasingkeys/ECE-2524 | /homework3/mult2.py | 796 | 3.625 | 4 | from sys import argv
import argparse
import sys
import fileinput
parser = argparse.ArgumentParser(description = "Process some numbers.")
parser.add_argument('infile', nargs='*')
args = parser.parse_args()
multiply = 1
for line in fileinput.input(args.infile):
try:
newVal = line
if(newVal == "\n"):
#Here would have if statement for --ignore-blank
#if it is there
continue
#else would do this
#print multiply
#multiply = 1
#continue
numVal = int(newVal)
multiply = multiply*numVal
except EOFError:
break;
except ValueError:
#Here would have an if statement for --ignore-non numeric
#if it is there
continue
#else do the following
#sys.stderr.write("Could not convert string to float: %s\n" % newVal)
#sys.exit(1)
print multiply
|
0e2c8ae71596e86304c9e478996432175eb06ba0 | MartinHvidberg/sudoku | /sudoku/SuDoKu_DaPr.py | 2,318 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8; -*-
""" DaPr - Data Preparation
Small and big pieces of code, to prepare data from wherever, to enter the EC-software SuDoKu universe
"""
import json
import os
def txt2ecs(s_sdktxt):
"""
Converts on line (string) with one SuDoKu in 'raw' text form
to one d_ecs (dictionary with an EC-software SuDoKu)
An d_ecs is essentially a dic, but with mandatory and optional fields,
that all have specific format rules ...
"""
s_sdktxt = s_sdktxt.strip()
if '#' in s_sdktxt: # Separate in SuDoKu and Comments, the only accepted main parts
s_sdk, s_com = [t.strip() for t in s_sdktxt.split('#', 1)]
else:
s_sdk, s_com = s_sdktxt.strip(), ''
if ',' in s_sdk: # Separate Givens from Solution, the only accepted sub-parts
s_gvn, s_sol = [t.strip() for t in s_sdk.split(',', 1)]
else:
s_gvn, s_sol = s_sdk.strip(), ''
if isinstance(s_gvn, str) and len(s_gvn) == 81: # Make a ecs
d_sdk = dict()
d_sdk['gvn'] = s_gvn.replace('0', '.')
if isinstance(s_sol, str) and len(s_sol) == 81: # There is a solution
d_sdk['sol'] = [s_sol]
if isinstance(s_com, str): # There is a comment
d_sdk['com'] = s_com
j_sdk = json.dumps(d_sdk)
else:
print(f" Warning: Can't make sensible SuDoKu from: {s_sdktxt}")
j_sdk = '{}' # return empty
##print(f" j: {j_sdk}")
return j_sdk
def fileconv_txt2ecs(s_fnin, s_fnou):
"""
Reads a 'raw' text SudoKu file, and
writes a .ecs file
Calls txt2ecs for the actual conversion
"""
with open(s_fnin) as f_in:
with open(s_fnou, 'w') as f_ou:
for row in f_in:
f_ou.write(str(txt2ecs(row.strip())) + '\n')
def main():
"""
Walk a dir and convert all relevant (.txt) files to .ecs files
"""
for root, dirs, files in os.walk("../data"):
for name in files:
if name.endswith('.txt'):
s_fnin = os.path.join(root, name)
print(s_fnin)
s_fnou = s_fnin.replace('.txt', '.ecs')
fileconv_txt2ecs(s_fnin, s_fnou)
else:
pass # print(f"wtf: {os.path.join(root, name)}")
if __name__ == '__main__':
main() |
26b18b75774a2c0d607d50b15f0e248eea55d505 | jeffriesd/competitive-programming | /other/addtwo.py | 1,027 | 3.75 | 4 | # problem:https://leetcode.com/problems/add-two-numbers/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
a = l1
b = l2
ans = None
carry = 0
while a or b:
a_val = a.val if a else 0
b_val = b.val if b else 0
sum_ab = a_val + b_val + carry
dig = sum_ab % 10
carry = sum_ab // 10
if ans:
c.next = ListNode(dig)
c = c.next
else:
ans = ListNode(dig)
c = ans
a = a.next if a else None
b = b.next if b else None
if carry:
c.next = ListNode(carry)
return ans
|
9cb79ba9753ee875827ca0db9b1da268717f8bf1 | ca-scribner/general_utils | /general_utils/trees.py | 5,526 | 4.3125 | 4 | from general_utils.dictionary import dictionaries_intersect
def count_leaves_of_tree(tree, this_level='<ROOT>', count_type='all'):
"""
Given a tree defined as a dictionary of lists or dicts, returns the number of leaves under each node
Args:
tree (dict): Tree defined as either:
dict of lists of keys that refer back to the original dict, eg:
{'<ROOT>': ['1', '2'],
'1': ['11', '12']
'2': ['21', '22', '23']
'23': ['231', '232']
}
(NOT IMPLEMENTED) dict of dicts, eg:
{'<ROOT>': {'1': {'11': None,
'12': None},
'2': {'21': None,
'22': None,
'23'" {'231': None,
'232': None,}
},
}
this_level (str): Key of tree level to start counting from
count_type (str): Specifies which type of count to be returned:
all: Returns a count of all descendants below a node (children, grandchildren, ...)
first: Returns a count of only first-generation descendants for each node (children)
last: Returns a count of only last-generation descendants (those without children). For
example:
{'<ROOT>': ['1', '2'],
'1': ['11', '12']
'2': ['21', '22', '23']
'23': ['231', '232']
}
would return:
{'<ROOT>': 6,
'1': 2,
'2': 4,
'23': 2,
}
Returns:
(dict): Dict of {key: children_count} for all nodes from this level down (with counts returned according to
count_type)
"""
try:
if isinstance(tree[this_level], list):
children = tree[this_level]
elif isinstance(tree[this_level], set):
children = list(tree[this_level])
elif isinstance(tree[this_level], dict):
raise NotImplementedError("Not implemented. Need code to know when at the bottom of a dict tree")
# children = list(tree[this_level].keys())
elif isinstance(tree[this_level], str):
raise TypeError(
"Lazy way to funnel strings into other type errors. "
"Strings might not raise an error if node labels are integers")
else:
raise ValueError(f"Unknown data type in tree[{this_level}]")
leaf_counts = {this_level: 0}
for child in children:
second_generation_counts = count_leaves_of_tree(tree, this_level=child, count_type=count_type)
# Error check to make sure the dictionaries don't intersect
if dictionaries_intersect(leaf_counts, second_generation_counts):
raise ValueError("Error: redundancy found in tree - two parents have the same child")
leaf_counts.update(second_generation_counts)
if count_type == 'all':
# Current level has this node plus any children under it
leaf_counts[this_level] += leaf_counts[child] + 1
elif count_type == 'first':
leaf_counts[this_level] += 1
elif count_type == 'last':
# If child has children, take that count. Otherwise, add 1 (as child is final-generation)
leaf_counts[this_level] += max(1, leaf_counts[child])
else:
raise ValueError(f'Invalid count_type {count_type}')
return leaf_counts
except (TypeError, KeyError):
# This node has no children as it is not a reference to other nodes
return {this_level: 0}
def count_future_generations(tree, this_level='<ROOT>'):
try:
if isinstance(tree[this_level], list):
children = tree[this_level]
elif isinstance(tree[this_level], set):
children = list(tree[this_level])
elif isinstance(tree[this_level], dict):
raise NotImplementedError("Code exists for dictionary defined by a tree of dicts, but it was never tested")
# children = list(tree[this_level].keys())
elif isinstance(tree[this_level], str):
raise TypeError(
"Lazy way to funnel strings into other type errors. "
"Strings might not raise an error if node labels are integers")
else:
raise ValueError(f"Unknown data type in tree[{this_level}]")
max_depth = 0
depths = {this_level: 0}
for child in children:
child_depths = count_future_generations(tree, this_level=child)
if dictionaries_intersect(depths, child_depths):
raise ValueError("Error: redundancy found in tree - two parents have the same child")
depths.update(child_depths)
depths[this_level] = max(depths[this_level], depths[child] + 1)
return depths
except (KeyError, TypeError):
return {this_level: 0}
|
bd1c79b62c3906e7c216d35649f99bc9e1faea54 | sharviljani/805 | /labs/week2/lab2.py | 2,497 | 4.15625 | 4 | """
Lab2.py
Sharvil Jani
1/30/2018
"""
def squared(num_list):
"""
Squares numbers in num_list
num_list: list of numbers
Returns: list of these numbers squared
"""
new_list = []
for num in num_list:
sq_num = pow(num, 2)
new_list.append(sq_num)
return new_list
def check_title(title_list):
"""
Removes strings in title_list that have numbers and aren't title case
title_list:list of strings
Returns:list of strings tat are titles
"""
new_list = []
for word in title_list:
if word.istitle():
new_list.append(word)
return new_list
def restock_inventory(inventory):
"""
Increases inventory of each item in dictionary by 10
inventory: a dictionary with:
key: string that is the name of the inventory item
value: integer that equals the number of that item currently on hand
Returns: updated dictionary where each inventory item is restocked
"""
new_dict = {} # Makes New Dictionary
for k, v in inventory.items(): #Runs the loop over the key to access values
new_dict[k] = v +10 # Adds 10 to the inventory of the key
return new_dict # Returns the new dictionary with updated values.
def filter_0_items(inventory):
"""
Removes items that have a value of 0 from a dictionary of inventories
inventory: dictionary with:
key: string that is the name of the inventory item
value: nteger that equals the number of that item currently on hand
Returns: the same inventory_dict with any item that had 0 quantity removed
"""
key_list = []
for k, v in inventory.items(): #Runs the loop over the key to access values
if inventory[k] == 0: # condition for Value of key as 0
key_list.append(k) # Append the list of keys with value 0
for items in key_list: # iterate through the list
del inventory[items] # delete the keys woth value 0 as given in above condition
return inventory # Returns the new dictionary with updated values.
def average_grades(grades):
"""
Takes grade values from a dictionary and averages them into a final grade
grades: a dictionary of grades with:
key: string of students name
value: list of integer grades received in class
Returns: dictionary that averages out the grades of each student
"""
avgDict = {} # creates new empty dictionary
for k,v in grades.items():# Runs loop to access Key and values in the dictionary
# v is the list of grades for student k
avgDict[k] = sum(v)/ float(len(v)) #Averages the values for key in the dictionary
return avgDict# returns the updated dictionary with average of the values |
238063c0065c0b18c194ea3d9bf0989caa3fb67c | joshavenue/TIL-python | /combo_tuple.py | 277 | 3.9375 | 4 | # If you have 2 list like this
# x = (1,2,3) and y = ('a','b','c')
# And you want to combine both of the tuples to this --> (1,'a',2,'b',3,'c')
# Use below
def combo(x,y):
tuple_list= []
for idx in range(len(x)):
tuple_list.append((x[idx],y[idx]))
return tuple_list
|
5d95e2436f7834e682461320b425400ae5e90c7d | Bakuutin/inf_sequence | /utils.py | 239 | 3.625 | 4 | def numbers_of_len(n):
return 9 * (10 ** (n-1))
def distanse_to_int(i):
length = len(str(i))
distanse = sum(n * numbers_of_len(n) for n in range(1, length))
distanse += length * (i - 10 ** (length-1))
return distanse
|
9334cd18fe076060151e2747b3969046a2b3f120 | kimuramaska/freeje | /task10.py | 208 | 4.125 | 4 | a = input("Введите первое число: ")
b = input("Введите второе число: ")
if a < b:
print(a + "<" + b)
elif a > b:
print(a + ">" + b)
if a == b:
print(a + "="+ b) |
e8ff3bf06b09e51210bf5425d26ff8d4d379e3a4 | bas20001/b21 | /7-8.py | 671 | 3.90625 | 4 | sandwich_orders = ['bacon','banana','xigua']
orders = []
finished_sandwiches = []
print("Today's sandwich have " + str(sandwich_orders))
print("Please input the number which sandwich did you want")
print("If you want to exit please input 'quit'")
switch = True
while switch != False :
order = raw_input("\nPlease input your order: ")
if order == "quit":
switch = False
elif order in sandwich_orders :
print("We will made: " + order + " sandwich for you")
order = sandwich_orders.remove(order)
finished_sandwiches.append(order)
elif order == "stock":
print(sandwich_orders)
else :
print("Sorry we have not " + order + " sandwich!")
|
3642bbdd2f1e3f34ccf06676194939f498d8f664 | MifengbushiMifeng/Pygo | /practice/practice5/first_PY_1.py | 595 | 4.03125 | 4 | # coding-utf-8
# practice filter in Python
def is_odd(n):
return n % 2 == 1
print filter(is_odd, [1, 2, 3, 4, 5, 7, 9, 10, 11])
print is_odd(2)
# def not_empty(s):
# return s and s.strip()
#
#
# # print not_empty()
# print not_empty(' ')
def not_empty(s):
return s and s.strip()
print not_empty(' ')
print filter(not_empty, ['A', '', 'B', None, 'C', ' '])
def is_prime(num):
if num == 2:
return True
for n in range(2, num):
if num % n == 0:
return False
return True
print filter(is_prime, [1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 23])
|
88583215b13be6e32fa96c2c30cd3c6a87d0b0a2 | wizplan/ml-essence | /02/ex2_18.py | 263 | 3.5 | 4 | import csv
data = [[1, "a", 1.1] # 리스트를 요소로 포함하는 리스트 생성
[2, "b", 1.2],
[3, "c", 1.3]]
with open("output.csv", "w") as f:
wr = csv.writer(f) # csv 파일에 저장
for row in data:
wr.writerow(row |
5b65ba83c63851dea049488e6056fe0282cdf501 | abdullatheef/Python-exercises | /chapter6/profile.py | 495 | 3.90625 | 4 | # Program to write a function profile, which takes a function as argument and returns a new function, which behaves exactly similar to the given function, except that it prints the time consumed in executing it
import time
def fib(n):
if n is 0 or n is 1:
return 1
else:
return fib(n-1) + fib(n-2)
def profile(f):
def g(x):
t=0
start=time.time()
v=f(x)
t=time.time()-start
return str(t)+' sec'
return g
fib = profile(fib)
print fib(30)
|
aa62185733742d174fd1e7d324dfdf506a24d5e6 | bingh0616/algorithms | /longest_palindromic_substring.py | 829 | 3.53125 | 4 | # problem description: https://leetcode.com/problems/longest-palindromic-substring/
class Solution:
# @param {string} s
# @return {string}
def longestPalindrome(self, s):
longest = 1
left, right = 0, 0
for i in range(len(s)-1):
new_max = max(self.get_length(i, i, s), self.get_length(i, i+1, s) if s[i] == s[i+1] else 1)
if new_max > longest:
longest = new_max
left, right = i-(new_max-1)/2, i+new_max/2
return s[left:right+1]
def get_length(self, left, right, s):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return right-left-1
def main():
print Solution().longestPalindrome('abb')
if __name__ == '__main__':
main()
|
238fb2d3ad8156adf9920e3c4b187cb7753d9de9 | j0hnk1m/leetcode | /medium/227.py | 470 | 3.59375 | 4 | s = "3+2*2"
num = 0
stack = []
op = '+'
s += '#'
for i in range(len(s)):
if s[i].isdigit():
num = 10 * num + int(s[i])
elif not s[i].isspace() or i == len(s) - 1:
if op == '-':
stack.append(-num)
elif op == '+':
stack.append(num)
elif op == '*':
stack.append(stack.pop() * num)
else:
stack.append(int(stack.pop() / num))
op = s[i]
num = 0
return sum(stack)
|
a94ba213d9d981936244a214a683d86ad4883c94 | krishsharan/guvi | /codekata/Character_count.py | 46 | 3.640625 | 4 | word=input()
print(len(word)-word.count(' '))
|
92bdcb4c12049fcc795dcce0f4bab054873c0add | romerik/GamePendu | /pendu.py | 3,227 | 3.625 | 4 | #coding:utf-8
from random import randrange
def menu():
print("Bienvenue dans pendu\n1-Appuie 1 pour voir l'aide\n2-Appuie 2 pour jouer")
while 1:
choix=input("Ton choix: ")
if choix!='1' and choix!='2':
print("Valeur du choix incorrecte")
continue
elif choix=='1' or choix=='2':
if choix=='1':
print("------------------Bienvenue---------------------\n---------------------AIDE----------------------------\nL'ordinateur choisit un mot au hasard dans une liste, un mot de huit lettres maximum. Le joueur tente de trouver les lettrescomposant le mot. À chaque coup, il saisit une lettre. Si la lettre figure dans le mot, l'ordinateur affiche le mot avec les lettres déjà trouvées. Celles qui ne le sont pas encore sont remplacées par des étoiles (*). Le joueur a 8 chances. Au delà, il a perdu.")
menu()
break
elif choix=='2':
jeu()
break
def jeu():
continuer_partie=0
while 1:
if continuer_partie==1:
break
try:
fichier=open("fichierpendu","r")
contenu=fichier.readlines()
fichier.close()
continuer_partie=0
while continuer_partie==0:
mot_a_deviner=contenu[randrange(len(contenu))]
mot_a_deviner=mot_a_deviner.replace('\n','')
score=len(mot_a_deviner)
chaine=str()
i=0
while i<len(mot_a_deviner):
chaine+='*'
i+=1
i=0
while chaine!=mot_a_deviner and score>=1:
print("Le mot a deviner est: {}".format(chaine))
caractere="par"
while len(caractere)!=1:
try:
caractere=input("Donner une lettre du mot: ")
except:
pass
nbre=mot_a_deviner.upper().find(caractere.upper())
if nbre!=-1:
copie_chaine=chaine
chaine=str()
i=0
while i<len(mot_a_deviner):
if mot_a_deviner.upper()[i]==caractere.upper():
chaine+=mot_a_deviner[i]
else:
chaine+=copie_chaine[i]
i+=1
else:
score=score-1
if score>=1:
print("----------------Bravo tu as trouvé le mot à dévinner et ton score est {}.\nLe mot a deviner est bien: {}".format(score,mot_a_deviner))
elif score==0:
print("---------------------Tu as perdu..Le mot était: {}".format(mot_a_deviner))
print("---------------->Continuer(o/n)?")
choix=input("Votre choix: ")
while choix!='o' and choix!='n':
choix=input("Votre choix: ")
if choix=='o':
continuer_partie=0
else:
continuer_partie=1
except:
fichier=open("fichierpendu","w")
fichier.write("Papa\nMaman\nTata\nAudrey\nYasmine\nDavid\nDaniel")
fichier.close()
"""def inserer_score(nom,score):
insertion=0
while insertion==0:
try:
fichier=open("score","r")
while fichier.readline():
if fichier.readline().find(nom):
i=fichier.readline().find(nom)
while fichier.readline()[i]!=':':
i+=1
i+=1
score_precedant=str()
while fichier.readline()[i]!='\n':
score_precedant+=fichier.readline()[i]
score_precedant=int(score_precedant)
score_precedant+=score
fichier.close()
fichier=open("score","w")
fichier.close()
except:
fichier=open("score","w")
fichier.close()"""
menu()
|
11a54d0fd3043bba52899228b67c58e03c13aea6 | salsafadhilah/salsa1 | /operator(salsa).py | 1,642 | 4.25 | 4 | print (" Operator Kondisi Pada Python \n")
print("\n 1. Arithmetic Operators\n")
#penjumlahan
a=10+4
#pengurangan
b=10-4
#perkalian
c=10*4
#pembagian
d=10/4
#floor(hasil bagi)
e=10//4
#modulus(sisa hasil bagi)
f=10%4
#exponent (pangkat)
g=10**4
print(a, b, c, d, e, f, g)
print("\n 2. Assighment Operators\n")
#sama dengan
a=3
print(a)
#tambah sama dengan
a+=2
print(a)
#ambil sama dengan
a-=2
print(a)
#kali sama dengan
a*=2
print(a)
#bagi sama dengan
a/=2
print(a)
#modulus sama dengan
a%=2
print(a)
#floor sama dengan
a//=2
print(a)
#pangkat sama dengan
a**=2
print(a)
print("\n 3. Comparison Operators\n")
#lebih dari
a=3>6
#kurang dari
b=3<6
#sama dengan
c=3==6
#faktorial sama dengan
d= 3!=6
#lebih dari sama dengan
e= 3>=6
#kurang dari sama dengan
f= 3<=6
print(a, b, c, d, f)
print("\n 4. Logical Operators\n")
#AND
a= True and True
b= True and False
c = False and False
print (a, b, c)
#OR
a= True or True
b= True or False
c= False or False
print(a, b, c)
#NOT
a= not True
b= not False
print(a, b)
print("\n 5. Bitwise Operator\n")
a=input("masukkan nilai a : ")
b = input("masukkan nilai b : ")
#And/&
c= a & b
print "a & b =%s" %c
#or/|
print"a | b =%s" %c
#xor/^
print"a ^ b =%s"%c
#negasi/~
print"a ~ b =%s"%c
#left shift/<<
print "a << b =%s"%c
#right shift
print"a >> b =%s"%c
print("\n 6. Membership Operators\n")
#in
a = [1, 2, 3, 4, 5]
print 5 in a
print 6 in a
#not in
b = [1, 2, 3, 4, 5]
print 5 not in b
print 6 not in b
print("\n 7. Identify Operators")
#is
a, b = 10, 10
print a is b #hasil akam true karena nilai sama
#is not
a, b = 10, 5
print a is not b #hasil akan true karena nilai berbeda
|
720dda52bee8e6fdf300ef79e70bbd2b14ec42c4 | ar90n/lab | /sandbox/algorithm/math/ternary_search.py | 571 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def ternary_search( l, r, f, n = 100, eps = 1e-24 ):
for i in range( n ):
ll = ( l + l + r ) / 3.0
rr = ( l + r + r ) / 3.0
vl = f( ll )
vr = f( rr )
if abs( vl - vr ) < eps:
break
if vl > vr :
r =rr
else:
l =ll
return ( l + r ) / 2.0
def main():
l = 0
r = 10
f = lambda x : -math.pow( ( x - 2.4 ), 2 )
print( ternary_search( l, r, f ) )
return
if __name__ == '__main__':
main()
|
4164d0049051fd39e1fdc7fe0da2a558fc4e1f55 | jamiezeminzhang/Leetcode_Python | /string/168_Excel_Sheet_Column_Title.py | 904 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 14 09:25:32 2016
168. Excel Sheet Column Title
Total Accepted: 51647 Total Submissions: 249119 Difficulty: Easy
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
@author: Jamie
"""
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
table = ['#','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S',\
'T','U','V','W','X','Y','Z']
res = []
ans = ''
while n>26:
d = (n-1)/26
res.append(n-26*d)
n = d
res.append(n)
res.reverse()
return ''.join(map(lambda x:table[x], res))
sol = Solution()
print sol.convertToTitle(703) |
5beb69b34c1be2388e027c12ea1f68425cbb29e0 | sardeepchhabra/TOC | /anagram.py | 154 | 4.09375 | 4 | str1=input()
str2=input()
if(sorted(str1)==sorted(str2)):
print("Both the strings are Anagrams")
else:
print("Both the strings are not anagrams")
|
e509c3fe0812b43c489a4d11e790392d372767e5 | SinghTejveer/stepic_python_in_action_eng | /solutions/s090.py | 277 | 4.25 | 4 | """
Find whether the given symbol is a digit.
Output "yes", is the symbol is a digit and "no" otherwise.
Please note that you should output words in a lowercase.
"""
def main():
print('yes' if input().rstrip().isdigit() else 'no')
if __name__ == '__main__':
main()
|
014a11f01b819b26c27e1a40fe2b71b5820b2dc9 | chinmayk1613/Artifical_Neural_Network | /Bank_Customer_Retention.py | 3,572 | 4.0625 | 4 | #import library
import numpy as np #contain maths
import tensorflow as tf
import pandas as pd #to import dataset and to manage data set
#Initializing the ANN#
ann = tf.keras.models.Sequential() #Intializes ANN as a sequence of layers
from sklearn.preprocessing import StandardScaler
sc_X=StandardScaler()
def ANN():
#####Data Pre-Processing######
#Importing Dataset#
dataset=pd.read_csv('Churn_Modelling.csv') #load data set
X=dataset.iloc[:,3:-1].values #independnt variables
y=dataset.iloc[:, -1].values #dependent data**************MISTAKE
#Encoding Categorical Data#
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
labelencoder_X=LabelEncoder()
X[:,2]=labelencoder_X.fit_transform(X[:,2])
#here problem is that machine learning algo thinks that 0<2 meaning
# France is less than spain but this is not the case at all
#hence we use dummy column buidling three column
#meanig put 1 if that France is there for ex. and put 0 if not.
ct=ColumnTransformer(transformers=[('encoder',OneHotEncoder(),[1])],remainder='passthrough')
X=np.array(ct.fit_transform(X))
#Split Data in train and test set#
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)
#Feature Scalling#It is very very important and compulsory when doing Deep Learning
X_train=sc_X.fit_transform(X_train)
X_test=sc_X.transform(X_test)
#####Building the ANN######
#Adding input and first hidden layer#
ann.add(tf.keras.layers.Dense(units=6,activation='relu'))
#Adding second hidden layer#
ann.add(tf.keras.layers.Dense(units=6,activation='relu'))
#Adding the output Layer#
ann.add(tf.keras.layers.Dense(units=1,activation='sigmoid'))
#when two or more output, actication fucntion would be #softmax
#####Training the ANN#####
#Compiling the ANN#
ann.compile(optimizer= 'adam',loss= 'binary_crossentropy',metrics=['accuracy'])
# when more than two output use #categorical_crossentropy
#Training the ANN on training set
ann.fit(X_train,y_train,batch_size=32,epochs=100)
#####Making the Predictions and evaluating the model#####
#####Predicting The Test Result#####
y_pred=ann.predict(X_test)
y_pred=(y_pred > 0.5)# True->1(0.5 to 1)---> High chance to leave bank False->0(0 to 0.5)---> Low chance to leave bank
#print(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1))
#####Confusion Metrics#####
# from sklearn.metrics import confusion_matrix, accuracy_score
# cm=confusion_matrix(y_test,y_pred)
# print(cm)
# print(accuracy_score(y_test,y_pred))
# from mlxtend.plotting import plot_confusion_matrix
# import matplotlib.pyplot as plt
# fig, ax = plot_confusion_matrix(conf_mat=cm)
# plt.show()
def single_test():
# Predicting the result of a single observation
print(ann.predict(sc_X.transform([[1, 0, 0, 500, 1, 40, 3, 100000, 2, 1, 1, 70000]])) > 0.5)
print(ann.predict(sc_X.transform([[1, 0, 0, 500, 1, 40, 3, 100000, 2, 1, 1, 70000]])))
# nned to input info in 2d double bracket array
# replace the categorical value as dummy value which map to one hot encoding values
# then predict this values on scalled value varible using transform method cause our maodel is trained on scalled values during
# feature scalling
if __name__ == '__main__':
ANN()
single_test()
|
d6ef63178b1a646669130000334f6919c3555a81 | ErdenebatSE/resource-of-python-book | /12-testing/prime/tests1.py | 815 | 3.703125 | 4 | import unittest
from prime import is_prime
class Tests(unittest.TestCase):
def test_1(self):
"""1 нь анхны тоо биш."""
self.assertFalse(is_prime(1))
def test_2(self):
"""2 нь анхны тоо мөн."""
self.assertTrue(is_prime(2))
def test_8(self):
"""8 нь анхны тоо биш."""
self.assertFalse(is_prime(8))
def test_11(self):
"""11 нь анхны тоо мөн."""
self.assertTrue(is_prime(11))
def test_25(self):
"""25 нь анхны тоо биш."""
self.assertFalse(is_prime(25))
def test_28(self):
"""28 нь анхны тоо биш."""
self.assertFalse(is_prime(28))
# Run each of the testing functions
if __name__ == "__main__":
unittest.main() |
b5eee1de545fa4652277d4c6ddddb90973de0992 | mattmakesmaps/python-algorithms-data-structures | /trees/parse_tree_exmple.py | 4,327 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'mkenny'
__date__ = '6/6/14'
from binary_tree_as_class import BinaryTree
import operator
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def buildParseTree(fpexp):
# split the expression into tokens.
fplist = fpexp.split()
pStack = Stack()
# Create a new binary tree with an empty root node.
eTree = BinaryTree('')
# Add node to stack
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
# create new node; push onto stack; move down.
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i not in ['+', '-', '*', '/', ')']:
# we have an operand.
currentTree.setRootVal(int(i))
# use the stack to get back to the parent.
parent = pStack.pop()
currentTree = parent
elif i in ['+', '-', '*', '/']:
# we have an operator.
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
# drop back down.
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
else:
raise ValueError
return eTree
def evaluate(parseTree):
"""
Recursively evaluate a Parse Tree.
The base case is a leaf node, representing
an operand (numerical value).
"""
opers = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
leftC = parseTree.getLeftChild()
rightC = parseTree.getRightChild()
# If we have a left and right child, evaluate them
# using the operator in the root node.
if leftC and rightC:
fn = opers[parseTree.getRootVal()]
return fn(evaluate(leftC), evaluate(rightC))
else:
return parseTree.getRootVal()
def preorderTraversal(tree):
"""
Reads from left to right going as deep as possible
for each node before moving right.
1. visit root node
2. traverse left subtree
3. traverse right subtree
"""
if tree:
print(tree.getRootVal())
preorderTraversal(tree.getLeftChild())
preorderTraversal(tree.getRightChild())
def postorderTraversal(tree):
"""
Reads from left to right going as deep as possible
for each node before moving right.
1. traverse left subtree
2. traverse right subtree
3. visit the root node
"""
if tree is not None:
postorderTraversal(tree.getLeftChild())
postorderTraversal(tree.getRightChild())
print(tree.getRootVal())
def postorderEval(tree):
opers = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
res1 = None
res2 = None
if tree:
res1 = postorderEval(tree.getLeftChild())
res2 = postorderEval(tree.getRightChild())
if res1 and res2:
return opers[tree.getRootVal()](res1, res2)
else:
# Base case, leaf node
return tree.getRootVal()
def inorderTraversal(tree):
if tree is not None:
inorderTraversal(tree.getLeftChild())
print(tree.getRootVal())
inorderTraversal(tree.getRightChild())
def printExp(tree):
sVal = ""
if tree:
sVal = '(' + printExp(tree.getLeftChild())
sVal = sVal + str(tree.getRootVal())
sVal = sVal + printExp(tree.getRightChild()) + ')'
return sVal
if __name__ == '__main__':
pt = buildParseTree("( ( 10 + 5 ) * 3 )")
print pt
print "evaluate(pt)"
print evaluate(pt)
print "Pre Order Traversal"
preorderTraversal(pt)
print "Post Order Traversal"
postorderTraversal(pt)
print "Post Order Eval"
print postorderEval(pt)
print "inorderTraversal"
print inorderTraversal(pt)
print "In Order Eval"
print printExp(pt)
|
3fcb17dabc8c7e57ad4fc6003c10c2339dcde76e | zin-lin/Unpredictable-Array-Competitive-Programming- | /Statics/definations.py | 224 | 3.6875 | 4 | def replacer(List,x,y):
for i in List:
if i==x:
List[List.index(i)]=y
def addAll(List):
var = 0
for i in range(len(List)-1):
var += abs( List[i]-List[i+1])
return var
|
a9c202511703fe2f8a1f8d02990dc58c63156d60 | godghdai/python | /案例式精讲Python开发技巧/第3章 对象迭代与反迭代技巧训练/3-4 如何进行反向迭代以及如何实现反向迭代.py | 786 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 3-4 如何进行反向迭代以及如何实现反向迭代
l = [1, 2, 3, 4, 5]
l.reverse()
print l
l = [1, 2, 3, 4, 5]
# 切片操作
print l[::-1]
for x in reversed(l):
print x
"""
l.__iter__()
l.__reversed__()
"""
class FloatRange:
def __init__(self, start, end, step=0.1):
self.start = start
self.end = end
self.step = step
def __iter__(self):
t = self.start
while t <= self.end:
yield t
t += self.step
def __reversed__(self):
t = self.end
while t >= self.start:
yield t
t -= self.step
for x in FloatRange(1.0, 4.0, 0.5): print x
print '--------------'
for x in reversed(FloatRange(1.0, 4.0, 0.5)):print x |
1293aedd5756b4b3e68f4315e3936414a5f0afec | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/removeAllAdjacentDuplicatesInString.py | 1,326 | 3.890625 | 4 | """
Remove All Adjacent Duplicates In String
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
Example 1:
Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
"""
"""
Algorithm
Initiate an empty output stack.
Iterate over all characters in the string.
Current element is equal to the last element in stack? Pop that last element out of stack.
Current element is not equal to the last element in stack? Add the current element into stack.
Convert stack into string and return it
Time: O(N)
Space: O(N-D) where D is the total length for all duplicates
"""
class Solution:
def removeDuplicates(self, S: str) -> str:
res = []
for ch in S:
if res and ch == res[-1]:
res.pop()
else:
res.append(ch)
return ''.join(res)
|
5e59333ea68a3a8a20e219f89c3d346ee2fbd7d7 | jerry3links/leetcode | /DifficultyMedium/sol322CoinChangeDP.py | 1,029 | 3.640625 | 4 | """
from DifficultyMedium.sol322CoinChangeDP import Solution
coins = [1,2,5]; amount = 3
ans = Solution().coinChange(coins, amount)
print("coins = {}; amount = {}".format(coins, amount))
print("ans = {}".format(ans))
"""
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
# beware of [1] and 0
if amount == 0:
return 0
dp = [float("inf") for _ in range(amount + 1)]
dp[0] = 0
coins.sort()
for coin in coins:
# print("for coin {}".format(coin))
# s = ""
for i in range(coin, amount + 1):
# s += str(i) + " "
# print("i = {}, amount - i = {}".format(i, amount - i))
dp[i] = min(dp[i], dp[i - coin] + 1)
# print(s)
# print(dp)
best = dp[-1]
if best == float("inf"):
return -1
return best
|
7f09372d409665866322429624e3fd0494ed2271 | ThomasYoungson/COSC326 | /11/Anagram.py | 2,960 | 4.1875 | 4 | """
Finds all anagrams from a word and dictionary.
Thomas Youngson - 7444007
Oliver Reid - 2569385
"""
"""
Imports
"""
import sys
from sys import argv
from collections import Counter
from collections import defaultdict
"""
Globals
"""
lineList = []
"""
Uses the start word (word) and parts_list words to create the anagram.
@param orig is the anagram word untouched.
@param word the start word that everything else need to be added to.
@param parts_list is the other words that can be added to the sentence.
@param letters_left is the letters left that need to be in the sentace.
@return the sentence formed from the starting word.
"""
def form_anagram(orig,word,parts_list,letters_left):
sentence = ""
sentence += word
ll = ""
letters_left_2 = letters_left[:]
parts_list_2 = parts_list[:]
for letter in word:
if letter in letters_left_2:
letters_left_2.remove(letter)
if(len(letters_left_2) > 0):
for char in letters_left_2:
ll += char
parts_list_2 = find_anagram_parts(parts_list_2,ll)
for wrdd in parts_list_2:
lineList.append(form_anagram(orig,word + " " + wrdd,parts_list,
letters_left))
else:
return sentence
return sentence
def isAnagram(w1, w2):
w1=list(w1.upper().replace(" ",""))
w2=list(w2.upper().replace(" ",""))
w2.sort()
w1.sort()
if w1==w2:
return True
else:
return False
"""
Sorts the anagram and each dict word alphabetically and checks if they are in
one another and added to a list.
@param dict is a list of dictionary words.
@param anagram is the string form of the anagram.
@return a list of all words that fit into the anagram.
"""
def find_anagram_parts(dict,anagram):
anList = []
for word in dict:
A = Counter(anagram)
B = Counter(word)
if (B & A) == B:
anList.append(word)
return anList
"""
Loads the dictionary and returns as a list.
"""
def load_dictionary():
dictionary = []
for word in sys.stdin:
dictionary.append(word.strip())
return dictionary
"""
Sorting words in each line
"""
def sorting(max):
listing = []
for group in lineList:
splitted = group.split()
if len(splitted) <= max:
splitted.sort()
splitted.sort(key=len,reverse=True)
stri = ""
for item in splitted:
stri += item + " "
listing.append(stri)
return listing
"""
Main function.
"""
def main():
words = load_dictionary()
max_words = int(argv[2])
anagram = ""
for letter in str(argv[1]):
if letter.islower():
anagram += letter
parts = find_anagram_parts(words,anagram)
orig = anagram
letters = []
for letter in anagram:
letters.append(letter)
for word in parts:
if isAnagram(word,anagram):
lineList.append(word)
else:
form_anagram(orig,word,parts,letters)
#Sort each line of the list.
listing = sorting(max_words)
list_2 = []
for wd in listing:
if wd not in list_2 and isAnagram(wd,anagram):
list_2.append(wd)
list_2.sort()
list_2.sort(key=len,reverse=False)
for i in list_2:
print(i)
main()
|
aa169e6df913b11060a32d7d757c1cbddce986ac | BEEMRAO/1 | /pro7.py | 92 | 3.546875 | 4 | a=int(input())
b=0
for i in range(0,a):
if(pow(2,i)>a):
break
b=a-pow(2,i)
print(b)
|
a1e546572d11b1424c7abf4e0ed9c2c022ee9807 | WDHSTechClub/raspberry-pi | /TechClub/fuelConsumption/components/mymath.py | 4,332 | 3.734375 | 4 | from components import arrays
def calcTorque(rpm:int, throttle:int)->float:
"""
Method to calculate torque
rpm: between 1400 and 3600
throttle: percentage divisible by 10
"""
if (throttle == 0):
return 0
# Ensure RPM is between 1400 and 3600
if (rpm >= 1400 and rpm <= 3600):
# Parse RPM as a string and strip decimal values
rString = str(int(rpm))
try:
# Only executes if no errors finding the "00" in rString
test = (rString.index("00") != 2)
# Gets torque at rpm if rpm is divisible by 100
return findTorque(rpm / 100, throttle)
except:
# The first two digits of RPM (used for torque lookup)
gets = int(rString[0:2])
# The last two digits of RPM (used for weighting torque multiplcation)
remain = int(rString[2:4])
# Find and weight the two torque values
t1 = findTorque(gets, throttle) * (float(100 - remain) / 100)
t2 = findTorque(gets + 1, throttle) * (float(remain) / 100)
# Return the sum of weighted torques
return t1 + t2
elif (rpm >= 3600):
return float(0)
else:
raise LookupError('rpm out of range! -> ' + str(rpm))
def calcBSFC(rpm:int, throttle:int)->float:
"""
Method to calculate brake specific fuel consumption
rpm: between 1400 and 3600
throttle: percentage divisible by 10
"""
if (rpm >= 1400 and rpm <= 3600):
return findBSFC(int(rpm / 100), throttle)
else:
return float(0)
def calcPower(rpm:int, throttle:int)->float:
"""
Method to calculate power
rpm: between 1400 and 3600
throttle: percentage divisible by 10
"""
if (rpm >= 1400 and rpm <= 3600):
return findPower(int(rpm / 100), throttle)
else:
return float(0)
def findTorque(msbRPM:int, throttle:int)->float:
"""
Lookup method to find torques in arrays.py
msbRPM: two-digit rpm (rpm / 100)
thorttle: throttle percentage divisble by 10
"""
# msbRPM = rpm / 100
if ((type(msbRPM) == int) and (type(throttle) == int)):
return findTuple(msbRPM, throttle)[0]
else:
raise TypeError('Type Error with _findTorque() call!')
def findPower(msbRPM:int, throttle:int)->float:
"""
Lookup method to find powers in arrays.py
msbRPM: two-digit rpm (rpm / 100)
thorttle: throttle percentage divisble by 10
"""
# msbRPM = rpm / 100
if ((type(msbRPM) == int) and (type(throttle) == int)):
return findTuple(msbRPM, throttle)[1]
else:
raise TypeError('Type Error with _findPower() call!')
def findBSFC(msbRPM:int, throttle:int)->float:
"""
Lookup method to find BSFC's in arrays.py
msbRPM: two-digit rpm (rpm / 100)
thorttle: throttle percentage divisble by 10
"""
# msbRPM = rpm / 100
if ((type(msbRPM) == int) and (type(throttle) == int)):
return findTuple(msbRPM, throttle)[2]
else:
raise TypeError('Type Error with _findBSFC() call!')
def findTuple(msbRPM:int, throttle:int)->tuple:
"""
Lookup method to find tuples in arrays.py
msbRPM: two-digit rpm (rpm / 100)
thorttle: throttle percentage divisble by 10
"""
# msbRPM = rpm / 100
print("369-", msbRPM, throttle)
if ((type(msbRPM) == int) and (type(throttle) == int)):
# Validate RPM Value
if (msbRPM >= 14 and msbRPM <= 36):
# Get Throttle Row based on RPM
index = int(msbRPM - 14)
# Validate Throttle Value to reduce chance of error
if ((throttle % 10 == 0) and (throttle > 0 and throttle <= 100)):
# Define array name to retrieve torque from based on throttle
arrayName = str("arrays.t" + str(int(throttle)) + "throttleArray")
# Get torque at certain throttle and RPM
cmd = str(arrayName + "[" + str(index) + "]")
tup = eval(cmd)
return tup
else:
return (0, 0, 0)
else:
return (0, 0, 0)
else:
raise TypeError('Type Error with __findTuple() call!') |
4aaac230de4ad2e5bb06a2f7514c3ef1a4beb125 | mttaborturtle/Image-converters | /JPGtoPNGconvert.py | 997 | 3.765625 | 4 | import sys
import os
from PIL import Image
# Take in the image folder/image and the dest folder
# from the command line
image_folder = sys.argv[1]
dest_folder = sys.argv[2]
# Check to see if the destination folder already
# exists and create it if it does not
try:
if os.path.isdir(dest_folder) == False:
os.mkdir(dest_folder)
print('Sucessfully created folder ' + dest_folder)
else:
print('Your intended dir already exists')
except OSError:
print("Creation of the directory %s failed" % dest_folder)
# Convert all images in folder from JPG to PNG
image_folder_dir = os.listdir(image_folder)
for filename in image_folder_dir:
if filename.endswith('.jpg'):
img = Image.open(f'{image_folder}{filename}')
clean_name = os.path.splitext(filename)[0]
img.save(f'{dest_folder}{clean_name}.png', 'png')
print(f'converted {filename} and saved it to: {dest_folder}')
else:
continue
print('Image Conversion Complete!')
|
40cd73adb31d2efe9a92c1f73add1cad972bbf97 | srinathalla/python | /algo/arrays/moveElementToEnd.py | 282 | 3.640625 | 4 | def moveElementToEnd(array, toMove):
i = 0
j = 0
while j < len(array):
if array[j] != toMove:
swap(array, i, j)
i += 1
j += 1
return array
def swap(array, i, j):
tmp = array[i]
array[i] = array[j]
array[j] = tmp
|
65d43f20f26c84940f72c6a26b9f40bd62726098 | phillipj06/Python-ProjectEuler | /problem20.py | 357 | 4 | 4 | from math import factorial
from utils import timeIt, sumDigits
'''
n! means n x (n - 1) x ... x 3 x 2 x 1 For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
'''
@timeIt
def sumUp():
print sumDigits(factorial(100))
sumUp()
|
920d3e936a6c858a23af86507b2444259b16a421 | jasimrashid/Data-Structures | /doubly_linked_list/doubly_linked_list.py | 9,282 | 4.34375 | 4 | """
Each ListNode holds a reference to its previous node
as well as its next node in the List.
"""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.prev = prev
self.value = value
self.next = next
"""
Our doubly-linked list class. It holds references to
the list's head and tail nodes.
"""
class DoublyLinkedList:
def __init__(self, node=None):
self.head = node
self.tail = node
self.length = 1 if node is not None else 0
def __len__(self):
return self.length
"""
Wraps the given value in a ListNode and inserts it
as the new head of the list. Don't forget to handle
the old head node's previous pointer accordingly.
"""
def add_to_head(self, value):
# create a new node setting it to value
node = ListNode(value)
if self.head == None or self.tail == None:
self.head = node
self.tail = node
else:
# link node's next to head & link head's prev to new node
self.head.prev = node
node.next = self.head
# update head to new new
self.head = node
self.length += 1
"""
Removes the List's current head node, making the
current head's next node the new head of the List.
Returns the value of the removed Node.
"""
def remove_from_head(self):
val = self.head.value
# remove head+1's prev to Null (do we have to set the head's next to null? )
if self.head == self.tail:
self.head = None
self.tail = None
else:
self.head.next.prev = None
# point head to head +1
self.head = self.head.next
self.length -= 1
return val
"""
Wraps the given value in a ListNode and inserts it
as the new tail of the list. Don't forget to handle
the old tail node's next pointer accordingly.
"""
def add_to_tail(self, value):
node = ListNode(value)
if self.head is None or self.tail is None:
self.head = node
self.tail = node
else:
self.tail.next = node
node.prev = self.tail
self.tail = node
self.length += 1
"""
Removes the List's current tail node, making the
current tail's previous node the new tail of the List.
Returns the value of the removed Node.
"""
def remove_from_tail(self):
val = self.tail.value
if self.head == self.tail:
self.head = None
self.tail = None
else:
self.tail.prev.next = None
self.tail = self.tail.prev
self.length -= 1
return val
"""
Removes the input node from its current spot in the
List and inserts it as the new head node of the List.
"""
def move_to_front(self, node):
found = False
current_node = self.head
while found == False:
if current_node == node:
found = True
if current_node != self.head:
if current_node == self.tail: # if current node is tail
current_node.prev.next = None
self.tail = current_node.prev
else:
current_node.prev.next = current_node.next
current_node.next.prev = current_node.prev
current_node.next = self.head
self.head.prev = current_node
self.head = current_node
else:
found = False
current_node = current_node.next
"""
Removes the input node from its current spot in the
List and inserts it as the new tail node of the List.
"""
def move_to_end(self, node):
found = False
current_node = self.head
while found == False:
if current_node == node:
found = True
if current_node != self.tail:
if current_node == self.head: # if current node is head
current_node.next.prev = None
self.head = current_node.next
else:
current_node.next.prev = current_node.prev
current_node.prev.next = current_node.next
current_node.prev = self.tail
self.tail.next = current_node
self.tail = current_node
else:
found = False
current_node = current_node.next
"""
Deletes the input node from the List, preserving the
order of the other elements of the List.
"""
def delete(self, node):
# traverse the linked list to find the node "current node"
# point current node's previous's node's next to current node's next node and vice versa
found = False
current_node = self.head
while found == False:
if current_node == node:
found = True
self.length -= 1
print('condition: ',self.head == self.tail)
if self.head == self.tail:
self.head = None
self.tail = None
elif current_node == self.head: # if current node is head
current_node.next.prev = None
self.head = current_node.next
elif current_node == self.tail:
current_node.prev.next = None
self.tail = current_node.prev
else:
current_node.next.prev = current_node.prev
current_node.prev.next = current_node.next
else:
found = False
current_node = current_node.next
"""
Finds and returns the maximum value of all the nodes
in the List.
"""
def get_max(self):
current_node = self.head
max = current_node.value
while True:
if current_node.value > max:
max = current_node.value
if current_node.next is None:
break
else:
current_node = current_node.next
return max
node = ListNode(1)
ll = DoublyLinkedList(node)
ll.remove_from_head()
# self.assertIsNone(self.dll.head)
# self.assertIsNone(self.dll.tail)
# self.assertEqual(len(self.dll), 0)
ll.add_to_head(2)
# self.assertEqual(self.dll.head.value, 2)
# self.assertEqual(self.dll.tail.value, 2)
# self.assertEqual(len(self.dll), 1)
# self.assertEqual(self.dll.remove_from_head(), 2)
ll.remove_from_head()
# ll.remove_from_head()
# # self.assertIsNone(self.dll.head)
# # self.assertIsNone(self.dll.tail)
# # self.assertEqual(len(self.dll), 0)
# ll.add_to_head(2)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# breakpoint()
# ll.add_to_head(2)
# ll.add_to_head(4)
# ll.add_to_head(2)
# ll.add_to_head(0)
# print('max: ',ll.get_max())
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.add_to_tail(1)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.add_to_tail('d')
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.remove_from_tail()
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.remove_from_head()
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.add_to_tail('b')
# ll.add_to_tail('c')
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# # print("----")
# ll.move_to_front(ll.tail)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.move_to_front(ll.tail)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.move_to_front(ll.tail.prev)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.move_to_front(ll.head)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.move_to_front(ll.head.next)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# # ll.move_to_front(ll.tail)
# # print(ll.head.value)
# # print(ll.tail.value)
# # print(ll.length)
# # ll.move_to_front(ll.tail)
# # print(ll.head.value)
# # print(ll.tail.value)
# # print(ll.length)
# ll.move_to_end(ll.tail)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# print("-----")
# ll.move_to_end(ll.tail)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.move_to_end(ll.head)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.move_to_end(ll.head.next)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.move_to_end(ll.tail.prev)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.delete(ll.tail)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.delete(ll.head)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.delete(ll.head.next)
# print(ll.head.value)
# print(ll.tail.value)
# print(ll.length)
# ll.delete(ll.head)
# print(ll.head)
# print(ll.tail)
# print(ll.length) |
8f222b0bc2beaa9d4234b0bda32712bbeeccc9df | Miguelflj/Prog1 | /UriLista/media3.py | 797 | 3.578125 | 4 | #UFMT CCOMP
#LISTA 1 MEDIA COM PESOS
#MIGUEL FREITAS
def main():
entrada = raw_input()
n1,n2,n3,n4 = entrada.split()
n1 = float(n1)
n2 = float(n2)
n3 = float(n3)
n4 = float(n4)
media = ((n1*2)+(n2*3)+(n3*4)+(n4))/10
print "Media: %0.1f" % (media)
if (media >= 7.0):
print "Aluno aprovado."
if (media >= 5.0 and media <= 6.9):
print "Aluno em exame."
ne = float(input())
media = (ne + media) /2
print "Nota do exame: %0.1f" % (ne)
if (media >= 5.0):
print "Aluno aprovado."
print "Media final: %0.1f" % (media)
else:
print "Aluno reprovado."
print "Media final: %0.1f" % (media)
if (media < 5.0):
print "Aluno reprovado."
main() |
ea2a473b48f40ba85028ec8a33f07ad1213b341b | MarcelaSilverio/exercicios-uri | /Iniciante/python/problema1113.py | 431 | 3.671875 | 4 | # Autor: Marcela Prata Silverio
# Turma: INF3A
if __name__ == "__main__":
respostas = []
while True:
dupla = input().split()
valores = [int(val) for val in dupla]
if valores[0] == valores[1]:
break
elif valores[0] > valores[1]:
respostas.append("Decrescente")
else:
respostas.append("Crescente")
for resposta in respostas:
print(resposta) |
b5a60d9c390bcb683e157744a15a29efe6368cf8 | TheMellyBee/udacity-projects | /support-classes/linear-alg/quiz4.py | 716 | 3.8125 | 4 | from vector import Vector
print "One"
v1 = Vector([-7.579,-7.88])
v2 = Vector([22.737,23.64])
print "Parallel: "
print v1.is_parallel(v2)
print "Orthogonal: "
print v1.is_orthogonal(v2)
print
print "Two"
v1 = Vector([-2.029,9.97,4.172])
v2 = Vector([-9.231,-6.639, -7.245])
print "Parallel: "
print v1.is_parallel(v2)
print "Orthogonal: "
print v1.is_orthogonal(v2)
print
print "Three"
v1 = Vector([-2.328, -7.284, -1.214])
v2 = Vector([-1.821, 1.072, -2.94])
print "Parallel: "
print v1.is_parallel(v2)
print "Orthogonal: "
print v1.is_orthogonal(v2)
print
print "Four"
v1 = Vector([2.118, 4.827])
v2 = Vector([0, 0])
print "Parallel: "
print v1.is_parallel(v2)
print "Orthogonal: "
print v1.is_orthogonal(v2)
|
b7e4032f3f20ba7fd264cd7bff65c9f854950b72 | RoshchynaA/Python | /step3_3.py | 391 | 3.96875 | 4 | def my_func(num1, num2, num3):
my_list = [num1, num2, num3]
min_el = min(my_list)
my_list.remove(min_el)
return sum(my_list)
num1 = int(input('Введите число: '))
num2 = int(input('Введите еще одно число: '))
num3 = int(input('И третье число, пожалуйста, укажите: '))
print(my_func(num1, num2, num3))
|
2e805f7ce0d6bd36bcee40e63ce097094eb30b9b | rabeehrz/isqip19 | /Day1/Hackerrank/staircase.py | 130 | 3.8125 | 4 | #https://www.hackerrank.com/challenges/staircase/problem
n = int(input())
for i in range(1,n+1):
print(" "*int(n-i) + "#"*int(i)) |
8be942ead7630ad828ccd31d82bbbb6836b486ea | tommahs/HU_Prog | /Les4/wordcount.py | 513 | 3.671875 | 4 | tekst = ('Wow echt al die mensen zoveel mensen nee mensen nee')
counters = {}
def wordCount(text):
newList = text.split(' ')
for text in newList:
if text in counters:
counters[text] += 1
else:
counters[text] = 1
for text in counters:
if counters[text] == 1:
print('{:8} appears {} time'.format(text, counters[text]))
else:
print('{:8} appears {} times'.format(text, counters[text]))
print(counters)
wordCount(tekst) |
d4c2bd94e04186aaf69287747e16cc46fa1f3391 | Under0Cover/Curso_Em_Video | /Python/Móulo 03/lista_exercicios_075.py | 989 | 4.1875 | 4 | # DESAFIO 075
# TUPLAS
# CRIE UM PROGRAMA QUE LEIA 04 VALORES PELO TECLADO E GUARDE-OS EM UMA TUPLA.
# NO FINAL MOSTRE:
# A) QUANTAS VEZES APARECEU O VALOR 9
# B) EM QUE POSIÇÃO FOI DIGITADO O PRIMEIRO VALOR 3
# C) QUAIS FORAM OS NÚMEROS PARES
numeros = (int(input('Digite um número: ')), int(input('Digite outro número: ')),
int(input('Digite mais um número: ')), int(input('Digite o último número: ')))
print(f'Você digitou os valores {numeros}')
print(f'O valor 9 apareceu: {numeros.count(9)} vezes.')
if 3 in numeros:
print(f'O valor 3 apareceu na {numeros.index(3) + 1}ª posição')
else:
print('O valor 3 não foi digitado em nenhuma posição.')
print('Os valores pares digitados foram: ', end='')
for n in numeros:
if n % 2 == 0:
print(n, end='')
# EU ACHEI A PARTE FINAL DO PROGRAMA RUIM
# PORÉM EU NÃO CONSEGUI PENSAR NUMA SOLUÇÃO EM QUE ENVOLVESSE DUAS ALTERNATIVAS NO CASO DE HAVER OU NÃO NÚMEROS PARES
|
e1bf7893168719f27795d77d72d9808c2d95206d | enextus/python_learnstuff | /fibonacci_recursive_02.py | 358 | 3.625 | 4 | """
# Ruby
def fibonacci(n)
if n < 3
1
else
fibonacci(n - 1) + fibonacci(n - 2)
end
end
(1..16).each {|n| puts "#{fibonacci(n)}, "}
puts "..."
"""
def fibonacci(n):
if n < 3:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
#for x in range(101):
# fibonacci(x)
print("Import was succesfull")
|
1fcd32afde23820a23a62df5df1567175711b07a | bitshares/DEXBot | /dexbot/styles.py | 528 | 3.984375 | 4 | """ This is helper file to print out strings in different colours
"""
def style(value, styling):
return styling + value + '\033[0m'
def green(value):
return style(value, '\033[92m')
def blue(value):
return style(value, '\033[94m')
def yellow(value):
return style(value, '\033[93m')
def red(value):
return style(value, '\033[91m')
def pink(value):
return style(value, '\033[95m')
def bold(value):
return style(value, '\033[1m')
def underline(value):
return style(value, '\033[4m')
|
1c80ec1b22b9bc0bb3758e6259c1943bea1877e6 | Gabriel-ino/python_basics | /exp_val.py | 285 | 3.890625 | 4 | lista = str(input('Digite aqui sua expressão:'))
if lista.index(')') < lista.index('('):
print('Sua expressão está errada!')
else:
if lista.count('(') == lista.count(')'):
print('Sua expressão está correta!')
else:
print('Sua expressão está errada!') |
b96334582b2631ad0b5489223e311b6a44f4e574 | liang12k/PandasLearning | /PythonForDataAnalysis/chapter4/ndarray/datatypes.py | 1,164 | 3.734375 | 4 | """
dtype: data type is a special obj containing info the
ndarray needs to interpret chunk of memory as
a particular type of data
** homegenous throughout np.array
syntax format:
<typename><bytes> # bytes = bits per element
ex: int64, float32
astype: converting array dtype to new dtype
** this always creates a new array (copy of data)
"""
import numpy as np
# explicitly casting array from one dtype to another
arr1 = np.arange(5)
# arr1.dtype # dtype('int64')
float_arr1 = arr.astype(np.float64)
# float_arr1.dtype # dtype('float64')
arr2 = np.array([3.7,-1.2,-2.6,0.5,12.9,10.1])
# arr2.dtype # dtype('float64')
# arr2.astype(np.int32) # array([ 3, -1, -2, 0, 12, 10], dtype=int32)
numeric_strings1 = np.array(
["1.25","-9.6","42"], dtype=np.string_
)
# # **Note: casting as float (same as np.float)
# numeric_strings1.astype(float) # array([ 1.25, -9.6 , 42. ])
# # using another array's dtype for converting
int_array = np.arange(10)
calibers = np.array(
[.22,.270,.357,.380,.44,.50],
dtype=np.float64
)
# int_array.astype(calibers.dtype)
# array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
|
076c69465b3c96fe6e5fe93b967e52d02a4531d0 | niall-oc/things | /codility/min_abs_sum_of_two.py | 2,931 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/15-caterpillar_method/min_abs_sum_of_two/
Let A be a non-empty array consisting of N integers.
The abs sum of two for a pair of indices (P, Q) is the absolute value
|A[P] + A[Q]|, for 0 ≤ P ≤ Q < N.
For example, the following array A:
A[0] = 1
A[1] = 4
A[2] = -3
has pairs of indices (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2).
The abs sum of two for the pair (0, 0) is A[0] + A[0] = |1 + 1| = 2.
The abs sum of two for the pair (0, 1) is A[0] + A[1] = |1 + 4| = 5.
The abs sum of two for the pair (0, 2) is A[0] + A[2] = |1 + (−3)| = 2.
The abs sum of two for the pair (1, 1) is A[1] + A[1] = |4 + 4| = 8.
The abs sum of two for the pair (1, 2) is A[1] + A[2] = |4 + (−3)| = 1.
The abs sum of two for the pair (2, 2) is A[2] + A[2] = |(−3) + (−3)| = 6.
Write a function:
def solution(A)
that, given a non-empty array A consisting of N integers, returns the minimal
abs sum of two for any pair of indices in this array.
For example, given the following array A:
A[0] = 1
A[1] = 4
A[2] = -3
the function should return 1, as explained above.
Given array A:
A[0] = -8
A[1] = 4
A[2] = 5
A[3] =-10
A[4] = 3
the function should return |(−8) + 5| = 3.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range
[−1,000,000,000..1,000,000,000].
100% solution #https://app.codility.com/demo/results/trainingQC5CQ4-G2D/
O(N * log(N))
"""
import time
def brute_force_validator(A):
n = len(A)
A.sort()
minimal = 2000000000
for low in range(n):
for high in range(n):
minimal = min(abs(A[low] + A[high]), minimal)
return minimal
def solution(A):
n = len(A)
A.sort()
head = n-1
tail = 0
m = 2000000000
while tail <= head:
m = min(m, abs( A[tail] + A[head] ))
if abs(A[tail]) > abs(A[head]) : # This will decide how to move the catepillar
tail +=1
else:
head -= 1
return m
if __name__ == '__main__':
tests = (
(1, ([1, 4, -3],)),
(3, ([-8, 4, 5, -10, 3],)),
(0, ([0],)),
(4, ([2, 2],)),
(6, ([8, 5, 3, 4, 6, 8],)),
# (None, ([random.randint(1, 10000) for i in range(100)],)),
)
for expected, args in tests:
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
if expected is None:
print(f'SPEED-TEST {len(args[0])} args finished in {toc - tic:0.8f} seconds')
continue # This is just a speed test
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!') |
90f58459631fae301ee115daa47394868e8ee1c9 | Areking-RS/Code-jam-2021 | /game/utils.py | 2,392 | 3.8125 | 4 | import dataclasses
import math
from functools import partial
from typing import ClassVar, Tuple, Union
Numeric = Union[int, float]
@dataclasses.dataclass
class Vector2(object):
"""Representation of 2D vectors and points."""
x: Numeric = 0
y: Numeric = 0
ZERO: ClassVar['Vector2']
UP: ClassVar['Vector2']
DOWN: ClassVar['Vector2']
LEFT: ClassVar['Vector2']
RIGHT: ClassVar['Vector2']
def __repr__(self):
return '({0}, {1})'.format(self.x, self.y)
def __iter__(self):
return iter((self.x, self.y))
def to_tuple(self) -> Tuple[Numeric, Numeric]:
"""
Get the tuple representation of this vector.
:return: Tuple containing x and y coordinates
"""
return self.x, self.y
def add(self, other: 'Vector2') -> 'Vector2':
"""
Add another vector to this vector.
:param other: Vector to add
:return: A new vector that is the addition of this vector and other
"""
return Vector2(self.x + other.x, self.y + other.y)
def __add__(self, other: 'Vector2'):
return self.add(other)
def sub(self, other: 'Vector2') -> 'Vector2':
"""
Subtract another vector from this vector.
:param other: Vector to subtract
:return: A new vector that is the subtraction of other from self
"""
return Vector2(self.x - other.x, self.y - other.y)
def __sub__(self, other: 'Vector2'):
return self.sub(other)
def mag(self) -> Numeric:
"""Get the magnitude of this vector."""
return math.sqrt(self.x * self.x + self.y * self.y)
def scale(self, scalar: Numeric) -> 'Vector2':
"""
Scale this vector by a scalar.
:param scalar: A scalar to multiply this vector by
:return: A scaled version of this vector
"""
return Vector2(self.x * scalar, self.y * scalar)
def __mul__(self, other: Numeric):
return self.scale(other)
def normalized(self) -> 'Vector2':
"""Get a normalized (unit) vector of this vector"""
mag = self.mag()
return Vector2() if mag == 0 else Vector2(self.x // mag, self.y // mag)
Vector2.ZERO = Vector2()
Vector2.UP = Vector2(0, -1)
Vector2.DOWN = Vector2(0, 1)
Vector2.LEFT = Vector2(-1, 0)
Vector2.RIGHT = Vector2(1, 0)
echo = partial(print, end='', flush=True)
|
41422a6b3f03a36d681ac232063ffc9790b59d58 | DieAntonie/eventstore-python | /src/DungeonsDragons/Game/Length.py | 928 | 3.703125 | 4 | import math
class Length(object):
pass
class Inch(Length):
def __init__(self, inches: int):
self.inches = inches
pass
class Foot(Length):
def __init__(self, feet: int, inches=0):
self.inches = inches % 12
self.feet = feet + math.trunc(inches/12)
pass
class Yard(Length):
def __init__(self, yards: int, feet=0, inches=0):
self.inches = inches % 12
self.feet = (feet + math.trunc(inches/12)) % 3
self.yards = yards + math.trunc((feet + math.trunc(inches/12))/3)
pass
class Mile(Length):
def __init__(self, miles: int, yards=0, feet=0, inches=0):
self.inches = inches % 12
self.feet = (feet + math.trunc(inches/12)) % 3
self.yards = yards + math.trunc((feet + math.trunc(inches/12))/3) % 1760
self.miles = miles + math.trunc((yards + math.trunc((feet + math.trunc(inches/12))/3))/1760)
pass
|
6b44dc8e79ed515f2df6a4acf3635d77380a6b57 | armandoroman1016/Sorting | /src/recursive_sorting/recursive_sorting.py | 2,334 | 4.3125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# TO-DO
a_index = 0
b_index = 0
print('a', arrA)
print('b', arrB)
if elements == 2:
smaller = min(arrA[0], arrB[0])
larger = max(arrA[0], arrB[0])
merged_arr[0] = smaller
merged_arr[1] = larger
return merged_arr
else:
for i in range(0, elements):
if a_index == len(arrA):
a_index = len(arrA)
merged_arr[i] = arrB[b_index]
b_index += 1
elif b_index == len(arrB):
b_index = len(arrB)
merged_arr[i] = arrA[a_index]
a_index += 1
elif arrA[a_index] < arrB[b_index]:
merged_arr[i] = arrA[a_index]
a_index += 1
elif arrA[a_index] > arrB[b_index]:
merged_arr[i] = arrB[b_index]
b_index += 1
elif arrA[a_index] == arrB[b_index]:
merged_arr[i] = arrA[a_index]
a_index += 1
return merged_arr
# TO-DO: implement the Merge Sort function below USING RECURSION
# Algorithm
'''
1. While your data set contains more than one item, split it in half
2. Once you have gotten down to a single element, you have also *sorted* that element
(a single element cannot be "out of order")
3. Start merging your single lists of one element together into larger, sorted sets
4. Repeat step 3 until the entire data set has been reassembled
'''
def merge_sort(arr):
# TO-DO
if len(arr) > 1:
middle_index = len(arr) // 2
left = arr[0: middle_index]
right = arr[middle_index:]
s_left = merge_sort(left)
s_right = merge_sort(right)
arr = merge(s_left, s_right)
return arr
print(merge_sort([10, 5, 99, 12, 65, 49, -10, 18, 33, 45, 88, 10]))
# STRETCH: implement an in-place merge sort algorithm
def merge_in_place(arr, start, mid, end):
# TO-DO
return arr
def merge_sort_in_place(arr, l, r):
# TO-DO
return arr
# STRETCH: implement the Timsort function below
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
def timsort(arr):
return arr
|
acc1598c9cc5ad11ebf51e83cb7bce767efc75a2 | zzhang115/python01 | /function.py | 415 | 3.5 | 4 | def sayHello():
print "hello world"
def saySth(name):
print "hello baby %s" %name
sayHello()
saySth("zzc")
def name_info(name, age, job, nationnality="Chinese"):
global gl, gl1
gl = 123
gl1 = 100
print "your name: %s age %d your nationnality:%s" %(name, age, nationnality)
return name
result = name_info("zzc", 23, "programmar", )
print result
print gl, gl1
import os
os.system("ls")
|
4806ca2245222beadc103ed628ecf23ce97fcecb | pomelo072/DataStructure | /ch03queue/queue.py | 1,041 | 3.953125 | 4 | # coding = utf-8
__author__ = "LY"
__time__ = "2018/5/7"
class Queue(object):
"""docstring for Queue"""
def __init__(self):
'''使用列表创建队列'''
self.items = []
def inQueue(self, data):
'''入队列(头出尾进)'''
self.items.append(data)
def isEmpty(self):
'''判断队列是否为空'''
return self.items == []
def deQueue(self):
'''出队列'''
if self.items == []:
print("Queue is empty")
return
del self.items[0]
def size(self):
'''输出队列大小'''
return len(self.items)
def delete(self):
'''销毁队列'''
k = len(self.items)
i = 0
while k > 0:
del self.items[i]
k -= 1
del k
del i
print("Delete queue successfully!")
if '__main__' == __name__:
q = Queue()
List = [1,2,3,4]
for i in List:
q.inQueue(i)
print("队列为:", q.items)
print("队列是否为空:", "空" if q.isEmpty()==True else "非空")
print("队列大小为:", q.size())
q.deQueue()
print("出队列:", q.items)
print("队列大小为:", q.size())
q.delete()
|
dd5dc9af4ce1c615b39006c624a6864dd1fd3aae | dohyekim/hello | /class_trythis.py | 830 | 3.984375 | 4 |
class Square:
def __init__(self):
self.name = Square
def multiply(self, a, b):
return a * b
class Paral(Square):
def __init__(self):
self.name = Paral
class Rec(Paral):
def __init__(self):
self.name = Rec
paral = Square()
print(paral.multiply(2,4))
square = Paral()
print(square.multiply(6,1))
rec = Square()
print(rec.multiply(9,2))
while (True):
cmd = input("사각형의 종류, 밑변, 높이>>> ")
if cmd == "quit":
break
cmds=cmd.split(',')
a = int(cmds[1])
b = int(cmds[2])
kind = cmds[0]
x = ["직사각형", "평행사변형"]
if kind == x[0]:
print(square.multiply(a,b))
elif kind == x[1]:
print(paral.multiply(a,b))
elif kind != x:
print("다시 써 주세요.")
|
c40e271a2b789ce4e377d859722bd5e544acc4a0 | PyeongGang-Kim/TIL | /algorithm/swex/7701.py | 289 | 3.59375 | 4 | T = int(input())
for t in range(1, T+1):
N = int(input())
tmp = set()
for _ in range(N):
tmp.add(input())
r = []
for word in tmp:
r.append([len(word), word])
r.sort(key=lambda x: (x[0], x[1]))
print('#%d' %t)
for i, w in r:
print(w)
|
05174165125cd145af3463647789e02503f018fc | Mateus-Silva11/AulasPython | /Aula_2/Aula2.py | 636 | 3.75 | 4 | #variaveis
idade = 16
salario = 67770
nome = "Mateus"
verdadeiro = True
falso = False
print("="*50, "\n"*2)
#Print Normal
print("\t Calypso mania", "Joelma é top")
print("\t Exalta mania")
print("\t",'Nome :',nome ,'idade', idade ,'Salario', salario )
print("\t",'Verdadeiro',verdadeiro)
print("\t",'Falso',falso)
#print Format
print('\t','Nome: {} idade: {} Salario: {} Verdadeiro : {} falso: {}'
.format(nome , idade , salario , verdadeiro , falso))
#printo Terceira opição interpolação de strings
print('\t',f'Nome: {nome} idade: {idade} Salario: {salario} Verdadeiro : {verdadeiro} falso: {falso}')
print("\n"*2,'='*50) |
c482fa97048710a800cf3a686fb5c6057ece03f1 | shravankumargulvadi/Majority-Element | /majority element.py | 3,184 | 3.546875 | 4 |
# coding: utf-8
# In[121]:
import numpy as np
import sys
def merge_sort(sequence):
if len(sequence)==1:
return sequence
else:
partition= round(len(sequence)/2)
sort_sequence1=merge_sort(sequence[:partition])
sort_sequence2=merge_sort(sequence[partition:])
sorted_array=[]
while len(sort_sequence1)!=0 and len(sort_sequence2)!=0:
#print(sort_sequence1)
#print(sort_sequence2)
#print(sort_sequence1[0])
#print(sort_sequence2[0])
if sort_sequence1[0]<=sort_sequence2[0]:
sorted_array.append(sort_sequence1[0])
sort_sequence1.pop(0)
#print(sorted_array)
else:
sorted_array.append(sort_sequence2[0])
sort_sequence2.pop(0)
#print(sorted_array)
if len(sort_sequence1)!=0:
for i in sort_sequence1:
sorted_array.append(i)
elif len(sort_sequence2)!=0:
for j in sort_sequence2:
sorted_array.append(j)
return sorted_array
def binary_search(sequence,low,high,element):#a is input sequence b is list of elements to search
index=low+round((high-low)/2)
#print(index)
if sequence[index]==element:
return index
elif sequence[index]<element:
if low==index:
return -1
else:
low=index
return binary_search(sequence,low,high,element)
else:
if high==index:
return -1
else:
high=index
return binary_search(sequence,low,high,element)
def repetition_count(sequence,index):
item=sequence[index]
k=index+1
flag=0
count=1
if k<len(sequence):
while flag!=1:
if sequence[k]==item:
count=count+1
if k== (len(sequence)-1):
break
k=k+1
else:
flag=1
flag=0
j=index-1
if j>0:
while flag!=1:
if sequence[j]==item:
count=count+1
if j==0:
break
j=j-1
else:
flag=1
return count
def majority_element(sequence):
sorted_seq=merge_sort(sequence)
#print(sorted_seq)
for i in range(len(sequence)):
#index=binary_search(sorted_seq,0,len(sequence),i)
#print('index, count')
#print(index)
count=repetition_count(sorted_seq,i)
#print(count)
if count>(len(sequence)/2):
#print(i)
return 1
return 0
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
a = data[1:]
print(majority_element(a))
# In[123]:
# In[21]:
|
7675a26de260df54a40f3b32842ecd56886a4e0f | MicheleCattaneo/USI_Algo_Bible | /DynamicProgramming/LongestPalindrome.py | 852 | 3.859375 | 4 | '''
Longest Palindromic Subsequence ( can be not consecutive )
ABBDCACB -> BCACB
'''
def longestPalinSequence(S):
if len(S) <= 1:
return S
else:
first = S[0] #first char
last = S[-1] #last char
body = S[1:-1] # in between
# if first and last char are the same, include
# them in the solution and find solution for the middle part
if first == last:
return first + longestPalinSequence(body) + last
else:
#otherwise find solution including only the first, or only the last
pos1 = longestPalinSequence(body+last)
pos2 = longestPalinSequence(first+body)
res = pos1 if len(pos1) > len(pos2) else pos2
return res
print(longestPalinSequence("ABBDCACB"))
print(longestPalinSequence("AXBYCSDREPFWFQETDICKBLA")) |
1b0c358167232971494ba494ee67f04dc40483a2 | OlavEspenes/INF200-2019-Exersices | /src/olav_espenes_ex/ex04/myrand.py | 774 | 3.625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Olav Espenes'
__email__ = 'olaves@nmbu.no'
class LCGRand:
def __init__(self, seed):
self.seed = seed
self.a = 16807
self.m = 2 ** 31 - 1
def rand(self):
while True:
self.seed = self.a * self.seed % self.m
return self.seed
class ListRand:
def __init__(self, a_list):
self.list = a_list
self.idx = 0
def rand(self):
self.idx += 1
if self.idx > len(self.list):
raise RuntimeError('Cannot make a list longer then input')
else:
return self.list[self.idx-1]
if __name__ == '__main__':
LCG = LCGRand(20)
LR = ListRand([1, 2, 3])
for _ in range(3):
print(LCG.rand())
print(LR.rand())
|
8e2ad43cc07c4b39aa0b4b3202b17d3ec639807e | surajgholap/python-Misc | /BasicOop.py | 3,508 | 4.5625 | 5 | # From Corey Schafer's OOP tutorial
import datetime
class Employee:
"""Classes allows us to logical group the
data(Attributes) and functions(methods)
in a way to reuse. Its basically an blueprint
for creating instances."""
"Class variables are shared by all the instances of the class."
num_of_emp = 0
raise_amount = 1.02
def __init__(self, fname, lname, age, salary):
"""This is the constructor for the Employee.
Instance variables like fname, lname...salary
are unique to each instance."""
self.fname = fname
self.lname = lname
self.email = fname + '.' + lname + '@company.com'
self.age = age
self.salary = salary
Employee.num_of_emp += 1
# Special methods are also called as magic/dunder methods.
# __repr__ is an unambiguous representation of an object and is
# used for logging debugging etc. Used by developers.
def __repr__(self):
return "Employee({}, {}, {})".format(self.fname, self.lname,
self.age)
# __str__ is more readable representation of an object.
# Used by end users in general.
def __str__(self):
return "{} - {}".format(self.fname, self.email)
def fullname(self): # regular method.
return '{} {}'.format(self.fname, self.lname)
def salary_raise(self):
self.salary = self.salary * self.raise_amount
@classmethod
def set_raise(cls, amount): # class method.
cls.raise_amount = amount
# class methods can also be used as an alternative constructor.
@classmethod
def from_string(cls, emp_str):
fname, lname, age, salary = emp_str.split('-')
return cls(fname, lname, age, salary)
# static methods: when you don't access instance methods or attributes.
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
class Developer(Employee):
raise_amount = 1.10
def __init__(self, fname, lname, age, salary, progl):
Employee.__init__(self, fname, lname, age, salary)
# super().__init__(fname, lname, age, salary)
self.progl = progl
class Manager(Employee):
raise_amount = 1.20
def __init__(self, fname, lname, age, salary, employees=None):
Employee.__init__(self, fname, lname, age, salary)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_emp(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def rem_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)
def list_emp(self):
for emp in self.employees:
print(emp.fullname())
emp_1 = Employee('John', 'Leon', 25, 90000)
emp_2 = Employee('hn', 'on', 26, 90000)
my_date = datetime.date(2017, 5, 2)
print(Employee.is_workday(my_date))
mgr = Manager('J', 'L', 25, 90000, [emp_1])
mgr.add_emp(emp_2)
mgr.list_emp()
print(mgr.fullname())
print(emp_1.fullname())
print(Employee.num_of_emp)
print(emp_1)
Employee.set_raise(2)
Employee.salary_raise(emp_1)
print(emp_1.salary)
emp1str = 's-g-22-100000'
new_emp = (Employee.from_string(emp1str))
print(new_emp.__dict__)
d1 = Developer('S', 'E', 22, 111000, 'python')
print(d1.progl)
print(d1.email)
print(isinstance(d1, Developer))
print(isinstance(mgr, Developer))
print(issubclass(Manager, Employee))
|
4d71cee2273545a768a4e1111eab474ebcf64121 | ChrisClaude/data-structure-algorithms | /challenges/leetcode/challenge_1.py | 654 | 3.828125 | 4 |
def challenge_one(secretMessage):
# @author: Elvis Gene
letters = [letter for letter in secretMessage]
msg_len = len(secretMessage)
for i in range(msg_len):
# Get numeric value of the letter
num = ord(letters[i])
if num % 2 == 0:
num = num - 1
else:
num = num + 1
# Get the letter of the new value
new_letter = chr(num)
# Appending or replacing the new character
letters[i] = new_letter
secretMessage = ''.join(letters)
print(secretMessage)
# Append or replace?
# Only capital letters?
challenge_one('ABC')
challenge_one('BAHHHDHJSJKDH')
|
7274a00666e4df68b2bb9df97f2a038766e88124 | nvs-abhilash/CorrectMe | /correctme/edit_distance.py | 1,092 | 3.84375 | 4 | # http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python
def levenshtein_distance(s, t):
m, n = len(s), len(t)
d = [list(range(n + 1))]
d += [[i] for i in range(1, m + 1)]
for i in range(0, m):
for j in range(0, n):
cost = 1
if s[i] == t[j]: cost = 0
d[i + 1].append(min(d[i][j + 1] + 1, # deletion
d[i + 1][j] + 1, # insertion
d[i][j] + cost) # substitution
)
return d[m][n]
# Call this function when making API calls.
class EditDistance:
def __init__(self, dist_func=levenshtein_distance):
self._dist_func = dist_func
def get_edit_distance(self, dictionary_string, input_string):
dictionary_string = dictionary_string.lower()
input_string = input_string.lower()
if dictionary_string == input_string:
edit_distance = 0
else:
edit_distance = self._dist_func(dictionary_string, input_string)
return edit_distance
|
1cf80eb013249143b3b259b42929ad3e4cd04c9b | kavyaachu47/luminarpython | /luminar/Flowcontrols/sortnos.py | 580 | 4.0625 | 4 | num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
first=0
second=0
third=0
if((num1>num2)&(num1>num3)):
first=num1
print(first)
if(num2>num3):
second=num2
print(second)
elif(num3>num2):
third=num3
print(third)
elif((num2>num1)&(num2>num3)):
first=num2
print(first)
if(num1>num3):
second=num1
print(num1)
else:
print(num3)
elif ((num3>num1)&(num3>num2)):
print(num3)
else:
print("not in order")
|
ae01924975c5caf41eb6727ffc0e7df346ac6af6 | http-www-testyantra-com/Shilpa_Sony | /oops/Bank.py | 2,354 | 3.84375 | 4 | class Bank:
Bank_name = "ICICI"
L_ROI = 14
MBL = "Mumbai"
def __init__(self,Name,age,phno,email,Bal = 0):
self.Name = Name
self.age = age
self.phno = phno
self.email = email
self.Bal = Bal
def deposit(self,amt):
self.Bal += amt
self.success()
def withdraw(self,amt = 0):
if amt == 0:
amt = self.get_amount()
if amt > self.Bal:
self.failure()
print("insufficient balance")
return self.Bal == amt
@staticmethod
def get_amount():
amount = int(input("enter the amount "))
return amount
@staticmethod
def failure():
print("transaction failure")
@classmethod
def change_BName(cls, new = " "):
if new == " ":
cls.Bank_name = new
cls.success()
@classmethod
def modify_ROI(cls, new = 0):
if new == 0:
new = cls.get_ROI()
cls.ROI = new
cls.success()
@staticmethod
def get_ROI():
new = float(input("enter new ROI "))
return new
@staticmethod
def sub(a,b):
return a-b
def display(self):
self.Name,self.age,self.phno,self.email,self.Bal
def modify(self,Name = " ",age = 0,email = ""):
if Name != " ":
self.Name = Name
if age != 0:
self.age = age
if email != email:
self.email = email
self.success()
@staticmethod
def success():
print("transaction successfull")
class Bank2(Bank):
def __init__(self,Name,age,phno,email,pan,aadhar,Bal = 0):
super(Bank2,self).__init__(Name,age,phno,email,Bal = 0)
self.pan = pan
self.aadhar = aadhar
def add_aadhar_pan(self,pan,aadhar):
self.pan = pan
self.aadhar = aadhar
def display(self):
print("aadhar number is ", self.aadhar)
print("pan is ", self.pan)
Reeta = Bank("reeta",25,934234923782142,"reeta@gmail.com",10000)
Seetha = Bank("reeta",26,934234923782142,"SEETHA@gmail.com",10000)
Bank.modify_ROI()
Reeta.display()
Reeta.withdraw()
Bank.get_amount()
Bank.display(Reeta)
# Bank.withdraw(Reeta,1000)
Bank.change_BName()
o2 = Bank2("reeta",25,934234923782142,"reeta@gmail.com","pan123","aad6789",10000)
Bank2.add_aadhar_pan(1231566151,"dhgdshfsdhfhsdf")
o2.display()
|
275e22ab8a67b5d011269c277c4a3599d6c19079 | chxj1992/leetcode-exercise | /subject_lcof/64/_1.py | 328 | 3.703125 | 4 | import unittest
class Solution:
def sumNums(self, n: int) -> int:
return n and n + self.sumNums(n - 1)
class Test(unittest.TestCase):
def test(self):
s = Solution()
self.assertEqual(6, s.sumNums(3))
self.assertEqual(45, s.sumNums(9))
if __name__ == '__main__':
unittest.main()
|
21b0e204dd66301c33aa51ac87784f3bd58b00c0 | EddyScotch/GWC-Python | /survey.py | 2,393 | 3.65625 | 4 | import json
import os
def fix_data(file_name):
with open(file_name, "r") as f:
a = "".join(f.readlines())
fixed_data = ",".join(a.split(']['))
with open(file_name, "w") as f:
f.write(json.dumps(fixed_data))
def save_data(file_name, data):
f = open(file_name, "r+")
old_data = json.load(f) # return a list of data that was already in data.json
old_data.extend(answers) # combine old data with the new data
f.write(json.dumps(old_data))
f.close()
user_input = True
questions = {
"Name" : "What is your name? ",
"Age" : "How old are you? ",
"Birthday" : "When is your birthday? ",
"Home" : "Where is your hometown? ",
"Favorite_icecream" : "What is your favorite flavor of icecream? ",
}
answers = []
def saveResp():
user_input2 = True
response = {}
for c, q in questions.items():
response[c] = input(q)
answers.append(response)
while user_input2:
ask = input ('\n'+"Would you like to view all entries? ")
if ask == "yes" or ask == "Yes":
print (answers)
user_input2 = False
elif ask == "no" or ask == "No":
user_input2 = False
else:
print ("Sorry, I don't understand")
while user_input:
userInput = input('\n'+"Would you like to complete this survey? ")
if userInput == "yes" or userInput == "Yes":
saveResp()
elif userInput == "no" or userInput == "No":
user_input = False
else:
print ("Sorry, I don't understand")
if os.path.isfile(answers.json):
file = open ("answers.json", "r+")
old_data = json.load(file)
old_data.extend(answers)
file.write(json.dumps(old_data))
file.close()
else:
file = open("answers.json", "w")
file.write(json.dumps(data))
file.close()
# # IF FILE EXISTS, JUST APPEND TO OLD DATA
# if os.path.isfile("data.json"):
# f = open("data.json", "r+")
# #m = json.dumps(f)
# old_data = json.load(f) # return a list of data that was already in data.json
# for d in old_data:
# print(d)
# #old_data.extend(data) # combine old data with the new data
# f.write(json.dumps(data))
# f.close()
#
# # FILE DOES NOT EXIST SO CREATE NEW FILE
# else:
#with open("data.json", "w") as f:
# f.write(json.dumps(data))
|
03d9e109afb71ae60356c7902edc12114334a216 | mrbrightside17/PythonScripts | /October7th/printingPatterns.py | 236 | 3.875 | 4 | def printPattern():
quantity=int(raw_input("Enter quantity of repetitions\n"))
for x in range(0,quantity):
string=''
for x in range(0,quantity):
string+=str('*')
print string
printPattern()
|
3712053bbf4932c7bbe64c35799d65fa216ca7b0 | lqhcpsgbl/python-standard-library-note | /collections/DefaultDict/defaultdict_example.py | 220 | 3.78125 | 4 | # DefaultDict: dict has default value of any key
from collections import defaultdict
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue', 'black']
d = defaultdict(list)
for i in colors:
d[i].append(i)
print(d)
|
fba3c38e703b29e56a9619bd5db910ea44eb8577 | Yomo/Development | /Tutorial/StandardPython/Tutorial.py | 228 | 3.84375 | 4 | '''
Created on 04.01.2013
@author: Timme
'''
def Fibonacci(a, b):
return b, a+b
a = 1
b = 2
p = lambda a,b: 'a:' + str(a) + ' b:' + str(b)
for i in range(10):
a,b = Fibonacci(a,b)
print p(a,b)
|
b49f985cb78db47398912d98d1bc4fe0128c96e6 | lolzao/aprendendoPython | /desafio40.py | 520 | 3.859375 | 4 | '''
40 - programa que le 2 notas de um aluno, calcula a média, mostrando uma mensagem no final, de acordo com a média:
- média abaixo de 5.0, reprovado
- média entre 5.0 e 6.9, recuperação
- média 7.0 ou superior, aprovado
'''
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
media = (n1 + n2) / 2
print(f'Sua média é {media:.1f}')
if media < 5.0:
print('Reprovado')
elif media >= 5.0 and media <=6.9:
print('Recuperação')
else:
print('Aprovado')
|
75b6e769ff4bdd559d07f4782cb2b76f72b1f1ca | leeyongjoo/solved-algorithm-problem | /programmers/level2/[스택큐] 프린터.py | 809 | 3.671875 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/42587?language=python3
def solution(priorities, location):
from collections import deque
dq_priotities = deque([(p, True) if i == location else (p, False) for i, p in enumerate(priorities)])
dq_sorted_priotities = deque(sorted(priorities, reverse=True))
time = 0
while True:
while dq_priotities[0][0] != dq_sorted_priotities[0]:
dq_priotities.append(dq_priotities.popleft())
time += 1
pri, loc = dq_priotities.popleft()
dq_sorted_priotities.popleft()
if loc:
return time
if __name__ == "__main__":
print(solution([2, 1, 3, 2], 2))
print(solution([2, 1, 3, 2], 2) == 1)
print(solution([1, 1, 9, 1, 1, 1], 0))
print(solution([1, 1, 9, 1, 1, 1], 0) == 5)
|
0a3d64550c53878277da3666c5899c6e8f08e783 | mohammedsiraj08/python_assignment | /pythonassignment/2ndprogram.py | 322 | 4 | 4 | # name:sai eshwar reddy kottapally
# roll no:100519733022
# program to print largest and second largest of a list
n=eval(input("enter the set size:"))
a=[]
for i in range(n):
a.append(eval(input("enter values a["+str(i)+"]:")))
a.sort()
print("largest number in the list is",a[-1])
print("second largest number in the list is",a[-2])
|
4d1e9934df6346b3c38c32a9a2dc9f5562ee1929 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/The Complete Data Structures and Algorithms Course in Python/Section 8 Python Lists/lists.py | 1,165 | 3.75 | 4 | # # Created by Elshad Karimov on 10/04/2020.
# # Copyright © 2020 AppMillers. All rights reserved.
#
# # Accessing/Traversing the list
#
# shoppingList = ['Milk', 'Cheese', 'Butter']
#
# ___ i __ ra__ le_ ?
# ? ? = ? ? + "+"
# # print(?[i])
# empty # list
# ___ i __ ?
# print("I am empty")
#
#
# # Update/Insert - List
#
# myList = [1,2,3,4,5,6,7]
# print(myList)
# myList.insert(4,15)
#
# myList.ap..(55)
#
# newList = [11,12,13,14]
# myList.ex..(newList)
# print(myList)
#
#
# # Searching for an element in the List
# myList = [10,20,30,40,50,60,70,80,90]
#
# ___ searchinList li__ value
# ___ i __ li__
# __ i __ v..
# r_ li__.i__ ?
# r_ 'The value does not exist in the list'
#
# print ? ? 100
#
#
# # List operations / functions
# total = 0
# count = 0
# w__ (T..
# inp = i..('Enter a number: ')
# __ inp __ 'done' b__
# value = fl__ i..
# total = ? + ?
# count = ? + 1
# average = ? / ?
#
# print('Average:' ?
#
#
#
# numlist = li__(
# w__ T..
# inp = i..('Enter a number: ')
# __ inp __ 'done' b__
# value = fl__ ?
# ?.ap.. ?
#
# average = su_ ? / le_ ?
# print('Average:' ?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.