blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
146a1363c28f972231c7885636b83a3c00651c94 | gad26032/python_study | /basics/string_tasks.py | 720 | 4 | 4 | s = "abcdef"
# 0. вывести на экран каждый символ
for i in s:
print(i)
# 1. вывести на экран каждый второй символ
print(s[1::2])
# 2. Вывести на экран индекс буквы "e"
print(len(s[3::-1]))
# 3. Вывести на экран буквы в обратном порядке
print(s[::-1])
# 4. Ввести "a_b_c_d_e_f"
s2 = "_"
print(s2.join(s))
# 5. Вывести на экран первые 3 буквы
print(s[:3])
'abc'
# 6. Вывести на экран последние 3 буквы
print(s[3:])
'def'
# 7. Вывести на экран все буквы кроме первой и последней
print(s[1:-1])
'bcde' |
5880536ee3e5982049b16eb9804183304d679a9c | shadowstep666/phamminhhoang-fundamental-c4e25 | /section3/homework_day3/2.6sheep.py | 1,022 | 3.5625 | 4 | size = [ 5 ,7,300 , 90 ,24,50,75]
print("Hello , my name is hiep and these are my sheep size :")
print(size)
print(" now my biggest sheep has size",max(size), " let's shear it")
x = size.index(max(size))
size[x]=8
print("after shearing , here is my flock")
print(size)
month = int(input(" nhap vao so thang thu hoach :"))
for i in range (month):
print("month",i+1,":")
x = 0
y = int(len(size))
for j in range(y):
size[x]=size[j]+50
x+=1
print("one month has pass , now here is my flock")
print(size)
if i < month-1 :
print(" now my biggest sheep has size",max(size), " let's shear it")
x = size.index(max(size))
size[x]=8
print("after shearing , here is my flock")
print(size)
else :
sum = 0
for k in range(y):
sum += size[k]
print("my flock is total",sum)
money = sum * 2
print("I would get" , sum , " *2$=", money,"$" )
|
543feb476cd90a33cf73360eec32aaa5472c50be | Harryhar1412/assignement4 | /eight.py | 322 | 4.40625 | 4 | # 8. Write a Python program to remove the nthindex character from a nonempty
# string
def truncate_char(str, n):
starttext = str[:n]
endtext = str[n + 1:]
return starttext + endtext
input_string = input("Enter String value: ")
pos = int(input("Enter the Position: "))
print(truncate_char(input_string, pos))
|
2ae2e976399151cfce8d34159e252a10b171dc3f | ABHINAVPRIYADARSHI/Computer-Networks | /crc.py | 2,452 | 3.765625 | 4 | def divide(divisor,codeword,new_codeword):
rem=[]
for i in codeword:
if(len(rem)==len(divisor)):
break
else:
rem.append(i)
cont=0
cont1=len(divisor)-1
new_divisor=divisor[:]
while(cont!=len(new_codeword)):
for i in range(len(divisor)):
if((rem[i]==1 and divisor[i]==1) or (rem[i]==0 and divisor[i]==0)):
rem[i]=0
else:
rem[i]=1
cont+=1
cont1+=1
if(cont==len(new_codeword)):
break
for i in range(len(divisor)):
if(i==len(divisor)-1):
rem[i]=codeword[cont1]
else:
rem[i]=rem[i+1]
if(rem[0]==0):
for i in range(len(divisor)):
divisor[i]=0
else:
for i in range(len(divisor)):
divisor[i]=new_divisor[i]
rem.pop(0)
return(rem)
#starting of program
codeword=[int(x) for x in input("enter the data: ").split()]
new_codeword=codeword[:]
new_codeword2=new_codeword[:]
divisor=[1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1]
#divisor=[1,1,1,1,1]
print("generating polynomial: ","".join([str(x) for x in divisor]))
codeword.extend([0 for x in range(len(divisor)-1)])
print("modified dataword: ","".join([str(x) for x in codeword]))
#calling the function divide
rem=divide(divisor,codeword,new_codeword)
print("CRC checksum is : ","".join([str(x) for x in rem]))
new_codeword.extend(rem)
print("the final codeword transmitted is: ","".join([str(x) for x in new_codeword]))
choice=int(input("do you want to do test error detection 0:No 1:yes"))
if(choice==0):
print("No error detected")
else:
errorcodeword=new_codeword[:]
pos=int(input("enter the position at which you want to insert error "))
if(errorcodeword[pos-1]==0):
errorcodeword[pos-1]=1
print("erroneous data is: ","".join([str(x) for x in errorcodeword ]))
rem=divide(divisor,errorcodeword,new_codeword2)
print("CRC checksum is: ","".join([str(x) for x in rem]))
print("error detected")
else:
errorcodeword[pos-1]=0
print("erroneous data is: ","".join([str(x) for x in errorcodeword ]))
rem=divide(divisor,errorcodeword,new_codeword2)
print("CRC checksum is: ","".join([str(x) for x in rem]))
print("error detected")
|
0f735c43bda9c3dbe67cd93f3024050e2c442eb2 | liujinshun/Python | /class.py | 546 | 4 | 4 | #!/usr/bin/python
#coding=utf-8
# 类名首字母大写
class Person(object):
def __init__(self,name):
self.name = name
age = 10
#第一位self不传参
def color(self,c):
print "%s is %s,he is %d"%(self.name,c,self.age)
boy1 = Person("Jame")
boy1.age = 12
print boy1.age
print boy1.name
boy1.face = "帅"
boy1.color("block")
print boy1.face
print "-------------------------"
boy2 = Person("Lilei")
print boy2.age
print boy2.name
boy2.color("write")
print "----------------------------"
print Person.age
|
3df918b51af606232e5fff239bf71bf1b580eaeb | girlingf/CSE331 | /CircularQueue.py | 5,044 | 4.125 | 4 | class CircularQueue(object):
def __init__(self, capacity=2):
"""
Initialize the queue to be empty with a fixed capacity
:param capacity: Initial size of the queue
@pre: a capacity of the circular queue, if no input is provided it will default to 2
@post: initializes a CircularQueue object
This is the CircularQueue constructor. It creates an object based on the capacity input or default value
"""
self._capacity = capacity
self._size = 0
self._list = [None] * self._capacity
self._sum = 0
self._read = 0
self._write = 0
def __str__(self):
"""
Return a string representation of RunningQueue
:return: string
@pre: None
@post: returns the CircularQueue object information in a string format
This method returns the CircularQueue object information in the following order: numbers from read to draw,
sum of the numbers, and current capacity
"""
if self._size > 0:
str1 = ""
if self._write > self._read:
for i in self._list[self._read:self._write]:
i = str(i)
str1 = str1 + i + " "
else:
for j in self._list[self._read:]:
j = str(j)
str1 = str1 + j + " "
for k in self._list[:self._write]:
k = str(k)
str1 = str1 + k + " "
str1 = str1.replace("None", "")
str1 = str1.strip()
str1 = str1 + " Sum:" + str(self._sum) + " Capacity:" + str(self._capacity)
return str1
else:
return "Queue is Empty"
def parse_command(self, command):
"""
Parse command given from the input stream
:param command: command from input stream
:return: None
@pre: An input, called command. It is expected to be an 'a' or 'r'
@post: Based on the input, either enqueue or dequeue. No return
This method takes in a command and based on the letter, enqueue or dequeues from the CircularQueue
"""
input_ = command
input_list = input_.strip().split()
if input_list[0] == 'a':
self.enqueue(input_list[1])
elif input_list[0] == 'r':
self.dequeue()
else:
pass
def enqueue(self, number):
"""
Add a number to the end of the queue
:param number: number to add
:return: None
@pre: a number to enqueue to the CircularQueue
@post: The number is attached to the end of the CircularQueue. No return
This method attaches the number to the end of the CircularQueue and increases its variables
"""
if self._size == self._capacity:
self.resize()
self._list[self._write % self._capacity] = number
self._size += 1
self._sum = self._sum + int(number)
self._write = (self._write + 1) % len(self._list)
def dequeue(self):
"""
Remove an element from the front of the queue
Do nothing if the queue is empty
:return: None
@pre: None
@post: Removes the first element from the CircularQueue. No return
This method removes the first element from the CircularQueue and changes its variables accordingly
"""
if self._size < 1:
pass
else:
self._sum = self._sum - int(self._list[self._read])
self._list[self._read] = None
self._read = (self._read + 1) % len(self._list)
self._size -= 1
def resize(self):
"""
Resize the queue to be two times its previous size
:return: None
@pre: None
@post: Doubles the capacity of the CircularQueue and changes the read and write pointers accordingly
This method is called when the CircularQueue is full. It doubles the capacity and copies the old values over
in the correct order, changing the read and write pointers to match the new capacity
"""
old = self._list
self._write = self._capacity
self._capacity = self._capacity * 2
self._list = [None] * self._capacity
count = self._read
for i in range(self._size):
self._list[i] = old[count]
count = (count + 1) % len(old)
self._read = 0
def get_sum(self):
"""
Get the sum of the numbers currently in the queue
:return: sum of the queue
@pre: None
@post: Returns the sum of the numbers in the CircularQueue
This method returns the sum of the numbers in the CircularQueue that is tracked when using enqueue or dequeue
"""
return self._sum
|
c8484de60223b833238af12ebaaa55c74675bc9b | Arix2019/myPythonRepo | /testExp.py | 238 | 3.75 | 4 | #parte do arquivo funcExp.py
from funcExp import exp
string = input('>>>Digite a expressão: ')
print('-+'*20)
if exp(string) == 0:
print('>>>Parâmetros aceitos.')
else:
print('>>>A sintaxe da sua expressão possui erros.')
|
bafafed53affad542425dc7680b57f95c2f80c50 | sophcarr/comp110-21f-workspace | /projects/cyoa.py | 3,353 | 4.09375 | 4 | """Which Disney Princess Are You?"""
__author__ = "730320301"
player: str = ""
points: int = 0
HAT: str = '\U0001F920'
def main() -> None:
"""Main program."""
global player
global points
player = input("Hello, player! What is your name? ")
greet()
print(player + ", do you want to keep playing?")
print("1) Yes")
print("2) No.")
keep_playing: int = int(input("Enter which number you choose: "))
while keep_playing == 1:
points = add_point(points)
level1: int = start()
if level1 == 1:
kissing()
elif level1 == 2:
bow()
elif level1 == 3:
adventure()
else:
print("I'm sorry, that is not an option.")
print(player + ", do you want play this game again?")
print("1) Yes")
print("2) No.")
keep_playing = int(input("Enter which number you choose: "))
points = points + 1
print("The End!")
print(f"Final adventure points: {points}")
def greet() -> None:
"""Greeting."""
print("Hello, " + player + "! This game will ask you a series of questions in order to determine which Disney Princess you are. Choose wisely, and good luck! :)")
def add_point(x: int) -> int:
"""Just to add a point to globals."""
x = x + 1
return x
def start() -> int:
"""Pick a weekend activity."""
global player
global points
print(player + ", pick a weekend activity.")
print("1) Kissing.")
print("2) Shooting a bow and arrow.")
print("3) Leaving home in search of an adventure.")
answer0: int = int(input("Enter which number you choose: "))
return answer0
def kissing() -> None:
"""Would you ever smooch a frog?"""
global player
global points
print(player + ", would you ever smooch a frog?")
print("1) If the situation calls for it.")
print("2) Definitely not, why are you asking me this you freak?")
answer1: int = int(input("Enter which number you choose: "))
if answer1 == 1:
print("It is pretty obvious your princess soulmate is Tiana " + HAT)
elif answer1 == 2:
print("It is pretty obvious your princess soulmate is Aurora " + HAT)
else:
print("I'm sorry, that is not an option. Please pick again.")
points = points + 1
print(f"Adventure Points: {points}")
def bow() -> None:
"""Bow and arrow."""
global player
global points
print(player + ", it is pretty obvious your princess soulmate is Merida " + HAT)
points = points + 1
print(f"Adventure Points: {points}")
from random import randint
fact: int = randint(1, 20)
print(f"Fun fact, Merida's favorite number is {fact}.")
def adventure() -> None:
"""Land or sea?"""
global player
global points
print(player + ", do you like the land or the sea better?")
print("1) Land.")
print("2) Sea.")
answer2: int = int(input("Enter which number you choose: "))
if answer2 == 1:
print("It is pretty obvious your princess soulmate is Rapunzel " + HAT)
elif answer2 == 2:
print("It is pretty obvious your princess soulmate is Ariel " + HAT)
else:
print("I'm sorry, that is not an option. Please pick again.")
points = points + 1
print(f"Adventure Points: {points}")
if __name__ == "__main__":
main()
|
c334472a739655927757a93c79396669e3989524 | ellismckenzielee/codewars-python | /decode_the_QR_code.py | 1,060 | 3.515625 | 4 | #decode the QR code kata
#https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f
import numpy as np
def scanner(qrcode):
qr_code_indeces = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for i in range(21)]
for i, row in enumerate(qrcode):
for j, val in enumerate(row):
if (i+j)% 2 == 0:
val = 1 - val
qr_code_indeces[i][j] = val
qr_code = np.array(qr_code_indeces)
qr_code = qr_code[9:]
odd, output = 0, []
for i in [19, 17, 15, 13]:
columns = qr_code[:,[i, i + 1]]
if odd == 1:
direction = 1
else:
direction = -1
for row in columns[::direction]:
output += row.tolist()[::-1]
odd = 1 - odd
output = ''.join(list(map(str,output[4:])))
letter_count = int(output[:8], 2)
output = output[8:]
word = ''
print(letter_count)
for i in range(0, (letter_count * 8) + 11, 8):
word += chr(int(output[i:i+8], 2))
if len(word) == letter_count:
return word
|
4571b5ca7d229fdc1f49e05d246d142ae246f27e | devin-kennedy/collatz | /collatz.py | 1,662 | 3.671875 | 4 | import math
solved = {}
def collatzAlgorithm(n):
if n % 2 == 1:
return 3 * n + 1
else:
return n // 2
def append_value(dict_obj, key, value):
if key in dict_obj:
dict_obj[key].append(value)
else:
dict_obj[key] = [value]
def collatz(n):
chain = n
nextValue = n
while nextValue != 1:
nextValue = collatzAlgorithm(nextValue)
if nextValue not in solved:
append_value(solved, chain, nextValue)
else:
append_value(solved, chain, nextValue)
solved[chain].extend(solved[nextValue])
break
def Log2(x):
if x == 0:
return False
return (math.log10(x) /
math.log10(2))
def isPowerOfTwo(n):
return (math.ceil(Log2(n)) ==
math.floor(Log2(n)))
def main():
for i in range(1,10001):
collatz(i)
print("Longest collatz chain between 2 and 10,000:")
length = 0
for key, i in solved.items():
if len(i) > length:
lchain = i
lkey = key
length = len(i)
print(lkey, lchain)
length = 300
print("\n Shortest collatz chain that is not a power of 2")
for key, i in solved.items():
if isPowerOfTwo(key) == False:
if len(i) < length:
schain = i
skey = key
length = len(i)
print(skey, schain)
length = 0
print("\n Average length of chains from 2 to 10,000")
lenlist = []
for key, i in solved.items():
lenlist.append(len(i) + 1)
average = sum(lenlist) / len(lenlist)
print(average)
if __name__ == "__main__":
main() |
ec542707625c4fb6c967ffd4da9b1544da67ec6c | brandonIT/grading | /grading.py | 2,477 | 4.09375 | 4 | def printDirections():
print("Welcome to the Grading Machine!\nThis program is designed to convert your grades (in numbers)\nto their letter version counter parts.\nThe program will continue to read in grades until you enter -1.")
def getInt():
num=0
print("Please enter the numerical value of the grade")
num=int(input())
return num
def grading():
grade = 0
gradeCount = 0
gradeSum = 0
gradeAverage = 0.0
gradeValue = 'A'
printDirections()
grade=getInt()
if(grade==-1):
print("You didn't enter any grades, please close the program and try again")
return
while(grade != -1):
if((grade <= 100) and (grade >= 90)):
gradeCount+=1
gradeSum += grade
print("The grade you entered is an A!")
elif((grade < 90) and (grade >= 80)):
gradeCount+=1
gradeSum += grade
print("The grade you entered is a B!")
elif((grade < 80) and (grade >= 70)):
gradeCount+=1
gradeSum += grade
print("The grade you entered is a C.")
elif((grade < 70) and (grade >= 60)):
gradeCount+=1
gradeSum += grade
print("The grade you entered is a D.")
elif((grade < 70) and (grade >= 1)):
gradeCount+=1
gradeSum+=grade
print("The grade you entered is an F.")
else:
print("You have entered an invalid grade, please try again")
grade=getInt()
grade=getInt()
gradeAverage = gradeSum/gradeCount
if((gradeAverage <= 100) and (gradeAverage >= 90)):
gradeValue = 'A'
elif((gradeAverage < 90) and (gradeAverage >= 80)):
gradeValue = 'B'
elif((gradeAverage < 80) and (gradeAverage >= 70)):
gradeValue = 'C'
elif((gradeAverage < 70) and (gradeAverage >= 60)):
gradeValue = 'D'
elif((gradeAverage < 60) and (gradeAverage >= 1)):
gradeValue = 'F'
else:
print("Error in average ifs.")
print("The average of the grades you entered (in numerical form) is {}.".format(gradeAverage))
if((gradeValue == 'A') or (gradeValue == 'F')):
print("The letter grade equivalent to {} is an {}.".format(gradeAverage,gradeValue))
else:
print("The letter grade equivalent to {} is a {}.".format(gradeAverage,gradeValue))
grading()
|
5eea149d88d72b84cc7d6e4c1b9236e9a81d741d | atanas-bg/SoftUni | /Python3/Lecture_03_Functions/demo_package/demo_functions.py | 2,021 | 4.03125 | 4 | def div_mod(number, divider):
num = number // divider
modulus = number % divider
return num, modulus # return(num, modulus)
print(div_mod(5, 2))
# по-удобно
r, m = div_mod(13, 3)
print(r) # отпечатва 4
print(m) # отпечатва 1
def print_greeting(name="everybody"):
print("Hello, ", name)
print_greeting("Atanas")
print_greeting()
def function(param1=-1, param2=13):
print(param1) # param1 е 10
print(param2) # param2 е 87
function(10, param2=87)
def sum_numbers(*args):
total = sum(args)
return total
print(sum_numbers(2, 3, 4, 5))
def print_record(**kwargs):
print(kwargs.pop('name', "Record"), ":")
for key, value in kwargs.items():
print("\t", key, "=", value)
print_record(name="ivan", age=23)
print_record(name="Mercury", distance_au=0.387, diameter_km=4878)
print_record(name="Venus", distance_au=0.723, diameter_km=12104)
print_record(name="Earth", distance_au=1, diameter_km=12742, average_temp_c=7.2,
atmosphere=["nitrogen", "oxygen", "argon"])
print("*" * 20)
print_record()
print("*" * 20)
number_of_calculations_performed = 10 # глобална променлива
def calculate(parameter1, parameter2):
...
# print(number_of_calculations_performed)
number_of_calculations_performed = 23
print("In the function: ", number_of_calculations_performed, id(number_of_calculations_performed))
print('Before: ', number_of_calculations_performed)
calculate(4, 5)
print('After: ', number_of_calculations_performed)
calculations_performed = [] # глобална променлива
def calculate(parameter1, parameter2):
...
# global calculations_performed
# print(number_of_calculations_performed)
calculations_performed.append(parameter1 * parameter2)
print("In the function: ", calculations_performed)
print('Before: ', calculations_performed)
calculate(4, 5)
calculate(40, 2)
calculate(50, 3)
calculate(60, 4)
print('After: ', calculations_performed)
|
a08eefc483eaa317ec83c5aca0050679833a3b4d | Alcamech/CSCE355-2017 | /src/searcher_DFA.py | 2,502 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import sys
'''
Text Search
- read a string w from a text file
- output a DFA that accepts a string x if and only if w is a substring of x
@Author: Lawton C. Mizell
DFA (Q, Σ, δ, q', F)
Q - states
Σ - alphabet
δ - transitions
q' - start_state
F - accepting_states
'''
def main():
#read file in from command line argument
string_w_file = sys.argv[1]
with open(string_w_file, 'r') as f: # open file
string_w = f.readlines()
string_w = [x.strip() for x in string_w]
char_in_string = ''.join(set(string_w[0])) # characters in the string_w
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
states = range(len(string_w[0])+1) # Q - states
accepting_states = [len(string_w[0])] # F - accepting_states
transitions = {} # δ - transitions
reference_table = {}
possible_strings_table = {}
print "Number of states:",len(string_w[0])+1
print "Accepting states:",len(string_w[0])
print "Alphabet: abcdefghijklmnopqrstuvwxyz"
# Create empty transition table for # states x alphabet
for i, i_val in enumerate(states):
for j, j_val in enumerate(alphabet):
string_w_whole = string_w[0]
if i < len(string_w_whole):
if j_val == string_w_whole[i]:
transitions[(i_val,alphabet[j])] = i_val+1
else:
transitions[(i_val,alphabet[j])] = 0
if i_val in accepting_states:
transitions[(i_val,alphabet[j])] = i_val # last row filled with accepting_state (loop on accepting)
# build reference table
curr_string=""
for i, i_val in enumerate(string_w[0]):
curr_string=curr_string+i_val
reference_table[curr_string]=i+1
# build possible strings table
for k,v in sorted(reference_table.iteritems()):
for i in char_in_string:
if k+i not in reference_table.keys():
possible_strings_table[k+i]=v
# fill loop back transitions
for k,v in sorted(reference_table.iteritems()):
for k2,v2 in possible_strings_table.iteritems():
if v not in accepting_states and v2 not in accepting_states:
if k2.endswith(k):
transitions[(v2,k2[-1])]=v
# print transitions table
for i in states:
for j in alphabet:
print transitions[(i,j)],
print
if __name__ == '__main__':
main()
|
dd01623027938f1566acbcb48c138bf1f3d9f844 | cinxdy/Python_practice | /Tutor/yesul_find.py | 492 | 3.78125 | 4 | # find_transfer.py
#다음과 같이 영어 문장과 찾을 단어를 입력 받아서,
#그 단어가 입력된 문장에 몇 번 나타나는지 출력한다.
#또 찾은 단어는 모두 대문자로 바꾼 후 문장을 출력한다
#19/4/1-10
#조예슬
input_str=input("Input a sentence :")
input_find=input("Input a word for search :")
count = input_str.count( input_find )
input_str = input_str.replace( input_find, input_find.upper() )
print(input_str)
print("count : ", count)
|
a7a50be19c818ea1b8f2ed52221f22fbc849a169 | mitoop/py | /knapsack.py | 790 | 3.953125 | 4 | #!/usr/bin/env python
# 类似 Knapsack problem 源代码来自于知乎
import random
random.seed()
# 组数 自定义
groups = 5
# 一百组0-1000内的随机数
values = [random.randint(0, 1000) for i in range(100)]
# 从大到小 减小之后的误差
values.sort(reverse=True)
# 生成对应数目的空列表数
target_groups = [[] for grp in range(groups)]
for v in values:
# 计算列表值得和 并从小到大排序
target_groups.sort(key=lambda x: sum(x))
# 给最小和的列表添加一个值
target_groups[0].append(v)
# 重复上面两项操作 趋近目标
# 结果是趋近的 可能并不是最优解 初始从大到小排序 会降低误差
for per in target_groups:
# 打印每一项
print(per)
# 打印总和
print(sum(per))
|
e2ab037688e6be8a6c13d94e4381a725853d11cb | alvas-education-foundation/Krishna_Katira | /coding_solutions/26-06-20.py | 168 | 3.578125 | 4 | a=[]
l=int(input("Enter lower limit: "))
u=int(input("Enter upper limit: "))
a=[x for x in range(l,u+1) if x%2!=0 and str(x)==str(x)[::-1]]
print("The numbers are: ",a) |
79759ba0edc4aa9cd5841aad1f08a5bdd0f1c7a1 | lxh935467355/hello-world | /weather.py | 958 | 3.75 | 4 | # 已知实时天气预报API接口为:
# http://www.weather.com.cn/data/sk/101110101.html
# 返回的是JSON格式的数据,请爬取天气预报信息,并将爬取到的信息保存到文件中。
import json
from urllib import request
url = "http://www.weather.com.cn/data/sk/101110101.html"
if __name__ == '__main__':
resp = request.urlopen(url) # 发送GET请求,返回响应对象
if resp.status == 200:
weather_str = resp.read().decode() # 获取响应中的内容
weather_dict = json.loads(weather_str) # 将字符串转换为字典
city = weather_dict["weatherinfo"]["city"] # 获取城市名称
temp = weather_dict["weatherinfo"]["temp"] # 获取温度
with open("./data/weather_info.txt",'w',encoding="utf-8") as f:
f.write("城市:"+city+"\n")
f.write("温度:"+temp)
print("保存成功!")
print('hello,world') |
4cf1d3eb5f26d69b8ce077d60630cb4b9ef31873 | Suspious/alweer | /while 5.py | 91 | 3.6875 | 4 | while True:
x = input("hoe heet je? ").lower()
if x =="anthony":
break
|
01224569b9761c6fa6ad2004d8d0856e498203c6 | jackx99/Python-Tutorial | /Sorting.py | 1,524 | 4.4375 | 4 | # Hello Guys
# Today lesson is Sorting a list. We are going to learn Selection Sort.
# How selection sort work? a list is sorted by selecting elements in the list, one at a time, and moving
# them to their proper positions. This algorithm finds the location of the smallest element in the unsorted portion
# of the list and moves it to the top of the unsorted portion of the list. The first time we locate the smallest item
# in the entire list; the second time we locate the smallest item in the list starting from the second
# element in the list; and so on.
# I'm going to show a presentation, How sorting is done.
"""
Redo Programming Exercise of Searching for a sorted list.
"""
# Let's start
def selectionSort(list, list_length):
temp = 0
smallestKey = 0
key = 0
minKey = 0
for key, _ in enumerate(list):
smallestKey = key # we assume that first key is the smallest element
minKey = key + 1 # we start to look for comparison of the smallest element from key 1 to list length
while minKey < list_length:
if list[minKey] < list[smallestKey]: # If evaluates to true,
smallestKey = minKey # Then the smallestKey value is updated to smaller than smallest
minKey += 1
# Swaps these values to implement the selection sort algorithm
temp = list[smallestKey]
list[smallestKey] = list[key]
list[key] = temp
return list
list = [71, 29, 67, 18, 92, 4, 49, 48, 86, 40]
print(selectionSort(list, len(list))) |
3992d1fd064ce6ddd78e3ac1637129757203aaff | Aleksandrov-vs/dz_ege | /task_26.py | 926 | 3.640625 | 4 |
DATA = []
def load_data():
with open('./26.txt') as f:
size, count = f.readline().split(' ')
size = int(size)
count = int(count)
for line in f:
DATA.append(int(line))
return size, count
def main():
size, count = load_data()
DATA.sort()
sum = 0
count = 0
max_el = int
# количество элементов которые влезут
for i in range(0, len(DATA)):
if DATA[0] <= size:
count += 1
el = DATA.pop(0)
max_el = el
size -= el
# берем сумму последнего элемента и оставшйся памяти и сотрим какой наибольший элемент влезет
rest_disk_space = max_el + size
for i in range(0, len(DATA)):
if rest_disk_space > DATA[i]:
max_el = DATA[i]
print(count, max_el)
main() |
6cb95a512c5584e0c6f4ad796ccecb7d9c2f1ea1 | florianjanke/Pythondateien | /Name+ frohe Weihnachten passt sich dynamisch an den Namen an.py | 366 | 3.5 | 4 | texteins=input("Wie heißt du?: ")
laengeeins=len(texteins)
textzwei=" Frohe Weihnachten "
laengezwei=len(textzwei)
sternchen="*"
laengedrei=int((laengezwei-laengeeins)/2)
print(sternchen*laengezwei+(2*sternchen))
print(sternchen+textzwei+sternchen)
print(sternchen+" "*laengedrei+texteins+" "*laengedrei+sternchen)
print(sternchen*laengezwei+(2*sternchen)) |
a85a1eaab4e5f670bc8989362cd759abee68c2e1 | HariData20/Rock-Paper-Scissors | /Rock-Paper-Scissors/task/rps/game.py | 2,606 | 3.96875 | 4 | # Write your code here
import random
import sys
name = input('Enter your name:')
print('Hello, {}'.format(name))
score = 0
selection = input()
if selection == '':
options = ['rock', 'paper', 'scissors']
else:
options = selection.split(',')
print("Okay, let's start")
# rock,gun,lightning,devil,dragon,water,air,paper,sponge,wolf,tree,human,snake,scissors,fire
winning_cases = {
'water': ['scissors', 'fire', 'rock', 'hun', 'lightning', 'devil', 'dragon'],
'dragon': ['snake', 'scissors', 'fire', 'rock', 'gun', 'lightning', 'devil'],
'devil': ['tree', 'human', 'snake', 'scissors', 'fire', 'rock', 'gun'],
'gun': ['wolf', 'tree', 'human', 'snake', 'scissors', 'fire', 'rock'],
'rock': ['sponge', 'wolf', 'tree', 'human', 'snake', 'scissors', 'fire'],
'fire': ['paper', 'sponge', 'wolf', 'tree', 'human', 'snake', 'scissors'],
'scissors': ['air', 'paper', 'sponge', 'wolf', 'tree', 'human', 'snake'],
'snake': ['water', 'air', 'paper', 'sponge', 'wolf', 'tree', 'human'],
'human': ['dragon', 'water', 'air', 'paper', 'sponge', 'wolf', 'tree'],
'tree': ['devil', 'dragon', 'water', 'air', 'paper', 'sponge', 'wolf'],
'wolf': ['lightning', 'devil', 'dragon', 'water', 'air', 'paper', 'sponge'],
'sponge': ['gun', 'lightning', 'devil', 'dragon', 'water', 'air', 'paper'],
'paper': ['rock', 'gun', 'lightning', 'devil', 'dragon', 'water', 'air'],
'air': ['fire', 'rock', 'gun', 'lightning', 'devil', 'dragon', 'water'],
'lightning': ['tree', 'human', 'snake', 'scissors', 'fire', 'rock', 'gun']
}
with open('rating.txt', 'r') as f:
for line in f:
if name in line:
score = int(line.split(' ')[1])
break
while True:
choice = input()
if choice in options:
system_choice = random.choice(options)
if choice == system_choice:
print("There is a draw ({})".format(system_choice))
score += 50
elif system_choice in winning_cases.get(choice):
print('Well done. The computer chose {} and failed'.format(system_choice))
score += 100
else:
print('Sorry, but the computer chose {}'.format(system_choice))
elif choice == '!rating':
print('Your rating:', score)
elif choice == '!exit':
print('Bye!')
sys.exit()
else:
print("Invalid input")
"""
if choice == 'scissors' and system_choice == '':
print('Sorry, but the computer chose rock')
elif choice == 'paper':
print('Sorry, but the computer chose scissors')
else:
print('Sorry, but the computer chose paper')
"""
|
367d7a5def6e2c307b27fbae5f043cd5bfab071d | 316112840/Programacion | /ActividadesEnClase/Class/Registro.py | 1,268 | 3.578125 | 4 | import random as r
class Registro:
numeroRegistros = 0
def __ini__ (self, nombre, apellidos, edad):
Registro.numeroRegistros += 1 # Para que cada vez que se cree un objeto, aumente una unidad
self.nombre = nombre
self.apellidos = apellidos
self.numero = Registro.numeroRegistros
self.edad = edad
def __str__(self):
cadena = ""
cadena += "Nombre: " + self.nombre + "\n"
cadena += "Apellidos: " + self.apellidos + "\n"
cadena += "Numero de cuenta: " + str(self.numero) + "\n"
cadena += "Edad: " + str(self.edad)
return cadena
def cadenaPseudoaleatoria(n):
abc = "abcdefghijklmnopqrstuvwxyz"
ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
cadena = ABC[r.randint(0,25)]
for i in range(n - 1):
cadena += abc[r.randint(0,25)]
return cadena
def RegistroPseudoaleatorio():
nombre = Registro.cadenaPseudoaleatoria(8)
apellidos = Registro.cadenaPseudoaleatoria(8) + " " + Registro.cadenaPseudoaleatoria(8)
numeroCuenta= Registro.numeroRegistros
edad = r.uniform(18,30)
return Registro(nombre, apellidos, numeroCuenta, edad)
r1 = Registro.RegistroPseudoaleatorio()
print(r1)
|
36969e16e9c5e5982123b07b6e4070fd4a55e3f5 | emmapatton/Programming-Module | /Practice and Revision/format.py | 264 | 4.03125 | 4 | # Emma Patton, 2018-03-02
# Formatting output
for i in range(1, 11):
print('{:2d} {:3d} {:4d} {:5d}'.format(i, i**2, i**3, i**4))
a = 5
print(f'The value of a is {a} and a+1 is {a+1}.')
for i in range(1, 11):
print(f'{i:2d} {i**2:3d} {i**3:4d} {i**4:5d}')
|
28a61445b2709c73184490340e621510d8d1600e | hobler/chanmap | /wedge.py | 5,576 | 4.1875 | 4 | """
Geometry operations with a wedge.
A wedge is defined by the triangle bounded by the lines y=0 and y=x, and by
a circle with its center on the negative x axis or at the origin.
"""
import numpy as np
from geom import Line, Circle, intersect
from stereographic import stereographic_projection, cartesian
class Wedge:
"""
Wedge defined as described above. The circle is defined upon
initialization by the stereographic projection of the plane spanned by two
crystal axes, or by a radius. In the latter case, the center of the
circle is assumed at the origin.
"""
def __init__(self, dir1=(1,0,1), dir2=(1,1,1), theta_max=None):
self.horizontal_line = Line(0, 1, 0)
self.diagonal_line = Line(1, -1, 0)
if theta_max is None:
dirn = np.cross(dir1, dir2)
if dirn[2] < 0:
dirn = - dirn
costheta = dirn[2] / np.linalg.norm(dirn)
phi = np.arctan2(dirn[1], dirn[0])
r = 2 / costheta
rc = r * np.sqrt(1 - costheta**2)
xc, yc = cartesian(rc, phi)
self.circle = Circle(xc, yc, r)
else:
rmax = stereographic_projection(theta_max)
self.circle = Circle(0, 0, rmax)
def contains(self, point, tol=0.001):
"""
Determine if wedge contains the point.
:param point: Point.
:return: Flag indicating whether wedge contains the point.
"""
return (self.horizontal_line.isbelow(point, tol) and
self.diagonal_line.isabove(point, tol) and
self.circle.contains(point, tol))
def intersect(self, object, tol=0.001):
"""
Intersect the wedge with a line or circle.
:param object: Line or circle to be intersected.
:param tol: absolute tolerance for containing points or
removing duplicate points.
:return [(x, y), ...]: List of intersection points.
"""
# intersect the lines and the circle defining the wedge with the line
points = list(intersect(self.horizontal_line, object))
points += list(intersect(self.diagonal_line, object))
points += list(intersect(self.circle, object))
# collect points outside the wedge
delete_points = set()
for point in points:
if not self.contains(point):
delete_points.add(point)
# collect duplicate points
points = list(set(points))
for point1 in points:
for point2 in points:
if point1 is point2:
break
x1, y1 = point1
x2, y2 = point2
if abs(x1-x2) < tol and abs(y1-y2) < tol:
delete_points.add(point1)
# remove points
for delete_point in delete_points:
points.remove(delete_point)
# order according to increasing distance from origin
def radius(point):
return np.hypot(*point)
points.sort(key=radius)
return points
def get_polygon(self, dangle=np.radians(1)):
"""
Get the wedge as a polygon.
:param dphi: Approximate phi increment of the circle part (deg)
:return xy: wedge as a polygon (Nx2 array)
"""
# end points and angles of arc
points = intersect(self.horizontal_line, self.circle)
if self.diagonal_line.isabove(points[0]):
point1 = points[0]
else:
point1 = points[1]
angle1 = np.arctan2(point1[1]-self.circle.yc, point1[0]-self.circle.xc)
points = intersect(self.diagonal_line, self.circle)
if self.horizontal_line.isbelow(points[0]):
point2 = points[0]
else:
point2 = points[1]
angle2 = np.arctan2(point2[1]-self.circle.yc, point2[0]-self.circle.xc)
# arc
xy = self.circle.get_polygon(angle1, angle2, dangle)
# prepend origin
origin = intersect(self.horizontal_line, self.diagonal_line)
xy = np.insert(xy, 0, origin[0], axis=0)
return xy
if __name__ == '__main__':
from math import isclose
wedge = Wedge()
print(wedge.circle.xc, wedge.circle.yc, wedge.circle.r)
print(wedge.get_polygon())
wedge = Wedge((1,1,2), (1,0,1))
print(wedge.circle.xc, wedge.circle.yc, wedge.circle.r)
print(wedge.get_polygon())
exit()
line1 = Line(1, 4, 6)
line2 = Line(-5, 2, -8)
circle1 = Circle(-1, 2, 5)
circle2 = Circle(-2, 0, 4)
solutions = intersect(line1, line2)
for solution in solutions:
x ,y = solution
print('x={}, y={}'.format(x, y))
assert isclose(x, 2)
assert isclose(y, 1)
solutions = intersect(circle1, line1)
for solution in solutions:
x ,y = solution
print('x={}, y={}'.format(x, y))
assert isclose((x-circle1.xc)**2 + (y-circle1.yc)**2, circle1.r**2)
assert isclose(line1.a * x + line1.b * y, line1.c)
solutions = intersect(line2, circle1)
for solution in solutions:
x ,y = solution
print('x={}, y={}'.format(x, y))
assert isclose((x-circle1.xc)**2 + (y-circle1.yc)**2, circle1.r**2)
assert isclose(line2.a * x + line2.b * y, line2.c)
solutions = intersect(circle1, circle2)
for solution in solutions:
x ,y = solution
print('x={}, y={}'.format(x, y))
assert isclose((x-circle1.xc)**2 + (y-circle1.yc)**2, circle1.r**2)
assert isclose((x-circle2.xc)**2 + (y-circle2.yc)**2, circle2.r**2)
|
0fe29c6e68cd83b86d240dcec155f0319b3c40d1 | priyankabb153/260150_daily_commits | /list/position.py | 411 | 3.921875 | 4 | # Write a Python program to change the position of every n-th value with the (n+1)th in a list
list1 = [1, 0, 3, 2, 5, 4]
"""
i=0
while i <= (len(list1)-1):
temp = list1[i]
list1[i] = list1[i + 1]
list1[i + 1] = temp
i = i + 2
"""
def position(list1):
for i in range(0, len(list1), 2):
list1[i], list1[i + 1] = list1[i + 1], list1[i]
return list1
print(position(list1))
|
060f59b1bfb2b219b102b38ac88d8d7685c4661d | LuongMonica/passwd-validator | /passwd-validator.py | 3,055 | 4.40625 | 4 | # password validator
""" must follow:
- Minimum length is 5;
- Maximum length is 10;
- Should contain at least one number;
- Should contain at least one special character (such as &, +, @, $, #, %, etc.);
- Should not contain spaces """
prompt = str(input("Enter a valid password. Password must be 5-10 characters long with at least 1 number and 1 special character (such &, +, @, $, #, %, etc.) No spaces are allowed.\n \n"))
# validate
if len(prompt) > 10:
print("Error! Password must be less than 10 characters long.")
while len(prompt) > 10:
prompt = str(input("Enter a valid password. Password must be 5-10 characters long with at least 1 number and 1 special character (such &, +, @, $, #, %, etc.) No spaces are allowed."))
if len(prompt) < 5:
print("Error! Password must be at least 5 characters long.")
while len(prompt) < 5:
prompt = str(input("Enter a valid password. Password must be 5-10 characters long with at least 1 number and 1 special character (such &, +, @, $, #, %, etc.) No spaces are allowed."))
if num_check(prompt) == False:
print("Error! Password must include at least 1 number.")
while num_check(prompt) == False:
prompt = str(input("Enter a valid password. Password must be 5-10 characters long with at least 1 number and 1 special character (such &, +, @, $, #, %, etc.) No spaces are allowed."))
if spec_check(prompt) == False:
print("Error! Password must include at least 1 special character.")
while spec_check(prompt) == False:
prompt = str(input("Enter a valid password. Password must be 5-10 characters long with at least 1 number and 1 special character (such &, +, @, $, #, %, etc.) No spaces are allowed."))
if spec_check(prompt) == False:
print("Error! Password must not contain whitespaces.")
while spec_check(prompt) == False:
prompt = str(input("Enter a valid password. Password must be 5-10 characters long with at least 1 number and 1 special character (such &, +, @, $, #, %, etc.) No spaces are allowed."))
else:
print("Password validated.")
# function to check for numbers in password, using loop
def num_check(input):
i = 0
for i in prompt[len(input) - 1]:
if prompt[i] == "0" or "1" or "2" or "3" or "4" or "5 or 6" or "7" or "8" or "9":
num = True
return num
else:
num = False
return num
# function to check for special characters in password, using loop
def spec_check(input):
i = 0
for i in prompt[len(input) - 1]:
if prompt[i] == "@" or "!" or "$" or "&" or "?" or ":" or "#" or "/" or "]" or "[" or "}" or "{" or "%" or ";" or "^" or "*" or "+" or "=" or "<" or "~" or "_":
spec = True
return spec
else:
spec = False
return spec
# function to check for whitespace in password, using loop
def space_check(input):
i = 0
for i in prompt[len(input) - 1]:
if prompt[i] == " ":
space = True
return space
else:
space = False
return space
|
0514f4538df9863ee99d0c3211e8c2745f98ac0b | kashyapa/interview-prep | /revise-daily/epi/revise-daily/stacks/max_api.py | 1,445 | 3.671875 | 4 | #!/usr/bin/env python
class max_stack:
max_cache = []
max_count = {}
def __init__(self):
self.st = []
def max_val(self):
return max_stack.max_cache[-1] if len(max_stack.max_cache) > 0 else -float('inf')
def pop(self):
val = self.st.pop()
if val in max_stack.max_count:
max_stack.max_count[val] -= 1
if max_stack.max_count[val] == 0:
max_stack.max_cache.pop()
del(max_stack.max_count[val])
print(self.st)
return val
def push(self, n):
if n > self.max_val():
max_stack.max_cache.append(n)
max_stack.max_count[n] = 1
elif n == max_stack.max_cache[-1]:
max_stack.max_count[n] += 1
self.st.append(n)
print(self.st)
if __name__ == "__main__":
stack = max_stack()
stack.push(1)
stack.push(3)
stack.push(-1)
stack.push(10)
stack.push(23)
stack.push(5)
print(stack.max_val())
stack.push(23)
stack.push(16)
print(stack.max_val())
stack.pop()
print(stack.max_val())
stack.pop()
print(stack.max_val())
stack.pop()
print(stack.max_val())
stack.pop()
print(stack.max_val())
stack.pop()
print(stack.max_val())
stack.pop()
print(stack.max_val())
stack.pop()
print(stack.max_val())
stack.pop()
print(stack.max_val())
stack.pop()
print(stack.max_val())
|
5ee368d55297cc6773de66f69aba1a849a09733e | cameronhawtin/Recursion-and-Homoglyph-Translation-in-Python | /Homoglpyh Translation.py | 2,558 | 4.1875 | 4 | #
# Cameron Hawtin
# 101047338
#
# Gaddis, T. (2015). "Starting Out With Python"
#
# This program loads a string from an external file and uses
# it's contents to form a homoglyph translation dictionary.
#
# The external file contains: ";R:12;I:1;E:3;D:cl;I:!;B:!3;G:(_+;J :(/;:"
#
# Function to insert a new translation
def myInsert(mydict, key, value):
if key in mydict:
print("This key already exists. Nothing was added.")
return False
else:
mydict[key] = value
return True
# Function to delete a translation
def myDelete(mydict, key):
if key in mydict:
mydict[key] = key
return True
else:
print("This key does not exist. Nothing was deleted.")
return False
def main():
mydict = {}
# Open and clean up the information into a list format
file = open("example glyphs.dat", "r")
list = file.read()
list = "".join(list.split())
list = list.strip(":")
list = list.strip(";")
list = list.split(";")
for i in range(8):
list[i] = list[i].split(":")
# Moves the list into a useable dictionary
for i in range (0, len(list)):
a = list[0][0]
b = list[0][1]
mydict[a] = b
del list[0]
# Loop through the menu to build up the dictionary and translate strings
while True:
print("\nYour current dictionary is: ")
print(mydict)
ans = input("\nWould you like to '(q)uit', '(t)ranslate', '(i)nsert', or '(d)elete'?: ")
# Quit program
if ans == "quit" or ans == "q":
break
# Translate input string
## Since my generator did not specify how it wanted me to translate
## given strings, I had to make the assumption that this is how
## it was supposed to be done. Only delete and insert functions were
## given instructions for my generated assignment.
elif ans == "translate" or ans == "t":
string = input("\nEnter the string you would like to translate: ")
print("\nTranslation: ")
for i in range(0, len(string)):
if string[i] in mydict:
print(mydict[string[i]], end="")
else:
print(string[i], end="")
print()
# Insert new translations
elif ans == "insert" or ans == "i":
newkey = input("\nEnter the key you would like to insert: ")
newvalue = input("Enter the value you would like associate with the key :")
myInsert(mydict, newkey, newvalue)
# Delete a translation
elif ans == "delete" or ans == "d":
newkey = input("\nEnter the key you would like to delete: ")
myDelete(mydict, newkey)
else:
print("Incorrect input. Please choose specified answer")
main()
|
1e0fa72d2b53299daad354fcd0cc42386802e3ef | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/s-z/vars_test.py | 997 | 4 | 4 | """vars([object])"""
# https://www.programiz.com/python-programming/methods/built-in/vars
from pprint import pprint
"""Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.
Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write
restrictions on their __dict__ attributes (for example, classes use a types.MappingProxyType
to prevent direct dictionary updates).
Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads
since updates to the locals dictionary are ignored.
"""
# Example: How vars() works?
class Foo:
def __init__(self, a=5, b=10):
self.a = a
self.b = b
InstanceOfFoo = Foo()
print(f"vars(InstanceOfFoo): {vars(InstanceOfFoo)}\n")
"""Also, run these statements on Python shell:
>>> vars(list)
>>> vars(str)
>>> vars(dict)"""
pprint(vars(list))
print()
pprint(vars(str))
print()
pprint(vars(dict)) |
d49e1bc7740518c58ad4c76d8ff01ce225230e16 | edumeirelles/Blue_modulo1 | /Aula_11/aula11.py | 968 | 3.53125 | 4 | # lista_contatos =[('Eduardo','16 99260-1155'),('Fulano','11 99999-0000'),('Beltrano','21 88888-5555'),('Sicrano','31 66666-7777'),('Zé','41 56565-7979')]
# # print(lista_contatos)
# dic_contatos = dict(lista_contatos)
# # print(dic_contatos)
# # print(len(dic_contatos))
# # dic1 = {'valor1':'valor2',}
# # print(len(dic1))
# print(dic_contatos['Eduardo'])
# nome = input('Digite o nome: ')
# #print(dic_contatos[nome])
# print(dic_contatos.get(nome,'Contato não encontrado'))
vingadores = {'Chris Evans':'Capitão América', 'Mark Ruffalo':'Hulk', 'Tom Hiddleston':'Loki', 'Chris Hemsworth':'Thor', 'Robert Downey Jr':'Homem de Ferro', 'Scarlet Johansson':'Viúva Negra'}
# ator = input('Digite o nome do(a) ator/atriz: ').title()
# while ator not in vingadores:
# print('Ator/atriz não encontrado.')
# ator = input('Digite o nome do(a) ator/atriz: ').title()
# if ator == '0':
# break
# print(vingadores.get(ator,'Ator/atriz não encontrado.'))
for i in vingadores.values():
print(i)
|
7a7a3c22c68db0ab6853978635105f56eabf237a | hellokejian/PythonBasic | /advanced/04tuple2.py | 2,079 | 4.0625 | 4 | """一 元组和列表"""
# 可将字符串和列表拉到一起
str = 'kejian'
num = [1, 2, 3, 4, 5, 6]
# iterator = zip(str, num).__iter__()
# while iterator.__next__:
# print(iterator)
"""可以使用for循环来访问元组的列表"""
tuplelist = [('kejian', 0), ('chenqi', 1), ('kechen', 3)]
for name, num in tuplelist:
print(name, num)
print("========================")
"""zip 与 for 放在一起使用会怎么样?"""
def zip_for(t1, t2):
for x, y in zip(t1, t2):
if x != y:
return False
return True
flag = zip_for('kejian', 'kejian')
print(flag)
"""如果要遍历序列中的元素和它们的下标,可以使用内置函数enumerate"""
for index, element in enumerate('kejian'):
print(index, element)
"""二 字典与元组"""
"""字典的item方法可以将字典的key-value对变成一个元组,接着将字典里的所有元组组成一个列表"""
print("================================")
dictionary = {'a': 0, 'b': 1, 'c': 2}
lists = dictionary.items()
print(lists)
"""逆向思考,如何将一个元组列表变成一个字典,可以使用dict方法"""
tuplelist = [('kejian', 0), ('chenqi', 1), ('kechen', 3)]
resultdict = dict(tuplelist)
print(resultdict)
"""使用zip 与 dict 方法可以创建出一个字典"""
print('==================================')
resultdict = dict(zip(range(6), "kejian"))
print(resultdict)
"""字典方法update接受一个元组列表,并将他们作为键值对添加到现有字典中"""
new_tuple_list = [(6, 'very'), (7, "good")]
resultdict.update(new_tuple_list)
print(resultdict)
"""列表不可以作为字典的键,但是可以使用元组作为字典的键"""
print('================================')
lastname = 'ke'
firstname = 'jian'
resultdict[lastname, firstname] = 'very handsome'
print(resultdict)
# 遍历这种字典的时候,可以使用元组赋值的方式来遍历字典(由于环境原因,下面的语句未能实现效果)
for lastname, firstname in resultdict:
print(firstname, lastname, resultdict[lastname, firstname])
|
39429b96083ac31aa5ccb870ecd1ab61397c5e0c | uniyalnitin/competetive_coding | /Codeforces/469_D2B(DreamoonAndWiFi).py | 591 | 3.546875 | 4 | '''
Problem Url: https://codeforces.com/contest/476/problem/B
Idea: Permutation and Combination
'''
import math
s1 = input()
s2 = input()
plus, minus = s1.count('+'), s1.count('-')
pre_plus = s2.count('+'); pre_minus = s2.count('-')
req_plus, req_minus = plus- pre_plus, minus - pre_minus
if req_minus < 0 or req_plus < 0:
print('%.12f'%0)
else:
unknowns = len(s1) - (pre_minus + pre_plus)
if unknowns == 0:
print('%.12f'%1)
else:
den = pow(2, unknowns)
num = math.factorial(unknowns)/(math.factorial(req_plus)*math.factorial(req_minus))
ans = num/den
print('%.12f'%ans) |
23b0d366b3dbaa5706af3cd3305a36715017f8fb | JitendraAlim/Data-Science-Toolkit | /Python/Python Programs/14. Sum Of Numbers From 1 to 100.py | 295 | 4.0625 | 4 | # Write A Progam To Obtain The Sum Of Numbers From 1 To 100
# Method 1
x = 1
y = 0
while x<101:
y = y + x
x = x + 1
print("The Sum Of Numbers From 1 To 100 is ",y)
# Method 2
y = 0
for x in range(1,101):
y = y + x
print("The Sum Of Numbers From 1 To 100 is ",y)
|
005a95217cf8643ee927dd587084e7fc7fa70941 | lewis-munyi/MSOMA-Boot-camp | /high-level-functions.py | 243 | 3.75 | 4 | from math import sqrt, pi, pow
def identity(k):
return k
def cube(k):
return pow(k,3)
def summation(n,term):
total, k = 0, 1
k = 1
while k <= n:
total = k
total += term(k)
k += 1
return total
|
f862925ff235296d410fb72d5332b6000b2202a9 | foureyes/csci-ua.0479-spring2021-001 | /_includes/classes/27/timer.py | 285 | 3.59375 | 4 | import turtle
t, wn = turtle.Turtle(), turtle.Screen()
# turn animation of turtles off
t.hideturtle()
wn.tracer(0)
def draw():
t.up()
t.forward(5)
t.down()
t.circle(20)
# update screen
wn.update()
# call again in 50 milliseconds
wn.ontimer(draw, 50)
draw()
wn.mainloop()
|
84e4e8331f89d1d0fd87d576ce75cb6ba3c4f139 | Bikram-Gyawali/pythonnosstop | /003/list2.py | 648 | 4.375 | 4 | items=[0,1,2,3,4,5,6,7,8,9,10]
print(items[-2]) #gives second last value
print(len(items))
print(items[:3]) #gives the first 3 value [0,1,2] //this is basically the slicing in python
print(items[:]) # gives all values
print(items[0:-1])
print(items[5:])
print(items[0:10:2])
print("============")
print(items[0::2])
print("============")
print(items[::-1]) #this reveress any array
print("============")
print(items[5:0:-1]) #reverse an array from the any point index of an array
print("============")
for i in range(len(items)):
print(items[0:i])
print("============")
size=3
for i in range(len(items)):
print(items[i:i+size]) |
8d5d1088f2ae9b1d7956b7ca9b5ee784d3f85b8a | laobadao/Python_Learn | /PythonNote/hello.py | 712 | 4.0625 | 4 | print("Hello,Python! and Hello Python")
if True:
print("oo true")
else:
print("oo false")
print("111", "number", "string")
print("100*2+33-90*2/2==", 100 * 2 + 33 - 90 * 2 / 2)
# print("请输入你的名字:")
# name = input()
#
# print("hello", name, "nice to meet you")
#
# name = input("please calculate 1024*768=")
#
# print("well,the true answer is =", 1024 * 768, " did you right?")
#
# 转义字符
print("I\'m learning \n python3. It\'s precise ")
print(r' \\\\'' 都是注意 转义 all of them')
# python 基础 数据类型和变量
# 记个额外 pip 升级的 命令 pip3 install --upgrade matplotlib
a = '我去'
print("我去", len(a)) # 2
|
68196a7aa6b9c031d13755882cf10fe4ae52516d | marlonsp/EP2 | /paciencia_acordeao.py | 4,476 | 3.828125 | 4 | #funções para o funcionamento do jogo
from f_cria_baralho import cria_baralho
from f_extrai_valor import extrai_valor
from f_extrai_naipe import extrai_naipe
from movimentos_possiveis import lista_movimentos_possiveis
from possibilidade_de_movimento import possui_movimentos_possiveis
from empilha_carta import empilha
#Funções para validar o input
from validacao import valida_inteiro
from validacao import valida_faixa
from colorir import colorir_cartas
#inicio do jogo
print('=-='*8)
Dstart = '\33[35m'
Dend = '\33[0m'
print(Dstart+ 'Paciencia Acordeão' + Dend)
print('=-='*8)
Jogar = str(input('Aperte Enter para iniciar o jogo: ')) # start do jogo
#verificador de start
while Jogar == '':
baralho = cria_baralho()
#Print do baralho
print('Estado atual do baralho: ')
n = 1
for i in baralho:
i = colorir_cartas(i)
print('{0}- {1}'.format(n, i))
n += 1
#Verifica se existem jogadas possíveis
continua = possui_movimentos_possiveis(baralho)
#Se existirem jogadas possíveis, o jogo continua
while continua:
print('')
movimento = input('Escolha o número de uma carta para movê-la (Entre 1 e {}): '.format(len(baralho)))
# Verifica se a entrada para o movimento é válida
verificar = False
while verificar == False:
if valida_faixa(1, len(baralho), movimento) == True:
movimento = int(movimento)
if len(lista_movimentos_possiveis(baralho, movimento-1)) == 0:
verificar = False
movimento = input('Essa carta não possui movimentos , escolha outro: ')
else:
verificar = True
elif movimento == '':
verificar = False
movimento = input('Isso não é um número válido , escolha outro: ')
else:
verificar = False
movimento = input('Isso não é um número válido , escolha outro: ')
movimento = int(movimento)
#empilha carta com apenas 1 opção de movimento
if len(lista_movimentos_possiveis(baralho, movimento-1)) == 1:
if lista_movimentos_possiveis(baralho, movimento-1)[0] == 1:
baralho = empilha(baralho, movimento-1, movimento-2)
else:
baralho = empilha(baralho, movimento-1, movimento-4)
#Escolha e empilha carta com 2 opções de movimento
elif len(lista_movimentos_possiveis(baralho, movimento-1)) == 2:
print('')
print('Essa carta possui duas opções de movimentos: ')
print('1- {}'.format(colorir_cartas(baralho[movimento-4])))
print('2- {}'.format(colorir_cartas(baralho[movimento-2])))
escolha_de_movimento = input('Qual sua escolha? (1 ou 2): ')
#valida a escolha de movimento
while escolha_de_movimento != '1' and escolha_de_movimento != '2':
escolha_de_movimento = input('Isso não é um movimento válido , escolha outro (1 ou 2): ')
if escolha_de_movimento == '1':
baralho = empilha(baralho, movimento-1, movimento-2)
else:
baralho = empilha(baralho, movimento-1, movimento-4)
print('')
#Print do baralho
n = 1
print('Estado atual do baralho: ')
for i in baralho:
i = colorir_cartas(i)
print('{0}- {1}'.format(n, i))
n += 1
#Verifica se existem jogadas possíveis
continua = possui_movimentos_possiveis(baralho)
print('')
#Print do resultado do jo
if len(baralho) == 1:
Dwin = '\33[92m'
Dend = '\33[0m'
print(Dwin + 'Fim de jogo: Você venceu, Parabéns!' + Dend)
else:
print('Não existem mais jogadas possíveis...')
Dlose = '\33[91m'
Dend = '\33[0m'
print(Dlose + 'Fim de jogo: Você perdeu' + Dend)
#Restart do jogo
quer_novamente = str(input('Deseja jogar novamente? (S/N) '))
#Valida a escolha
while quer_novamente != 'S' and quer_novamente != 's' and quer_novamente != 'N' and quer_novamente != 'n':
quer_novamente = str(input('Essa não é uma resposta válida, deseja jogar novamente? (S/N) '))
if quer_novamente == 'S' or quer_novamente == 's':
Jogar = ''
else:
Jogar = 'fim'
#Encerramento final do jogo
else:
print('=-='*8)
print('Fim de jogo') |
7a1bb5983db731a81c471168c5b89e909f73bc5d | Maerig/advent_of_code_2017 | /day11/main.py | 1,285 | 3.875 | 4 | ORIGIN = 0, 0
def read_input():
return open('input.txt').read().rstrip().split(',')
def move(x, y, direction):
if direction == 'n':
return x, y - 1
if direction == 's':
return x, y + 1
north_offset = (-1 if (x % 2 == 0) else 0)
south_offset = (1 if (x % 2 == 1) else 0)
if direction == 'ne':
return x + 1, y + north_offset
if direction == 'nw':
return x - 1, y + north_offset
if direction == 'se':
return x + 1, y + south_offset
if direction == 'sw':
return x - 1, y + south_offset
raise ValueError(direction)
def distance(x1, y1, x2, y2):
x_distance = abs(x2 - x1)
y_distance = max(abs(y2 - y1) - int(x_distance / 2), 0)
return x_distance + y_distance
def part_1(directions):
pos = ORIGIN
for direction in directions:
pos = move(*pos, direction)
return distance(*ORIGIN, *pos)
def part_2(directions):
pos = ORIGIN
max_dist = 0
for direction in directions:
pos = move(*pos, direction)
max_dist = max(max_dist, distance(*ORIGIN, *pos))
return max_dist
if __name__ == '__main__':
directions_input = read_input()
print(f"Part 1: {part_1(directions_input)}")
print(f"Part 2: {part_2(directions_input)}")
|
d3a3bd9cfcf6ac493f50d678412c86d44d0f1f42 | muhammedessa/python_database | /pythonDatabase/2/create_database.py | 732 | 3.515625 | 4 | #create a database named "mydatastore"
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="muhammed",
password="muhammed"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatastores")
mydb.close()
#Check if Database Exists
# import mysql.connector
#
# mydb = mysql.connector.connect(
# host="localhost",
# user="muhammed",
# password="muhammed"
# )
#
# mycursor = mydb.cursor()
#
# mycursor.execute("SHOW DATABASES")
#
# for x in mycursor:
# print(x)
#Try connecting to the database "mydatastore"
# import mysql.connector
#
# mydb = mysql.connector.connect(
# host="localhost",
# user="muhammed",
# password="muhammed",
# database="mydatastore"
# ) |
3be72e509c43b421faf00327874041930830d29c | CPurely/basic_practice | /practice_code/chapter2tab.py | 5,843 | 3.6875 | 4 | import tkinter as tk # imports
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import messagebox as mBox
from tkinter import *
win = tk.Tk() # Create instance
win.title("Python GUI") # Add a title
# win.resizable(0,0)
# Change the main windows icon
win.iconbitmap(r'C:\Python\DLLs\pyc.ico')
tabControl = ttk.Notebook(win) # Create Tab Control
tab1 = ttk.Frame(tabControl) # Create a tab
tabControl.add(tab1, text='Tab 1') # Add the tab
tab2 = ttk.Frame(tabControl) # Add a second tab
tabControl.add(tab2, text='Tab 2')
tab3=ttk.Frame(tabControl)
tabControl.add(tab3,text='Tab 3')
tab3 = tk.Frame(tab3, bg='blue')
tab3.pack()
for orangeColor in range(2):
canvas = tk.Canvas(tab3, width=150, height=80,highlightthickness=0, bg='orange')
canvas.grid(row=orangeColor, column=orangeColor)
tabControl.pack(expand=1, fill="both") # Pack to make visible
monty = ttk.LabelFrame(tab1, text=' Monty Python ')
monty.grid(column=0, row=0, padx=8, pady=4)
monty2 = ttk.LabelFrame(tab2, text=' The Snake ')
monty2.grid(column=0, row=0, padx=8, pady=4)
aLabel = ttk.Label(monty, text="Enter your name")
aLabel.grid(column=0, row=0, sticky='W')
name = tk.StringVar()
nameEntered = ttk.Entry(monty, width=12, textvariable=name)
nameEntered.grid(column=0, row=1, sticky='W')
nameEntered.focus()
ttk.Label(monty, text='your age').grid(column=1, row=0)
age = tk.StringVar()
agechosen = ttk.Combobox(monty, width=12, textvariable=age, state='readonly')
agechosen['values'] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
agechosen.grid(column=1, row=1)
agechosen.current(0)
def clickme():
action.configure(text='Hello ' + name.get() + ' ' + 'you are' + ' ' +
age.get() + 'years old')
action = ttk.Button(monty, text='click me', command=clickme)
action.grid(column=2, row=1)
chVarDis = tk.IntVar() # 2
check1 = tk.Checkbutton(monty2, text="Disabled", variable=chVarDis, state
='disabled') # 3
check1.select()
check1.grid(column=0, row=4, sticky=tk.W) # 5
chVarUn = tk.IntVar() # 6
check2 = tk.Checkbutton(monty2, text="UnChecked", variable=chVarUn)
check2.deselect() # 8
check2.grid(column=1, row=4, sticky=tk.W) # 9
chVarEn = tk.IntVar() # 10
check3 = tk.Checkbutton(monty2, text="Enabled", variable=chVarEn)
check3.select() # 12
check3.grid(column=2, row=4, sticky=tk.W, columnspan=3) # 13
# Radiobutton Globals # 1
COLOR1 = "Blue" # 2
COLOR2 = "Gold" # 3
COLOR3 = "Red" # 4
# Radiobutton Callback # 5
def radCall(): # 6
radSel = radVar.get()
if radSel == 1:
monty.configure(text=COLOR1)
elif radSel == 2:
monty.configure(text=COLOR2)
elif radSel == 3:
monty.configure(text=COLOR3)
# create three Radiobuttons # 7
radVar = tk.IntVar() # 8
# radVar = tk.IntVar()
rad1 = tk.Radiobutton(monty, text=COLOR1, variable=radVar, value=1, command=radCall) # 9
rad1.grid(column=0, row=5, sticky=tk.W) # 10
rad2 = tk.Radiobutton(monty, text=COLOR2, variable=radVar, value=2, command=radCall) # 11
rad2.grid(column=1, row=5, sticky=tk.W) # 12
rad3 = tk.Radiobutton(monty, text=COLOR3, variable=radVar, value=3, command=radCall) # 13
rad3.grid(column=2, row=5, sticky=tk.W) # 14
# Spinbox callback
def _spin():
value = spin.get()
print(value)
scr.insert(tk.INSERT, value + '\n')
# Adding a Spinbox widget
#spin = Spinbox(monty, from_=0, to=100,width=5,bd=5,command=_spin)
spin = Spinbox(monty, value=(1,2,40,64,80,128),width=5,relief=tk.GROOVE,bd=5,command=_spin)
spin.grid(column=0, row=2,sticky='W')
scrolW = 30
scrolH = 5
scr = scrolledtext.ScrolledText(monty, width=scrolW, height=scrolH, wrap=tk.WORD)
scr.grid(column=0, sticky='WE', columnspan=3)
colors = ["Blue", "Gold", "Red"]
radVar2 = tk.IntVar()
radVar2.set(99)
def radCal1():
radSel = radVar2.get()
if radSel == 0:
win.configure(background=colors[0])
elif radSel == 1:
win.configure(background=colors[1])
elif radSel == 2:
win.configure(background=colors[2])
for col in range(3): # 3
curRad = 'rad' + str(col)
curRad = tk.Radiobutton(monty2, text=colors[col], variable=radVar2, value=col, command=radCal1)
curRad.grid(column=col, row=7, sticky=tk.W)
labelsFrame2 = ttk.LabelFrame(monty2, text=' Labels in a Frame2 ')
labelsFrame2.grid(column=0, row=8, padx=20, pady=20)
labelsFrame = ttk.LabelFrame(labelsFrame2, text=' Labels in a Frame ') # 1
labelsFrame.grid(column=0, row=0)
ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0)
ttk.Label(labelsFrame, text="Label2").grid(column=1, row=1)
ttk.Label(labelsFrame, text="Label3").grid(column=2, row=2)
for child in labelsFrame.winfo_children():
child.grid_configure(padx=4, pady=4)
def _quit(): # 7
win.quit()
win.destroy()
exit()
menuBar = Menu(win)
win.config(menu=menuBar)
fileMenu = Menu(menuBar)
fileMenu.add_command(label="New")
fileMenu.add_separator()
fileMenu.add_command(label="Exit", command=_quit)
menuBar.add_cascade(label="File", menu=fileMenu)
# Display a Message Box
# Callback function
def _msgBox():
mBox.showinfo('Python Message Info Box', 'A Python GUI createdusing tkinter:\nThe year is 2017.')
mBox.showwarning('Python Message Warning Box',
'A Python GUI created using tkinter:\nWarning: There might be a bug in this code.')
mBox.showerror('Python Message Error Box',
'A Python GUI createdusing tkinter:\nError: Houston ~ we DO have a serious PROBLEM!')
answer = mBox.askyesno('Python Message Dual Choice Box', 'Are you sure need todo this?')
print(answer)
# Add another Menu to the Menu Bar and an item
helpmenu = Menu(menuBar, tearoff=0)
helpmenu.add_command(label="About", command=_msgBox)
menuBar.add_cascade(label='help', menu=helpmenu)
win.mainloop() # Start GUI
|
10960d1308483d9ed4889e7e7fe08f3b6cbed48b | daniel-reich/turbo-robot | /e5XZ82bAk2rBo9EfS_20.py | 1,338 | 3.890625 | 4 | """
Given a series of lists, with each individual list containing the **time of
the alarm set** and the **sleep duration** , return **what time to sleep**.
### Examples
bed_time(["07:50", "07:50"]) ➞ ["00:00"]
# The second argument means 7 hours, 50 minutes sleep duration.
bed_time(["06:15", "10:00"], ["08:00", "10:00"], ["09:30", "10:00"]) ➞ ["20:15", "22:00", "23:30"]
# The second argument of each sub list means 10 hours sleep duration.
bed_time(["05:45", "04:00"], ["07:10", "04:30"]) ➞ ["01:45", "02:40"]
# Sleep duration can be different among the lists.
### Notes
* Times should be given in 24-hrs (i.e. "23:25" as opposed to "11:25PM").
* Return a list of strings.
"""
def clean_time(s):
if s == 0:
return '00'
elif s < 10:
return '0' + str(s)
else:
return str(s)
def bed_time(*times):
ans = []
for time in times:
start = time[0]
end = time[1]
s_hour = start.split(":")[0]
e_hour = end.split(":")[0]
s_min = start.split(":")[1]
e_min = end.split(":")[1]
hour_diff = int(s_hour) - int(e_hour)
min_diff = int(s_min) - int(e_min)
if hour_diff < 0:
hour_diff += 24
if min_diff < 0:
min_diff += 60
hour_diff -= 1
ans.append(clean_time(hour_diff) + ':' + clean_time(min_diff))
return ans
|
f495b14cd4061bb6a223dea6c9cdbcecebde9722 | geshem14/my_study | /Coursera_2019/Python/week2/week2task37.py | 1,019 | 4.25 | 4 | # week 2 task 37
"""
текст задания
Определите количество четных элементов в последовательности,
завершающейся числом 0.
Формат ввода
Вводится последовательность целых чисел, оканчивающаяся числом 0
(само число 0 в последовательность не входит,
а служит как признак ее окончания).
"""
bool_step = True # вспом. логическая переменная для разршения след шага
amount_of_even_elements = -1 # переменная для кол-ва четных элем-тов посл-ти
while bool_step:
i = int(input()) # вспом. переменная для вводимого числа послед-ости
if i % 2 == 0:
amount_of_even_elements = amount_of_even_elements + 1
if i == 0:
bool_step = False
print(amount_of_even_elements)
|
6c962fcb2dfc25ae2365627f9f0623c6693487b6 | MrColinHan/Twitter-US-Airline-Sentiment | /GeoSpatial Analysis/tweet_location_count.py | 1,321 | 3.578125 | 4 | import csv
def read_csv(filedir, listname):
file = open(filedir)
reader = csv.reader(file)
for row in reader:
listname.append(row)
def write_csv(x, y): # write list x into file y
with open(y,'w+') as file:
wr = csv.writer(file, dialect='excel')
wr.writerows(x)
file.close()
def main():
input_list = []
read_csv("Kaggle_Tweets.csv", input_list)
address_column_header = 'tweet_location'
header_index = input_list[0].index(address_column_header) # input_list[0] is the 1st row
print(header_index)
address_count_dict = {}
for row in input_list[1:]: # exclude first row
if row[header_index] != '':
if row[header_index] not in address_count_dict:
address_count_dict[row[header_index]] = 1
else:
address_count_dict[row[header_index]] += 1
print(address_count_dict)
output_list = [list(address_count_dict.keys()), list(address_count_dict.values())]
write_csv(output_list, "GeoSpatial Analysis/location counts.csv")
'''
Next step:
open the output file 'location counts.csv' in Excel
transpose paste the first two rows into two columns
add two headers "location" "count"
then open the edited file in Power BI
'''
main()
|
9cfc89aeb1354133c45aef0f7bc28b5555d66d0a | jduan/cosmos | /python_sandbox/python_sandbox/tests/effective_python/test_item10.py | 1,136 | 3.890625 | 4 | import unittest
class TestItem10(unittest.TestCase):
"""
enumerate provides concise syntax for looping over an iterator and getting the index of each
item from the iterator as you go.
"""
def test1(self):
flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry']
mapping = {}
for i, flavor in enumerate(flavor_list):
mapping[i+1] = flavor
expected = {
1: 'vanilla',
2: 'chocolate',
3: 'pecan',
4: 'strawberry',
}
self.assertEqual(expected, mapping)
def test2(self):
"""
This is similar to test1. The only difference is that you can pass
the initial index to enumerate!
:return:
:rtype:
"""
flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry']
mapping = {}
for i, flavor in enumerate(flavor_list, 1):
mapping[i] = flavor
expected = {
1: 'vanilla',
2: 'chocolate',
3: 'pecan',
4: 'strawberry',
}
self.assertEqual(expected, mapping)
|
22033d72ae8125b073f53299c82fc06085a920ec | unsortedhashsets/VUT-ISJ | /MINITASKS on lecctures/isj_task41_xabram00.py | 1,400 | 3.609375 | 4 | # minitask 4.1
default_qentry = ('How do you feel today?', ['sad','happy','angry'])
funcqpool = [('If return statement is not used inside the function, the function will return:',
['0',
'None object',
'an arbitrary integer',
'Error! Functions in Python must have a return statement.'
]),
('Which of the following function calls can be used to invoke function definition:\n def test(a, b, c, d):?',
['test(1, 2, 3, 4)',
'test(a = 1, 2, 3, 4)',
'test(a = 1, b = 2, c = 3, 4)',
'test(a = 1, b = 2, c = 3, d = 4)',
'test(1, 2, 3, d = 4)])'])
]
funcquiz1 = [('Which of the following keywords marks the beginning of the function block?',
['func',
'define',
'def',
'func',
])]
def add_question(a, pool, *quiz):
if not quiz:
try:
quiz2=[]
quiz2.append(default_qentry)
quiz2.append(pool[a])
except:
return("unsuccess",quiz2)
else:
return("success",quiz2)
else:
try:
quiz[0].append(pool[a])
except:
return("unsuccess",quiz[0])
else:
return("success",quiz[0])
print(add_question(0, funcqpool, funcquiz1))
print(funcquiz1)
print(add_question(0, funcqpool))
|
5cf16491a4644b2b59cef1e5b87806aa202142d3 | diable201/Grokking_Algorithms | /lec_04/recursive_max.py | 365 | 4.03125 | 4 | def recursive_max(list):
if len(list) == 0:
return None
elif len(list) == 1:
return list[0]
else:
max_element = recursive_max(list[1:])
if list[0] > max_element:
return list[0]
else:
return max_element
list = [0, 4, 1023, 511, -11, 9]
print("Maximum element is: %s" %recursive_max(list)) |
15546cc3ec9be09fef629ad95af6afc77602b6e4 | itandjaya/Iris-Classification | /NN_IRIS_main.py | 5,457 | 3.5625 | 4 | ## NN_digits_main.py
## Main function to test the Neural Network - digits.
#####################################################
## 4-Layers NN: [28*28, 60, 15, 10].
## Image size is 28 x 28 pixels.
##
from import_data import load_data;
from NN_Model import NN_Model, one_hot;
from random import randint;
from numpy import save as np_save, load as np_load;
import numpy as np;
import os;
import matplotlib.pyplot as plt; # To plot Cost vs. # of iterations.
CURRENT_PATH = os.getcwd();
#CURRENT_HOME = (os.path.expanduser('~'))
Grad_Descent_Method, Minimize_funct_method = True, False;
PLOT_COST = True; ## Plot J_cost vs. # of iterations to check if J_cost converges to minimum.
LOAD_PREV_THETAS = False; ## Load the previous trained weights. Otherwise, randomize initial weights.
CONTINUOUS_TRAINING = True; ## If True, then it will train the NN (10k training iterations.)
COUNT_ERROR = False; ## Compute the error rate of the trained prediction function.
## against the test samples (60k images). So far, ~8.5% error.
CLASS_GROUPS = ("Iris Setosa", "Iris Versicolour", "Iris Virginica");
def plot_iris_data(x, y):
## Using matplotlib to display the gray-scaled digit image.
## Preparing data by classification groups
groups_sepal = [0]*max(y+1);
groups_petal = [0]*max(y+1);
for i in range(len(y)):
if groups_sepal[y[i]] == 0:
groups_sepal[y[i]] = ( [ x[i][0] ], [ x[i][1] ]);
groups_petal[y[i]] = ( [ x[i][2] ], [ x[i][3] ]);
else:
groups_sepal[y[i]][0].append( x[i][0] );
groups_sepal[y[i]][1].append( x[i][1] );
groups_petal[y[i]][0].append( x[i][2] );
groups_petal[y[i]][1].append( x[i][3] );
## Setting up the plot variables.
COLOR_LOOKUP = {0:'red', 1:'green', 2:'yellow'};
colors = ('red', 'green', 'blue');
#fig = plt.figure();
fig, (ax_sepal, ax_petal) = plt.subplots(2, sharex = True);
## Plotting Sepal length and width.
for data, color, group in zip(groups_sepal, colors, CLASS_GROUPS):
x, y = data;
ax_sepal.scatter( x, y , alpha=0.8, c = color, edgecolors='none', s=30, label=group);
plt.title('Iris Sepal & Petal Length and Width');
## Plotting Petal length and width.
for data, color, group in zip(groups_petal, colors, CLASS_GROUPS):
x, y = data;
ax_petal.scatter( x, y , alpha=0.8, c = color, edgecolors='none', s=30, label=group);
plt.legend(loc=1);
plt.show();
return;
def main():
x_data, y_data = load_data(); ## Set parameter to True for initial download.
## Once data is present, set this to False to
## prevent re-downloading data.
## Plotting the Iris Petal and Sepal length and width.
plot_iris_data(x_data, y_data);
y_data = one_hot(y_data);
#Split data: 80% test set, 20% validation set.
i_80 = int(len(y_data)*0.8);
x_train, y_train = x_data[:i_80], y_data[:i_80];
x_test, y_test = x_data[i_80:], y_data[i_80:];
iris_nn = NN_Model ( x_train, ## input data.
y_train, ## output data.
3, ## 3 NN layers: Input, hidden-layer, output.
[4,4,3] ); ## num of nodes for each layer.
if Grad_Descent_Method:
print("\nNeural Network XNOR - using GRADIENT DESCENT ITERATION\n", "#"*30, "\n");
# File location where learned weight is saved.
theta_file = CURRENT_PATH + r'/' + 'theta.npy';
if LOAD_PREV_THETAS:
flat_thetas = np_load( theta_file);
iris_nn.unflatten_Thetas( flat_thetas);
if CONTINUOUS_TRAINING:
iris_nn.train_NN();
np_save( theta_file, iris_nn.flatten_Thetas());
else:
iris_nn.train_NN();
np_save( theta_file, iris_nn.flatten_Thetas());
# Display final cost after learning iterations.
print("Final Cost J = ", iris_nn.J_cost(iris_nn.a[-1]));
if PLOT_COST:
# Plot the J Cost vs. # of iterations. J should coverge as iteration increases.
x_axis = range(len(iris_nn.J_cost_values));
y_axis = iris_nn.J_cost_values;
plt.plot( x_axis, y_axis, label='J_cost vs. # of Iterations');
plt.show();
# Test model accuracy on Validation/Test set.
acc_count = 0;
for i in range( len(x_test)):
x_input = x_test[i].flatten();
y_val = np.argmax(y_test[i]);
y_pred = iris_nn.predict( x_input )[0];
#print(y_pred, y_val);
if y_pred == y_val: acc_count += 1;
print( "Test Accuraccy = {}".format( acc_count/len(x_test)));
return 0;
if __name__ == "__main__": main();
|
99b83234b8abc52a45191c4f66d76546e96d4cf7 | sam-kumar-sah/Leetcode-100- | /53a. Maximum Subarray.py | 703 | 3.984375 | 4 | //53. Maximum Subarray
'''
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
'''
//code:
//method-1:
def ms(nums):
em=nums[0]
im=nums[0]
for i in nums[1:]:
if(i < em+i):
em+=i
else:
em=i
if(im < em):
im=em
return im
nums=[-2,-1]
nums=[-2,1,-3,4,-1,2,1,-5,4]
print(ms(nums))
//method-2:
def mss(nums):
if not nums:
return 0
n=len(nums)
cur=prev=0
res=float("-Inf")
for i in range(n):
cur=nums[i]+(prev if prev >0 else 0)
prev=cur
res=max(res,cur)
return res
nums=[-2,-1]
nums=[-2,1,-3,4,-1,2,1,-5,4]
print(mss(nums)) |
8c3963443701156f5abd53f03aa01c2d475d9a78 | aakib97/Python_Learning | /Code for thought 7/sorting.py | 1,308 | 3.984375 | 4 | ## Code for thought 07
## Change the following sorting algorithms so that each algorithm returns
## the number of swaps between the list items,
## the number of comparisons between list items,
## and the sum of these two operations in the sorting algorithm
def bubblesort(L):
count_s = count_c = 0
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L) - 1):
count_c +=1
if L[i] > L[i + 1]:
count_s +=1
L[i], L[i + 1] = L[i + 1], L[i]
keepgoing = True
return count_s, count_c, count_s + count_c
def selectionsort(L):
count_s = count_c = 0
n = len(L)
for i in range(n - 1):
max_index = 0
for index in range(n - i):
count_c += 1
if L[index] > L[max_index]:
max_index = index
L[n - i - 1], L[max_index] = L[max_index], L[n - i - 1]
count_s +=1
return count_s, count_c, count_s + count_c
def insertionsort(L):
count_s = count_c = 0
n = len(L)
for i in range(n):
j = n - i - 1
while j < n - 1 and L[j] > L[j + 1]:
L[j], L[j + 1] = L[j + 1], L[j]
count_s +=1
j += 1
count_c += 1
return count_s, count_c, count_s + count_c
|
230573190255493b53a56615c3c25fd87d7cb531 | mhussain790/SatData | /SatData.py | 1,630 | 3.625 | 4 | """
Author: Masud Hussain
Course: CS162
Assignment: 5C
"""
import json
class SatData:
def __init__(self):
"""
Opens the sat.json file when a SatData object is created and reads info from file.
JSON data is stored in sat_dictionary and then file is closed.
"""
with open("sat.json", "r") as infile:
sat_dictionary = json.load(infile)
self._sat_dictionary = sat_dictionary
def save_as_csv(self, dbn_list):
"""
Takes an input of a list of dbns.
Hard codes the column headers to the output.csv file.
Searches through the json file to find the matching information.
Wraps each value from the dictionary in double quotes and separates them with commas.
Outputs the formatted row to the output.csv file
:param dbn_list:
:return: output the matching dbn information to output.csv
"""
column_list = ["DBN", "School Name", "Number of Test Takers", "Critical Reading Mean", "Mathematics Mean", "Writing Mean"]
for items in column_list:
columns = ','.join(map(str, column_list))
with open('output.csv', 'w') as outfile:
outfile.write(str(columns) + '\n')
for keys in self._sat_dictionary["data"]:
for items in keys:
for dbns in dbn_list:
if items == dbns:
values = ','.join([str(f'"{keys[i]}"') for i in range(keys.index(dbns), len(keys))])
with open('output.csv', 'a') as outfile:
outfile.write(str(values) + '\n')
|
8e23a64a9caeef0a7eba6989a1a3fcfe9350cfd8 | nivedipagar12/PythonSamples | /Tic_Tac_Toe_Game/main.py | 5,994 | 4.3125 | 4 | '''Title : Tic Tac Toe
Author : Nivedita Pagar
Date : 10/04/2018
Details : 1) The code plays the Tic Tac Toe Game with Two players sitting on the same computer
and declares whether a player won the game or it was a tie.
2) It keeps playing until the players want to stop
'''
import random
def print_board(board):
'''This function prints the board every time this function is called. The changes made to the variable the_board
don't affect the code as we are printing the values associated with the indices '''
print(str(board[7]) + ' | ' + str(board[8]) + ' | ' + str(board[9]))
print('---------')
print(str(board[4]) + ' | ' + str(board[5]) + ' | ' + str(board[6]))
print('---------')
print(str(board[1]) + ' | ' + str(board[2]) + ' | ' + str(board[3]))
def player_input():
'''This function decides which marker (X, O) belongs to which player and returns a tuple (X,O) depending on the
players choice'''
marker = ''
while marker.upper() != 'X' and marker.upper() != 'O':
marker = input('Player 1: Choose your marker : ')
if marker.upper() == 'X':
return ('X', 'O')
else:
if marker.upper() == 'O':
return ('O', 'X')
def place_marker(board, marker, position):
'''This function takes in the arguments board, marker and position and places the marker at the specified position
on the board'''
board[position] = marker
def win_check(board, mark):
'''This function checks if a player has won by checking if the marker on the board satisfies any of the win combinations'''
return ((board[1] == mark and board[2] == mark and board[3] == mark) or # row 1
(board[4] == mark and board[5] == mark and board[6] == mark) or # row 2
(board[7] == mark and board[8] == mark and board[9] == mark) or # row 3
(board[1] == mark and board[4] == mark and board[7] == mark) or # column 1
(board[2] == mark and board[5] == mark and board[8] == mark) or # column 2
(board[3] == mark and board[6] == mark and board[9] == mark) or # column 3
(board[3] == mark and board[5] == mark and board[7] == mark) or # diagonal
(board[1] == mark and board[5] == mark and board[9] == mark)) # diagonal
def choose_first():
'''This functions randomly decides which player goes first'''
flip = random.randint(0,1)
if flip == 0:
return 'Player 1'
else:
return 'Player 2'
def space_check(board, position):
'''This function decides if the specified position on the board is free or not'''
return position in range(1,10) and board[position] == ' '
def full_board_check(board):
'''This function uses the space_check() function to determine if the board is full or not'''
for i in range(1,10):
if space_check(board,i):
return False
return True
def player_choice(board):
'''This function asks the user to choose a position at which they want to place their marker and places it if the
specified position is available'''
position = 0
while not space_check(board,position):
position = int(input('Choose a position (1-9)'))
return position
def replay():
'''This function asks the player if they want to play again or quit'''
choice = input('Do you want to play again? Enter y/n')
return choice.lower() == 'y'
'''The main logic of the code starts here '''
print('Welcome to Tic Tac Toe')
while True:
# Create an empty board of length 10
# We actually only need 9 but it is easier to associate the indices with positions
the_board = [' ']*10
# unpack the tuple generated by the player_input() function and assign the corresponding markers
player1_marker, player2_marker = player_input()
# Decide who goes first and let the players know by printing it out
turn = choose_first()
print(turn + ' will go first')
# This is optional : Ask the players if they are ready to play and continue if they enter 'y'
play_game = input('Ready to play ? y/n')
if play_game.lower() == 'y':
game_on = True
else:
game_on = False
# If the players are ready to play, i.e if game_on == True, start playing
while game_on:
if turn == 'Player 1':
# Print the board for the players to see
print_board(the_board)
# Ask for the players preferred position to place the marker and place it if the position is free
position = player_choice(the_board)
place_marker(the_board, player1_marker, position)
# Check if a player has won
if win_check(the_board, player1_marker):
print_board(the_board)
print('PLAYER 1 HAS WON !!!')
game_on = False
# If no one has won, check if there is a tie by checking if the board is full
else:
if full_board_check(the_board):
print_board(the_board)
print('ITS A TIE !!!')
game_on = False
# If no one has won and there is no tie, its the next players turn to play
else:
turn = 'Player 2'
# Repeat the same for the next player
else:
print_board(the_board)
position = player_choice(the_board)
place_marker(the_board, player2_marker, position)
if win_check(the_board, player2_marker):
print_board(the_board)
print('PLAYER 2 HAS WON !!!')
game_on = False
else:
if full_board_check(the_board):
print_board(the_board)
print('ITS A TIE !!!')
game_on = False
else:
turn = 'Player 1'
# Check if the players want to play again, if not, break out of the while True loop and end the program
if not replay():
break
|
ba6b615a3efb7b68509ce9156b582fd678081cc2 | aindrila2412/Algorithms | /Online_Challenges/Vaccine.py | 2,116 | 3.953125 | 4 | # Finally, a COVID vaccine is out on the market
# and the Chefland government has asked you to form a plan to distribute it to the public as soon as possible.
# There are a total of N people with ages a1,a2,…,aN
# There is only one hospital where vaccination is done and it is only possible to vaccinate up to D people per day.
# Anyone whose age is ≥80 or ≤9 is considered to be at risk.
# On each day, you may not vaccinate both a person who is at risk and a person who is not at risk.
# Find the smallest number of days needed to vaccinate everyone.
# The first line of each test case contains two space-separated integers N and D.
# The second line contains N space-separated integers a1,a2,…,aN.
# link https://www.codechef.com/DEC20B/problems/VACCINE2
import sys
import math
def Vaccine2 (people_number, test_cases, people_age):
days = 0
# convert every data to integer type
people_number = int(people_number)
test_cases = int(test_cases)
int_people_age = map(lambda x: int(x), people_age)
# if test case is 1, there's no need for grouping
if test_cases == 1:
days = people_number
return days
elif test_cases > 1:
at_risk_people = []
normal_people = []
for i in int_people_age:
if i <= 9 or i >= 80:
at_risk_people.append(i)
elif 9 < i < 80:
normal_people.append(i)
days += (math.ceil(len(normal_people)/test_cases))
days += (math.ceil(len(at_risk_people)/test_cases))
return days
# read input
user_input = [line.rstrip() for line in sys.stdin.readlines()]
people_number = []
test_cases = []
people_age = []
for i in user_input[1:]:
if user_input.index(i) % 2 != 0:
a_list = i.split(' ')
people_number.append(a_list[0])
test_cases.append(a_list[1])
elif user_input.index(i) % 2 == 0:
a_list = i.split(' ')
people_age.append(a_list)
i = 0
while i < int(user_input[0]): # number of data tests
print(Vaccine2(people_number[i], test_cases[i], people_age[i]))
i += 1 |
eee1ca44c09c1d54d5ab985f3f415a9e6f8a2aa8 | soroushh/PythonLearningUdemy | /loop.py | 229 | 4.03125 | 4 | my_variable = "hello"
for letter in my_variable:
print(letter)
user_wants_true = True
counter = 0
while counter <= 5 :
if user_wants_true == True:
print("still true")
counter += 1
print("it is over")
|
ee6ab97f8af871d7dedbe2807945d357d920d22e | shollercoaster/madlib | /madlib.py | 770 | 3.6875 | 4 | import re
def madlib():
fresh=open("fresh.txt", 'w+') #fresh.txt is just an empty text file where the changed paragraph is written.
story=open("story.txt", 'r')
with open("write.txt", 'r+') as output:
read=story.readlines()
write=output.readlines()
# print(read)
# print(write)
for iter in range(0,11):
print(read[iter], '\n')
choice= input("enter choice:")
line=write[iter]
linenew=re.sub("_", choice, line)
fresh.write(linenew)
print("the final story is:")
fresh.seek(0)
final=fresh.read()
print(final)
#if __name__== "__main__":
madlib()
fresh=open("fresh.txt", 'r+')
fresh.truncate()
fresh.close()
|
4e6b237741d61ebddb8a27203968807b7f4c08b5 | harshil1903/leetcode | /Math/1281_product_and_sum_of_digit_of_number.py | 820 | 3.71875 | 4 |
# 1281. Subtract the Product and Sum of Digits of an Integer
#
# Source : https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
#
# Given an integer number n, return the difference between the product of its digits and the sum of its digits.
class Solution:
def subtractProductAndSum(self, n: int) -> int:
digits = [int(i) for i in str(n)]
sm, mul = 0, 1
for j in digits:
sm += j
mul *= j
return mul - sm
def subtractProductAndSum1(self, n: int) -> int:
sm, mul = 0, 1
for digit in str(n):
sm += int(digit)
mul *= int(digit)
return mul - sm
if __name__ == '__main__':
s = Solution()
print(s.subtractProductAndSum(234))
print(s.subtractProductAndSum1(4421)) |
d76dbaeee5891faa8dee8623777bef6d0451956d | Ghanshyam1296/Python-Basics | /oop.py | 875 | 4.03125 | 4 | #Python Object Oriented Programming
class Employee:
pass
#Instance of class
emp_1=Employee()
emp_2=Employee()
print(emp_1)
print(emp_2)
emp_1.first='Ghanshyam'
emp_1.last='Rathore'
emp_1.pay=50000
emp_2.first='Narseh'
emp_2.last='Rathore'
emp_2.pay=6000
print(emp_1.first)
print(emp_2.pay)
#__init__ function (constructor)
class employee:
def __init__(self,first,last,pay):
self.first=first
self.last=last
self.pay=pay
self.email=first+'.'+last+'@company.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
emp_1=employee('ghanshyam','rathore',80000)
emp_2=employee('naresh','rathore',90000)
print(emp_1.email)
print(emp_2.pay)
print(emp_1.fullname().upper())
print(employee.fullname(emp_2))
#self->instance, (first,last,pay)->Attributes, fullname()->Method
|
b78b459957df836523cb5f3b446cb75257a0291f | CHIRRANJIT/Python-language | /modules.py | 1,271 | 3.859375 | 4 | # importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print math.sqrt(25)
# using pi function contained in math module
print math.pi
# 2 radians = 114.59 degreees
print math.degrees(2)
# 60 degrees = 1.04 radians
print math.radians(60)
# Sine of 2 radians
print math.sin(2)
# Cosine of 0.5 radians
print math.cos(0.5)
# Tangent of 0.23 radians
print math.tan(0.23)
# 1 * 2 * 3 * 4 = 24
print math.factorial(4)
# importing built in module random
import random
# printing random integer between 0 and 5
print random.randint(0, 5)
# print random floating point number between 0 and 1
print random.random()
# random number between 0 and 100
print random.random() * 100
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print random.choice(List)
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print time.time()
# Converts a number of seconds to a date object
print date.fromtimestamp(454554)
|
6252e1df6973ee6db76fa2031936467cb26eb64b | wmm0165/crazy_python | /07/7.2/gobang.py | 1,223 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/6/23 18:43
# @Author : wangmengmeng
# 定义棋盘的大小
BOARD_SIZE = 15
# 定义一个二维列表来充当棋盘
board = []
def initBoard() :
# 把每个元素赋为"╋",用于在控制台画出棋盘
for i in range(BOARD_SIZE) :
row = ["╋"] * BOARD_SIZE
board.append(row)
# 在控制台输出棋盘的方法
def printBoard() :
# 打印每个列表元素
for i in range(BOARD_SIZE) :
for j in range(BOARD_SIZE) :
# 打印列表元素后不换行
print(board[i][j], end="")
# 每打印完一行列表元素后输出一个换行符
print()
initBoard()
printBoard()
input_str = input("请输入您下棋的坐标,应以x,y的格式:\n")
while input_str != None:
try:
x_str,y_str = input_str.split(sep=',')
if board[int(x_str)-1][int(y_str)-1] != '+':
continue
board[int(y_str) - 1][int(x_str) - 1] = "●"
except Exception:
inputStr = input("您输入的坐标不合法,请重新输入,下棋坐标应以x,y的格式\n")
continue
printBoard()
input_str = input("请输入您下棋的坐标,应以x,y的格式:\n")
|
06312b8f1b2c0d2c5b29bb010b832a98105d5c5c | NicoleRL25/cincy_employee_analysis | /code/data_cleaning.py | 12,807 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 10 09:12:02 2021
@author: letti
"""
import pandas as pd
from pandas.api.types import CategoricalDtype
import numpy as np
from datetime import datetime
def clean_emp_list(file_name=None):
"""
Reads the cincinnati employee csv file and outputs a clean file
Returns
-------
None.
"""
if file_name==None:
file_name='..\data\input\cincinnati_employees.csv'
today=datetime.today()
try:
#read csv containing cincinnati employee data into a pandas dataframe
emps=pd.read_csv(file_name,
dtype={'SEX':'category' ,'RACE':'category',
'DEPTNAME':'category','DEPTID':'str',
'POSITION_NBR':'str','JOBCODE':'str',
'GRADE':'str'},
parse_dates=['JOB_ENTRY_DT','HIRE_DATE'])
#changes column names to lower case
emps.columns=emps.columns.str.lower()
#create an ordered category type for age groups
cat_type = CategoricalDtype(categories=['UNDER 18','18-25','26-30',
'31-40','41-50','51-60',
'61-70', 'OVER 70'],
ordered=True)
#casts the age_range as a categorical data type
emps['age_range']=emps.age_range.astype(cat_type)
#creates a dictionary to map eeo job codes to category names
eeo_dict={1:'Officials and Administrators',2:'Professionals',
3:'Technicians' ,4:'Protective Service Workers',
5:'Protective Service Workers' ,6:'Administrative Support',
7:'Skilled Craft Workers',8:'Service-Maintenance'}
#maps the eeo codes to the text category
emps['eeo_job_class']=(emps.eeo_job_group.map(eeo_dict)
.fillna('Uncategorized'))
#creates a dictionary to map paygroups to a descriptive label
paygroup_dict={'GEN':'General','MGM':'Management','POL':'Police',
'FIR':'Fire Department','CCL':'City Council'}
#maps the paygroup to a label
emps['paygroup_label']=(emps.paygroup.map(paygroup_dict)
.fillna('Uncategorized'))
#change M and F to male and female
emps['sex']=emps.sex.apply(lambda x: 'Male' if x=='M' else 'Female')
#consolidated race groups by assigning Chinese to the
#Asian/Pacific Islander group and assigned Torres Strait Islander
#Origin to Aboriginal/Torres Strait Island
#Formatted text to title case
emps['race']=emps.race.str.title()
emps['race']=emps['race'].str.replace('Chinese',
'Asian/Pacific Islander')
emps['race']=emps['race'].str.replace('Torres Strait Islander Origin',
'Aboriginal/Torres Strait Island')
#add a column for full time / part-time based on FTE column
emps['full_time']=emps.fte.apply(lambda x: 'Full-Time'
if x == 1 else 'Part-Time')
#calculate employee tenure and time in job in years
emps['tenure']=round((today-emps.hire_date)/np.timedelta64(1,'Y'),2)
#convert salary to float
emps['annual_rt']=emps.annual_rt.str.replace(',','')
emps['annual_rt']=emps.annual_rt.astype('float')
return emps
except Exception as e:
print(e)
def save_emp_list(emps):
"""
outputs cleaned file to output folder
"""
try:
emps.to_csv('..\data\output\cleaned_cincy_emp_list.csv',index=False)
except Exception as e:
print(e)
def get_data_for_plots(emps):
data_dict={}
race_categories=['White','Black','Asian/Pacific Islander', 'Hispanic',
'American Indian/Alaskan Native']
emps=emps.copy()
if emps.empty:
pass
else:
race_df=emps.loc[emps.race.isin(race_categories)].copy()
data_dict['race_df']=race_df
#Creates list of eeo job classes
eeo_job_classes=list(emps.eeo_job_class.unique())
#Copies list of eeo job classes and removes officials
emps_non_officials=eeo_job_classes.copy()
emps_non_officials.remove('Officials and Administrators')
#Copies list of eeo job classes and removes protective service workers
emps_non_protective=eeo_job_classes.copy()
emps_non_protective.remove('Protective Service Workers')
#counts of full-time and part time employees
emps_ft_pt=emps.full_time.value_counts(normalize=True)
data_dict['full_time']=emps_ft_pt
#counts by age group
emp_ages=emps.age_range.value_counts(sort=False)
data_dict['age_groups']=emp_ages
#counts by race
emps_race=emps.race.value_counts()
emps_race.sort_values(ascending=False,inplace=True)
data_dict['race']=emps_race
#percent of employees by gender
emps_gender=emps.sex.value_counts(normalize=True)
data_dict['gender']=emps_gender
#percent of employees by job class
emps_by_jobclass=(emps.eeo_job_class.value_counts(normalize=True)
.sort_values())
data_dict['job_class']=emps_by_jobclass
#count of employees in each job class segmented by gender
job_class_by_gender=emps.pivot_table(index='eeo_job_class',
values='name',columns='sex',
aggfunc='count')
data_dict['jobs_by_gender']=job_class_by_gender
#percent of employees in each job class segmented by gender
job_class_by_gender_pct=job_class_by_gender.div(job_class_by_gender
.sum(axis=1), axis=0)
data_dict['jobs_by_gender_pct']=job_class_by_gender_pct
#gets the total of employees in non-leadership roles
emps_non_official=(job_class_by_gender.loc[emps_non_officials].copy()
.sum())
emps_officials=(job_class_by_gender.loc['Officials and Administrators']
.copy())
#count of employees in leadership and non-leadership roles
#segmented by gender
leadership_by_gender=(pd.concat([emps_non_official,emps_officials],
axis=1)
.rename(columns={0:'Non-Leadership',
'Officials and Administrators':
'Leadership'}))
data_dict['leaders_by_gender']=leadership_by_gender
#percent of employees in leadership and non-leadership roles
#segmented by gender
leadership_by_gender_pct=(leadership_by_gender
.div(leadership_by_gender.sum()))
data_dict['leaders_by_gender_pct']=leadership_by_gender_pct
emps_non_protective_df=job_class_by_gender.loc[emps_non_protective]
emps_protective_df=job_class_by_gender.loc['Protective Service Workers']
protective_vs_general=(pd.concat([emps_protective_df,
emps_non_protective_df.sum()],
axis=1)
.rename(columns=({0:'General Workforce'})))
data_dict['pro_vs_general_gender']=protective_vs_general.T
protective_vs_general_gender_pct=(protective_vs_general
.div(protective_vs_general.sum(),axis=1))
data_dict['pro_vs_gen_gender_pct']=protective_vs_general_gender_pct.T
gender_police_fire=(emps.pivot_table(index='paygroup_label',
columns='sex',values='name',
aggfunc='count')
.loc[['Fire Department','Police']])
data_dict['gender_police_fire']=gender_police_fire
#count of employees in each job class segmented by race
job_class_by_race=emps.pivot_table(index='eeo_job_class',
values='name', columns='race',
aggfunc='count')
data_dict['job_class_race']=job_class_by_race
race_col_list=list(emps.race.value_counts().index)
#percent of employees in each job class segmented by race
job_class_by_race_pct=(job_class_by_race
.div(job_class_by_race.sum(axis=1)
,axis=0))
job_class_by_race_pct=(job_class_by_race_pct
.reindex(columns=race_col_list))
data_dict['job_class_race_pct']=job_class_by_race_pct
#count of the top 10 most frequent job titles
top_job_titles=emps.business_title.value_counts()[:10].sort_values()
data_dict['top_jobs']=top_job_titles
data_dict['cincy_race_demos']=get_cincinnati_racial_demographics()
expected_counts=(round(data_dict['cincy_race_demos']['expected']
*data_dict['race_df'].race.value_counts()
.sum(),0))
observed_counts=(data_dict['race_df'].race.value_counts()
.rename("observed"))
data_dict['chi_square']=(pd.concat([observed_counts,
expected_counts],axis=1)
.sort_values(by='expected'))
data_dict['chi_square']['std_residual']=(data_dict['chi_square']
.apply(lambda x: (x.observed
-x.expected)
/np.sqrt(x.expected),
axis=1))
data_dict['chi_square']['r_squared']=(data_dict['chi_square']
.apply(lambda x:
((x.observed
-x.expected)**2)
/x.expected,axis=1))
return data_dict
def get_cleaned_emp_list(file_name=None):
"""
Reads the cleaned Cincinnati employee list into a Pandas dataframe
Returns
-------
emps : df
Pandas dataframe of Cincinnati employees.
"""
if file_name==None:
file_name='..\data\output\cleaned_cincy_emp_list.csv'
try:
#create an ordered category type for age groups
cat_type = CategoricalDtype(categories=['UNDER 18','18-25','26-30',
'31-40','41-50','51-60',
'61-70', 'OVER 70']
,ordered=True)
emps=pd.read_csv(file_name)
#casts the age_range as a categorical data type
emps['age_range']=emps.age_range.astype(cat_type)
except Exception as e:
print(e)
else:
return emps
def get_cincinnati_racial_demographics():
cincy_pop_estimate=303940
cincy_race_distribution={'White':0.482,'Black':0.423,
'Asian/Pacific Islander':0.023,
'Hispanic':0.038,
'American Indian/Alaskan Native':.001}
df=(pd.DataFrame.from_dict(list(cincy_race_distribution.items()))
.rename(columns={0:'race',1:'percent'}))
df.set_index('race',inplace=True)
df['count']=round(df['percent']*cincy_pop_estimate,0)
df['expected']=df['count'].div(df['count'].sum())
return df
|
6477c414cce91b179ca8677cdfc3eacbbbd94086 | ho-kyle/python_portfolio | /023.py | 224 | 3.875 | 4 | from math import pi, tan
s = eval(input('Please enter the value of s: '))
n = eval(input('Please enter the value of n: '))
area = n * s**2 / 4 * tan(pi / n)
print(f'The area of the regular polygon constructed is {area}') |
2b30b4688fe1df288682af5aabb5f521b8fb33ae | amoljagadambe/python_studycases | /apptware/apptware/elasticsearch/itertool_test.py | 436 | 3.5625 | 4 | import itertools
input_list = [
{'a':'tata', 'b': 'bar'},
{'a':'tata', 'b': 'foo'},
{'a':'pipo', 'b': 'titi'},
{'a':'pipo', 'b': 'toto'},
]
# data = {k:[v for v in input_list if v['a'] == k] for k, val in itertools.groupby(input_list,lambda x: x['a'])}
# print(data)
for k, val in itertools.groupby(input_list,lambda x: x['a']):
print("--", k, "--")
for things in val:
print(things) |
ec27b5fb1eabd7e5b7d56c96392ced2356f07f9d | rajeshsvv/Lenovo_Back | /1 PYTHON/9 PYTHON PROGRAMS/PYTHON PROGRAMS NOUS/Techbeamers/ds list techbeam1.py | 3,126 | 3.953125 | 4 | # https://www.techbeamers.com/python-programming-questions-list-tuple-dictionary/'''
# Tuples have structure, lists have an order
# Tuples are immutable, lists are mutable.
# '''
"""
a=[1,2,3,4,5,6,7,8,9]
print(a[::2]) answer [1, 3, 5, 7, 9]
"""
'''
a=[1,2,3,4,5,6,7,8,9]
a[::2]=10,20,30,40,50,60
print(a) # answer:ValueError: attempt to assign sequence of size 6 to extended slice of size 5
'''
'''
a=[1,2,3,4,5,6,7]
print(a[1::-2]) # answer:[4, 3, 2]
'''
'''
def f(value, values):
v = 1
values[0] = 44
t = 3
v = [1, 2, 3]
f(t, v)
print(t, v[0]) # answer:3 44
'''
'''
import random
fruit=['apple', 'banana', 'papaya', 'cherry']
random.shuffle(fruit)
print(fruit)
'''
'''
data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
def fun(m):
v = m[0][0]
for row in m:
for element in row:
if v < element: v = element
return v
print(fun(data[0])) # answer:4
'''
arr = [[1, 2, 3, 4],[4, 5, 6, 7],[8, 9, 10, 11],[12, 13, 14, 15]]
for i in range(0,4):
print(arr[i].pop()) # answer:4 7 11 15
'''
def f(i, values = []):
values.append(i)
print (values)
return True
f(1)
f(2)
f(3)
'''
'''
arr = [1, 2, 3, 4, 5, 6,7]
for i in range(1, 6):
arr[i - 7] = arr[i]
for i in range(0, 7):
print(arr[i], end = " ")
'''
'''
fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']
fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]
fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi':
sum += 20
print (sum) answer:22
'''
'''
init_tuple = ()
print (init_tuple.__len__()) answer:0
'''
'''
init_tuple_a = 'a', 'b'
init_tuple_b = ('a', 'b')
print (init_tuple_a == init_tuple_b) answer:True
'''
'''
init_tuple_a = '1', '2'
init_tuple_b = ('3', '4')
print (init_tuple_a + init_tuple_b) answer:('1', '2', '3', '4')
'''
'''
init_tuple_a = 1, 2
init_tuple_b = (3, 4)
[print(sum(x)) for x in [init_tuple_a + init_tuple_b]] answer:10
'''
'''
init_tuple = [(0, 1), (1, 2), (2, 3)]
result = sum(n for _, n in init_tuple)
print(result) answer:6
'''
'''
l = [1, 2, 3]
init_tuple = ('Python',) * (l.__len__() - l[::-1][0])
print(init_tuple) # answer: ()
'''
'''
init_tuple = ('Python') * 5
print(init_tuple,"\n")
print(type(init_tuple)) # answer:str
'''
'''
init_tuple = (1,) * 3
init_tuple[0] = 2
print(init_tuple) # answer:tuple object does not support item assignment
'''
'''
init_tuple = ((1, 2),) * 7
print(init_tuple)
print(len(init_tuple[3:8])) # answer:4
'''
|
a9d6dd10d09c4c1f8e787bd8d188c53c72582c82 | QuanAVuong/dsa-py | /03.1-Stacks.py | 1,260 | 4.0625 | 4 | class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
return self.stack == []
def showStack(self, operation=""):
for i, v in enumerate(self.stack):
if i == 0 and operation == "push":
print("|___|" if self.sizeStack() == 1 else "| |", f"<-- {self.stack[-i-1]}")
elif i == 0 and operation == "pop":
print(f"| | --> {self.stack[-1]}")
elif i < len(self.stack)-1:
print(f"| {self.stack[-i-1]} |")
else:
print(f"|_{self.stack[-i-1]}_|")
def sizeStack(self):
return len(self.stack)
def push(self, data):
self.stack.append(data)
print(f"pushing {data} to the stack: ", f"( list view: {self.stack} )")
self.showStack("push")
def pop(self):
data = self.stack[-1]
print(f"Popped last item {data} from stack: (list view: {self.stack} )")
self.showStack("pop")
del self.stack[-1]
return data
# return self.stack.pop()
def peek(self):
return self.stack[-1]
stack1 = Stack()
stack1.push(1)
stack1.push(2)
stack1.push(3)
stack1.push(4)
stack1.push(5)
print("Stack's size:", stack1.sizeStack())
stack1.pop()
stack1.pop()
print("Stack's size:", stack1.sizeStack())
print(f"Peeking...( ~ .o) | {stack1.peek()} |") |
0e90edfbcd7dce7f95b41148df73482c4da77b5b | aliakseik1993/skillbox_python_basic | /module1_13/module4_hw/task_4.py | 1,559 | 3.984375 | 4 | print('Задача 4. Калькулятор скидки')
# Андрей переехал на новую квартиру, и ему нужно купить три стула в разные комнаты.
# Естественно, цена на стулья в разных магазинах различается,
# а где-то ещё и скидка есть.
# Вот для одного из таких магазинов он и написал калькулятор скидки,
# чтобы проще ориентироваться в ценах.
# Напишите программу,
# которая запрашивает три стоимости товара и вычисляет сумму чека.
# Если сумма чека превышает 10 000 рублей,
# то нужно вычесть из этой суммы скидку 10% (умножить на 10, разделить на 100).
# В конце вывести итоговую сумму на экран.
number_input_1 = int(input("Введите стоимость первого товара: "))
number_input_2 = int(input("Введите стоимость второго товара: "))
number_input_3 = int(input("Введите стоимость третьего товара: "))
expenses = number_input_1 + number_input_2 + number_input_3
if expenses > 10000:
discount = expenses * 10 / 100
expenses -= discount
print("Итоговая стоимость:", expenses)
else:
print("Итоговая стоимость:", expenses) |
a896d68de280b2ad9bc3788ad1ccad29f15c6a0b | Nicendredi/exercices-python | /fibonacci/fibonacci.py | 7,067 | 3.765625 | 4 | from liste import *
# Cette ligne permet à {fibonacci.py} d'accéder aux fonctions de liste.py
# Une suite de Fibonacci est une suite où chaque élément est la somme des deux
# éléments précédents :
# f(0) = 1
# f(1) = 1
# f(2) = 2 = 1 + 1
# f(3) = 3 = 1 + 2
# f(4) = 5 = 2 + 3
# f(5) = 8 = 3 + 5
def combiner(objet1, objet2):
# Cette fonction sert à être sûr qu'on peut combiner deux objets qu'ils
# soient deux nombres, deux chqines de carqctère ou deux listes. On pourra
# rajouter des cas au fur et à mesure
if not isinstance(objet1, type(objet2)):
# Beaucoup de languages ont une fonction similaire pour tester le type
return False
if isinstance(objet1, type(1)):
# sont des nombres ?
return objet1 + objet2
# Addition
elif isinstance(objet1, type("")):
# sont des chaînes de caractère ?
res = ""
# Création d'une nouvelle chaîne
for char in objet1:
res = res + char
# On ajoute les caractères de objet1
for char in objet2:
res = res + char
# On ajoute les caractères de objet2
return res
elif isinstance(objet1, type([])):
# sont des listes ?
res = []
for valeur in objet1:
res.append(valeur)
# On ajoute les valeurs de objet1
for valeur in objet2:
res.append(valeur)
# On ajoute les valeurs de objet2
return res
return True
def afficherFibo(n):
# Affiche la valeur de la suite de fibonacci à la position n et
# renvoie True.
# ex : afficherFibo(0) => print(1)
# afficherFibo(5) => print(8)
pass
# ----------------
# Les exercices suivants peuvent utiliser les fonctions créées dans {liste.py}
# pour simplifier le code et gagner du temps, mais ce n'est pas obligatoire
#
# Exemple : Pour verifierFibo(l) : on compare la liste 'l' avec une liste
# 'lfibo' de même taille générée par listeFibo(n)
#
# compareListes(l, lfibo) -> renvoie vrai si l et lfibo sont identiques
# ----------------
def listeFibo(n):
# Créé une suite de Fibonacci jusqu'à n, organisé sous la forme d'une
# liste, puis renvoie cette liste.
pass
def verifierFibo(l):
# Vérifie que la liste 'l' est bien une suite de Fibonacci. Renvoie True si
# bien formée, False sinon
pass
def elementNonFibo(l):
# Renvoie le premier élément de la liste qui ne respecte pas la suite de
# Fibonacci
pass
# ----------------
# Tests écris à l'avance : vérifier dans la console si les résultats sont
# justes avant de passer à la fonction suivante
# ----------------
if combiner(1, 1):
print("combiner(3,5) =", combiner(3, 5))
print('combiner("ABC", "123") =', combiner("ABC", "123"))
print(
"combiner(['a', 'b'], ['%', '%', '%']) =",
combiner(['a', 'b'], ['%', '%', '%']))
print()
fibo = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
if afficherFibo(-1):
print("afficherFibo(0) =", end=' ')
afficherFibo(0)
print("devrait afficher :", fibo[0])
print("afficherFibo(1) =", end=' ')
afficherFibo(1)
print("devrait afficher :", fibo[1])
print("afficherFibo(5) =", end=' ')
afficherFibo(5)
print("devrait afficher :", fibo[5])
print("afficherFibo(-5) =", end=' ')
afficherFibo(-5)
print("devrait afficher :", 0)
print()
if listeFibo(0):
print("listeFibo(0) =", listeFibo(0))
print("devrait afficher :", fibo[0])
print("listeFibo(5) =", listeFibo(5))
print("devrait afficher :", fibo[0:6])
print("listeFibo(7) =", listeFibo(7))
print("devrait afficher :", fibo[0:8])
print()
if verifierFibo([]):
print("verifierFibo([1,1,2,3,5]) =", verifierFibo([1, 1, 2, 3, 5]))
print("devrait afficher :", fibo[0:5] == [1, 1, 2, 3, 5])
print("verifierFibo([0,1,2,3,5]) =", verifierFibo([0, 1, 2, 3, 5]))
print("devrait afficher :", fibo[0:5] == [0, 1, 2, 3, 5])
print("verifierFibo([1,1,2,3,4]) =", verifierFibo([1, 1, 2, 3, 4]))
print("devrait afficher :", fibo[0:5] == [1, 1, 2, 3, 4])
print("verifierFibo([8,1,3,2,5,1]) =", verifierFibo([8, 1, 3, 2, 5, 1]))
print("devrait afficher :", fibo[0:56] == [8, 1, 3, 2, 5, 1])
print()
if elementNonFibo([]):
print("elementNonFibo([1,1,2,3,5]) =", elementNonFibo([1, 1, 2, 3, 5]))
print("devrait afficher : Null")
print("elementNonFibo([0,1,2,3,5]) =", elementNonFibo([0, 1, 2, 3, 5]))
print("devrait afficher : 0")
print("elementNonFibo([1,1,2,3,4]) =", elementNonFibo([1, 1, 2, 3, 4]))
print("devrait afficher : 4")
print(
"elementNonFibo([8,1,3,2,5,1]) =",
elementNonFibo([8, 1, 3, 2, 5, 1]))
print("devrait afficher : 8")
print()
# ----------------
# Exercices bonus
# ----------------
def estFibo(l):
# Vérifie que la liste NON-TRIEE 'l' est une suite de Fibonacci. Renvoie
# True si bien formée, False sinon
pass
# ----------------
# La fonction print, peut accepter un paramètre spécial "end"
#
# Exemple : le code
# print("premier print", end=" ")
# print("deuxième print")
# print("troisième print")
#
# affiche :
# ==================
# premier print deuxième print
# troisième print
# ==================
# ----------------
def afficheTriangleListeFibo(l):
# Affiche la liste 'l' (qui est une suite de Fibonacci) de la façon
# suivante et renvoie True :
# ==================
# 1
# 1 1
# 1 1 2
# 1 1 2 3
# 1 1 2 3 5
# ...
# ==================
pass
def afficheTriangleFibo(n):
# Afficher la suite de Fibonacci jusqu'à 'n' avec le même visuel que
# précédement et renvoie True
pass
# ----------------
# Tests écris à l'avance : vérifier dans la console si les résultats sont
# justes avant de passer à la fonction suivante
# ----------------
if estFibo([1]):
print("estFibo([1,1,2,3,5])", estFibo([1, 1, 2, 3, 5]))
print("devrait afficher : True")
print("estFibo([0,1,2,3,5])", estFibo([0, 1, 2, 3, 5]))
print("devrait afficher : False")
print("estFibo([1,1,2,3,4])", estFibo([1, 1, 2, 3, 4]))
print("devrait afficher : False")
print("estFibo([8,1,3,2,5,1])", estFibo([8, 1, 3, 2, 5, 1]))
print("devrait afficher : True")
print()
if afficheTriangleListeFibo([1]):
print(
"afficheTriangleListeFibo([1,1,2,3,5])",
afficheTriangleListeFibo([1, 1, 2, 3, 5]))
print(
"afficheTriangleListeFibo([0,1,2,3,5])",
afficheTriangleListeFibo([0, 1, 2, 3, 5]))
print(
"afficheTriangleListeFibo([1,1,2,3,4])",
afficheTriangleListeFibo([1, 1, 2, 3, 4]))
print(
"afficheTriangleListeFibo([8,1,3,2,5,1])",
afficheTriangleListeFibo([8, 1, 3, 2, 5, 1]))
print()
if afficheTriangleFibo(0):
print("afficheTriangleFibo(0)", afficheTriangleFibo(0))
print("afficheTriangleFibo(5)", afficheTriangleFibo(5))
print("afficheTriangleFibo(7)", afficheTriangleFibo(7))
|
2f1024bf5398050f4b09e277a312a660dc11e6ca | JaceHo/AlgorithmsByPython | /QuickSort.py | 1,740 | 3.921875 | 4 | def quickSort(alist):
quickSortHelper(alist, 0, len(alist) - 1)
def quickSortHelper(alist, first, last):
if first < last:
splitPoint = partition(alist, first, last)
quickSortHelper(alist, first, splitPoint - 1)
quickSortHelper(alist, splitPoint + 1, last)
def partition(alist, first, last):
pivotvlue = alist[first]
leftmark = first + 1
rightmark = last
done = False
while not done:
while alist[leftmark] <= pivotvlue and leftmark <= rightmark:
leftmark += 1
while alist[rightmark] >= pivotvlue and rightmark >= leftmark:
rightmark -= 1
if leftmark > rightmark:
done = True
else:
alist[leftmark], alist[rightmark] = alist[rightmark], alist[leftmark]
alist[rightmark], alist[first] = alist[first], alist[rightmark]
return rightmark
def qsort(lists, low, high):
print('this', lists[low:high + 1])
left = low
right = high
pivot = low
while high > low:
while lists[high] >= lists[pivot] and high > low:
high -= 1
while lists[low] <= lists[pivot] and high > low:
low += 1
lists[high], lists[low] = lists[low], lists[high]
print('swape', lists, high, low)
high -= 1
low += 1
pivot = low - 1
lists[left], lists[pivot] = lists[pivot], lists[left]
print('parted', lists, 'left', left, 'pivot', pivot)
if pivot > left + 1:
qsort(lists, left, pivot - 1)
if pivot < right - 1:
qsort(lists, pivot + 1, right)
return lists
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
alist2 = [1]
print(alist2)
quickSort(alist2)
print(alist2)
print(alist)
quickSort(alist)
print(alist)
|
8321f5e0132f856215d328d4df68c23eb26ac99c | thomasyu929/Leetcode | /Tree/recoverBST.py | 1,518 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 1
# def recoverTree(self, root: TreeNode) -> None:
# """
# Do not return anything, modify root in-place instead.
# """
# from collections import deque
# res = []
# self.helper(root, res)
# res.sort()
# # print(res)
# res = deque(res)
# stack = []
# while stack or root:
# while root:
# stack.append(root)
# root = root.left
# root = stack.pop()
# root.val = res.popleft()
# # print(root.val)
# root = root.right
# def helper(self, root, res):
# if not root: return
# self.helper(root.left, res)
# res.append(root.val)
# self.helper(root.right, res)
# 2 better
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
res, rlist = [], []
self.helper(root, res, rlist)
res.sort()
for i in range(len(res)):
rlist[i].val = res[i]
def helper(self, root, res, rlist):
if not root: return
self.helper(root.left, res, rlist)
rlist.append(root)
res.append(root.val)
self.helper(root.right, res, rlist) |
1291ac60ec8af117e7a7f6712aa4243b7848a688 | ArsRoz/Homework3-Arseni-Rozum | /task1.py | 284 | 4.1875 | 4 | # 1. Создайте словарь с помощью генератора словарей,
# так чтобы его ключами были числа от 1 до 20,
# а значениями кубы этих чисел.
dict_1 = {x: x**3 for x in range(1, 20)}
print(dict_1)
|
27a033ae52d97efb68adfdb9ddf7f18f3b608c5a | anthonychl/Head-First-Python-2ndEd | /chapter4/vsearch_old.py | 344 | 4.125 | 4 | #defining a function that utilizes the code in vowels7.py
def search4vowels():
""" display any vowels found in an asked-for word """
vowels = {'a','e','i','o','u'} #or vowels = set('aeiou')
word = input("Provide a word to search for vowels: ")
found = vowels.intersection(set(word))
for vowel in found:
print(vowel) |
289f3db4eac1853c86a88288ffa9387cf4675c0a | possientis/Prog | /python/decorator.py | 149 | 3.53125 | 4 |
def double(f):
def newFunc(x):
return 2*f(x)
return newFunc
@double
def h(x):
return x + 3
print("Hello world!")
print(h(7))
|
989ef438482139675f44fe1817dce039d4499002 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/sentenceSimilarityII.py | 2,879 | 3.84375 | 4 | """
Sentence Similarity II
Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar.
For example, words1 = ["great", "acting", "skills"] and words2 = ["fine", "drama", "talent"] are similar, if the similar word pairs are pairs = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]].
Note that the similarity relation is transitive. For example, if "great" and "good" are similar, and "fine" and "good" are similar, then "great" and "fine" are similar.
Similarity is also symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.
Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar, even though there are no specified similar word pairs.
Finally, sentences can only be similar if they have the same number of words. So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"].
Note:
The length of words1 and words2 will not exceed 1000.
The length of pairs will not exceed 2000.
The length of each pairs[i] will be 2.
The length of each words[i] and pairs[i][j] will be in the range [1, 20].
"""
"""
DFS
Two words are similar if they are the same, or there is a path connecting them from edges represented by pairs.
We can check whether this path exists by performing a depth-first search from a word and seeing if we reach the other word. The search is performed on the underlying graph specified by the edges in pairs.
Time: O(NP) where NN is the maximum length of words1 and words2, and PP is the length of pairs. Each of NN searches could search the entire graph.
Space: O(P) the size of pairs
"""
class Solution:
def areSentencesSimilarTwo(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool:
if len(words1) != len(words2):
return False
similarity = collections.defaultdict(list)
for pair in pairs:
a, b = pair
similarity[a].append(b)
similarity[b].append(a)
for w1, w2 in zip(words1, words2):
if w1 != w2 and (w1 not in similarity or w2 not in similarity):
return False
stack = [w1]
seen = {w1}
similar = False
while stack:
word = stack.pop()
if word == w2:
similar = True
break
if word not in similarity:
return False
for sim in similarity[word]:
if sim not in seen:
seen.add(sim)
stack.append(sim)
if not similar:
return False
return True
|
b774c8ded079fe43192fae1a057c45c17f3eef35 | jabberwocky0139/recursion-drill | /rec06.py | 1,037 | 3.875 | 4 | # -*- coding: utf-8 -*-
from functools import reduce
# (0, 0)から(x, y)までの経路の総数を出力する
def maze(x, y):
if x == 0 and y == 0:
return 1
elif x > 0 and y > 0:
return maze(x-1, y) + maze(x, y-1)
elif x > 0 and y == 0:
return maze(x-1, y)
elif y > 0 and x == 0:
return maze(x, y-1)
def half_maze(x, y):
if x == 0 and y == 0:
return 1
elif x == y:
return maze(x, y-1)
elif x > 0 and y > 0:
return maze(x-1, y) + maze(x, y-1)
elif x > 0 and y == 0:
return maze(x-1, y)
## print(half_maze(13, 13))
# n個のノードを持つ二分木の総数
def node(n):
if n == 0:
return 1
else:
return sum([node(i) * node(n-i-1) for i in range(0, n)])
## print(node(13))
def coin(n, arr):
if n == 0:
return 1
elif len(arr) == 0:
return 0
elif n < 0:
return 0
else:
return coin(n - arr[0], arr) + coin(n, arr[1:])
print(coin(100, [1, 5, 10, 50, 100, 500]))
|
1811f4aaf710e74a23b2f8098ba521d2b875a9b8 | Lupin0/Capston | /demo11.py | 1,176 | 3.5625 | 4 | import sqlite3
conn = sqlite3.connect('abc.db') # 라이브러리와 연결
cur = conn.cursor() # cursor는 핸들러와 같은 역할
# cursor를 통 SQL 명령을 보내고 cursor를 통해 답을 받는다
cur.execute('DROP TABLE IF EXISTS Counts') # 이미 테이블이 존재하면 제거
cur.execute('''CREATE TABLE Counts (name TEXT)''')
fname = 'output.txt'
fh = open(fname)
for line in fh:
pieces = line.split()
name = pieces
#cur.execute('SELECT count FROM Counts WHERE name = ? ', (name))
# ?는 자리를 표시, sql 주입 방지, (email,) 형태는 튜플 안에 내용이 하나밖에 없다는 표시
# cur.excute 는 직접 데이터를 빼오지 않 SQL을 훓어보고 문법 문제가 있는지 확인
# 즉 데이터를 읽지는 않고 커서를 준비
row = cur.fetchone() # 첫번째 레코드를 읽어 들인다
cur.execute('''INSERT INTO Counts (name) VALUES (?)''', (name))
conn.commit() # 메모리에 정보를 저장했다가 정보를 디스크로 옮긴다
# commit은 속도가 느리기 때문에 하나하나 할때마다 하는 것은 비효율적
cur.close() |
db3157ee3b4794209cbd4d84b8cf4d6a92e15f53 | Deiwin-Ignacio-Monsalve-Altamar/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 176 | 3.703125 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new_matrix = []
for x in matrix:
new_matrix.append(list(map(lambda x: x * x, x)))
return new_matrix
|
ae0cca5203ef28ec7a350b5e701b0822467192ad | zhanhuijing/JianzhiGallery_Python | /Strings/no50_OccurOnlyOnceInString.py | 663 | 3.75 | 4 | import pdb
def OccurOnlyOnceInString(str):
if str==None:
return False
charhashtable = [None]*256
for i in range(256):
charhashtable[i]=-1
strlength = len(str)
for j in range(strlength):
if charhashtable[ord(str[j])-ord('a')]==-1:
charhashtable[ord(str[j])-ord('a')] = j
elif charhashtable[ord(str[j])-ord('a')]>-1:
charhashtable[ord(str[j])-ord('a')] = -2
else:
charhashtable[ord(str[j])-ord('a')]=-2
index=0
minindex=strlength
for j in range(256):
if charhashtable[j]>-1:
index=j
if index<minindex:
minindex=index
return str[minindex]
if __name__=='__main__':
minindex=OccurOnlyOnceInString('abaccdeff')
print(minindex) |
00f203d143663cf60727cff4584e1d89d28b529b | fengshuai1/1807-2 | /14day/学生类.py | 265 | 3.5 | 4 | class student():
count = 0
def __init__(self,name):
self.name = name
student.count+=1
def ji(self):
print('学生')
@classmethod
def getcount(cls):
return cls.count
a = student('赵')
a = student('孙')
a = student('老')
a.ji()
print(a.getcount())
|
454b641b451099893036fc5966f414c83f1d4910 | kousei03/coffee-projects | /python/jtclub/okapi.py | 415 | 3.640625 | 4 | def okapi():
rolls = str(raw_input("Enter dice rolls: "))
x, y, z = int(rolls[0]), int(rolls[1]), int(rolls[2])
if x == y and y == z:
print("The payout is $", x+y+z, ".")
elif x == y:
print("The payout is $", x+y, ".")
elif y == z:
print("The payout is $", y+z, ".")
elif x == z:
print("The payout is $", x+z, ".")
else:
print("The payout is $0.") |
209767c710919961ecde0c5542f6b6d1a1a887b2 | joincode/pythontraining | /FizzBuzz.py | 474 | 3.765625 | 4 | import os
os.system('cls')
# O %s é utilizado como marcador de posicao
#https://docs.python.org/3.4/library/string.html
print ("Criar um Programa Teste FizzBuzz!!!")
line = 0
while (line < 100):
line += 1
if (line % 3 == 0 ) and (line % 5 == 0):
print ("%s - FizzBuzz!!!" % line )
elif (line % 3 == 0):
print ("%s - Fizz!!" % line)
elif (line % 5 == 0):
print ("%s - Buzz!!" % line)
else:
print (line) |
3a3b854841896bae886acc935fba4bdfb7ad2d85 | kis619/SoftUni_Python_Basics | /6.Nested_loops/Exercise/02. Equal Sums Even Odd Position.py | 1,670 | 3.671875 | 4 | # first_number = input()
# second_number = input()
#
# first_digit = first_number[0]
# third_digit = first_number[2]
# fifth_digit = first_number[4]
# second_digit = first_number[1]
# fourth_digit = first_number[3]
# sixth_digit = first_number[5]
# odd_sum_first_number = int(first_digit) + int(third_digit) + int(fifth_digit)
# even_sum_first_number = int(second_digit) + int(fourth_digit) + int(sixth_digit)
# first_digit_second_number = second_number[0]
# third_digit_second_number = second_number[2]
# fifth_digit_second_number = second_number[4]
# second_digit_second_number = second_number[1]
# fourth_digit_second_number = second_number[3]
# sixth_digit_second_number = second_number[5]
#
# odd_sum_second_number = int(first_digit_second_number) + int(third_digit_second_number) + int(fifth_digit_second_number)
# even_sum_second_number = int(second_digit_second_number) + int(fourth_digit_second_number) + int(sixth_digit_second_number)
# first_number_int = int(first_number)
# second_number_int = int(second_number)
first_number = int(input())
second_number = int(input())
for number in range(first_number, second_number+ 1):
value = str(number)
first_digit = value[0]
third_digit = value[2]
fifth_digit = value[4]
second_digit = value[1]
fourth_digit = value[3]
sixth_digit = value[5]
odd_sum_first_number = int(first_digit) + int(third_digit) + int(fifth_digit)
even_sum_first_number = int(second_digit) + int(fourth_digit) + int(sixth_digit)
if odd_sum_first_number == even_sum_first_number:
print(number, end= " ")
# if odd_sum_second_number == even_sum_second_number:
# print(number, end= " ")
|
f16a84e1df6888696f91533699957a1c9b9e5045 | sturnerin/Katerina | /HW-5/HW-5.py | 412 | 3.65625 | 4 | with open("latinwords.txt", "a", encoding="utf-8") as f:
print("пожалуйста, вводите латинские слова, пока вам не надоест ")
a=input()
if a=="":
print("вы ничего не ввели :(")
else:
while a!="":
if a.endswith("tur"):
f.write(a)
f.write("\n")
a=input()
|
b2caa3e2ed79f075f8362bfb4aea09cc58cd36cd | JulieRoder/Practicals | /Activities/prac_02/randoms.py | 777 | 4.1875 | 4 | """
Random Numbers
"""
import random
print(random.randint(5, 20)) # line 1
print(random.randrange(3, 10, 2)) # line 2
print(random.uniform(2.5, 5.5)) # line 3
# What did you see on line 1?
# smallest: 10, largest: 20, smallest possible is 5.
# What did you see on line 2?
# smallest: 3, largest: 9, got a lot of 5's.
# Could line 2 have produced a 4?
# no, because range is set for odd numbers.
# What did you see on line 3?
# smallest: 2.859181026094012
# largest: 5.266427815701068
print(random.randint(1, 100)) # will produce random integer between 1-100 inclusive
print(random.randrange(1, 101)) # will produce random integer between 1-100 inclusive
print(random.uniform(1, 100)) # will produce random multi-decimal numbers between 1-100, inclusive with rounding
|
482436c614aae6bcd015f2664e2ba99d6e21b51d | dimaswahabp/Kumpulan-Catatan-Fundamental | /Kumpulan Tugas/ganjil genap.py | 165 | 3.671875 | 4 |
x = int(input('masukkan angka anda :'))
if x % 2 == 0:
print(f'angka ini {x} adalah angka genap')
else:
print(f'angka ini {x} adalah angka ganjil') |
518f7d94d1f230478bc8cca59388dce959bbbd3e | MartinThoma/algorithms | /Python/dataclasses/impl_class.py | 1,472 | 3.953125 | 4 | from typing import Optional
class Position:
MIN_LATITUDE = -90
MAX_LATITUDE = 90
MIN_LONGITUDE = -180
MAX_LONGITUDE = 180
def __init__(
self, longitude: float, latitude: float, address: Optional[str] = None
):
self.longitude = longitude
self.latitude = latitude
self.address = address
@property
def latitude(self) -> float:
"""Getter for latitude."""
return self._latitude
@latitude.setter
def latitude(self, latitude: float) -> None:
"""Setter for latitude."""
if not (Position.MIN_LATITUDE <= latitude <= Position.MAX_LATITUDE):
raise ValueError(f"Latitude was {latitude}, but has to be in [-90, 90]")
self._latitude = latitude
@property
def longitude(self) -> float:
"""Getter for longitude."""
return self._longitude
@longitude.setter
def longitude(self, longitude: float) -> None:
"""Setter for longitude."""
if not (Position.MIN_LONGITUDE <= longitude <= Position.MAX_LONGITUDE):
raise ValueError(f"Longitude was {longitude}, but has to be in [-180, 180]")
self._longitude = longitude
pos1 = Position(49.0127913, 8.4231381, "Parkstraße 17")
pos2 = Position(42.1238762, 9.1649964)
pos3 = Position(49.0127913, 8.4231381, "Parkstraße 17")
def get_distance(p1: Position, p2: Position) -> float:
pass
print(pos1)
# <__main__.Position object at 0x7f1562750640>
|
d5c69935b79382015b832815efc76de876ca9420 | econmang/Student-Files | /cs356/hw/chap_3/hw3_2.py | 1,145 | 4.28125 | 4 | print("Problem 3-2")
print("Complementary Colors\n")
quit = False
while not quit:
color = input("Enter a color:\n")
color = color.strip().lower()
if color == "red":
print("The complementary color to red is: Green!")
elif color == "green":
print("The complementary color to green is: Red!")
elif color == "yellow":
print("The complementary color to yellow is: Violet!")
elif color == "violet":
print("The complementary color to violet is: Yellow!")
elif color == "blue":
print("The complementary color to blue is: Orange!")
elif color == "orange":
print("The complementary color to orange is: Blue!")
else:
print("ERROR: You did not enter a correct color.")
answer = False
response = input("Would you like to quit? (y/n)\n")
while not answer:
if response == "y":
answer = True
quit = True
print("Thanks for trying!\n")
elif response == "n":
answer = True
print("Let's go again!\n")
else:
print("ERROR: Invalid input; Would you like to quit?")
|
ff50e9adeddb7e9c0882722cbaafc8e8524bdbaf | ExileSaber/2019-year | /python操作数据库/python操作Mongodb数据库/插入.py | 722 | 3.546875 | 4 | import pymongo
#创建数据库连接
client = pymongo.MongoClient(host='localhost', port=27017)
#另一种连接方式
#client = pymongo.MongoClient('mongodb://localhost:27017/')
#指定数据库
db = client.test
# 或者
#db = client['test']
#指定集合
collection = db.students
#collection = db['students']
#插入数据
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
result = collection.insert_many([student1, student2]) #insert_one方法用于插入一条数据,不推荐使用insert方法
print(result)
print(result.inserted_ids)
|
0e4b714761e6e3380cd5312ae1bffac6783f6e0e | karist7/Python-study | /함수의 활용 1번.py | 401 | 3.90625 | 4 | counter = 0
def flatten(data):
out = []
for i in data:
if type(i) == list:
out += flatten(i)
else:
out.append(i)
return out
example = [[1,2,3],[4,[5,6],7, [8, 9]]]
print("원본:", example)
print("변환:", flatten(example))
#append활용 빈리스트 생성은 맞췄지만 리스트 활용에 대한 생각이 부족했다. |
d130e56b25bb59801e350794da3756addb8e9a13 | Bhaktidave/my_first_blog | /elseif.py | 166 | 3.90625 | 4 | a="bhakti"
b="bansi"
c="harshita"
n=input("enter name")
if n==a:
print("hi"+a)
elif n==b:
print("hie"+b)
elif n==c:
print("hi"+c)
else :
print("hie")
|
0cab2835d9d753b1a7a1e8f38724146c956a1d48 | jaegyeongkim/Today-I-Learn | /알고리즘 문제풀이/프로그래머스/Level 1/정수 제곱근 판별.py | 158 | 3.6875 | 4 | import math
def solution(n):
if (math.sqrt(n)+1)**2 == int((math.sqrt(n)+1)**2):
return (math.sqrt(n)+1)**2
else:
return -1
print(1) |
7eec5687d5353f37dac3b3093a5f3f7f691ee0a9 | bssrdf/pyleet | /B/BitwiseANDofNumbersRange.py | 669 | 3.90625 | 4 | '''
-Medium-
*Bit Manipulation*
Given two integers left and right that represent the range [left, right],
return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7
Output: 4
Example 2:
Input: left = 0, right = 0
Output: 0
Example 3:
Input: left = 1, right = 2147483647
Output: 0
Constraints:
0 <= left <= right <= 2^31 - 1
'''
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
while left < right:
right &= right - 1
return right
if __name__ == "__main__":
print(Solution().rangeBitwiseAnd(5, 7))
print(Solution().rangeBitwiseAnd(1, 2147483647)) |
284a5de4db1d1448056e9fc744a98f62f05396b7 | qinzhouhit/leetcode | /777canTransform.py | 1,042 | 3.5 | 4 | '''
keys: two pointers
Solutions:
Similar:
T:
S:
'''
from typing import List
# https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/217070/Python-using-corresponding-position-
class Solution:
# T: O(N)
# S: O(1)
def canTransform(self, start: str, end: str) -> bool:
if len(start) != len(end):
return False
# track the idx of L and R, s for start and e for end
A = [(s, idx) for idx, s in enumerate(start) if s == "L" or s == "R"]
B = [(e, idx) for idx, e in enumerate(end) if e == "L" or e == "R"]
# number of L and R must be equal
if len(A) != len(B): return False
for (s, i), (e, j) in zip(A, B):
if s != e: # since RXLX -> XRLX, the order of R and L won't change
return False
if s == "L":
if i < j: # XL -> LX, L will move to the left
return False
if s == "R":
if i > j:
return False
return True |
2f99d5f30b846c92f0941d11d84191ab7fb3d8fe | Taranoberoi/PYTHON | /13_Reading_Writing_file.py | 1,654 | 4.0625 | 4 | # for Writing in file
# f= open("C:\\Taran,Courses & others\\Machine Leanring Codebasics\Python\\funny.txt","w")
# f.write("I love Java")
# f.close()
# for appending in the file
# f = open("C:\\Taran,Courses & others\\Machine Leanring Codebasics\\Python\\funny.txt","a")
# f.write("\nOne more time I am appending data by writing that I love Mahcine learning")
# f.close()
# Reading from file
# f = open("C:\\Taran,Courses & others\\Machine Leanring Codebasics\\Python\\funny.txt","r")
# print(f.read())
# f.close()
# for reading line by line from file
# f = open("C:\\Taran,Courses & others\\Machine Leanring Codebasics\\Python\\funny.txt", "r")
# for line in f:
# print(line)
# f.close()
# Read the number of words in line and push it into the new file
# f = open("C:\\Taran,Courses & others\\Machine Leanring Codebasics\\Python\\funny.txt", "r")
# f_out = open("C:\\Taran,Courses & others\\Machine Leanring Codebasics\\Python\\count.txt", "w")
# Line is justa a variable
# for line in f:
# tokens=line.split(' ')
# # print(len(tokens))
# # print(tokens)
# # print(str(tokens))
# f_out.write("word count:"+str(len(tokens))+"\t"+line)
#
#
# f.close()
# f_out.close()
# With statement
# IF we dont want to close the file explicitly for ex while writing big piece of code one is tend to forget so use with to avoid close liek show below:
with open("C:\\Taran,Courses & others\\Machine Leanring Codebasics\\Python\\funny.txt", "r") as f:
print(f.read())
# Next statement will show if answer is true or false...it shud be false since used with statement.
print(f.closed) |
5ab97cf74d57899236308ffb9fcc9d817fddd411 | ali-mohammed200/HangmanPython | /v1-5a.py | 2,177 | 4.21875 | 4 | #####################
#####################
## Version 1-5a Below ##
#####################
#####################
### Fixed some loop holes in guessing
# and added the letter banks
## Adding loop functionality to show letters guessed
## without using regex
print("Welcome to Hangman!")
word = "anonymous"
original = word # This is a copy of the word
count = len(word) #This is the length of characters in the word
tries = 6 # We only have 6 tries to guess the word
print("The word is " + str(count) + " letters long.")
letterBank = "" # A bank of every correctly guessed letter
incorrectLetters = ""
def wordmaker():
# Checks each letter of the word to see if we have guessed
# it and if it is included in the word bank
# and then if it is, keep the letter,
# otherwise make it an empty slot.
# example: an[_]n[_][_][_][_][_]
i = 0
ourGuess = ""
while i < len(word):
if letterBank.find(word[i]) != -1:
ourGuess += word[i]
else:
ourGuess += "[_]"
i += 1
return ourGuess
while count != 0 and tries > 0:
print("\n") #Makes white space in the command line
guess = input("Guess a letter: ")[0] #taking the first character inputted
occurence = word.count(guess)
if occurence != 0 and letterBank.count(guess) == 0:
print("Yes, you guessed correctly!")
letterBank += guess
print("Letter bank: [" + letterBank + "] Incorrect letters: [" + incorrectLetters + "]")
currentGuess = wordmaker()
print("currentGuess: " + currentGuess)
count -= occurence
print("Letters remaining to guess: " + str(count))
print(word)
elif incorrectLetters.find(guess) == -1 and letterBank.count(guess) == 0:
incorrectLetters += guess
tries -= 1
print("Letter bank: [" + letterBank + "] Incorrect letters: [" + incorrectLetters + "]")
#print(word)
print("Bad guess, " + str(tries) + " tries left")
else:
print("You already guessed that!!")
if count < 1:
print("You Win! The word is " + original)
elif tries == 0:
print("You lose!, The word was " + original)
|
7219e9e118e3f3a8fc5964c97da08b51b6653a51 | hardikpatel21/python_udemy | /tkinter/weight_convert.py | 1,010 | 4.0625 | 4 | from tkinter import *
# Create window
window=Tk()
def from_kg():
# get the vallue of e1_value
# print(e1_value.get())
grams=float(e2_value.get())*1000
pounds=float(e2_value.get())*2.20462
ounces=float(e2_value.get())*35.274
# adding value of e1_value to text widget at the end of the text
t1.insert(END, grams)
t2.insert(END, pounds)
t3.insert(END, ounces)
e1=Label(window,text="Kg")
e1.grid(row=0,column=0)
e2_value = StringVar()
# put input field in window
e2=Entry(window, textvariable=e2_value)
e2.grid(row=0,column=1)
# Creating button to put in window
b1=Button(window,text='Convert',command=from_kg)
# putting button into the window panel
# b1.pack()
# putting button into the window panel using grid
b1.grid(row=0,column=3)
# put text widget
t1=Text(window,height=1,width=20)
t1.grid(row=1,column=0)
t2=Text(window,height=1,width=20)
t2.grid(row=1,column=1)
t3=Text(window,height=1,width=20)
t3.grid(row=1,column=2)
# end of the window
window.mainloop()
|
6a8e1a20eebf10456e1020491806920c3cee8a6a | 0911707/-INFDEV02-1_0911707 | /ListPractice/ListPractice/ListPractice.py | 551 | 4.0625 | 4 | class Empty:
def __init__(self):
self.IsEmpty = True
Empty = Empty()
class Node:
def __init__(self, value, tail):
self.IsEmpty = False
self.Value = value
self.Tail = tail
y = 0
l = Empty
m = Empty
cnt = int(input("how big of a list? "))
for i in range(0, cnt):
a = input("What value? ")
l = Node(a, l)
x = l
while not(x.IsEmpty):
print(x.Value)
m = Node(x.Value, m)
x = x.Tail
y = m
print("-----------------------")
while not(y.IsEmpty):
print(y.Value)
y = y.Tail |
757b25ae87cda15b8ace96f11198f1d544c11884 | Xiaoyin96/Algorithms_Python | /interview_practice/Other/QuickSort.py | 424 | 3.984375 | 4 | #!/usr/bin/env python
# encoding: utf-8
'''
@author: Xiaoyin
'''
def quick_sort(array):
if len(array) < 2:
return array
pivot = array[0]
less = [i for i in array[1:] if i <= pivot] # exclude pivot
great = [i for i in array[1:] if i > pivot]
return quick_sort(less) + [pivot] + quick_sort(great)
import random
array = list(range(20))
random.shuffle(array)
print(array)
print(quick_sort(array)) |
6a4671ca3728cbca2f708f9bc87a9f16a2113341 | boomNDS/prepro_play | /w3/what_math.py | 187 | 3.875 | 4 | """What a Math"""
import math
def main():
"""What a Math"""
numx = float(input())
numa = float(input())
radians = numa*(math.pi/180)
numy =
print(radians)
main()
|
28493f7c832a426a9548310928d457e8d1595637 | guanxv/Codecademy_note | /Python_sys/Python_sys.py | 577 | 3.5625 | 4 | #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
#-#-#-#-#-#-#- python Sys. #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
import sys
print(sys.version)
print(sys.executable)
# to find out where is python in windows
# try
where python
# or try
python
>>>import sys
>>>sys.executable
# this should find the address of python. |
22b28809790d9f3a07e316e262386918860fa0c9 | 1BM16CS007/PythonLab-1BM16CS007-aatithya | /DivBy5.py | 179 | 3.65625 | 4 | str1=input("Enter the binary sequence: ")
lis = str1.split(",")
str2=""
for i in range(len(lis)):
if int(lis[i],2)%5==0:
str2+=lis[i]+","
print ("Output is: ",str2[:len(str2)-1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.