blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
90597f852e1fab8bf523132577e8dfbdde2446c8 | franktank/py-practice | /fb/hard/int-to-eng.py | 2,111 | 3.890625 | 4 | """
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
"""
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "Zero"
THOUSANDS = ["", "Thousand", "Million", "Billion"]
res = []
thousands_counter = 0
while num > 0:
rem = num % 1000
if rem == 0:
num /= 1000
thousands_counter += 1
continue
rem_to_eng = self.helper(rem)
res.insert(0, THOUSANDS[thousands_counter])
res.insert(0, rem_to_eng)
thousands_counter += 1
num /= 1000
return ' '.join(res).strip()
def helper(self, rem):
NUMBERS = {
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine',
10: 'Ten',
11: 'Eleven',
12: 'Twelve',
13: 'Thirteen',
14: 'Fourteen',
15: 'Fifteen',
16: 'Sixteen',
17: 'Seventeen',
18: 'Eighteen',
19: 'Nineteen',
20: "Twenty",
30: "Thirty",
40: "Forty",
50: "Fifty",
60: "Sixty",
70: "Seventy",
80: "Eighty",
90: "Ninety"
}
res = []
if rem >= 100:
hundred = rem // 100
res.append('{} Hundred'.format(NUMBERS[hundred]))
rem = rem % 100
if rem >= 20:
t = (rem // 10)*10
res.append(NUMBERS[t])
rem = rem % 10
if rem < 20 and rem > 0:
res.append(NUMBERS[rem])
return ' '.join(res)
|
5324abd28ea56372a32fcfba3f6b952b52bea5d0 | daniel-reich/ubiquitous-fiesta | /LMoP4Jhpm9kx4WQ3a_11.py | 511 | 3.59375 | 4 |
def is_ascending(s):
Sample_A = str(s)
Length = len(Sample_A)
Ending = 1
while (Ending < Length - 1):
Sample_B = Sample_A[0:Ending]
Number = int(Sample_B) + 1
Length_A = len(Sample_A)
Length_B = len(Sample_B)
while (Length_B < Length_A):
Sample_B = Sample_B + str(Number)
Number += 1
Length_A = len(Sample_A)
Length_B = len(Sample_B)
if (Sample_A == Sample_B):
return True
else:
Ending += 1
return False
|
610eac3b0622cf0471f863facece6fee1a8b03df | NeroCube/leetcode-python-practice | /medium20/singleNumber.py | 409 | 3.6875 | 4 | '''
260. Single Number III
[題目]
找只有出現一次的數
'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
one = set()
two = set()
for num in nums:
if num not in one:
one.add(num)
else:
two.add(num)
return list(one - two) |
5faa882e942559db7ed45d4af956a12d7151ae76 | xqx1998/learn_python | /fun_triangles.py | 163 | 3.5 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
def triangles():
a = [1]
while True:
yield a
a = [sum(i) for i in zip([0] + a, a + [0])]
|
0d819d7dfe001c89c55437a79f9464cfd9cb7dae | realpython/materials | /python-doctest/user.py | 1,278 | 3.9375 | 4 | class User_One:
def __init__(self, name, favorite_colors):
self.name = name
self._favorite_colors = set(favorite_colors)
@property
def favorite_colors(self):
"""Return the user's favorite colors.
Usage examples:
>>> john = User("John", {"#797EF6", "#4ADEDE", "#1AA7EC"})
>>> john.favorite_colors
{'#1AA7EC', '#4ADEDE', '#797EF6'}
"""
return self._favorite_colors
class User_Two:
def __init__(self, name, favorite_colors):
self.name = name
self._favorite_colors = set(favorite_colors)
@property
def favorite_colors(self):
"""Return the user's favorite colors.
Usage examples:
>>> john = User("John", {"#797EF6", "#4ADEDE", "#1AA7EC"})
>>> sorted(john.favorite_colors)
['#1AA7EC', '#4ADEDE', '#797EF6']
"""
return self._favorite_colors
class User_Three:
def __init__(self, name, favorite_colors):
"""Initialize instances of User.
Usage examples:
>>> User(
... "John", {"#797EF6", "#4ADEDE", "#1AA7EC"}
... ) # doctest: +ELLIPSIS
<sets.User object at 0x...>
"""
self.name = name
self._favorite_colors = set(favorite_colors)
|
8a86a75419d5c5e817373e4ce0f35ff9f017404d | JorgeTranin/Python_Curso_Em_Video | /Exercicios Curso Em Video Mundo 1/ex026.py | 136 | 3.515625 | 4 | frase = input('Digite uma frase: ')
p = (frase.count('a'))
print('Aparecem ', (frase.count('a')))
print('A primeira vez aparece em: ', ) |
df8852014d55250f139db09a4605c66cb643743c | brkyydnmz/PythonCamp | /PythonKamp-Hızlı Kısa/workshop2.py | 403 | 3.78125 | 4 | #girdiğin faktoriyeli hesaplama çalışması
sayi=int(input("Kaçıncı faktoriyeli hesaplayayım?:"))
faktoriyel=1
if sayi<0:
print("Negatif sayıların faktoriyeli hesaplanmaz")
elif sayi==0:
print("Sonuc:1")
else:
for i in range(1,sayi+1): # artı 1,5 girdiysek 5 de dahil olsun diye artı 1 var.
faktoriyel= faktoriyel * i
print("Sonuc:",faktoriyel)
|
812f9593a2a3ea3d49c9bbda4b2bac8f8a6535c6 | DavidArmendariz/python-basics-hse | /Week_5/list_comprehensions_3.py | 249 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
def isprime(x):
for j in range(2, x):
if x % j == 0:
return False
return True
x = [(i,'prime') if isprime(i) == True else i for i in range(10,51)]
print(x)
# In[ ]:
|
4ad818aa2c682360cebec9e1866e4fe31a6cf990 | npmajisha/spam_filter | /megam_formatter.py | 1,842 | 3.515625 | 4 | #this is to convert a file generated from readfiles.py into MegaM format
#takes 2 arguments 1.input file which is generated output of the readfiles.py 2.output filename
import re
import codecs
import sys
def main():
#usage details
if len(sys.argv) < 3:
print("Usage : python3 megam_formatter.py input_filename output_filename")
return
#open input file
input_file = open(sys.argv[1], 'r', encoding = 'latin-1',errors='ignore')
#MegaM format file
output_file = open(sys.argv[2] , 'w+', encoding = 'latin-1', errors = 'ignore')
for line in input_file:
mega_line = ""
word_count = {}
feature_vector = {}
words = re.split(r'\s+', line.replace('#','#_').rstrip()) #pound symbol was leading to exception in megam learn, therefore replacing
if words[0] == 'HAM' or words[0] == 'POS':
mega_line = '1\t'
n = 1
elif words[0]== 'SPAM' or words[0] == 'NEG':
mega_line = '0\t'
n = 1
else:
mega_line = '0\t'
n = 0
#calculating counts for each word
for word in words[n:]:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
#MegaM non bernoulli format class_label (feature_name feature_value)
for word in sorted(word_count):
mega_line += str(word)+ ' '+ str(word_count[word])+' '
#write each line to output file
output_file.write(mega_line.rstrip() + '\n')
#close the files
input_file.close()
output_file.close()
return
#boilerplate for main
if __name__ == '__main__':
main() |
e142d546533b59f7a7faf1cfcef614aab687769e | rahulcode22/Data-structures | /Backtracking/The-Power-Sum.py | 391 | 4.15625 | 4 | '''
Find the number of ways that a given integer X, can be expressed as the sum of N the power of unique, natural numbers.
'''
def countWaysUtil(x, n, num):
val = x - (num**n)
if val == 0:
return 1
if val < 0:
return 0
return countWaysUtil(val, n, num + 1) + countWaysUtil(x, n, num+1)
x = int(raw_input())
n = int(raw_input())
print countWaysUtil(x, n, 1)
|
8d2b65252c49edc35f9c2e4c93e18666c0a013f7 | naranundra/python5 | /hicheel7.py | 1,108 | 4 | 4 | # pop -> list ees salgaj awna
names = ["bat " , "bold" , 'delger']
a = names.pop(2)
print(names)
print(a)
# remove -> shuud ustgana
names = ["bat " , "bold" , 'delger']
a = names.remove("bat ")
print(a)
#clear
names = ["bat " , "bold" , 'delger']
names.clear()
print(names)
# del
names = ["bat " , "bold" , 'delger']
del names
print(names)
# элемент тоолоход Count ашиглана
numbers = [2, 0, 6, 1, ]
c = numbers.count(2)
print(c)
# index oloh
numbers = [2, 0, 6, 1]
numbers1 = [9, 9, 6]
c = numbers.count(2)
i = numbers.index(0)
print("too: " , c)
print("index: " , i)
print(numbers + numbers1)
# sort эрэмбэлэх
numbers = [2, 0, 6, 1]
numbers1 = [9, 9, 6]
c = numbers.count(2)
i = numbers.index(0)
print("too: " , c)
print("index: " , i)
print(numbers + numbers1)
print(numbers.sort())
print(numbers1.reverse())
# if ашиглах
names = ["bat " , "bold" , 'delger']
if 'bat' in names:
print("bvrtgegdsen")
else:
print("bvrtgegdegvi")
# for ашиглах
for i in names:
print(i)
|
dada92d04f88313ca59e51edefb2781666fb16c5 | AmirrezaGhafoori/DFA-NFA- | /NFA.py | 9,745 | 3.703125 | 4 | '''
Converting NFa to DFA, implemented by Amirreza Ghafoori
notice: use "λ" character for "landa" in nontations
'''
import collections
filename = "NFA_Input_22.txt"
target_filename= "DFA_Output_22.txt"
#first we define class for nfa to extract the features from the file
class nfa:
def __init__(self, filename):
f = open(filename)
#by using split lines method we will ignore line breaks '\n'
machine_features = f.read().splitlines()
f.close()
#first we put featuers in machine_feature array and then assign them
#to the machine features!!
self.alphabet = machine_features[0].split(" ")
self.state = machine_features[1].split(" ")
self.initial_state = machine_features[2].split(" ")[0]
self.final_state = machine_features[3].split(" ")
self.function = machine_features[4:]
#We will save each state's landa closure in this dictionary
self.landa_closure_dict = {}
#In this dictionary we save which states are reachable through each state and character
self.all_reachable_states_dict = {}
#we use this list to handle landa_closure recursive function
self.visited = []
#We will initiate the acceptor with this function; after this landa_closure_dict
#will be filled up
self.landa_closure()
#This method will initiate all reachalbe states through all alphabet whithin each state
self.all_reachable_states()
#This method will find landa closure of all the states
def landa_closure(self):
for x in self.state:
landa_list = []
self.recursive_landa_closure(x, landa_list)
self.visited = []
self.landa_closure_dict[x] = landa_list
def all_reachable_states(self):
for state in self.state:
state_through_char_list = {}
for char in self.alphabet:
state_through_char_list[char] = self.reachable_states(state, char)
self.all_reachable_states_dict[state] = state_through_char_list
#this method will check which states are reachable through this given state and character
def reachable_states(self,state, character):
reachable_list = []
state_landa_closure_list = self.landa_closure_dict[state]
for x in state_landa_closure_list:
x_character = self.directly_reachable_states(x, character)
for element in x_character:
element_land = self.landa_closure_dict[element]
for y in element_land:
if y not in reachable_list:
reachable_list.append(y)
return reachable_list
#this method will return true if the acceptor, accept's landa and false if not
def check_landa(self):
reachable_states = self.landa_closure_dict[self.initial_state]
# print("reachable states: ", reachable_states)
for x in reachable_states:
if x in self.final_state:
return True
else:
return False
def directly_reachable_states(self,state, character):
#here we find which states are directly reachable through certain specified character
#at the end of this for loop direct_state list will contain direct states from current state
#through input character
direct_states = []
for x in self.function:
movement = x.split(" ")
if state== movement[0]:
if character == movement[1]:
direct_states.append(movement[2])
return direct_states
#In this method we use recursion to find all of the landa closures of a state
def recursive_landa_closure(self,state, landa_list):
landa_list.append(state)
self.visited.append(state)
neighbors = self.directly_reachable_states(state, "λ")
for x in neighbors:
if x not in self.visited:
self.recursive_landa_closure(x, landa_list)
#This is dfa class and we will complete it with nfa information
class dfa:
def __init__(self):
self.alphabet = []
self.state = []
self.initial_state = []
self.final_state = []
self.function = []
#In this method we will extract information from nfa and make the dfa acceptor
def convert_nfa2dfa(nfa, dfa):
dfa.alphabet = nfa.alphabet
dfa_state_list = []
dfa_state_list.append([nfa.initial_state])
state_counter = 0
for x in dfa_state_list:
new_state_list = []
for character in dfa.alphabet:
new_state = []
reachable = check_reachable_for_list(x, character, nfa.all_reachable_states_dict)
new_state_list.append(reachable)
# print("new state: ",new_state, character)
#if length of new state = 0 it means there isn't any movement
#for this state with this char in nfa so we have to make a TRAP
#state on DFA acceptor and add 2 functions to loop on there
for new in new_state_list:
if len(new) == 0:
if new not in dfa_state_list:
dfa_state_list.append(new)
else:
this_is_new = True
for x in dfa_state_list:
if collections.Counter(x) == collections.Counter(new):
this_is_new = False
if this_is_new:
dfa_state_list.append(new)
state_counter += 1
# print(dfa_state_list)
# print(dfa.state)
make_function(dfa_state_list, nfa, dfa)
#This is a funciton that gets a list of states and a char and return union of all reachable states
#through states in the list with a given char
def check_reachable_for_list(state_list, character, all_reachable_states_dict):
target_list = []
for state in state_list:
slist = all_reachable_states_dict[state][character]
for x in slist:
if x not in target_list:
target_list.append(x)
return target_list
#in this function we will creat all needed functions in new acceptor
def make_function(states, nfa, dfa):
print("DFA states before rename: ",states)
new_state_name = []
new_state_list = states
function_list = []
final_states = []
for i in range(len(new_state_list)) :
new_name = "Q" + str(i)
new_state_name.append(new_name)
all_reachable_states = nfa.all_reachable_states_dict
for state in new_state_list:
#This loop will make function for a char for upper state
for char in nfa.alphabet:
reachable_state = []
dst_new_index = 0
#This loop indicates which states are reachable from X through char
for x in state:
reachable = nfa.all_reachable_states_dict[x][char]
for y in reachable:
if y not in reachable_state:
reachable_state.append(y)
for element in new_state_list:
if collections.Counter(element) == collections.Counter(reachable_state):
dst_new_index = new_state_list.index(element)
src_new_index = new_state_list.index(state)
function = new_state_name[src_new_index] + " " + char + " " + new_state_name[dst_new_index]
function_list.append(function)
#we determine final states of dfa here
for x in new_state_list:
for char in nfa.final_state:
if char in x:
final_states.append(new_state_name[new_state_list.index(x)])
#we check if landa is accepted in nfa acceptor to specify initial state as final state in dfa or not
if nfa.check_landa():
if new_state_name[0] not in final_states:
final_states.append(new_state_name[0])
# print("new namesss: ",new_state_name)
# print("functions: ", function_list)
# print("Finite stats: ", final_states)
dfa.alphabet = nfa.alphabet
dfa.state = new_state_name
dfa.initial_state = [new_state_name[0]]
dfa.final_state = final_states
dfa.function = function_list
def make_text(dfa):
alphabet = ""
for i in range(len(dfa.alphabet)):
alphabet += dfa.alphabet[i]
if i == len(dfa.alphabet) - 1:
break
alphabet += " "
states = ""
for i in range(len(dfa.state)):
states += dfa.state[i]
if i == len(dfa.state) - 1:
break
states += " "
initial_state = ""
for i in range(len(dfa.initial_state)):
initial_state += dfa.initial_state[i]
if i == len(dfa.initial_state) - 1:
break
initial_state += " "
final_states = ""
for i in range(len(dfa.final_state)):
final_states += dfa.final_state[i]
if i == len(dfa.final_state) - 1:
break
final_states += " "
f = open(target_filename, "w+")
f.write(alphabet)
f.write("\n")
f.write(states)
f.write("\n")
f.write(initial_state)
f.write("\n")
f.write(final_states)
f.write("\n")
for i in range(len(dfa.function)):
f.write(dfa.function[i])
f.write("\n")
f.close()
if __name__ == "__main__":
nfa = nfa(filename)
dfa = dfa()
# print(nfa.all_reachable_states_dict)
convert_nfa2dfa(nfa, dfa)
print("Dfa : ", dfa.alphabet, "\n", dfa.state, "\n", dfa.initial_state, "\n" ,dfa.final_state,"\n", dfa.function)
make_text(dfa)
|
486450eff36c703b12133f155b4347170e604408 | osmanseytablaev/Learn-Python | /reference.py | 1,032 | 4.09375 | 4 | print('Простое присваивание')
shoplist = ['яблоки', 'манго', 'морковь', 'бананы']
mylist = shoplist # mylist - лишь ещё одно имя, указывающее на тот же объект!
del shoplist[0] # Я сделал первую покупку, поэтому удаляю её из списка
print('shoplist:', shoplist)
print('mylist:', mylist)
# Обратите внимание, что и shoplist, и mylist выводят один и тот же список
# без пункта "яблоко", подтверждая тем самым, что они указывают на один объект.
print('Копирование при помощи полной вырезки')
mylist = shoplist[:] # создаём копию путём полной вырезки
del mylist[0] # удаляем первый элемент
print('shoplist:', shoplist)
print('mylist:', mylist)
# Обратите внимание, что теперь списки разные |
df3615b3a1c05af42848b8a64c717efc20174bf7 | abhi98khandelwal/Next-episode-date | /send_email.py | 959 | 3.65625 | 4 | import smtplib
class SendEmail:
"""
A class to send email given the email and message.
Args:
email (str): email id of recipient.
message (str): message that needs to be sent.
"""
#username : senders gmail username
username = 'senders gmail username'
#password : senders gmail password
password = 'senders gmail password'
def __init__(self,email,message):
self.email = email
self.message = 'Subject: {}\n\n{}'.format("Tv Series next episode dates", message)
def send(self):
#Method sends the mail via smtp lib
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.login(self.username,self.password)
server.sendmail(
self.username,
self.email,
self.message
)
server.quit()
if __name__=='__main__':
email = input("Email Id: ")
message = input("Message: ")
a = SendEmail(email,message)
a.send() |
df095f1a821bcc9b6568a58a5f34ac3a8dd32e13 | Yujunw/leetcode_python | /14_最长公共前缀.py | 1,072 | 3.8125 | 4 | '''
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:所有输入只包含小写字母 a-z 。
'''
class Solution:
def longestCommonPrefix(self, strs):
if not strs:
return ''
if len(strs) == 1:
return strs[0]
res = ''
while strs:
try:
word = set(map(lambda x: x[0], strs))
# print(word)
if len(word) == 1:
res += list(word)[0]
else:
return res
# print(res)
strs = list(map(lambda x: x[1:],strs))
# print(strs)
except:
# print('error')
return res
return res
s = Solution()
strs = ["abc","abcc","abc","abca","abca"]
print(s.longestCommonPrefix(strs))
|
d12a0177b5905529321a0b4ea7690812194bd979 | thu4nvd/project_euler | /prob026.py | 1,007 | 3.828125 | 4 | #!/usr/bin/env python3
'''
Reciprocal cycles
Problem 26
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
https://projecteuler.net/problem=26
'''
import itertools
def reciprocal_cycle_len(n):
seen = {}
x = 1
for i in itertools.count():
if x in seen:
return i - seen[x]
else:
seen[x] = i
x = x * 10 % n
def solve():
result = max(range(1,1000), key=reciprocal_cycle_len)
return str(result)
def main():
print(solve())
if __name__ == "__main__":
main()
|
74844bb2b4603d14218a1f157ed8c938577d6a51 | xzeromath/euler | /ep29.py | 760 | 3.53125 | 4 | # 2 ≤ a ≤ 5 이고 2 ≤ b ≤ 5인 두 정수 a, b로 만들 수 있는 ab의 모든 조합을 구하면 다음과 같습니다.
# 2^2=4, 2^3=8, 2^4=16, 2^5=32
# 3^2=9, 3^3=27, 3^4=81, 3^5=243
# 4^2=16, 4^3=64, 4^4=256, 4^5=1024
# 5^2=25, 5^3=125, 5^4=625, 5^5=3125
# 여기서 중복된 것을 빼고 크기 순으로 나열하면 아래와 같은 15개의 숫자가 됩니다.
# 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
# 그러면, 2 ≤ a ≤ 100 이고 2 ≤ b ≤ 100인 a, b를 가지고 만들 수 있는 a^b는 중복을 제외하면 모두 몇 개입니까?
# 김현기t
my_list=[]
for a in range(2,101):
for b in range(2,101):
my_list.append(a**b)
print(len(set(my_list)))
# 9183 |
d2dc181514425276220c7a2b35d01ec7bf07a053 | PedroHenr1que/AtividadesFaculdadeProgramacao | /Outros/Cadastro Pessoa.py | 5,812 | 4.03125 | 4 | nome = []
idadeDefinitiva = []
alturaDefinitiva = []
opcaoDefinitiva = [1,2,3,4,5,6]
opcaoAlteracaoDados = [1,2]
condicao = True
while condicao == True:
#----------------------------------------------Opções------------------------------------------
print("\n" * 10)
print("-------Opções-------")
print("1 - Lista das Pessoas (Apenas Nomes)")
print("2 - Cadastrar uma Pessoa")
print("3 - Consultar os detalhes de uma pessoa")
print("4 - Editar dados de uma Pessoa")
print("5 - Remover uma Pessoa")
print("6 - Encerrar")
opcao = int(input("Opção: "))
while not(opcao in opcaoDefinitiva):
print("\nError - Sua opção não corresponde com nenhuma das alternativas.")
opcao = int(input("Opção: "))
#----------------------------------------------Lista--------------------------------------------
if opcao == 1:
print("\n\n-LISTA DOS NOMES EM ORDEM ALFABÉTICA-\n")
nomeAlfabetica = nome.copy()
nomeAlfabetica.sort()
print(nomeAlfabetica)
#----------------------------------------------Cadastro------------------------------------------
elif opcao == 2:
print("\n\n------------CADASTRAMENTO------------\n")
#Nome
nome.append(input("\nNome: "))
#Idade
idade = int(input("\nIdade: "))
while idade < 0:
print("\nError --- Idade Não pode ser menor que 0")
idade = int(input("Idade: "))
idadeDefinitiva.append(idade)
#Altura
altura = int(input("\nAltura: "))
while altura < 0:
print("Erro --- Altura não pode ser menor que zero")
altura = int(input("Altura: "))
alturaDefinitiva.append(altura)
#---------------------------------------------Detalhes--------------------------------------------
elif opcao == 3:
print("\n\n---CONSULTAR DETALHES DE UMA PESSOA---")
print("Nomes:")
for i in range(len(nome)):
print(nome[i])
nomeDados = input("\nNome da pessoa que deseja Consultar: ")
while not(nomeDados in nome):
print("\nErros - O nome não corresponde a nenhum no sistema, tente de novo.")
nomeDados = input("Nome da pessoa que deseja Consultar: ")
print("\nRESULTADO: ")
print(f"Nome: {nomeDados}")
print(f"Idade: {idadeDefinitiva[nome.index(nomeDados)]}")
print(f"Altura: {alturaDefinitiva[nome.index(nomeDados)]}")
#---------------------------------------------Editar------------------------------------------------
elif opcao == 4:
print("\n\n-----EDITAR DADOS DE UMA PESSOA-----")
print("Nomes:")
for i in range(len(nome)):
print(nome[i])
nomeDados = input("\nNome da pessoa que deseja alterar dados: ")
while not(nomeDados in nome):
print("\nErros - O nome não corresponde a nenhum no sistema, tente de novo.")
nomeDados = input("Nome da pessoa que deseja alterar dados: ")
print(f"\nNome: {nomeDados}")
print(f"1 - Idade: {idadeDefinitiva[nome.index(nomeDados)]}")
print(f"2 - Altura: {alturaDefinitiva[nome.index(nomeDados)]}")
opcao = int(input("Opção que deseja alterar: "))
while not(opcao in opcaoAlteracaoDados):
print("\nError - Sua opção não corresponde com nenhuma das alternativas.")
opcao = int(input("Opção que deseja alterar: "))
if opcao == 1:
idadeDefinitiva.pop(nome.index(nomeDados))
print("\n-----Vamos Alterar a Idade-----")
idade = int(input("Nova idade: "))
while idade < 0:
print("\nError --- Idade Não pode ser menor que 0")
idade = int(input("\nNova idade: "))
idadeDefinitiva.insert(nome.index(nomeDados), idade)
print("\n----------Novos Dados----------")
print(f"Nome: {nomeDados}")
print(f"Idade: {idadeDefinitiva[nome.index(nomeDados)]}")
print(f"Altura: {alturaDefinitiva[nome.index(nomeDados)]}")
elif opcao == 2:
alturaDefinitiva.pop(nome.index(nomeDados))
print("\n-----Vamos Alterar a Altura-----")
altura = int(input("Nova altura: "))
while altura < 0:
print("\nError --- Altura Não pode ser menor que 0")
altura = int(input("Nova altura: "))
alturaDefinitiva.insert(nome.index(nomeDados), altura)
print("\n----------Novos Dados----------")
print(f"Nome: {nomeDados}")
print(f"Idade: {idadeDefinitiva[nome.index(nomeDados)]}")
print(f"Altura: {alturaDefinitiva[nome.index(nomeDados)]}")
#------------------------------------------Remover---------------------------------------------
elif opcao == 5:
print("\n\n------REMOVER UM PESSOA------")
print("Nomes:")
for i in range(len(nome)):
print(nome[i])
nomeDados = input("\nNome da pessoa que deseja remover: ")
while not(nomeDados in nome):
print("\nErros - O nome não corresponde a nenhum no sistema, tente de novo.")
nomeDados = input("Nome da pessoa que deseja remover: ")
alturaDefinitiva.pop(nome.index(nomeDados))
idadeDefinitiva.pop(nome.index(nomeDados))
nome.pop(nome.index(nomeDados))
print("\n---PESSOA REMOVIDA COM SUCESSO---")
for i in range(len(nome)):
print(nome[i])
#----------------------------------------------------------------------------------------------
else:
condicao = False
print("\n" * 10)
print("--------------------OBRIGADO--------------------") |
a06c2edbe7c34815b3952b7e147bfae43f1e6508 | hongxuli/python-learning- | /mongodb/mongo_db.py | 527 | 3.53125 | 4 | import pymongo
# client = MongoClient('mongodb://localhot:27017/')
client = pymongo.MongoClient(host='localhost', port=27017)
# db = client['test']
db = client.test
collection = db.students
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170102',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
collection.insert_many([student1, student2])
results = collection.find({'age': 20})
print(results)
for result in results:
print(result)
|
6a9ef6554beb0cb61d495960db593157bb2b5d8f | 1605125/newthing11 | /inherit_multilevel.py | 691 | 3.796875 | 4 | class A:
def __init__(self, a):
self.a = a
def getA(self):
return self.a
def display(self):
return "A:{0}\n".format(self.a)
class B(A):
def __init__(self, a, b):
super(B, self).__init__(a)
self.b = b
def getB(self):
return self.b
def display(self):
return "{0}\nB:{1}\n".format(super(B, self).display(), self.b)
class C(B):
def __init__(self, a, b, c):
super(C, self).__init__(a, b)
self.c = c
def getC(self):
return self.c
def display(self):
return "{0}\nC:{1}\n".format(super(C, self).display(), self.c)
c = C(1, 2, 3)
temp = c.display()
print(temp)
|
16ccca18cf7f0baf9102f2986e11265d89eb899a | JungChaeMoon/Algorithm | /single_number.py | 279 | 3.640625 | 4 | def single_number(nums):
dup_dict = {}
for num in nums:
if num not in dup_dict:
dup_dict[num] = 1
else:
dup_dict[num] += 1
for key, value in dup_dict.
if value == 1:
return key
print(single_number([2,2,1])) |
404eb31c5d5825de5a20c694576f292d67484991 | pontusahlqvist/algorithmsAndDataStructures | /lecture3/python/binarySearch.py | 433 | 3.859375 | 4 | def binarySearch(A,key):
n = len(A)
if n == 1 and A[0] == key:
return 0
elif n == 1:
return None
if A[n/2] == key:
return n/2
elif key > A[n/2]:
posInSubArray = binarySearch(A[n/2:], key)
if not posInSubArray:
return None
else:
return n/2 + posInSubarray
else:
return binarySearch(A[:n/2], key) #let potential None pass through
A = [1,2,3,4,5,6,7,8,9]
print binarySearch(A, 3)
print binarySearch(A, 10)
|
bf12562582fc79a90ca62982c4722588fed45ea3 | LinkleYping/BlockImage_System | /BImgAssist/getkey.py | 581 | 3.546875 | 4 | from random import Random
def random_str(randomlength):
str = ''
chars = 'abcdef0123456789'
length = len(chars) - 1
random = Random()
for i in range(randomlength):
str += chars[random.randint(0, length)]
return str
def varserification():
str = ''
chars = 'qwertyuiopasdfghjklzxcvbnm1234567890'
length = len(chars) - 1
random = Random()
varserificationlength = 6
for i in range(varserificationlength):
str += chars[random.randint(0, length)]
return str
#
# if __name__ == '__main__':
# print(random_str(6))
|
2b38262cb4ce0f8eba24636e1224d34850d79f60 | almehj/project-euler | /old/problem0078/partitions.py | 798 | 3.5625 | 4 | #!/usr/bin/env python
def max_in_table(table):
answer = -1
for row in table:
for n in row:
if n > answer:
answer = n
return answer
def print_table(table):
m = max_in_table(table)
width = len(str(m))
fmt_str = "%%%dd"%width
i = 1
for row in table:
print("%3d: %s"%(i," ".join([fmt_str%n for n in row])))
i += 1
table = []
n = 1
while True:
table.append([1]*n)
table[0].append(1)
for i in range(1,n):
table[i].append(-1)
for j in range(n+1):
table[i][j] = table[i-1][j]
if j >= i+1:
table[i][j] += table[i][j-i-1]
n_parts = table[-1][-1]
print("%5d: %d"%(n,n_parts))
if n_parts%1000000 == 0:
break
n += 1
|
570211ba2d75ba42dea06ba488053d1cf998b4bb | Gautham-code/normaldistribution | /normal.py | 2,336 | 3.671875 | 4 | import statistics
import pandas as pd
import csv
df = pd.read_csv("StudentsPerformance.csv")
male_list = df["reading score"].tolist()
female_list = df["writing score"].tolist()
male_mean = statistics.mean(male_list)
female_mean = statistics.mean(female_list)
male_median = statistics.median(male_list)
female_median = statistics.median(female_list)
male_std = statistics.stdev(male_list)
female_std = statistics.stdev(female_list)
maleStdStart1,maleStdEnd1 = male_mean - male_std,male_mean + male_std
maleStdStart2,maleStdEnd2 = male_mean - (2*male_std),male_mean + (2*male_std)
maleStdStart3,maleStdEnd3 = male_mean - (3*male_std),male_mean + (3*male_std)
femaleStdStart1,femaleStdEnd1 = female_mean - female_std,female_mean + female_std
femaleStdStart2,femaleStdEnd2 = female_mean - (2*female_std),female_mean + (2*female_std)
femaleStdStart3,femaleStdEnd3 = female_mean - (3*female_std),female_mean + (3*female_std)
male_listWithin_1_st = [result for result in male_list if result > maleStdStart1 and result < maleStdEnd1]
male_listWithin_2_st = [result for result in male_list if result > maleStdStart2 and result < maleStdEnd2]
male_listWithin_3_st = [result for result in male_list if result > maleStdStart3 and result < maleStdEnd3]
female_listWithin_1_st = [result for result in female_list if result > femaleStdStart1 and result < femaleStdEnd1]
female_listWithin_2_st = [result for result in female_list if result > femaleStdStart2 and result < femaleStdEnd2]
female_listWithin_3_st = [result for result in female_list if result > femaleStdStart3 and result < femaleStdEnd3]
print("{}% is the data for male within 1 standard deviation ".format(len(male_listWithin_1_st)*100.0/len(male_list)))
print("{}% is the data for male within 2 standard deviation ".format(len(male_listWithin_2_st)*100.0/len(male_list)))
print("{}% is the data for male within 3 standard deviation ".format(len(male_listWithin_3_st)*100.0/len(male_list)))
print("{}% is the data for female within 1 standard deviation ".format(len(female_listWithin_1_st)*100.0/len(female_list)))
print("{}% is the data for female within 2 standard deviation ".format(len(female_listWithin_2_st)*100.0/len(female_list)))
print("{}% is the data for female within 3 standard deviation ".format(len(female_listWithin_3_st)*100.0/len(female_list)))
|
ac8b2b38b04f34d8aab9f35e553ab80dc396acd1 | bryanlie/Python | /HackerRank/printString.py | 267 | 3.921875 | 4 | '''
Read an integer N.
Without using any string methods, try to print the following:
12...N
'''
def gen(n):
if n == 1:
return '1'
else:
return (gen(n-1) + str(n))
if __name__ == '__main__':
n = int(input())
print(gen(n))
|
51f43080a876765ae956726b9db6457f3a40ed84 | yqin47/leecode | /79.searchword.py | 321 | 3.953125 | 4 | """Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those
horizontally or vertically neighboring. The same letter cell may not be used more than once. """
class Solution:
def exist(self,board, word):
|
4a25ad2d037044b8f1c16cab805cff13de82a080 | cfspoway/python101 | /Homework13/Homework13_Palindrome..py | 291 | 3.875 | 4 | s = input('Please input any thing here: ')
l = len(s)
mid = int((l-1)/2)
palindrome = True;
for i in range(mid):
if s[i] != s[len(s)-1-i]:
palindrome = False;
break;
if palindrome:
print(s + ' is palindrome')
else:
print(s + ' is not palindrome')
|
8c940fff629593bbee2f120d8c7255b3089360ad | gsaisudheer/ML-Univ-of-Washington | /3_Classification/BinaryDecisionTree.py | 9,771 | 4.03125 | 4 | '''
Created on 08-Apr-2017
Programming Assignment 2 of Week 3 from the Classification course of
Coursera Machine Learning Specialization
@author: sudheer
'''
import pandas as pd
import numpy as np
def identify_categorical_variables(data):
categorical = []
for feat_name, feat_type in zip(data.columns, data.dtypes):
if feat_type == object:
categorical.append(feat_name)
return categorical
def turn_into_categorical_variables(data, categorical_features):
#get one-hot encoding of the columns listed in categorical_variables
one_hot = pd.get_dummies(data[categorical_features])
data = data.drop(categorical_features, axis=1)
data = data.join(one_hot)
return data
def intermediate_node_num_mistakes(labels_in_node):
if len(labels_in_node) == 0:
return 0
#Count the number of 1's (safe loans)
positive_loans = (labels_in_node.where(labels_in_node == +1)).count()
#Count the number of -1's (risky loans)
negative_loans = (labels_in_node.where(labels_in_node == -1)).count()
#Return the number of mistakes. Since, we are using majority class, points that are
#not in majority class are considered as mistakes
if positive_loans > negative_loans: #majority class prediction is positive.
return negative_loans #num mistakes is number of negative loans
else:
return positive_loans
def best_splitting_feature(data, features, target):
target_values = data[target]
best_feature = None #Keep track of best feature
best_error = 10 #Keep track of best error so far
#Convert to float to make sure that error gets computed correctly
num_data_points = float(len(data.index))
#Loop through each feature for considering to split on that feature
for feature in features:
#Left split will have all data points where feature value is 0
left_split = data[data[feature] == 0]
#Right split will have all data points where feature value is 1
right_split = data[data[feature] == 1]
#Calculate the number of misclassified examples in the left node
left_mistakes = intermediate_node_num_mistakes(left_split[target])
#Calculate the number of misclassified examples in the right node
right_mistakes = intermediate_node_num_mistakes(right_split[target])
#Compute the classification error of this split
error = (left_mistakes + right_mistakes)/num_data_points
#if error is less than best_error, store feature as best_feature and error as best_error
if error < best_error:
best_feature = feature
best_error = error
return best_feature
def create_leaf (target_values):
#Create a leaf node
leaf = {'splitting_feature': None,
'left': None,
'right': None,
'is_leaf': True}
#Count the number of nodes that are +1 and -1 in this node
num_ones = len(target_values[target_values == +1])
num_minus_ones = len(target_values[target_values == -1])
#For the leaf node, set the prediction to be the majority class
if num_ones > num_minus_ones:
leaf['prediction'] = +1
else:
leaf['prediction'] = -1
#Return leaf node
return leaf
def decision_tree_create(data, features, target, current_depth = 0, max_depth = 10):
remaining_features = features[:]
target_values = data[target]
print ("--------------------------------------------------------------------")
print ("Subtree, depth = %s (%s data points)." % (current_depth, len(target_values)))
#Stopping condition 1
#Check if there are mistakes at current node
mistakes = intermediate_node_num_mistakes(target_values)
if mistakes == 0:
print ('Stopping condition 1 reached.')
#if no mistakes at current node, make current node a leaf node
return create_leaf(target_values)
#Stopping condition 2
#Check if there are no more features to split on
if remaining_features == None:
print('Stopping condition 2 reached.')
#if there are no more remaining features to consider, make it a leaf node
return create_leaf(target_values)
#Stopping condition 3 (limit tree depth)
if current_depth >= max_depth:
print('Reached maximum depth. Stopping for now')
#if max tree depth is reached, make current node a leaf node
return create_leaf(target_values)
#Find the best splitting feature
splitting_feature = best_splitting_feature(data, remaining_features, target)
#Split on the best feature that was found
left_split = data[data[splitting_feature] == 0]
right_split = data[data[splitting_feature] == 1]
remaining_features = remaining_features[remaining_features != splitting_feature]
print("Split on feature %s. (%s, %s)" %(\
splitting_feature, len(left_split), len(right_split)))
#Create a leaf node if the split is perfect
if len(left_split) == len(data):
print('Creating a leaf node')
return create_leaf(left_split[target])
if len(right_split) == len(data):
print('Creating a leaf node')
return create_leaf(right_split[target])
#Repeat on left and right subtrees
left_tree = decision_tree_create(left_split, remaining_features, target, current_depth + 1, max_depth)
right_tree = decision_tree_create(right_split, remaining_features, target, current_depth + 1, max_depth)
return{'is_leaf': False,
'prediction': None,
'splitting_feature': splitting_feature,
'left': left_tree,
'right': right_tree}
def classify(tree, x, annotate = False):
#if the tree is a leaf node.
if tree['is_leaf']:
if annotate:
print("At leaf, predicting %s" % tree['prediction'])
return tree['prediction']
else:
#split on feature
split_feature_value = x[tree['splitting_feature']]
if annotate:
print("Split on %s = %s" % (tree['splitting_feature'], split_feature_value))
if split_feature_value == 0:
return classify(tree['left'], x, annotate)
else:
return classify(tree['right'], x, annotate)
def evaluate_classification_error(tree, data, target):
#Apply the classify(tree,x) for each x in the data
prediction = data.apply(lambda x: classify(tree,x), axis=1)
actual = data[target]
return 1-(np.sum(np.equal(prediction,actual))*1.0/np.shape(actual)[0])
def print_stump(tree, name = 'root'):
split_name = tree['splitting_feature'] # split_name is something like 'term. 36 months'
if split_name is None:
print ("(leaf, label: %s)" % tree['prediction'])
return None
#split_feature, split_value = split_name.split('.')
print (' %s' % name)
print (' |---------------|----------------|')
print (' | |')
print (' | |')
print (' | |')
print (' [{0} == 0] [{0} == 1] '.format(split_name))
print (' | |')
print (' | |')
print (' | |')
print (' (%s) (%s)' \
% (('leaf, label: ' + str(tree['left']['prediction']) if tree['left']['is_leaf'] else 'subtree'),
('leaf, label: ' + str(tree['right']['prediction']) if tree['right']['is_leaf'] else 'subtree')))
loans = pd.read_csv('Data/Week3/3a/lending-club-data.csv')
loans['safe_loans'] = loans['bad_loans'].apply(lambda x: +1 if x==0 else -1)
del loans['bad_loans']
#We will be considering only the following features
features = ['grade', # grade of the loan
'term', # the term of the loan
'home_ownership', # home_ownership status: own, mortgage or rent
'emp_length', # number of years of employment
]
target = 'safe_loans'
#Extract from the loans data only the above features and the target
loans = loans[features+[target]]
train_idx = pd.read_json('Data/Week3/3b/train-idx.json').values[:,0] #indices of the training data
test_idx = pd.read_json('Data/Week3/3b/test-idx.json').values[:,0] #indices of the test data
#Form training and test data
train_data = loans.iloc[train_idx]
test_data = loans.iloc[test_idx]
#Transform train_data and test_data such that they have categorical values for the features
train_data_categorical = turn_into_categorical_variables(train_data, features)
test_data_categorical = turn_into_categorical_variables(test_data, features)
categorical_features = train_data_categorical.columns.values
categorical_features = categorical_features[categorical_features != target]
#Train a tree model with max_depth = 6
my_decision_tree = decision_tree_create(train_data_categorical,categorical_features, target, 0, 6)
print(test_data_categorical.iloc[0])
print("Predicted class: %s " % classify(my_decision_tree, test_data_categorical.iloc[0][categorical_features]))
#Find the prediction path to find the output for the first test point
classify(my_decision_tree, test_data_categorical.iloc[0],True)
#Evaluate the classification error on the test_data
classification_error = evaluate_classification_error(my_decision_tree, test_data_categorical, target)
print('classification_error is %s' %classification_error)
print_stump(my_decision_tree)
print_stump(my_decision_tree['right']['right'], my_decision_tree['right']['splitting_feature'])
|
e6d98cf5ebd858dcd54102445ee0de92664d9d3a | fahaddd-git/bachRandomizer | /main.py | 1,567 | 3.703125 | 4 | import random
import time
suite_data = {1: "Suite No. 1 in G major, BWV 1007", 2: "Suite No. 2 in D minor, BWV 1008",
3: "Suite No. 3 in C major, BWV 1009",
4: "Suite No. 4 in E♭ major, BWV 1010", 5: "Suite No. 5 in C minor, BWV 1011",
6: "Suite No. 6 in D major, BWV 1012"}
movement_data = {1: "Prelude", 2: "Allemande", 3: "Courante", 4: "Sarabande", 5: "Minuet I / II", 6: "Gigue"}
def initial_instructs(name):
print(f'Hi, {name} welcome to the Bach randomizer!\n')
initial_input = input("Ready to roll? (y/n): ")
print("\n")
return initial_input
def select_random():
suite_key, random_suite = random.choice(list(suite_data.items()))
movement_key, random_movement = random.choice(list(movement_data.items()))
if (suite_key == 3 or suite_key == 4) and movement_key == 5:
return random_suite + ": Bourrée I / II"
if (suite_key == 5 or suite_key == 6) and movement_key == 5:
return random_suite + ": Gavotte I / II"
return random_suite + ": " + random_movement
def reroll():
response = input("Reroll? (y/n): ")
print("\n")
return response
def farewell():
print("Thanks for playing! Goodbye! <3")
time.sleep(2)
quit()
if __name__ == '__main__':
program_beginning = initial_instructs('Rebecca')
if program_beginning != "y":
farewell()
else:
while True:
print(select_random())
user_response = reroll()
if user_response != "y":
break
farewell()
|
d300c8d916450a363fef461dff13acc914dc73dc | MuhammedAkinci/pythonEgitimi | /python101/08.08.19/untitled7.py | 622 | 3.5625 | 4 |
dizi = [5,6,1,7,10,3,14]
print(dizi)
dizi.append(10)
print(dizi)
dizi.append(5)
print(dizi)
dizi.insert(3,5)
print(dizi)
dizi.insert(len(dizi), 16)
print(dizi)
print(dizi.index(3))
index = 10
count = 0
for i in range(len(dizi)):
if dizi[i] == index:
count += 1
break
if count == 0:
print("eleman yok")
else:
print("10un indexi = " + str(i))
dizi.insert(90, 100)
print(dizi)
print(dizi.index(100))
dizi.remove(100)
print(dizi)
print(dizi.pop())
print(dizi)
print(dizi.pop(0))
print(dizi)
dizi = [5,6,1,7,10,3,14]
print(dizi)
dizi.sort()
print(dizi)
dizi.sort(reverse = True)
print(dizi)
|
51cd37aeecbc486ddc965af29a5dcd7ac839e46c | subbuinti/python_practice | /numberpyramid.py | 260 | 3.71875 | 4 | n = int(input())
for i in range(1, n+1):
spaces = " "*(n - i)
left_nums = ""
right_nums = ""
for j in range(1, i+1):
left_nums = str(j) + left_nums
right_nums = right_nums + str(j)
print(spaces + left_nums + right_nums[1:])
|
01fa0a6a4d32a12141511a0c27784f5952e75445 | rheehot/Algorithm-coding_test | /괄호 짝 확인.py | 565 | 3.640625 | 4 | from stack import Stack
# def solution(str1):
# s = Stack()
# result = True
# index = 0
# while index < len(str1) and result:
# symbol = str1[index]
# if symbol == "(":
# s.push(symbol)
# else:
# if s.isEmpty():
# result = False
# else:
# s.pop()
# index = index + 1
# if result and s.isEmpty():
# return True
# else:
# return False
# print(solution('(())'))
symbol = '('
s = Stack()
print(s)
print(s.push(symbol))
|
7a960b6a6e335ba8cf87c361070c0e31814046c7 | Eacruzr/python-code | /clase 5/autos.py | 1,355 | 3.5625 | 4 | autos = {'autos':{
1:{'marca':'Tesla',
'modelos':{
1:'Model S',
2:'Model E',
3:'Model X',
4:'Model Y',
}
},
2:{'marca':'Toyota',
'modelos':{
1:'Fortuner',
2:'Prado',
3:'Tundra',
4:'Corola',
}
},
3:{'marca':'Range Rover',
'modelos':{
1:'Evoque',
2:'Defender',
}
},
4:{'marca':'Mazda',
'modelos':{
1:'Mazda 3',
2:'Mazda 2',
3:'CX 30',
}
},
5:{'marca':'Audi',
'modelos':{
1:'A7',
2:'A5',
3:'A3',
}
}
}
}
m1=len(autos['autos'][1]['modelos'])
m2=len(autos['autos'][2]['modelos'])
m3=len(autos['autos'][3]['modelos'])
m4=len(autos['autos'][4]['modelos'])
m5=len(autos['autos'][5]['modelos'])
def mas(m1,m2,m3,m4,m5):
if m1 > m2 and m1 > m3 and m1 > m4:
print('La marca con mayor numero de modelos es: '+m1)
elif m2>m3 and m2>m4 and m2>m5:
print(m2)
elif m3>m4 and m3>m5:
print(m3)
elif m4>m5:
print(m4)
else:
print(m5) |
a1361de4d247ed066ce1cfae65cf778a79f94fa7 | aryan152345/Python-Spinbox-program | /Spinbox_1.py | 477 | 3.5 | 4 | from tkinter import *
mywindow = Tk( )
mywindow.title("COLOUR")
rd=Label(text="Red",font="chiller 24",fg="red")
rd.grid(row=0,column=0)
gr=Label(text="Green",font="chiller 24",fg="green")
gr.grid(row=0,column=1)
blu=Label(text="Blue",font="chiller 24",fg="blue")
blu.grid(row=0,column=2)
rd1=Spinbox(from_=0,to=225)
rd1.grid(row=1,column=0)
gr1=Spinbox(from_=0,to=225)
gr1.grid(row=1,column=1)
blu1=Spinbox(from_=0,to=225)
blu1.grid(row=1,column=2)
mywindow.mainloop()
|
e0a950b5258c400925d521b42f72a8316979061e | hrandonbong/graph-algorithm | /d_graph.py | 10,697 | 4.03125 | 4 | # Course: CS261 - Data Structures
# Author: Brandon Hong
# Date: 6/10/21
# Description: A directed graph that utilizes DFS, BFS, and Dijkstra's algorithm to compute graph inputs
# and desired outputs. Can be used to find shortest paths to certain problems.
import heapq
class DirectedGraph:
"""
Class to implement directed weighted graph
- duplicate edges not allowed
- loops not allowed
- only positive edge weights
- vertex names are integers
"""
def __init__(self, start_edges=None):
"""
Store graph info as adjacency matrix
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.v_count = 0
self.adj_matrix = []
# populate graph with initial vertices and edges (if provided)
# before using, implement add_vertex() and add_edge() methods
if start_edges is not None:
v_count = 0
for u, v, _ in start_edges:
v_count = max(v_count, u, v)
for _ in range(v_count + 1):
self.add_vertex()
for u, v, weight in start_edges:
self.add_edge(u, v, weight)
def __str__(self):
"""
Return content of the graph in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
if self.v_count == 0:
return 'EMPTY GRAPH\n'
out = ' |'
out += ' '.join(['{:2}'.format(i) for i in range(self.v_count)]) + '\n'
out += '-' * (self.v_count * 3 + 3) + '\n'
for i in range(self.v_count):
row = self.adj_matrix[i]
out += '{:2} |'.format(i)
out += ' '.join(['{:2}'.format(w) for w in row]) + '\n'
out = f"GRAPH ({self.v_count} vertices):\n{out}"
return out
# ------------------------------------------------------------------ #
def add_vertex(self) -> int:
"""
Adds a vertex to the weighted graph
"""
self.v_count = self.v_count + 1
if self.v_count == 1:
self.adj_matrix.append([0])
return self.v_count
self.adj_matrix.append([0]*self.v_count)
temp = 0
for i in range(0,self.v_count-1):
self.adj_matrix[i].append(temp)
return self.v_count
def add_edge(self, src: int, dst: int, weight=1) -> None:
"""
Adds a weighted edge between 2 vertices
"""
if src == dst:
return
elif src > self.v_count-1:
return
elif dst > self.v_count-1:
return
elif weight < 0:
return
self.adj_matrix[src][dst] = weight
def remove_edge(self, src: int, dst: int) -> None:
"""
Removes the edge between specified vertex
"""
if src == dst:
return
elif src > self.v_count-1 or src < 0:
return
elif dst > self.v_count-1 or dst < 0:
return
elif self.adj_matrix[src][dst] < 0:
return
self.adj_matrix[src][dst] = 0
def get_vertices(self) -> []:
"""
Returns the vertices in the graph
"""
list = []
for i in range(0,self.v_count):
list.append(i)
return list
def get_edges(self) -> []:
"""
Returns the edges of vertex with their weights
"""
list = []
for i in range(0,self.v_count):
for j in range(0,self.v_count):
if self.adj_matrix[i][j] > 0:
list.append((i,j,self.adj_matrix[i][j]))
return list
def is_valid_path(self, path: []) -> bool:
"""
Returns true for valid paths and false for invalid paths
"""
if len(path) == 0 or (len(path) == 1 and path[0] < self.v_count-1):
return True
for i in range(1,len(path)):
if self.adj_matrix[path[i-1]][path[i]] == 0:
return False
return True
def dfs(self, v_start, v_end=None) -> []:
"""
Depth First Search
"""
list = []
stack = []
stack.append(v_start)
#means the vertex is not in our matrix
if v_start > self.v_count-1:
return list
while len(stack) > 0:
pop = stack.pop()
if pop not in list:
list.append(pop)
#Ending with the loop
if v_end is not None:
if pop == v_end:
break
path = self.adj_matrix[pop]
actual_path = []
for i in range(0,self.v_count):
if path[i] != 0:
actual_path.append(i)
for i in range(len(actual_path)-1,-1,-1):
if actual_path[i] not in list:
stack.append(actual_path[i])
return list
def bfs(self, v_start, v_end=None) -> []:
"""
Uses a breadth first search algorithm
"""
list = []
queue = []
queue.append(v_start)
# means the vertex is not in our matrix
if v_start > self.v_count - 1:
return list
while len(queue) > 0:
pop = queue.pop(0)
if pop not in list:
list.append(pop)
# Ending with the loop
if v_end is not None:
if pop == v_end:
break
path = self.adj_matrix[pop]
actual_path = []
for i in range(0, self.v_count):
if path[i] != 0:
actual_path.append(i)
for i in range(0,len(actual_path)):
if actual_path[i] not in list:
queue.append(actual_path[i])
return list
def has_cycle(self):
"""
Detects a cycle in the graph
"""
def isCyclicUtil(node, visited, recStack,matrix):
visited[node] = True
# recStack[node] = node
inner = []
for i in range(0,len(matrix)):
if matrix[node][i] != 0:
inner.append(i)
for neighbor in range(0,len(inner)):
if visited[inner[neighbor]] == False:
if isCyclicUtil(inner[neighbor], visited, recStack,matrix) == True:
return True
elif recStack == inner[neighbor]:
return True
for node in range(0,self.v_count):
visited = [False] * (self.v_count)
recStack = node
if visited[node] == False:
if isCyclicUtil(node, visited, recStack,self.adj_matrix) == True:
return True
return False
def dijkstra(self, src: int) -> []:
"""
Returns the shortest path from Src node to all other nodes
"""
distances = [float('inf')] * self.v_count
distances[src] = 0
heap = []
heap.append([0,src])
while len(heap) > 0:
pop = heapq.heappop(heap)
node = pop[1]
row = self.adj_matrix[node]
for i in range(0, self.v_count):
if row[i] != 0:
# Making sure we take the shortest path
#If distance has a value it means we visited it
if distances[i] != float('inf'):
compare = row[i] + distances[node]
distances[i] = min(distances[i], compare)
#Else we can move on
else:
distances[i] = row[i] + distances[node]
heapq.heappush(heap, [distances[i], i])
return distances
if __name__ == '__main__':
print("\nPDF - method add_vertex() / add_edge example 1")
print("----------------------------------------------")
g = DirectedGraph()
print(g)
for _ in range(5):
g.add_vertex()
print(g)
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
for src, dst, weight in edges:
g.add_edge(src, dst, weight)
print(g)
print("\nPDF - method get_edges() example 1")
print("----------------------------------")
g = DirectedGraph()
print(g.get_edges(), g.get_vertices(), sep='\n')
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
print(g.get_edges(), g.get_vertices(), sep='\n')
print("\nPDF - method is_valid_path() example 1")
print("--------------------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
test_cases = [[0, 1, 4, 3], [1, 3, 2, 1], [0, 4], [4, 0], [], [2]]
for path in test_cases:
print(path, g.is_valid_path(path))
print("\nPDF - method dfs() and bfs() example 1")
print("--------------------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
for start in range(5):
print(f'{start} DFS:{g.dfs(start)} BFS:{g.bfs(start)}')
print("\nPDF - method has_cycle() example 1")
print("----------------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
edges_to_remove = [(3, 1), (4, 0), (3, 2)]
for src, dst in edges_to_remove:
g.remove_edge(src, dst)
print(g.get_edges(), g.has_cycle(), sep='\n')
edges_to_add = [(4, 3), (2, 3), (1, 3), (4, 0)]
for src, dst in edges_to_add:
g.add_edge(src, dst)
print(g.get_edges(), g.has_cycle(), sep='\n')
print('\n', g)
print("\nPDF - dijkstra() example 1")
print("--------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
for i in range(5):
print(f'DIJKSTRA {i} {g.dijkstra(i)}')
g.remove_edge(4, 3)
print('\n', g)
for i in range(5):
print(f'DIJKSTRA {i} {g.dijkstra(i)}')
print("\nPDF - dijkstra() example 2")
print("--------------------------")
edges = [(2, 6, 5), (2, 8, 7),(3, 1, 20),(3, 2, 15),(4, 10, 7),
(5, 12, 1), (6, 12, 3),(7, 12, 17),(8, 12, 10),(11, 9, 12)
, (12, 4, 4), (12, 9, 14)]
g = DirectedGraph(edges)
print(f'DIJKSTRA {2} {g.dijkstra(2)}')
|
42d65aec11891ced490bb4f982504103b75b2d58 | jlcatonjr/Learn-Python-for-Stats-and-Econ | /In Class Projects/In Class Examples Fall 2019/Section 1/concatenateStrings2.py | 389 | 3.609375 | 4 | #concatenateStrings2.py
line1 = "Today we learned things we did not"
line2 = "know, and surprised we were and thought"
line3 = "Python may not be easy, but its not that hard"
line4 = "Learn more I will, and be a Pythonista(r)"
# concatenate the above strings while passing to print()
print(line1, line2, line3, line4, sep ="\n")
print(line1 + "\n" + line2 + "\n" + line3 + "\n" + line4 )
|
fb770d5c72587c0665bc0d61be3869da009a6498 | wangyannhao/final-stock-market-website | /stock/linear_regression.py | 4,547 | 3.578125 | 4 | from numpy import *
import numpy
import math
# // written by: Yanhao Wang
# // assisted by: Xin Zhang
# // debugged by:
# // etc.
alpha = 0.005
beta = 11.1
fileName = {1: 'Square.csv',
2: 'Twitter.csv',
3: 'Facebook.csv',
4: 'Amazon.csv',
5: 'Alphabet.csv',
6: 'Netflix.csv',
7: 'Tesla.csv',
8: 'Alibaba.csv',
9: 'GoPro.csv',
10: 'Fitbit.csv'}
def readfile(filename,len):
file = open(filename)
X = []
i = 0
for line in file.readlines():
if i<len:
item = line.split(',')
X.append(float(item[4]))
i += 1
return X
def chooseFile():
print 'Choose the number of train data to read: '
num = []
for j in fileName:
print str(j) + ':' + fileName[j]
num.append(str(j))
file = raw_input()
while file not in num:
print 'input is invalid, please input the number of train data: '
file = raw_input()
print 'The train data file is: ' + fileName[int(file)]
print 'Choose the length of train data (100-240): '
length = input()
while length<100 or length>240:
print 'input is invalid, please input a length between 100 and 240: '
length = input()
print 'The length of train data is: ' + str(length)
Datas = readfile(fileName[int(file)], length)
x = length+1
Dlength = length
N = numpy.arange(1,x,1)
return Datas,x,Dlength,N
def getPhiX(x,Mp):
PhiX = []
i = 0
while i < Mp:
PhiX.append(math.pow(x, i))
i += 1
PhiXX = numpy.array(PhiX)
return PhiXX
def getInvS(N,Mp):
I = numpy.ones((Mp, Mp))
tmp = numpy.zeros((Mp, Mp))
for n in range(0, len(N)):
PhiX = getPhiX(N[n],Mp)
PhiX.shape = (Mp, 1)
PhiXT = numpy.transpose(PhiX)
tmp += numpy.dot(PhiX, PhiXT)
betaPhi = beta * numpy.matrix(tmp)
alphaI = alpha * numpy.matrix(I)
InverseS = alphaI + betaPhi
return InverseS
def getm(x,data,N,Mp):
tmp = numpy.zeros((Mp, 1))
PhiX = getPhiX(x,Mp)
PhiX.shape = (Mp, 1)
InverseS = getInvS(N,Mp)
S = numpy.linalg.inv(InverseS)
PhiXT = numpy.transpose(PhiX)
tmp1 = numpy.dot(PhiXT, S)
mult = beta * numpy.matrix(tmp1)
n = 0
while n < len(N):
phiXn = getPhiX(N[n],Mp)
phiXn.shape = (Mp, 1)
z = numpy.dot(phiXn, data[n])
tmp = numpy.add(tmp, z)
n += 1
result = numpy.dot(mult, tmp)
return result[0,0]
def gets2(x):
PhiX = getPhiX(x)
PhiX.shape = (Mp, 1)
InverseS = getInvS()
PhiXT = numpy.transpose(PhiX)
S = numpy.linalg.inv(InverseS)
tmp = numpy.dot(PhiXT, S)
s2 = numpy.dot(tmp, PhiX)
s2 += (1 / beta)
return s2[0,0]
# def error():
# meanErr = 0
# relativeErr = 0
# predict = getm(x)
# i = 0
# while i<Dlength:
# meanErr += Datas[i] - predict
# relativeErr += (Datas[i] - predict)/Datas[i]
# i += 1
# meanErr /= Dlength
# relativeErr /= Dlength
# print 'Absolute Mean Error is: '+ str(meanErr)
# print 'Average Relative Error is: '+ str(relativeErr)
def predict(table, range):
M=10
Datas = table[len(table)-range:len(table)]
x = len(Datas)+1
Dlength = len(Datas)
N = numpy.arange(1,x,1)
# print len(N),"hahahahha"
mean = getm(x,Datas,N,M+1)
return mean
def predictLong(table, rrange):
M = 1
Datas = table[len(table)-rrange:len(table)]
sum = 0
ma = []
for i in range(0,len(Datas)):
sum = sum + Datas[i]
if ( (i+1) % 7 == 0 ):
ma.append(sum/7.0)
sum = 0
x = len(ma)+1
Dlength = len(ma)
N = numpy.arange(1,x,1)
# print len(N),"hahahahha"
mean = getm(x+8,ma,N,M+1)
return mean
# def predictLong(table, rrange):
# # long term t
# start = len(table) % rrange
# distance = (len(table)-start) / rrange
# # print distance,"distance ", len(table),'table'
# # x = len(Datas)+1
# # N_s = numpy.arange(1,x,1)
# N = []
# Datas = []
# count = 0
# for i in range(start, len(table)):
# count = count + 1
# if count % distance == 0:
# Datas.append(table[i])
# N.append(i)
# # Datas = table[len(table)-rrange:len(table)]
# x = len(Datas)+1
# # print x,"xxxxxxxxxxxx"
# Dlength = len(Datas)
# # N = numpy.arange(1,x,1)
# mean = getm(x+distance,Datas,N)
# # print len(N),"xixiixixi"
# return mean
|
db9ee7dd4555be573c84fb18d2633c6c8c6ea9df | jjh9000507/pythonStudy | /int_convert.py | 192 | 3.703125 | 4 | string_a = input("입력A> ")
int_a = int(string_a)
string_b = input("입력B> ")
int_b = int(string_b)
print("문자열 치료:", string_a + string_b)
print("숫자 치료:", int_a + int_b) |
0e531209c465dbf528a76e786ab75f9a1e3654c0 | alexpereiramaranhao/guppe | /lambdas-funcoes-integradas/reduce.py | 768 | 4.3125 | 4 | """
Já foi uma função integrada, mas a partir do Python3, reduce deixou de ser função integrada (built-in). Agora temos
que importar o módulo "functools".
Utilize a função reduce se realmente precisa delas. 99% das vezes um loop for é mais legível
Funcionamento:
Na lista, pega o primeiro e o segundo valor, manda para a função, pega o resultado e devolve para a função junto com o
terceiro valor, pega o resultado e manda novamente para a função junto com o quarto valor e assim por diante.
"""
import functools
valores = [1, 3, 4, 5, 9, 8, 1, 5]
def soma(val1, val2):
return val1 + val2
resultado = functools.reduce(soma, valores)
print(resultado)
resultado = functools.reduce(lambda val1, val2: val1 + val2, valores)
print(resultado)
|
fb4e313c4b7dcfdaced531de36d921cd34980cfd | Nasnini/String_Calculator | /tests/test_calculator.py | 1,363 | 3.703125 | 4 | from string_calculator.calculator import add
#import pytest
# Testing invalid inputs
# def test_invalid_input():
# assert add(string) == "invalid input"
# Testing id add function is 0
def test_add_empty_str():
assert add("") == 0
# Testing that the add function has one value
def test_add_one_integer():
assert add("1") == 1
# Testing that the add function has two values
def test_add_two_integers():
assert add("1,2") == 3
# Testing the add function can have multiple integers
def test_add_many_integers():
assert add("1,2,3,4") == 10
# Testing if add can handle new lines between integers instead of commas
def test_new_lines():
assert add("1\n2,3") == 6
# Testing different delimeters
def test_diff_delimiters():
assert add("//;\n1;2") == 3
# Testing if there are negatives values
def test_check_negatives():
with pytest.raises(Exception) as err:
assert add("//;\n-1;2,-3")
assert str(err.value) == "Negatives not allowed: -1,-3,"
# Testing if any number bigger than 20 will be ignored
def test_more_than_twenty():
assert add("//;\n1;2,21") == 3
# Testing if delimeters can be of any length
def test_delimeter_len():
assert add("//[***]\n1***2***3") == 6
# Testing if the add function can allow multiple delimeters
def test_multiple_delimeters():
assert add("//[*][%]\n1*2%3") == 6
|
a3e506b82863e83a46712428d2f4df0ca23bfaba | jimmcgaw/CodeEval | /repeatedsubstring.py | 2,213 | 3.796875 | 4 | #!/usr/bin/python
import string
import sys
import re
# check that a filename argument was provided, otherwise
if len(sys.argv) < 2:
raise Exception("Filename must be first argument provided")
filename = sys.argv[1]
lines = []
# open file in read mode, assuming file is in same directory as script
try:
file = open(filename, 'r')
# read Fibbonacci indexes from file into list
lines = file.readlines()
file.close()
except IOError:
print "File '%s' was not found in current directory" % filename
lines = [line.replace('\n', '') for line in lines]
try:
lines.remove("")
except:
pass
def get_substrings(value, substring_length):
""" returns all substrings in string value of length n """
string_length = len(line)
substrings = []
lower_bound = 0
upper_bound = substring_length
while upper_bound <= string_length:
substrings.append(value[lower_bound:upper_bound])
lower_bound += 1
upper_bound += 1
return substrings
def get_repeated_strings(string_list):
""" return first duplicate string in list string_list if found, otherwise return empty list """
dups = [x for x in string_list if string_list.count(x) > 1]
if dups:
dups = dups[0:len(dups)/2]
return dups
else:
return []
def do_substrings_overlap(string, substring):
""" substring occurs in string at least once, return True if occurrences overlap within string """
substring_length = len(substring)
left_index = string.find(substring)
right_index = string.rfind(substring)
diff = right_index - left_index
if diff < substring_length and diff != 0:
return True
return False
for line in lines:
string_length = len(line)
# start with half of string length
substring_length = string_length / 2
while substring_length > 1:
substrings = get_substrings(line, substring_length)
repeated_substrings = get_repeated_strings(substrings)
if repeated_substrings:
for substring in repeated_substrings:
overlap = do_substrings_overlap(line, substring)
if not overlap:
# we have a winner!
print substring
break
#print substrings
substring_length -= 1
|
8d92dcacb8f8db152b2f064ba2f1905424938dff | jzsun/Python | /dict.py | 848 | 3.859375 | 4 | #-*-coding:utf-8-*-
print "python里的字典相当于C++里的Map,使用键值对存储"
print "{"":"", "":""}","字典花括号为边界,key-value以:分隔,key-avl值遵循python的语法规则"
#输出顺序随机
d = {"zhao":18, "qian":17, "sun":20}
print d
d["zhao"] = 28
print d
d["sun"] = 25
d["sun"] = 26 #覆盖上一次的赋值
print d
print "print d[\"li\"]", "#key不存在报错"
#检测key值是否存在的方法
#方法1,in
print "li" in d
print "sun" in d
#2 get()方法
print d.get("li") #不存在则输出None,在交互命令行不提示
#指定不存在时的输出方式,假设输出bucunzai
print d.get("li", "bucunzai")
#输出key-val
#d.pop("li") 删除不存在的值,也会报错
d.pop("zhao")
print d
print "Note: dict的可以、必须是不可变对象"
#key = [1, 2]
#d[key] = "a list"
|
507d22523309ea30f8058dfa40ff6e60d7e2a936 | natfontanesi/30_dias_de_codigo | /Dia23-desafios/wx_81.py | 386 | 3.59375 | 4 | from random import randint
from time import sleep
from operator import itemgetter
jogo = {"jogador1": randint(1,6), "jogador2": randint(1,6),"jogador3": randint(1,6),"jogador4": randint(1,6)}
print("Valores sorteados:")
for k, v in jogo.items():
print(f"{k} tirou {v} no dado")
sleep(1)
ranking={}
ranking = sorted(jogo.items(),key=itemgetter(1), reverse=True)
print(ranking) |
3ef96e598d15a995be1156756f514e8023c3fe21 | tahsinalamin/codesignal_problems | /my_solutions/43_isBeautifulString.py | 687 | 3.546875 | 4 | def isBeautifulString(inputString):
d={}
s="abcdefghijklmnopqrstuvwxyz"
s=list(s)
print(s)
for i in range(len(inputString)):
if inputString[i] in d:
d[inputString[i]]+=1
else:
d[inputString[i]]=1
dic = d.items()
dic=sorted(dic)
print(dic)
for i in range(len(d)-1):
#print(dic[i][1],dic[i+1][1])
print(dic[i][0],s[i])
if dic[i][0]!=s[i] or dic[i+1][0]!=s[i+1]:
return False
if int(dic[i][1])<int(dic[i+1][1]):
return False
return True
inputString = "bbbaacdafe"
print(isBeautifulString(inputString))
|
24963b434eff3636ca9ef479cbdf1b8c10359568 | IanC162/project-euler | /057 sqrtconverge.py | 292 | 3.625 | 4 | #Problem: compute the number of iterations of continued frac. of root 2
# whose numerator has more digits than its denominator
n, d, count = 2, 3, 0
for k in range(1000):
if len(str(n)) > len(str(d)): count += 1
last = n
n += 2*d
d += last
print count
raw_input()
|
919aa44b7fb7a8639875ee66b629bf898db3e7df | Winte/Python_misc_algorithms | /range_sum_BST.py | 1,129 | 3.84375 | 4 | """
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Ex:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
def sum_tree(root, L, R, total):
if root.left: # in case there is a left noode
sum_tree(root.left, L, R, total) # call sum_tree on the left node
if root.val >= L and root.val <= R: # if value between L and R inclusive
total.append(root.val) # add it to the list
if root.right:
sum_tree(root.right, L, R, total) # if there's right node, call function on it
return total # when there isn't right and left node, just return a list
total = []
return sum(sum_tree(root, L, R, total)) # return the sum of the list |
522e56e1b3299c1d267992d94f8ad382c612050a | goodwin64/pyLabs-2013-14 | /1 семестр/lab 5/5lab_04var_Donchenko.py | 259 | 3.765625 | 4 | # 4) Написати програму виведення всіх чисел
# від 1 до N, які закінчуються цифрою 3.
N=input('Введіть число N: ')
for i in range (1, int(N)+1):
if str(i)[-1]=='3':
print (i)
|
051921ef34b8d0f7a12600e33a0990b638af3894 | valeriacavalcanti/IP-2019.1 | /Lista 01/lista_01_questao_07.py | 183 | 3.734375 | 4 | n1 = float(input("Informe a primeira nota: "))
n2 = float(input("Informe a segunda nota: "))
media_ponderada = ((n1 * 6) + (n2 * 4)) / 10
print("Média ponderada =", media_ponderada) |
e63a107deaa34a2b5a4bb3118514a3b60e1a11a0 | ZhenJie-Zhang/Python | /workspace/m2_type/casting.py | 184 | 3.859375 | 4 | x = 3.8
print(x)
x = int(3.8)
print(x)
# x= '123' + 456
# print(x)
x= '123' + '456'
print(x)
x= int('123') + 456
print(x)
x= '123' + str(456)
print(x)
# x= int('a123')
# print(x) |
eab002799de73fcc0d0014e22d82acdf2a1243ab | Mishal-Mansha/Task | /question4sol.py | 150 | 4.125 | 4 | alphabet=input("Enter an alphabet")
list={'a','e','i','o','u'}
if alphabet in list:
print("It is a vowel")
else:
print("It is a consonant")
|
9806187bce8ff6e7cb7e5c6d8ba00c600a67da2a | almirgon/LabP1 | /Unidade-1/ponderada.py | 335 | 3.546875 | 4 | #coding: utf-8
#@Crispiniano
#Unidade 1: Média Mágica
nota1 = float(raw_input())
nota2 = float(raw_input())
nota3 = float(raw_input())
peso1 = float(raw_input())
peso2 = float(raw_input())
peso3 = 100 - (peso1+peso2)
media = (nota1*(peso1/100) + nota2*(peso2/100) + nota3*(peso3/100))
print "Média Final: {:.1f}".format(media)
|
65ba7aa91008eba1160be5f8d2299e1531fc749b | haorenxwx/python_note | /leetcode22parentheses.py | 1,048 | 3.703125 | 4 | #leetcode22parentheses.py
'''def ParenGe(l,r,item, res):
if r < 1:
return
if r == 0 and l == 0:
res.append(item)
print("for every item append:\n")
print(res)
if l > 0:
print("for every left modify:\n")
print(item)
ParenGe(l-1, r, item+'(', res)
if r > 0:
print("for every right modify\n")
print(item)
ParenGe(l, r-1, item+')', res)
res = []
ParenGe(3,3,'',res)
print(res)
'''
#create Q as a generater
def generate(p,left,right):
if right >= left >= 0:
if not right:
return p
for q in generate(p+'(',left-1,right):
yield q
print('for every left q yield\n'+p+'(')
print(left,right)
for q1 in generate(p+')',left,right-1):
yield q1
print('for every right q1 yield\n'+p+')')
print(left,right)
print(list(generate('',3,3)))
'''
def generate(p, left, right):
if right >= left >= 0:
if not right:
yield p
for q in generate(p + '(', left-1, right): yield q
for q in generate(p + ')', left, right-1): yield q
print(list(generate('', 3, 3)))
'''
|
e71c9c1bbd1d1c2e0a002912019453d5b6e6b58a | Baistan/FirstProject | /list_method_tasks/Задача20.py | 143 | 3.65625 | 4 | s = input()
if len(s) == 11 and s[0:2] == "+7":
print(s)
elif len(s) == 10:
print("+7" + s[1:])
elif len(s) == 9:
print("+7" + s)
|
09a6475ac8d16fc204e50785c3058bb38661f192 | mohammadgoli/sql | /up&del.py | 384 | 3.640625 | 4 | #!/usr/bin/python
import sqlite3
with sqlite3.connect('thetable.db') as db:
crs = db.cursor()
crs.execute("UPDATE population SET population = 9000000 WHERE city = 'New York City'")
print "\nNEW DATA:\n"
crs.execute("DELETE FROM population WHERE city = 'Boston'")
crs.execute("SELECT * FROM population")
rows = crs.fetchall()
for row in rows:
print row[0], row[1], row[2] |
0016393f414b11be95109d8f4c91a3777c46dabb | dpezzin/dpezzin.github.io | /test/Python/dataquest/enumeration_catching_errors/replace_loop.py | 444 | 4.03125 | 4 | #!/usr/bin/env python
# We can replace values in a list with a for loop.
# All of the 0 values in the first column here will be replaced with a 5.
lolists = [[0,5,10], [5,20,30], [0,70,80]]
for row in lolists:
if row[0] == 0:
row[0] = 5
# We can see the new list.
print(lolists)
# Loop through the rows in legislators and replace any gender values of "" with "M".
for row in legislators:
if row[3] == "":
row[3] = "M" |
00156efaca26c75b2cc092442b9302b0449cde35 | Halverson-Jason/cs241 | /asteroids/velocity.py | 633 | 3.515625 | 4 | class Velocity:
def __init__(self,dx=0.0,dy=0.0):
self.velocity_dx = dx
self.velocity_dy = dx
def copy(self):
return Velocity(self.dx,self.dy)
@property
def dx(self):
return self.velocity_dx
@dx.setter
def dx(self,dx):
self.velocity_dx = dx
@property
def dy(self):
return self.velocity_dy
@dy.setter
def dy(self,dy):
self.velocity_dy = dy
@property
def vector(self):
return (self.velocity_dx,self.velocity_dy)
@vector.setter
def vector(self, coordinates):
self.velocity_dx, self.velocity_dy = coordinates |
67a86fd78c8e834753182e5aef6acf2d9f4ec202 | python4eg/Python-test-repo-phase-1 | /lesson10_2.py | 2,673 | 3.796875 | 4 | import json
class Person:
name = None
city = None
def __init__(self, name, city):
Person.name = name
Person.city = city
person1 = Person('name', 'city')
print('Person 1 name: ' + person1.name)
person2 = Person('name2', 'city2')
print('Person 1 name: ' + person1.name)
print('Person 2 name: ' + person2.name)
class Person:
name = None
city = None
def __init__(self, name, city):
self.name = name
self.city = city
def __str__(self):
return f'{self.name} з {self.city}'
def __repr__(self):
return f'{self.name} from {self.city}'
def convert(self):
return {
'name': self.name,
'city': self.city
}
class SuperPerson:
name = None
city = None
super_power = None
def __init__(self, name, city, super_power):
self.name = name
self.city = city
self.super_power = super_power
def convert(self):
return {
'name': self.name
}
mykola = Person('Mykola', 'city')
print('Person 1 name: ' + mykola.name)
fedir = Person('Пилип', 'конопель')
print('Person 1 name: ' + mykola.name)
print('Person 2 name: ' + fedir.name)
print(f'Fedir: {fedir}')
print('{fedir!r}'.format(fedir=fedir))
#name = input('Name: ')
#city = input('City: ')
#new_person = Person(name, city)
try:
json_data = json.load(open('test.json'))
except json.decoder.JSONDecodeError:
json_data = []
new_list = []
for item in json_data:
new_list.append(Person(**item))
new_list.append(SuperPerson('Batman', 'Gotham', 'Money'))
print(new_list)
for item in new_list:
if item.name == 'Fedir':
print(item)
new_list = [person.convert() for person in new_list]
with open('test2.json', 'w+') as f:
json.dump(new_list, f, indent=4)
# Not recommended
x = 10
def func1():
global x
x = 1
print(x)
print(x)
func1()
print(x)
# Likee
x = 10
def func1(x):
x += 1
return x
print(x)
x = func1(x)
print(x)
#non local
x = 10 # global scope
def func2():
global y
print(y)
y = 1
x = 1 #local scope for func 2
def closure():
y = 10 # local scope closure
nonlocal x
x = 2 # local scope func2
print(f'closure x {x}')
print(f'local 1 x {x}')
closure()
print(f'local 2 x {x}')
y = 20
print(f'global 1 x {x}')
print(f'global 1 y {y}')
func2()
print(f'global 2 x {x}')
print(f'global 2 y {y}')
# example of using global and don't trigger teacher
global_x = 100
def first_func():
global global_x
global_x = 300
def second_func():
print(global_x)
second_func()
first_func()
second_func() |
d43c4b3d9485366a4fb8f2a96ee1c1be5346fb26 | Viraculous/python | /Recycle and Earn.py | 2,830 | 4.1875 | 4 | #Excercise 1:
'''In many jurisdictions a small deposit is added to drink containers to encourage people
to recycle them. In one particular jurisdiction, drink containers holding one liter or
less have a $0.10 deposit, and drink containers holding more than one liter have a
$0.25 deposit.
Write a program that reads the number of containers of each size from the user.
Your program should continue by computing and displaying the refund that will be
received for returning those containers. Format the output so that it includes a dollar
sign and always displays exactly two decimal places'''
#Here is my Advertisement tag
Ad = "Recycle your bottles for every drink you buy here and get paid"
#This executes my Advertisement tag
print(Ad)
#This is intended to collect the user data assuming the platform requires the users data for records,reference or rebates
print("Start recycling today by registering with us first")
print("REGISTER HERE")
#This recieves the user data on specified input requirement
Firstname = str(input("Firstname: "))
Middlename = str(input("Middlename: "))
Surname = str(input("Surname: "))
Email = str(input("Email:"))
#This receives data from users to know weather or not they want to recycle.
Type = str(input("Enter YES if you want to start recycling, else enter NO:"))
#This states the condition and exceptions for the execution of user input
if Type == "YES":
#Error handling using try-except functions
try:
number_of_bottles = int(input("How many bottle do you want to recycle?: "))
except ValueError:
print("Error...numbers only. Retry")
quit()
#Error handling using try-except functions
try:
litre = float(input("What are their sizes respectively(ltr)?:"))
except ValueError:
print("Error...numbers only. Retry")
quit()
#This states the condition for execution for the ranges of size stipulated in this excercise and its return value
def bottle_deposit(litre):
if litre <= 1:
return 0.10 * number_of_bottles
elif litre > 1:
return 0.25 * number_of_bottles
elif number_of_bottles == 0:
return 0
else:
pass
#This print function is executed if the expected input is "YES" and fulfills the sub-conditions preceding it.
print("Congratulations! ", Firstname + " " + Surname, "you have recieved,","$"+ format(bottle_deposit(litre),".2f"),"for recycling your bottle")
elif Type == "NO":
#This print function is executed if the alternate expected input "NO" is met
print("Thanks")
else:
#This print function is executed when neither of the first conditional requirement("YES" or"NO") of the Type function is met. i.e for anything else than "YES" or "NO".
print("wrong entry: input either uppercase YES/NO") |
9359ea6801cbc89c36f0e97c9f7da6357039076b | bperard/PDX-Code-Guild | /python/lab16-pick6.py | 1,636 | 3.875 | 4 | '''
lab 16: pick 6
'''
import random
# create ticket with definable range parameters
def pick_six (low, high):
pix = []
i = 0
while i < 6:
check = random.randint(low, high)
# prevent repeated choices on same ticket
while check in pix:
check = random.randint(low, high)
pix.append(check)
i += 1
return pix
# user input for number of random tickets purchased and range of numbers used by game
runs = int(input('How many times would you like me to invest for you?'))
print('Next, we\'ll define the range for your number choices.')
low = int(input('What is the bottom of your number range?'))
high = int(input('What is the top of your number range?'))
winner = pick_six(low, high) # create winning ticket
win_table = [0, 4, 7, 100, 50000, 1000000, 25000000] # values for correct matches per ticket
# earnings, cost, and run variables initiated
earnings = 0
cost = 0
i = 0
# simulated ticket play with same winning ticket & user defined number of runs
while i < runs:
gamble = pick_six(low, high) # generate new random ticket for run
match = 0 # track matches per ticket
read = 0 # used to cycle through indices of winning ticket
# check/track matches per ticket, track cost, determine winnings per ticket, progress to next run(i)
for ticket in gamble:
if ticket == winner[read]:
match += 1
read += 1
cost += 2
earnings += win_table[match]
i += 1
# display cost, winning, ROI
print('Cost = $' + str(cost))
print('Winnings = $' + str(earnings))
print('ROI = ' + str((earnings - cost) / cost )) |
9d68a1b2394ec1989e454c6caa16045b4df3734e | michaelvitello/python-exercises | /exercise-5.py | 981 | 3.9375 | 4 | #Password verification method
# Conditions:
# Password OK if :
# 1+ cap letter
# 1+ lowercase letter
# 1 number between 0-9
# 1 spec carac between $ & or @
# length min: 6 carac
# Length max: 12 carac
import re
password = raw_input("Choose a password / Choisir un mot de passe: ")
print password
def password_check(password):
print("checking...")
i = True
while i:
if (len(password)<6 or len(password)>12):
break
elif not re.search("[a-z]",password):
break
elif not re.search("[0-9]",password):
break
elif not re.search("[A-Z]",password):
break
elif not re.search("[$#@]",password):
break
elif re.search("\s",password):
break
else:
print("Valid password / Mot de passe valide")
i = False
break
if i:
print("Invalid password / Mot de passe invalide")
password_check(password)
|
f5208676c40fb7812706ff9f0d9a870039c236ed | liaowen9527/multi_tech | /python/zero_learn/6-for_while.py | 2,745 | 4.125 | 4 | #本章节讲得是循环语句
#每件事,我们不可能只做一次,重复做的事,我们可以通过for循环简单实现
#在前面的章节中,我们已经预先学些了一些简单的循环用法
#本章节中会讲解一些更高级的用法,使代码更简洁,好看
#跳出循环
#我们不希望一件事一直运行下去,在必要的时候应该退出循环
def break_loop():
print("告诉你一个秘密哟: 输入exit可以退出循环")
#while(True)表达的是一个死循环,死循环的意思就是无限循环
while(True):
a = input("随便输入吧,反正我是死循环,嘿嘿\n")
if a == "exit":
print("oh, no。你怎么发现exit可以退出的。")
break
break_loop()
#跳出本次循环,重新开始循环
#这个解释可能不好理解,我们来说个场景
#比如,除了lucy休息, 其他人呢,先去做早操;做完早操呢,男同学提水,女同学打扫卫生
#我们来用代码表示
def do_something():
print("告诉你一个秘密哟: 输入exit可以退出循环")
print("老师:除了lucy休息, 其他人呢,先去做早操;做完早操呢,男同学提水,女同学打扫卫生")
while(True):
name = input("你叫什么名字:")
if name == "lucy":
continue
elif name == "exit":
break
print("做早操")
sex = input("性别boy or girl:")
if sex == "boy":
print("去提水")
elif sex == "girl":
print("去打扫卫生")
else:
print("卧槽,这是什么性别? 我只知道boy和girl")
do_something()
#for循环
#for也可以实现循环,一般用于范围内循环
#例如输出1-10
def print_1_10():
print("通过for循环,打印1-10")
for i in range(1, 11):
print(i)
#我们也可以通过while来实现输出1-10,但是code会显得不优美
def while_print_1_10():
print("通过while循环,打印1-10")
i = 1
#当i == 11 的时候,就会自动退出循环了,这里不是死循环
#while括号后为False时就会自动退出循环
while(i < 11):
print(i)
i = i + 1
def loop_array():
print("遍历数组中的水果")
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print('当前水果 :', fruit)
print_1_10()
while_print_1_10()
loop_array()
#双重循环
#双重循环也是经常用到的
def loop_twice():
for i in range(1, 10):
for j in range(1, 10):
print("i * j =", i, "*", j, "=", i * j )
loop_twice()
|
eea08c9a582099e2b72e40307bdfa8d946e283e8 | atozzini/CursoPythonPentest | /PycharmProjects/ExerciciosGrupo/exercicio113.py | 236 | 3.90625 | 4 | texto = raw_input('Digite qualquer coisa: ')
print(str(texto))
# o input pega o valor que e digitado na tela, no codigo pegamos este valor
# e atribuimos a uma variavel
# o raw_input() e por causa da versao do python que estou usando |
6919ad6e10f24adaeb31f6a205d65555826057ff | LYZhelloworld/Leetcode | /keyboard-row/solution.py | 464 | 3.953125 | 4 | class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
res = []
row1 = 'qwertyuiopQWERTYUIOP'
row2 = 'asdfghjklASDFGHJKL'
row3 = 'zxcvbnmZXCVBNM'
for word in words:
if all([c in row1 for c in word]) or all([c in row2 for c in word]) or all([c in row3 for c in word]):
res.append(word)
return res
|
ebabbfb989ce5fadcf5e47dedb6c141f2fe751ed | somphorsngoun/pyhon-_week_17 | /Week_17/test.py | 359 | 3.921875 | 4 | def sum(array):
sum = 0
for n in array:
sum += n
return sum
def createNewArray(array, value):
return array.append(value)
def getAvg(array):
return int(sum(array) / len(array))
numbers = [10, 5, 7, 8, 6]
evenList = []
for n in numbers:
if n%2 != 1:
createNewArray(evenList, n)
print(getAvg(evenList)) |
d0d35976135dba7a1acd087dd2c8dd068e2c7e76 | Ahsanhabib1080/CodeForces | /problems/A/PensAndPencils.py | 802 | 3.5625 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1244/A
Solution: If we have to take m notes and one stationary item can write n notes, the no. of those stationary items needed
is ceil(m/n) = (m + n - 1) / n. This way we calculate the minimum pens and pencils needed. If their sum is <= k, we return
that as the answer, else it is -1. Note that the question doesn't require minimization but it seems straightforward for
calculation purposes.
'''
def solve(a, b, c, d, k):
pens = (a + c - 1) / c
pencils = (b + d - 1) / d
return -1 if pens + pencils > k else str(pens) + " " + str(pencils)
if __name__ == "__main__":
t = int(raw_input())
for _ in xrange(0, t):
a, b, c, d, k = map(int, raw_input().split(" "))
print solve(a, b, c, d, k)
|
aaafe7a4ae484ae125ed2c0d15f17e0ff18b166b | deepanshu102/python | /ass3.9.py | 190 | 3.90625 | 4 | def count(num):
i=int(0)
print(num);
while(num>0):
num=num/10;
i=i+int(1);
return i;
a=int(input("Enter the number"));
print("Number of the digit",count(a));
|
9b9555711299362fd159cd81e8bc285ee0fb2aa4 | pierri/ud120-projects | /datasets_questions/explore_enron_data.py | 4,034 | 3.859375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You should explore features_dict as part of the mini-project,
but here's an example to get you started:
enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000
"""
import pickle
enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))
print "Number of people in the dataset:", len(enron_data)
print "Number of features:",
first_person = enron_data.keys()[0]
first_set_of_features = enron_data[first_person]
print len(first_set_of_features)
print "Number of POIs:",
pois = {name: features for name, features in enron_data.iteritems() if features["poi"]} # filter using a dict comprehension
print len(pois)
print "Total value of stock belonging to James Prentice:",
print enron_data["PRENTICE JAMES"]["total_stock_value"]
print "Email messages from Wesley Colwell to POIs:",
print enron_data["COLWELL WESLEY"]["from_this_person_to_poi"]
print "Value of stock options exercised by Jeffrey Skilling:",
print enron_data["SKILLING JEFFREY K"]["exercised_stock_options"]
print "Total payments for Lay:",
print enron_data["LAY KENNETH L"]["total_payments"]
print "Total payments for Skilling:",
print enron_data["SKILLING JEFFREY K"]["total_payments"]
print "Total payments for Fastow:",
print enron_data["FASTOW ANDREW S"]["total_payments"]
print "No of folks with quantified salary:",
with_salary = {name: features for name, features in enron_data.iteritems() if features["salary"] != "NaN"}
print len(with_salary)
print "No of folks with known email address:",
with_email_address = {name: features for name, features in enron_data.iteritems() if features["email_address"] != "NaN"}
print len(with_email_address)
# We’ve written some helper functions (featureFormat() and targetFeatureSplit() in tools/feature_format.py) that can take a list of feature names and the data dictionary, and return a numpy array.
# In the case when a feature does not have a value for a particular person, this function will also replace the feature value with 0 (zero).
def printPartPercentage(part, whole):
print part, "i.e.",
percentage = float(part)/float(whole) * 100.0
print("{0:.2f}".format(percentage)), "%"
print "No of people having “NaN” for their total payments:",
without_total_payments = {name: features for name, features in enron_data.iteritems() if features["total_payments"] == "NaN"}
printPartPercentage(len(without_total_payments), len(enron_data))
print "No of POIs having “NaN” for their total payments:",
pois_without_total_payments = {name: features for name, features in pois.iteritems() if features["total_payments"] == "NaN"}
printPartPercentage(len(pois_without_total_payments), len(pois))
def without_nan(enron_data, feature):
return {name: features for name, features in enron_data.iteritems() if name != "TOTAL" and features[feature] != "NaN"}
def minimum_feature(enron_data, feature):
minimum_feature = lambda memo,current: memo if (enron_data[memo][feature] < enron_data[current][feature]) else current
min_index = reduce(minimum_feature, without_nan(enron_data, feature))
print "Minimum value for", feature, ":", enron_data[min_index][feature], "for", min_index
def maximum_feature(enron_data, feature):
maximum_feature = lambda memo,current: memo if (enron_data[memo][feature] > enron_data[current][feature]) else current
max_index = reduce(maximum_feature, without_nan(enron_data, feature))
print "Maximum value for", feature, ":", enron_data[max_index][feature], "for", max_index
minimum_feature(enron_data, "exercised_stock_options")
maximum_feature(enron_data, "exercised_stock_options")
minimum_feature(enron_data, "salary")
maximum_feature(enron_data, "salary") |
ebf9119ed1aa0de3ef2cf4b7573fe3250773a5a0 | bukatja567/LP | /examle2.py | 390 | 3.9375 | 4 | #if-elif-else
"""
company = input("Введите слово: ")
if "my" and "google" in company:
print("Условие выполнено!")
elif "google" in company:
print("Он нашел google")
elif "my" in company:
print("Есть не все")
else:
print("Неа, не пущу!")
"""
a=3
b=8
sum = 0
i=3
while i != 1:
sum = sum + a + b
i = i-1
print(sum)
|
0c6d5a16e30be92e3956bfbec2efcb9a17afbb5e | tanaypatil/code-blooded-ninjas | /dynamic_programming_1/angry_children.py | 1,482 | 3.953125 | 4 | """
Angry Children
Send Feedback
Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has N packets of candies and would like to distribute one packet to each of the K children in the village (each packet may contain different number of candies). To avoid a fight between the children, he would like to pick K out of N packets such that the unfairness is minimized.
Suppose the K packets have (x1, x2, x3,....xk) candies in them, where xi denotes the number of candies in the ith packet, then we define unfairness as
unfairness=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
unfairness+=abs(xi-xj)
abs(x) denotes absolute value of x.
"""
def get_min_unfairness(arr, k):
target = 0
s = arr[0]
for i in range(1, k):
target += i*arr[i] - s
s += arr[i]
min_unfairness = target
for i in range(k, len(arr)):
unfairness = target - 2*(s-arr[i-k]) + (k-1)*(arr[i-k]+arr[i])
if unfairness < min_unfairness:
min_unfairness = unfairness
s = s-arr[i-k]+arr[i]
target = unfairness
return min_unfairness
def main():
n = int(input())
k = int(input())
arr = []
for i in range(n):
arr.append(int(input()))
if k == 1:
print(max(arr))
return
if n == 2 and k == 2:
print(abs(arr[0]-arr[1]))
return
if k > n:
print(0)
return
arr.sort()
print(get_min_unfairness(arr, k))
if __name__ == "__main__":
main()
|
81a74fb841052b705a4f60c85cc7c9b8b4ac45a3 | Divisekara/Python-Codes-First-sem | /other/Prime Number checking More Efficiency.py | 298 | 3.96875 | 4 | while True:
n=int(raw_input("Give a number "))
is_prime = True
for i in range(2,int(n**0.5)+1):
if n%i==0:
is_prime=False
print 'not a prime'
break
if is_prime==True:
print n ,'is a prime'
|
a96394b510716fbafe4611c12719507e5145be2a | joyonto51/Basic-Algorithm | /check_prime_number.py | 218 | 4 | 4 | n = int(input())
flag = 1
i = 2
while(i<(n/2)):
if n%i == 0:
flag = 0
break
i+=1
if flag==0:
print("{} is not a prime number".format(n))
else:
print("{} is a prime number".format(n)) |
9756fe6fd6eca8f9615b71d5e31ca04acad08018 | imhari4real/Python-Programming-lab | /CO1/CO1-Q15.py | 197 | 3.53125 | 4 | colorlist1=set(['orange','green','blue','violet','pink','white'])
print(colorlist1)
colorlist2=set(['white','blue','violet'])
print(colorlist2)
a=(colorlist1.difference(colorlist2))
print(a)
|
7e35c3595968329f0cdf5077c5e02216c76fd2d9 | awarnes/projects | /card_games/deck_mechanics.py | 3,164 | 4.59375 | 5 | """
This is a method to build a deck of cards for a card game.
Using the standard 52 card deck with two optional jokers, calling this method will build a
randomized list with the card name (K, Q, 3), the value (10, 10, 3), and the suit (H, D, S, C).
This method will be used for other card games between human and computer AI opponents. The intention
is that popping off the back (or front) of the list will produce a random card.
This file also contains the method for shuffling or reshuffling a deck with the desired cards.
For determining card values:
for card in deck:
test = card.split()
if card[1].isalpha():
print("Face!")
elif card[1] == '1':
print(10)
else:
print(int(card[1]))
"""
# def shuffle(deck):
# """
# Shuffles the remaining cards in the deck to a new random but static order.
# """
# Prior to understanding that random has a shuffle function....
# This did not generate sucsessively random inputs as one might have hoped....
# for i in range(7):
# new_deck = list()
#
# # If the deck is an odd number of cards split it with one more in the right hand.
# if len(deck) % 2 != 0:
# lh_deck = deck[len(deck)//2:]
# rh_deck = deck[:(len(deck)//2) + 1]
#
# else:
# lh_deck = deck[len(deck)//2:]
# rh_deck = deck[:len(deck)//2]
#
# for i in range(len(rh_deck)):
# new_deck.append(lh_deck[i])
# new_deck.append(rh_deck[i])
#
# deck = new_deck
#
# print(lh_deck)
# print(rh_deck)
# print(deck)
#
# return deck
def shuffle(deck):
"""
Shuffles a deck of cards as randomly (or close to?) as Python allows.
"""
import random
random.shuffle(deck)
return deck
def deck_builder(joke_bool=False):
"""
Build a list that contains all 52 cards in random order and allows the user to decide to
include jokers.
"""
import random
deck = []
suits = ['H', 'D', 'S', 'C']
cards = [x for x in range(2, 11)]
faces = ['J', 'Q', 'K', 'A']
cards.extend(faces)
for suit in suits:
for value in cards:
deck.append(suit + str(value))
if joke_bool:
deck.append('Joker')
deck.append('Joker')
random.shuffle(deck)
return deck
def card_value(card):
"""
Returns the value of the card.
Attempting to be as generic as possible:
If the card is a face card it is possible for it to have two states depending on the other
cards in the hand, or the rules of the game. This will not be handled here without
significantly more information from the other card values and specific game rules.
"""
if card[1].isalpha():
return card[1]
elif card[1] == '1':
return 10
else:
return int(card[1])
def card_suit(card):
"""
Returns the suit of a card.
This will be important in valuing next moves for possible AI difficulties as well as
different game rules (solitare for example).
"""
return card[0]
print(card_value('HQ'))
|
c60937a9cf6f918a91df269780bdae402dfdbcf8 | isaacdias/curso-logica-testes-devfuria | /nivel-06-strings/contar_vogais.py | 241 | 3.53125 | 4 | # coding: utf-8
s = 'python'
vogais = 'aeiou'
#
# retorna quantidade de vogais
#
def quant_vogais(s):
cont = 0
for i in s:
if i in vogais:
cont += 1
return cont
#
# testes
#
assert 1 == quant_vogais(s)
|
bb9ed6cc871d729d6a22e58724095ac4a0c30e7b | buksi91/harness_sudoku | /sudoku_m.py | 2,207 | 3.578125 | 4 | #!/usr/bin/env python3
import os
from termcolor import colored
player_moves_list = []
def input_check(input):
if input.isdigit():
for x in range(len(input)):
if input[x] == "0":
return True
if len(input) != 3:
return True
elif int(input) >= 111 and int(input) <= 999:
for x in range(len(input)):
player_moves_list.append(input[x])
return False
else:
return True
def clear():
os.system('clear')
def make_yellow(anystring):
anystring = colored(anystring, "yellow", attrs=["bold"])
return anystring
def print_grid(rows_file):
box_border = make_yellow("-" * 37)
line_border = make_yellow(":")
for i in range(3):
line_border += "-" * 11 + make_yellow(":")
print(box_border, " " * 12, )
for j, num_row in enumerate(rows_file):
row_list = []
for num in num_row:
if num == "0":
row_list.append(" ")
else:
row_list.append(num)
row = make_yellow("|")
for i, cell in enumerate(row_list):
cell = colored(cell, "cyan", attrs=["bold"])
if i % 3 == 2:
row += f" {cell} " + make_yellow("|")
else:
row += f" {cell} |"
print(row)
if j % 3 == 2:
print(box_border)
else:
print(line_border)
clear()
index_dict = {}
for x in range(81):
row = x // 9
column = x % 9
box = 3 * (row // 3) + column // 3
index_dict[x] = [row, column, box]
with open("test_grid.txt", "r") as grid_file:
rows_file = []
for line in grid_file.read().splitlines():
rows_file.append(line)
print_grid(rows_file)
input_loop = True
while input_loop:
clear()
print_grid(rows_file)
output = ''
box = input("Please choose a box (1-9): ")
brancket = input("Please choose a bracket (1-9): ")
number = input("Please input a number(1-9): ")
output = str(box)+str(brancket)+str(number)
player_moves_list = []
input_loop = input_check(output)
print(player_moves_list)
print(input_loop)
input("dikmoree")
|
90ef075e4942b7cc0c08ea9c5a967a5a8a6cd170 | wuqiangroy/LeetCodeSolution | /PowerOfFour.py | 516 | 4.40625 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
"""
Given an integer (signed 32 bits),
write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
"""
def power_of_four(num):
if num < 0:
return 'false'
if int(num**0.25) == num**0.25:
return 'true'
else:
return 'false'
if __name__ == '__main__':
n = 16
print power_of_four(n)
|
98071112e537607f01bf58969c36034a3be2e2b0 | mashaprostotak/get_ripo | /dz1.py | 2,025 | 3.5625 | 4 | __author__ = 'Ваши Ф.И.О.'
# Задача-1: Дано произвольное целое число (число заранее неизвестно).
# Вывести поочередно цифры исходного числа (порядок вывода цифр неважен).
# Подсказки:
# * постарайтесь решить задачу с применением арифметики и цикла while;
# * при желании решите задачу с применением цикла for.
# код пишем тут...
#просим пользователя ввести число
a=int(input("введите число"))
i=10
while (a//i)>0:
i=i*10
while i>1:
i=i/10
r=a//i
print (int(r))
a=a-r*i
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
# Подсказка:
# * постарайтесь сделать решение через дополнительную переменную
# или через арифметические действия
# Не нужно решать задачу так:
# print("a = ", b, "b = ", a) - это неправильное решение!
x=float(input('введите первое число'))
y=float(input('введите второе число'))
m=x
x=y
y=m
print(x,y)
# Задача-3: Запросите у пользователя его возраст.
# Если ему есть 18 лет, выведите: "Доступ разрешен",
# иначе "Извините, пользование данным ресурсом только с 18 лет"
age=int(input(' укажите свой возраст'))
if (age>17):
print("Доступ разрешен")
else:
print("Извините, пользование данным ресурсом только с 18 лет")
|
a3bb2c3d61aa8a779a9e8f72d70b73f82b7b19d2 | mominrazashahid/HTRS | /src/hand.py | 1,624 | 3.71875 | 4 | # Example Python Program for contrast stretching
from PIL import Image
# Method to process the red band of the image
def normalizeRed(intensity):
iI = intensity
minI = 86
maxI = 230
minO = 0
maxO = 255
iO = (iI - minI) * (((maxO - minO) / (maxI - minI)) + minO)
return iO
# Method to process the green band of the image
def normalizeGreen(intensity):
iI = intensity
minI = 90
maxI = 225
minO = 0
maxO = 255
iO = (iI - minI) * (((maxO - minO) / (maxI - minI)) + minO)
return iO
# Method to process the blue band of the image
def normalizeBlue(intensity):
iI = intensity
minI = 100
maxI = 210
minO = 0
maxO = 255
iO = (iI - minI) * (((maxO - minO) / (maxI - minI)) + minO)
return iO
# Create an image object
def create_image(path):
x=path
imageObject = Image.open(x)
# Split the red, green and blue bands from the Image
multiBands = imageObject.split()
# Apply point operations that does contrast stretching on each color band
normalizedRedBand = multiBands[0].point(normalizeRed)
normalizedGreenBand = multiBands[1].point(normalizeGreen)
normalizedBlueBand = multiBands[2].point(normalizeBlue)
# Create a new image from the contrast stretched red, green and blue brands
normalizedImage = Image.merge("RGB", (normalizedRedBand, normalizedGreenBand, normalizedBlueBand))
# Display the image before contrast stretching
# imageObject.show()
normalizedImage.save("pre.jpg")
# Display the image after contrast stretching
# normalizedImage.show() |
f0c1eb645da9b68f3f8c64edc4ec645518c2d78e | parkjihwanjay/session5 | /assignment_answers/problem6.py | 412 | 4.0625 | 4 | print('문제 2. 영어 이름 받기')
print('choi juwon 을 입력 받으면,')
print('first name : Choi, last name: Juwon 이 출력되게 만들기')
# full_name = input()
# name_list = full_name.split(' ')
# first_capital = name_list[0][0].upper()
# second_capital = name_list[1][0].upper()
# print(first_capital + name_list[0][1:], second_capital + name_list[1][1:])
name = input()
print(name.title())
|
0c577bfa7402bbd1cf39d2849a7a14b86ee7fe0b | dangiotto/Python | /pythonteste/desafio79.py | 609 | 4.09375 | 4 | num = list()
while True:
num.append(int(input('Digite um valor : '))) #poderia receber o valor em um variável simpler
if num.count(num[len(num)-1]) != 2: # verificar se está na lista
print('Valor adicionado com sucesso...') # if n not in num: para add ou não
else:
num.pop()
print('Número duplicado, não será adicionado...')
op = str(input('Quer continuar... [S/N]')).strip().upper()
if op not in 'NS':
op = str(input('Opção inválida!!\nQuer continuar... [S/N]')).strip().upper()
if op == 'N':
break
num.sort()
print(num) |
8d322a3a7d2658292ce214204c93240af31ee112 | ragzilla/acnh-shotgunsim | /field.py | 2,735 | 3.609375 | 4 | #! /usr/bin/python3
from itertools import product
from numpy.random import shuffle
from sys import exit
class Field:
name = None
layout = None
matrix = None
def __init__(self, name, configuration):
self.name = name
self.layout = configuration
self.x = len(self.layout[0])
self.y = len(self.layout)
self.matrix = [ [ None for i in range(self.x) ] for j in range(self.y) ]
# print(self.name, self.matrix, self.y, self.x)
return
def place(self, flower1, flower2 = None):
"""place 1-2 flowers in the layout from the feeder"""
### find an open spot
# print("Field(\"{}\").place:".format(self.name), flower1, flower2)
flowers = [flower1,]
if flower2 != None:
flowers.append(flower2)
for y in range(self.y):
if len(flowers) == 0:
break
for x in range(self.x):
if self.layout[y][x] == 1 and self.matrix[y][x] == None:
self.matrix[y][x] = flowers.pop()
if len(flowers) == 0:
break
# print(self.matrix)
return
def neighbors(self, x, y):
cell = (x,y)
for c in product(*(range(n-1, n+2) for n in cell)):
if c != cell and (0 <= c[0] < self.x) and (0 <= c[1] < self.y): # for n in c)
yield c
def run(self):
"""reset the plants, run the day"""
cull = [] # grid locations to cull and return when we're done
harvest = []
flowerstobreed = []
for y in range(self.y):
for x in range (self.x):
if self.matrix[y][x] != None:
self.matrix[y][x].reset_day()
flowerstobreed.append((x,y))
# randomize the list
shuffle(flowerstobreed)
# print("run/", self.name, "/", flowerstobreed)
# run through them, one by one
for grid in flowerstobreed:
x = grid[0]
y = grid[1]
parent = self.matrix[y][x]
# print("breeding at",grid,parent)
if not parent.is_valid():
continue # already bred today, skip
opentile = None
partner = None
neighbors = list(self.neighbors(x, y))
shuffle(neighbors)
for neighbor in neighbors:
nx = neighbor[0]
ny = neighbor[1]
n = self.matrix[ny][nx]
if n == None:
if opentile == None:
opentile = neighbor
elif partner == None and n.is_valid():
partner = n
if opentile != None and partner != None:
break
if opentile == None:
continue ## we can't breed without a target tile
new_flower = parent.breed(partner)
if new_flower != None:
# print("flower",parent,"breeding with",partner,"into tile",opentile,"new:",new_flower)
cull.append(opentile)
harvest.append(new_flower)
nx = opentile[0]
ny = opentile[1]
self.matrix[ny][nx] = new_flower
for opentile in cull:
nx = opentile[0]
ny = opentile[1]
self.matrix[ny][nx] = None
return harvest
def __repr__(self):
return str(self.layout)
|
8bb7f78b1aa02fb3fd0fb45e7634b7801124e9a4 | SooYong-Jeong/Python_Quiz | /Day 2/Quiz 2-1.py | 156 | 3.84375 | 4 | Email = input("이메일을 입력하세요.\n")
if Email[Email.index('@'):] == "@co.kr":
print("domain is co.kr.")
else : print("domain is not co.kr") |
92d6e54c2534efc5669bccc63f53b2d5dd78ec9c | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DepthFirstSearch/306_AdditiveNumber.py | 2,012 | 3.640625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
class Solution(object):
# According to:
# https://leetcode.com/discuss/70089/python-solution
# The key point is choose first two number then recursively check.
# DFS: recursice implement.
def isAdditiveNumber(self, num):
length = len(num)
for i in range(1, length/2+1):
for j in range(1, (length-i)/2 + 1):
first, second, others = num[:i], num[i:i+j], num[i+j:]
if self.isValid(first, second, others):
return True
return False
def isValid(self, first, second, others):
# Numbers in the additive sequence cannot have leading zeros,
if ((len(first) > 1 and first[0] == "0") or
(len(second) > 1 and second[0] == "0")):
return False
sum_str = str(int(first) + int(second))
if sum_str == others:
return True
elif others.startswith(sum_str):
return self.isValid(second, sum_str, others[len(sum_str):])
else:
return False
class Solution_2(object):
# DFS: iterative implement.
def isAdditiveNumber(self, num):
length = len(num)
for i in range(1, length/2+1):
for j in range(1, (length-i)/2 + 1):
first, second, others = num[:i], num[i:i+j], num[i+j:]
if ((len(first) > 1 and first[0] == "0") or
(len(second) > 1 and second[0] == "0")):
continue
while others:
sum_str = str(int(first) + int(second))
if sum_str == others:
return True
elif others.startswith(sum_str):
first, second, others = (
second, sum_str, others[len(sum_str):])
else:
break
return False
"""
"1123"
"1203"
"112324"
"112334"
"112358"
"""
|
814fc1e147c52d2263f4f2c6b9d7c71b8599a21f | eriickluu/curso-de-introduccion-a-la-programacion | /3-El Comienzo/casting.py | 270 | 3.84375 | 4 | print("Ingresa el primer valor:")
numero1 = int(input())
print("Ingresa el segundo valor:")
numero2 = int(input())
suma = numero1 + numero2
resta = numero1 - numero2
multiplicacion = numero1 * numero2
division = numero1 / numero2
print("El resultado es:" + str(suma))
|
a1047a82339bb11a6452b19e22ecfeaa8fd29754 | pamelot/calculator-2-practice | /calculator.py | 1,943 | 4.34375 | 4 | """
calculator.py
Using our arithmetic.py file from Exercise02, create the
calculator program yourself in this file.
"""
from arithmetic import *
def main():
# This is where the user can input the calculation.
# This will be a series of if statements for determining which function to call.
cond = True
while cond:
input = raw_input("> ")
numbers = input.split(' ')
try:
if numbers[0] == "+":
addition = add(int(numbers[1]), int(numbers[2]))
print addition
elif numbers[0] == "-":
subtraction = subtract(int(numbers[1]), int(numbers[2]))
print subtraction
elif numbers[0] == "*":
multiplication = multiply(int(numbers[1]), int(numbers[2]))
print multiplication
elif numbers[0] == "/":
division = divide(float(numbers[1]), float(numbers[2]))
print division
elif numbers[0] == "square":
squaring = square(int(numbers[1]))
print squaring
elif numbers[0] == "cube":
cubed = cube(int(numbers[1]))
print cubed
elif numbers[0] == "pow":
if (float(numbers[2]) <= 0) or (float(numbers[1]) <=0):
powered = power((float(numbers[1])), (float(numbers[2])))
else:
powered = power(float(numbers[1]), float(numbers[2]))
print powered
elif numbers[0] == "mod":
module = mod(int(numbers[1]), int(numbers[2]))
print module
elif numbers[0] == "q":
break
else:
print "Looks like you're not using our syntax! Try again!"
except ValueError:
print "Value Error: Please type an integer!"
if __name__ == '__main__':
main() |
5a18f6aab5cab399793567accb11ba72858a6d32 | Acrelion/various-files | /Python Files/se31.py | 271 | 3.796875 | 4 | a1 = raw_input("Number? ")
b2 = raw_input("Number? ")
a = int(a1)
b = int(b2)
if a != b:
a += 1
print "a is now %d" % a
else:
if (a and b) == 2:
print "They are now two."
else:
print "I dont care. a and b are = %d and %d now " % (a, b)
|
f6d38a206f67aeb05d462dcf49a34140c19ba315 | nugroha/BeadTeam15 | /ml_modeling.py | 850 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
This program retrieve data from hdfs and perform prediction on the probability of the "Risk of heart diseases"
using OLS Regression.
@author: ongby
"""
import pandas as pd
import numpy as np
import statsmodels.api as sm
import sklearn
#=========================
# Main
#=========================
data = pd.read_csv("C:\Users\Andy\Google Drive\School\EB5001 Big Data Engineering for Analytics\Project 2\Datasets\final_data3.csv")
data = data.fillna(0)
A = data.columns
A = A.drop("Risk of heart diseases")
A = A.drop("SEQN")
X = data[A]
y = data["Risk of heart diseases"]
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33, random_state=42)
mod = sm.OLS(y_train,X_train)
results = mod.fit()
print(results.summary())
sm.add_constant(X_test)
|
246be275398511e273951e708aa135c3ed526c1e | AidenLong/ai | /python-study/base/datatype/01-list.py | 2,131 | 3.828125 | 4 | #_*_ conding:utf-8 _*_
'''
访问列表
'''
# list01 = ['jack','jane','joe','black']
# print(list01[2]) #通过下标
# list01 = ['jack','jane',['leonaldo','joe'],'black']
# l = list01[2]
# print(list01[2][0])
# print(list01[2][0])
# list01 = ['jack','jane',['leonaldo','joe'],'black']
# list01[0] = 'lili' #通过下标获取到元素,并且给其赋新的值
# print(list01)
#
# list01[2][0] = 'susan'
# print(list01)
#列表是一个可变的类型数据 允许我们对立面的元素进行修改
'''
列表的操作
-》append往列表末尾增加元素
-》insert往列表中指定位置添加元素 (位置,元素)
'''
#append
# list02 = ['jack','jane','joe','black']
# list02.append('susan')
# print(list02)
#insert
# list02 = ['jack','jane','joe','black']
# print('追加前')
# print(list02)
# print('_'*20)
# list02.insert(1,'susan')
# print(list02)
'''
删除元素
-》pop 默认删除最后一个
-》del 通过指定位置删除
-》remove 通过值删除元素
'''
#pop
# list03 = ['jack','jane','joe','black']
# print('删除前')
# print(list03)
# print('_'*20)
# print(list03.pop()) #执行删除操作 并且返回删除的元素
# print(list03)
# print('继续删除')
# print('_'*20)
# print(list03.pop(1)) #执行删除操作 并且返回删除的元素
# print(list03)
#del
# list03 = ['jack','jane','joe','black']
# print('删除前')
# print(list03)
# print('_'*20)
# del list03 #从内存中将其删除
# print(list03)
#remove
# list03 = ['jack','jane','joe','black']
# print('删除前')
# print(list03)
# print('_'*20)
# list03.remove('jane') #通过元素的值进行删除
# print(list03)
#查找元素
# list04 = ['jack','jane','joe','black']
# name = 'jack'
# print(name in list04)
#
# name = 'jacks'
# print(name not in list04)
'''
列表函数
'''
list05 = ['jack','jane','joe','black','joe']
#查看列表的长度 返回列表元素的个数
print(len(list05))
#返回指定元素在列表中出现的次数
print(list05.count('joe'))
#extend
# ll = ['aaa','bbb']
# list05.extend(ll)
# print(list05)
|
5b5cd489a23edc5c6cac1f1b7b684ecd73d4b030 | agentnova/LuminarPython | /Luminaarpython/Functionalpgms/intro.py | 462 | 4 | 4 | #reduce code
# lambda
# map
# filter
# listcomprehen
#reduce
# lambda functions also called anonymous function
# f=lambda num1,num2 :num1*num2
# print(f(9,67))
# map-used in where all objects need an alteration
#filter-used in where only some objects have to be altered
def square(num):
return num*num
lst=[1,2,3,4]
sq=list(map(square,lst))
print(sq)
lst2=[1,2,3,4,5,6,7]
def even(num):
return num%2==0
evens=list(filter(even,lst))
print(evens)
|
57d6eaa8fd6aa8aa1576e35957a4f4e44771f04a | ystop/algorithms | /sword/滑动窗口的最大值.py | 1,175 | 3.78125 | 4 | # -*- coding:utf-8 -*-
# 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,
# 那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5};
# 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个:
# {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1},
# {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
# 双端队列,存下标。 遍历num,每次都append到队列中,并且维护,队列的第一个一定是最大的数据。
class Solution:
def maxInWindows(self, num, size):
# write code here
if not num or not size:
return []
queue = []
ret = []
for i in range(0, len(num)):
if queue:
if i - queue[0] >= size:
queue.pop(0)
while queue and num[queue[-1]] < num[i]:
queue.pop()
queue.append(i)
if i >= size - 1:
ret.append(num[queue[0]])
return ret
s = Solution()
print s.maxInWindows([2,3,4,2,6,2,5,1], 3) |
3e2740a668cadf9f03841db92f40dae55c31c568 | MichaelSchwar3/LeetCode | /swapnodespairs.py | 726 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
newHead = head.next
currentNode = head
prevNode = None
while currentNode and currentNode.next is not None:
if prevNode is not None:
prevNode.next = currentNode.next
node = currentNode.next.next
currentNode.next.next = currentNode
prevNode = currentNode
currentNode.next = node
currentNode = currentNode.next
return newHead
|
c5e720339d00b998a7c3ab7f8d067f1af91c5d9f | eriamavro/python-recipe-src | /src/062/recipe_062_01.py | 66 | 3.5625 | 4 | list1 = [1, 2, 3]
list2 = [val * 2 for val in list1]
print(list2)
|
49efbe7d47924c4bbded0bb985c4dce613592490 | pravencraft/engr3703_2_sums_and_products | /old/python_intro_7.py | 7,443 | 4.3125 | 4 | # This is a comment
# The following is the import section
# This brings in other python files that have pre-defined functions in them
# This will be present in every single program you write
from math import *
import numpy as np
from tabulate import tabulate
# The following area is a sort of "global" area this code will execute first and will always execute
# Below is a function definition for the main function. This function is meant to hold the code
# that will run every time thhis python code file is executed
# you do have to do something special to make sure it runs though... see the end of the file
def main():
# now we will learn to take our knowledge of loops to the next level
# there are some very common problems in comp. methods
# NOTE: All equations referenced below are in the document sums_and_products.pdf
# Summations
# here is an example summation in eq. 1:
summ = 0 #int
x = [12, 14, 11, 10, 15, 11] # define x list
n = len(x) # get length of list #n=6
#range(0,6) = 0,1,2,3,4,5
for i in range(0, n): # first list index is 0... so the i in the equation we are trying to calc.
#i = 0,1,2,3,4,5
summ = summ + x[i] # This loop will execute for i values of 0-5, which correspond to
print(summ) # The six elements in x
"""
i summ (at start of loop) summ statement
0 0 summ + x[0] = 0 + 12 = 12
1 12 summ + x[1] = 12 + 14 = 26
2 26 summ + x[2] = 26 + 11 = 37
3 37 summ + x[3] = 37 + 10 = 47
4 47 summ + x[4] = 47 + 15 = 62
5 62 summ + x[5] = 62 + 11 = 73 <--- ending value in summ
"""
del x
# ENGR3703 Using what you learned about just above
# ENGR3703 Write code to calcluate and print a mean value (Eq. 7)
# ENGR3703 Also write code to calculate a sample standard deviation (see Eq. 8)
# ENGR3703 Below is the data you should use
x = [3, 2, 4, 4, 3, 3, 2, 3, 4, 3, 3, 3, 2, 4]
summ = 0
n = len(x) # get length of list n = 14
#range(0,14) = 0,1,2,...,12,13
for i in range(0, n): # first list index is 0... so the i in the equation we are trying to calc.
summ += x[i] # This loop will execute for i values of 0-5, which correspond to
mean = summ/n
print("Mean value = ",mean)
dev = 0
for i in range(0, n): # first list index is 0... so the i in the equation we are trying to calc.
dev += (x[i] - mean)**2 # This loop will execute for i values of 0-5, which correspond to
stdev = sqrt(dev/(n-1))
print("Std. Dev. = ",stdev)
##########################################Your code here
# here is an example summation from eq. 2:
summ = 0
n = 10
for i in range(0, n):
summ += (i + 1) ** 3 # here we have to use i+1 since i is being used in the calculation
print(summ)
# here is an example summation from eq. 3:
summ = 0
n = 10
a = 2
for i in range(0, n):
summ += a ** i # here we have to use i+1 since i is being used in the calculation
print(summ)
# here is an example summation in eq. 4:
# here we are going to implement a loop that proceeds until the fractional relative error drops below 1e-5
# The fractional relative error is defined in Eq. 5 (we will use rel_err in the code below)
f = 0 # this is the function value we are calculating
f_old = 0 # holding place for old value of f in iterations
err_stop = 1e-9 # this is what is called the stopping criterion
rel_err = 1.1 * err_stop # initially make sure rel_err is defined to be more than the err_stop
max_iter = 1000 # set a max number of iterations
x = 1 # argument of function in Eq. 4
f_string = "f"
i_string = "i"
rel_err_string = "rel err"
table = [[i_string,f_string,rel_err_string]]
for i in range(0, max_iter): # for loop that will execute max_iter times unless there is a 'break'
f = f + pow(x, i) / factorial(i) # here we have to use i+1 since i is being used in the calculation
if i > 0: # calc rel_err for all iterations but the first
rel_err = abs((f - f_old) / f) # calc rel_err
if rel_err <= err_stop: # is rel_err less than the err_stop
#print("%d %1.10wf %1.3e" % (i+1,f, rel_err))
#table.append([i,f,rel_err])
table.append([i + 1, f, f"{rel_err:.2e}"])
break # if it is less then stop iterating
else: # if rel_err is still > than err_stop place the current value of f in f_old
f_old = f # the new value of f_old will be used in the next iteration
table.append([i + 1, f, f"{rel_err:.2e}"])
else:
table.append([i+1, f, "NA"])
#print("%d %1.10f %1.3e" % (i + 1, f, rel_err))
#print(f, i + 1, rel_err)
print(tabulate(table,tablefmt="fancy_grid", headers="firstrow"))
# ENGR3703 Place your code here to find the result of Equation 6
# ENGR3703 Your loop should continue until the relative error is less than 1e-6
# ENGR3703 Print out the final value of the function, the number of terms require, and the final relative error
##########################################Your code here
# please just leave this and don't change it...
# these next two lines make sure main() runs everytime this code file is executed
if __name__ == '__main__':
main()
# here is an example summation in eq. 4:
# here we are going to implement a loop that proceeds until the fractional relative error drops below 1e-5
# The fractional relative error is defined in Eq. 5 (we will use rel_err in the code below)
f = 0 # this is the function value we are calculating
f_old = 0 # holding place for old value of f in iterations
err_stop = 1e-9 # this is what is called the stopping criterion
rel_err = 1.1 * err_stop # initially make sure rel_err is defined to be more than the err_stop
max_iter = 1000 # set a max number of iterations
x = 1 # argument of function in Eq. 4
f_string = "f"
i_string = "i"
rel_err_string = "rel err"
table = [[i_string,f_string,rel_err_string]]
for i in range(0, max_iter): # for loop that will execute max_iter times unless there is a 'break'
f = f + pow(x, i) / factorial(i) # here we have to use i+1 since i is being used in the calculation
if i > 0: # calc rel_err for all iterations but the first
rel_err = abs((f - f_old) / f) # calc rel_err
if rel_err <= err_stop: # is rel_err less than the err_stop
#print("%d %1.10wf %1.3e" % (i+1,f, rel_err))
#table.append([i,f,rel_err])
table.append([i + 1, f, f"{rel_err:.2e}"])
break # if it is less then stop iterating
else: # if rel_err is still > than err_stop place the current value of f in f_old
f_old = f # the new value of f_old will be used in the next iteration
table.append([i + 1, f, f"{rel_err:.2e}"])
else:
table.append([i+1, f, "NA"])
#print("%d %1.10f %1.3e" % (i + 1, f, rel_err))
#print(f, i + 1, rel_err)
print(tabulate(table,tablefmt="fancy_grid", headers="firstrow"))
|
3d63f0745f1bc3e95f9834c0d672954f9453b8e5 | wikisity/TestSelf | /step3.py | 1,673 | 4.15625 | 4 | #-----------> STEP3 CODE2040 CHALLENGE
# Description: This python code is a solution to the problem of 'Needle in a haystack'
# The code obtain a dictionary of two values and keys from an API. One
# value of key 'needle' is a string and the other value of key 'haystack'
# is an array of strings. The program POSTS back to an API of validation,
# the position of the Needle in the array
import requests # import library to post request to my API endpoint
import json # import library to convert objects to a dictionary format
# This method requests an Object from an Endpoint API and returns
# a dictionary object
def get_dictionary():
endpoint_url = "http://challenge.code2040.org/api/haystack"
body = {"token": "770b31d581955134adc9c583414686f6"}
response = requests.post(endpoint_url, data = body)
result = json.loads(response.text)
return (result)
def main():
this_dict = get_dictionary() # Save my dictionary for usage
print(this_dict) # Display my dictionary for verification purpose
this_list = this_dict["haystack"]
this_string = this_dict["needle"]
# Looking for the position of my string in the array
for index in range(len(this_list)):
if (this_string == this_list[index]):
position_of_needle = index # Save this position
# Post result to an Endpoint API for validation
endpoint_url = "http://challenge.code2040.org/api/haystack/validate"
body = {"token": "770b31d581955134adc9c583414686f6", "needle": position_of_needle}
response = requests.post(endpoint_url, data = body)
print(response.text) # Obtain response from the requests
main() |
9c79a406fc1eab118de77eae81db48c2227dd84a | Caccer1/Python-Challenge-FINAL | /Python-Challenge/PyBank/main.py/PyBankJC.py | 2,602 | 3.671875 | 4 | import os
import csv
csvpath = os.path.join('..', 'Resources', 'budget_data.csv')
#list
total_months = []
total_profit = []
monthly_profit_change = []
#variables
#month_count = 0
#total_profit = 0
#average_change = 0
with open(csvpath, newline='', encoding="utf-8") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_head = next(csvreader)
#writer file - giving 1) syntax error and 2) indent error and 3) string error
# with open (csvpath, 'newPyBankanswers', 'w') as new_file:
# csv_writer = csv.writer(new_file, delimiter=",")
#sum function
for row in csvreader:
total_months.append(row[0])
total_profit.append(int(row[1]))
for i in range(len(total_profit)-1):
monthly_profit_change.append(total_profit[i+1]-total_profit[i])
max_increase_value = max(monthly_profit_change)
max_decrease_value = min(monthly_profit_change)
max_increase_month = monthly_profit_change.index(max(monthly_profit_change)) + 1
max_decrease_month = monthly_profit_change.index(min(monthly_profit_change)) + 1
# Print Statements
print("Financial Analysis")
print("----------------------------")
print(f"Total Months: {len(total_months)}")
print(f"Total: ${sum(total_profit)}")
print(f"Average Change: {round(sum(monthly_profit_change)/len(monthly_profit_change),2)}")
print(f"Greatest Increase in Profits: {total_months[max_increase_month]} (${(str(max_increase_value))})")
print(f"Greatest Decrease in Profits: {total_months[max_decrease_month]} (${(str(max_decrease_value))})")
with open(csvfile, "w") as txtFile:
txtFile.write(print)
#TpeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
#did work is above - didn't work is below
#You can use a set to remove duplicates, and then the len function to count the elements in the set:
#len(set(budgetdata)) - using len and set to calculate unique rows but that isn't working
#def unique(Datelist1
#(sum(profits/losses) / num_periods )
#example from 3-7 Solved
#def average(numbers):
# length = len(numbers)
# total = 0.0
# for number in numbers:
# total += number
#return total / length
#The greatest increase in profits (date and amount) over the entire period
#MAX function on column: used same as average but what to return?
#def MAX(numbers):
#length = len(numbers)
#total = 0.0
#for number in numbers:
# total += number
#return total |
c843d7c55a95e6cfa8cb373e35ba3325f09f82e3 | Jai-Prakash-Singh/avg_word_length | /ave_word_length.py | 1,022 | 4.09375 | 4 | #!/usr/bin/env python
import sys
def ave_word_length(filename):
try:
f = open(filename)
contents = f.read()
lst_content = contents.split()
set_content = list(set(lst_content))
length = 0
for el in set_content:
num = lst_content.count(el)
length += num*len(el)
avg_w_length = int(length) / int(len(lst_content))
return avg_w_length
except:
return (-1)
if __name__=="__main__":
if len(sys.argv) < 2:
print "python avg_word_length filename"
print "filename according to u "
sys.exit(-1)
else:
avg_w_length = ave_word_length(sys.argv[1])
if avg_w_length ==-1:
print
print "file does not exit"
print "python avg_word_length filename"
print "filename according to u "
print
sys.exit(-1)
else:
print
print " the sum of all the lengths of the word tokens in the text, divided by the number of word tokens is:",
print avg_w_length
print
|
e48567e5a658b03f3e37b1959429a2d19688a5e1 | gigennari/mc102 | /tarefa14/menor_ausente.py | 999 | 4.1875 | 4 | """
Dada uma seuquência ordenada (crescente) de números, o programa encontra
o menor elemento ausente dessa sequência
Entrada: uma sequência ordenada de números separados por espaço
0 1 2 3 4 5 6 7 8 9 10 11 13 14 15 16
Saída: o menor número ausente da seuência
12
Caso básico:
numero atual é diferente do numero esperado, sendo numero esperado
o elemento anterior da lista mais 1
Caso geral:
incrementar 1 na posição a ser verificada
atualizar numero esperado para a proxima recursao
chamar a função novamente
"""
def menor_ausente(lista, posicao, numeroesperado):
"""Acha o menor numero ausente em uma lista ordenada"""
if lista[posicao] != numeroesperado:
return posicao
else:
posicao += 1
numeroesperado += 1
return menor_ausente(lista, posicao, numeroesperado)
def main():
lista = input().split()
for i in range(len(lista)):
lista[i] = int(lista[i])
print(menor_ausente(lista, 0, lista[0]))
main() |
8fd7d1f6bea0317a2db553ed35e6128e38cdfdc6 | jpages/twopy | /unit_tests/arithmetic/fact.py | 178 | 3.65625 | 4 | def fact(n):
if n<2:
return 1
else:
return n*fact(n-1)
print(fact(5))
print(fact(1))
print(fact(20))
print(fact(-10))
#120
#1
#2432902008176640000
#1
|
7d8c53dde1c54ca0816bc14390aee9a16d5ec7fa | HeraldoAlmeida/EEL891 | /src/MBTI_2020/03_Classificar_Digits_KNN.py | 5,360 | 3.625 | 4 | #==============================================================================
# Carga e Visualizacao do Conjunto de Dados IRIS (problema de classificacao)
#==============================================================================
#------------------------------------------------------------------------------
# Importar o conjunto de dados Iris em um dataframe do pandas
#------------------------------------------------------------------------------
import pandas as pd
dataframe = pd.read_excel('../../data/D11_Digits.xlsx')
#------------------------------------------------------------------------------
# Separar em dataframes distintos os atributos e o alvo
# - os atributos são todas as colunas menos a última
# - o alvo é a última coluna
#------------------------------------------------------------------------------
attributes = dataframe.iloc[:,1:-1]
target = dataframe.iloc[:,-1]
#------------------------------------------------------------------------------
# Criar os arrays numéricos correspondentes aos atributos e ao alvo
#------------------------------------------------------------------------------
X = attributes.to_numpy()
y = target.to_numpy()
#------------------------------------------------------------------------------
# Criar os arrays numéricos correspondentes aos atributos e ao alvo
#------------------------------------------------------------------------------
import matplotlib.pyplot as plt
for sample in range(0,10):
plt.figure(figsize=(4,4))
d_plot = plt.subplot(1,1,1)
d_plot.set_title("y = %.2f" % y[sample])
d_plot.imshow(X[sample,:].reshape(8,8),
interpolation='nearest',
cmap='binary',
vmin=0,
vmax=16
)
plt.show()
#------------------------------------------------------------------------------
# Dividir os dados em conjunto de treinamento e conjunto de teste
#------------------------------------------------------------------------------
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=500,
random_state=20200702
)
#------------------------------------------------------------------------------
# Aplicar uma escala de -1 a 1 nas variáveis
#------------------------------------------------------------------------------
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler((-1,1))
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
#------------------------------------------------------------------------------
# Treinar um classificador KNN para identificar o digito
#------------------------------------------------------------------------------
from sklearn.neighbors import KNeighborsClassifier
knn_classifier = KNeighborsClassifier(
n_neighbors = 1,
weights = 'uniform'
)
from sklearn.tree import DecisionTreeClassifier
# knn_classifier = DecisionTreeClassifier()
#------------------------------------------------------------------------------
# Treinar o classificador e obter o resultado para o conjunto de teste
#------------------------------------------------------------------------------
from sklearn.metrics import confusion_matrix, accuracy_score
knn_classifier.fit(X_train,y_train)
y_pred = knn_classifier.predict(X_test)
#------------------------------------------------------------------------------
# Mostrar a matriz de confusão e a acuracia
#------------------------------------------------------------------------------
cm = confusion_matrix(y_test,y_pred)
print("Confusion Matrix =")
print(cm)
accuracy = accuracy_score(y_test,y_pred)
print("Accuracy = %.1f %%" % (100*accuracy))
import matplotlib.pyplot as plt
for sample in range(0,4):
plt.figure(figsize=(4,4))
d_plot = plt.subplot(1,1,1)
d_plot.set_title("y = %.2f %.2f" % ( y_test[sample] , y_pred[sample] ) )
d_plot.imshow(X_test[sample,:].reshape(8,8),
interpolation='nearest',
cmap='binary',
vmin=0,
vmax=16
)
plt.show()
#------------------------------------------------------------------------------
# Explorar a variacao da acuracia com o parametro k
#------------------------------------------------------------------------------
from sklearn.ensemble import RandomForestClassifier
print("K Accuracy")
print("-- --------")
for k in range(-6,+7):
# classifier = KNeighborsClassifier(
# n_neighbors = k,
# weights = 'uniform'
# )
# classifier = DecisionTreeClassifier(
# criterion='gini',
# max_features=None,
# max_depth=k
# )
ne = k*5
classifier = RandomForestClassifier(
n_estimators=ne,
max_features='auto'
)
from sklearn.svm import LinearSVC
c = 10**k
classifier = LinearSVC(
penalty='l2',
C=c,
max_iter = 100000
)
classifier.fit(X_train,y_train)
y_pred = classifier.predict(X_test)
accuracy = accuracy_score(y_test,y_pred)
#print ( "%2d" % k , "%.2f %%" % (100*accuracy) , 'ne = %d'%ne )
print ( "%2d" % k , "%.2f %%" % (100*accuracy) , 'C = %f'%c )
#y_pred vs y_test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.