blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7a864aba254e7531917b197c8dcc53e3cd0e20ce | jrg-sln/basic_python | /comparaciones7.py | 935 | 4.21875 | 4 | # -*- coding: utf-8 -*-
###########################Ejercicio sobre comparaciones####################
'''Ahora que ya sabe utilizar comparaciones hacer un programa que contenga la edad de varias personas y decir si es cierta o falsa la afirmación mediante una función, además use la impementación de la función main'''
persona1 = 10
persona2 = 30
def main():
print "\n\t\t\t\tComparaciones\n La edad de la persona 1 es de:",persona1,"años \n La edad de la persona 2 es de:",persona2,"años\n"
print "La persona 1 es menor que la persona 2:" + str(verificam(persona1,persona2))
print "La persona 2 es menor que la persona 1:",verificam(persona2,persona1)
print "La persona 1 es mayor que la persona 2:",verificaM(persona1,persona2)
print "La persona 2 es mayor que la persona 1:",verificaM(persona2,persona1)
def verificam(p1,p2):
return p1 < p2
def verificaM(p1,p2):
return p1 > p2
if __name__ == '__main__':
main()
| false |
5f4783efff3f567033bff8c2752602a13a3b7b2e | jackfish823/Hangman_Python | /Guess.py | 597 | 4.125 | 4 | import re #lib to search in a string
def is_valid_input(letter_guessed):
# checks if the function the input letter_guessed is good
spread_guess = re.findall('[A-Za-z]', letter_guessed) #list of the guess_input of only english
if len(letter_guessed) == len(spread_guess):
if len(letter_guessed) == 1:
return True
else:
return False
else:
return False
word_input = input("Enter word: ")
word_len = int(len(word_input))
print("_ " * word_len) #print the _ _ _ _
guess_input = input("\nGuess a letter: ") #to guess the letter
| true |
ecfc083467a06ff836565a89858b8218e64bd56b | npradha/multTables | /multTables.py | 386 | 4.28125 | 4 |
while True:
print("\n")
print("What number do you want the multiplication table of?")
num = input()
print("\n")
for mul in range(13):
answer = num * mul
print(str(num) + " x " + str(mul) + " = " + str(answer))
print("\n")
print("Do you want to input another number? (y/n)")
ans = raw_input()
if ans == 'y':
continue
else:
break
print("\n")
print("Happy Learning!!")
| true |
20b3bba2480a4ec504aee0a1db35c01348c1b21d | Unrealplace/PythonProject | /基础知识学习/list_demo.py | 1,440 | 4.25 | 4 |
arr = ['hello','world','nice to ','meet','you']
print(arr)
# for 循环遍历
for x in arr:
print(x)
pass
#通过下标来取列表中的元素
print(arr[0])
print(arr[-1])
#列表的增删改查操作
motor_cycles = ["honda","ymaha","suzuki"]
# 列表末尾增加一个数据
motor_cycles.append("nice to meet you")
# 修改
motor_cycles[1] = "oliverlee"
#插入元素
motor_cycles.insert(0,"liyang")
motor_cycles.insert(0,"liyang")
print(motor_cycles)
print("***************")
#删除知道位置的元素
del motor_cycles[1]
print(motor_cycles)
#从列表中pop 出数据,这个数据还可以使用,弹出最后一个元素
pop_motor = motor_cycles.pop()
print(pop_motor)
print(motor_cycles)
#弹出指定位置的元素
pop_motor = motor_cycles.pop(0)
print(pop_motor)
print("\n*********\n")
#不知道要删除的元素的位置,只知道元素
motor_cycles.remove("suzuki")
print(motor_cycles)
print("***************")
#创建一个空列表
animals = []
animals.append("dog")
animals.append("cat")
animals.append("fish")
animals.append("flower")
print(animals)
#*********永久行排序***#
#排序
animals.sort()
print(animals)
#反向排序
animals.sort(reverse=True)
print(animals)
print("***************")
#临时性排序,相当于又返回值的排序哦
new_animals = sorted(animals)
print(animals)
print(new_animals)
new_animals.reverse()
print(new_animals)
print("count"+str(len(new_animals)))
| false |
585fcfed03865a69f179d04818c5e1e1cf6cd470 | MaxCosmeMalasquez/Ejercicios-Python- | /example2.12.py | 943 | 4.125 | 4 | # print("Write first number")
# x = int(input())
# print("Write second number")
# y = int(input())
# print("Write third number")
# z= int(input())
# cadena = [x,y,z]
# cadena.sort()
# print(cadena)
print("Write first number")
x = int(input())
print("Write second number")
y = int(input())
print("Write third number")
z= int(input())
if x>y and x>z and y>z :
print("The order is " + "[" + str(x)+"," +str(y)+ "," + str(z) + "]")
elif x>y and x>z and z>y :
print(" The order is " + "[" + str(x)+ "," + str(z) + "," + str(y) + "]")
elif y>x and y>z and x>z :
print(" The order is " + "[" + str(y)+ "," + str(x)+ "," + str(z) + "]")
elif y>x and y>z and z>x :
print(" The order is " + "[" + str(y) + "," + str(z)+ "," + str(x) + "]")
elif z>x and z>y and x>y:
print("The order is " + "[" +str(z) + "," + str(x) + "," + str(y) + "]")
else :
print(" The order is " + "[" + str(z)+ "," + str(y) + "," + str(x) + "]") | false |
f1fe2d0ee08fd6ff898efdfb5c2335c8552504f7 | katoluo/Python_Crash_Course | /chapter_04/4-11.py | 381 | 4.25 | 4 | my_pizzas = [ 'one', 'two', 'three' ]
print("my_pizzas: " + str(my_pizzas))
friend_pizzas = my_pizzas[:]
print("friend_pizzas: " + str(friend_pizzas))
my_pizzas.append('my_four')
friend_pizzas.append('friend_four')
print("My favorite pizzas are:")
for value in my_pizzas:
print(value)
print("My friend's favorite pizzas are:")
for value in friend_pizzas:
print(value)
| false |
365d066474e18dafccfeecf141a6f339052edc73 | LinsonJoseph/python | /use_of_is.py | 1,090 | 4.1875 | 4 | #Use of 'is'
list_123 = [1, 2, 3]
list_321 = [3, 2, 1]
tuple_123 = (1, 2, 3)
tuple_321 = (3, 2, 1)
# == compares the value of both operands
if id(list_123[0]) == id(list_321[2]):
print(f'ID of 1st element of list_123 is {id(list_123[0])} and is same as id of 3rd element of list_321 {id(list_321[2])}')
else:
print('id of list_[1]23 {id(list_123[0]) is not same as id of list_32[1] {id(list_321[2])}')
print()
if id(list_123[0]) is id(list_321[2]):
print(f'Object of 1st element of list_123 IS same as object of 3rd element of list_321')
else:
print('Object of 1st element of list_[1]23 IS NOT same as Object of 3rd element of list_32[1]')
print()
print("id of tuple_[1]23 is: ", id(tuple_123[0]))
print("id of tuple_32[1] is: ", id(tuple_321[2]))
print()
# is checks if both operands refer to same object
print("object of list_123[0] is same as object of tuple_321[2]: ", id(list_123[0]) is id(tuple_321[2]))
print()
print("list_123 is a tuple: ", isinstance(list_123, tuple))
print("tuple_123 is a tuple: ", isinstance(tuple_123, tuple))
| false |
53b5e0a564b279e63ceb6458310fcbaeec68d933 | DustinRPeterson/lc101 | /crypto/vigenere.py | 2,230 | 4.125 | 4 |
#Encrypts text using the vignere algorithm (https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher)
from helpers import alphabet_position, rotate_character #import alphabet_position and rotate_character from helpers.py
lower_case_dict = dict() #create dictionary for lowercase letters
upper_case_dict = dict() #create dictionary for uppercase letters
def create_lower(lower_string):
#fill in the lower case dictionary where [a==0, z==25]
dict_index = 0
for c in lower_string:
lower_case_dict[dict_index] = c
dict_index += 1
def create_upper(upper_string):
#fill in the lower case dictionary where [A==0, Z==25]
dict_index = 0
for c in upper_string:
upper_case_dict[dict_index] = c
dict_index += 1
def encrypt(text, rot):
#Encrypts the text, uses helpers.rotate_character()
rotation_list = list() #create the list that will store the numbers to rotate for each character in cypher
rotation_num = 0
new_text = ''
for i in rot:
#use the rotation_list to store the position of each letter in the cypher word used
rotation_list.append(alphabet_position(i))
print(rotation_list)
for c in text:
if c.isalpha() == True:
try:
#rotate the character by the amount given in the rotation_list
rotation = rotation_list[rotation_num]
new_text += rotate_character(c, rotation)
rotation_num += 1 #move to the next amount in rotation list
except IndexError:
#if rotation_num is moved out of the rotation_list index reset to 0
rotation_num = 0
rotation = rotation_list[rotation_num]
new_text += rotate_character(c, rotation)
rotation_num += 1
else:
#if not alphabetic charcter do not change
new_text += c
return new_text
def main():
create_lower('abcdefghijklmnopqrstuvwxyz')
create_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
message = input("Type a message: ")
rotate = input("Encryption string: ")
encrypted_message = encrypt(message, rotate)
print(encrypted_message)
if __name__ == "__main__":
main()
| true |
0ebc30ff3f710310db361194090f163abcf9e8c7 | MarsWilliams/PythonExercises | /How-to-Think-Like-a-Computer-Scientist/DataFiles.py | 2,582 | 4.34375 | 4 | #Exercise 1
#The following sample file called studentdata.txt contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student.
#joe 10 15 20 30 40
#bill 23 16 19 22
#sue 8 22 17 14 32 17 24 21 2 9 11 17
#grace 12 28 21 45 26 10
#john 14 32 25 16 89
#Using the text file studentdata.txt write a program that prints out the names of students that have more than six quiz scores.
infile = open("studentdata.txt", "r")
aline = infile.readline() #could omit this line if using a for loop
while aline:
data = aline.split()
if len(data[1:]) > 6:
print data[0]
aline = infile.readline() #could omit this line if using a for loop
infile.close()
#Exercise 2
#Using the text file studentdata.txt (shown in exercise 1) write a program that calculates the average grade for each student, and print out the student’s name along with their average grade.
infile = open("studentdata.txt", "r")
aline = infile.readline()
while aline:
aline = (aline.rstrip()).split()
scores = 0
for a in aline[1:]:
scores = scores + int(a)
print "%s's average score is %s." % (aline[0].capitalize(), str(int(scores / len(aline[1:]))))
aline = infile.readline()
infile.close()
#Exercise 3
#Using the text file studentdata.txt (shown in exercise 1) write a program that calculates the minimum and maximum score for each student. Print out their name as well.
infile = open("studentdata.txt", "r")
aline = infile.readline()
while aline:
aline = (aline.rstrip()).split()
print "%s's maximum score is %s and h/er minimum score is %s." % (aline[0].capitalize(), max(aline[1:]), min(aline[1:]))
aline = infile.readline()
infile.close()
#At the bottom of this page is a very long file called mystery.txt The lines of this file contain either the word UP or DOWN or a pair of numbers. UP and DOWN are instructions for a turtle to lift up or put down its tail. The pairs of numbers are some x,y coordinates. Write a program that reads the file mystery.txt and uses the turtle to draw the picture described by the commands and the set of points.
infile = open("mystery.txt", "r")
aline = infile.readline()
import turtle
wn = turtle.Screen()
ben = turtle.Turtle()
while aline:
aline = (aline.rstrip()).split()
if aline[0] == "UP":
ben.penup()
elif aline[0] == "DOWN":
ben.pendown()
else:
ben.goto(int(aline[0]), int(aline[1]))
aline = infile.readline()
infile.close()
| true |
cca0db286b81980ff0def1e502f924a21b46d3c1 | weiyuyan/LeetCode | /剑指offer/21. 斐波那契数列.py | 574 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/11
'''
输入一个整数 n ,求斐波那契数列的第 n 项。
假定从0开始,第0项为0。(n<=39)
样例
输入整数 n=5
返回 5
'''
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
res = [0, 1, 1]
if n <= 2:
return res[n]
for i in range(3, n+1):
res.append(res[i-1]+res[i-2])
return res[-1]
solution = Solution()
res = solution.Fibonacci(0)
print(res) | false |
0dca0b990610cc3d92d4e89e3cc33fd367b63abc | weiyuyan/LeetCode | /24. 两两交换链表中的节点.py | 2,180 | 4.125 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time:2020/1/13
'''
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
'''
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 分析:我这里借用了一个数组来存储临时的链表并精进行转换,时间复杂度为o(n),遍历了整个列表
# 空间复杂度o(1),因为我只借用了大小为3的列表空间。
# class Solution:
# def swapPairs(self, head: ListNode) -> ListNode:
# # 新建边缘节点r
# r = ListNode(-1)
# if(head and head.next):
# r.next = head.next
# else:
# return head
#
# # 新建标记节点p
# p = ListNode(-1)
# p.next = head
# while(p.next and p.next.next and p.next.next.next):
# tmp_list = [p.next, p.next.next, p.next.next.next]
# p.next = tmp_list[1]
# tmp_list[1].next = tmp_list[0]
# tmp_list[0].next = tmp_list[2]
# p = tmp_list[0]
# if (p.next and p.next.next) and not p.next.next.next:
# tmp_list = [p.next, p.next.next]
# p.next = tmp_list[1]
# tmp_list[1].next = tmp_list[0]
# tmp_list[0].next = None
# return r.next
# 递归的写法
# 这个傻逼递归的原理我还没懂!
class Solution():
def swapPairs(self, head: ListNode) -> ListNode:
if(head == None or head.next == None):
return head
p = head.next
head.next = self.swapPairs(p.next)
p.next = head
return p
if __name__ == '__main__':
solution = Solution()
a = ListNode(6)
a.next = ListNode(7)
b = a.next
b.next = ListNode(8)
c = b.next
c.next = ListNode(9)
d = c.next
d.next = ListNode(10)
e = d.next
head = solution.swapPairs(a)
while(head):
print(head.val)
head = head.next
| false |
7ee4ed2d1167372fad229e6daf1958767613e19b | weiyuyan/LeetCode | /AcWing算法基础课/堆/838. 堆排序.py | 1,653 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/17
'''
输入一个长度为n的整数数列,从小到大输出前m小的数。
输入格式
第一行包含整数n和m。
第二行包含n个整数,表示整数数列。
输出格式
共一行,包含m个整数,表示整数数列中前m小的数。
数据范围
1≤m≤n≤105,
1≤数列中元素≤109
输入样例:
5 3
4 5 1 3 2
输出样例:
1 2 3
'''
# 如何手写一个堆?
# 1、插入一个数
# 2、求集合中的最小值
# 3、删除最小值
# 4、删除任意一个元素
# 5、修改任意一个元素
# 堆是一棵完全二叉树
# 小根堆性质:每一个点都小于它的左右儿子
# 堆的存储:一种全新的存储方式:用一个一维数组存
# 根节点编号是1
# 编号x的左儿子:2x
# 编号x的右儿子:2x+1
# 函数:
# down(x)往下调整
# up(x)往上调整
# 插入一个数:heap[++x]; up(size)
# 求最小值:heap[1]
# 删除一个数:取出堆最后一个元素,放到堆顶:heap[1] = heap[size]; size--; down(1)
# 删除第k个数:heap[k] = heap[size]; size--; down(k) or up(k)
def down(u):
t = u
if(u*2 <= size and heap[u*2]<heap[t]):
t = u*2
if(u*2+1 <= size and heap[u*2+1]<heap[t]):
t = u*2+1
if u!=t:
heap[u], heap[t] = heap[t], heap[u]
down(t)
if __name__ == '__main__':
heap = [0]
n, m = list(map(int, input().split()))
heap += list(map(int, input().split()))
size = n
for j in range(n>>1, 0, -1):
down(j)
while(m):
m-=1
print(heap[1])
size-=1
down(1)
| false |
da656c7b187d415acfe8ebe2f8180d42582bed8a | weiyuyan/LeetCode | /每日一题/March/面试题 10.01. 合并排序的数组.py | 2,114 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/3
'''
给定两个排序后的数组 A 和 B,其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法,将 B 合并入 A 并排序。
初始化 A 和 B 的元素数量分别为 m 和 n。
示例:
输入:
A = [1,2,3,0,0,0], m = 3
B = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
'''
from typing import List
# 第一种方法:直接拼接到A的尾部然后使用sort()方法排序
# class Solution:
# def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
# """
# Do not return anything, modify A in-place instead.
# """
# A[m:] = B
# A.sort()
pass
# 第二种方法,使用额外数组空间
# class Solution:
# def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
# """
# Do not return anything, modify A in-place instead.
# """
# if not A or not B: return
# sorted = []
# pa=pb=0
# while pa<=m and pb<=n:
# if pa==m: sorted[pa+pb:]=B[pb:]; break
# if pb==n: sorted[pa+pb:]=A[pa:m]; break
# if A[pa]<=B[pb]: sorted.append(A[pa]); pa+=1
# else: sorted.append(B[pb]); pb+=1
# A[:] = sorted
pass
# 第三种方法,利用A后面的额外空间,从大到小倒序排列
class Solution:
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
"""
Do not return anything, modify A in-place instead.
"""
tail= m+n-1
pa, pb = m-1, n-1
while pa>=0 or pb>=0:
if pa==-1:
A[tail]=B[pb]
pb -= 1
elif pb == -1:
A[tail] = A[pa]
pa -= 1
elif A[pa] > B[pb]:
A[tail] = A[pa]
pa -= 1
else:
A[tail] = B[pb]
pb -= 1
tail -= 1
A = [1,2,3,0,0,0]; m = 3
B = [2,5,6]; n = 3
# A = [2, 0]; m = 1
# B = [1]; n = 1
solution = Solution()
solution.merge(A, m, B, n)
print(A) | false |
12185824be7220a825a20e5ff5dd522e4f5f7523 | Kostiancheck/dict | /home_task_matrix/task6.py | 810 | 4.15625 | 4 | """Дан двумерный массив и два числа: i и j. Поменяйте в массиве столбцы с номерами i и j и выведите результат.
Программа получает на вход размеры массива n и m, затем элементы массива, затем числа i и j. """
n=int(input('n='))
m=int(input('m='))
list=[[int(input('Введіть число ')) for j in range(m)]for i in range(n)]
a=int(input('a='))
b=int(input('b='))
for row in list:
print(' '.join([str(el) for el in row]))
print('\n\n')
for j in range(m):
for i in range(n):
some_var=list[i][a]
list[i][a]=list[i][b]
list[i][b]=some_var
for row in list:
print(' '.join([str(el) for el in row])) | false |
61cbccec85567b98ffced9ee24e41e1d83b36654 | PickUpLiu/day1 | /day3/my_toninght.py | 1,375 | 4.25 | 4 |
# 等边三角形
# 九九乘法表
def multiplicationTable(num=9):
i = 1
while i <= num:
j = 1
while j <= i:
print(j, "X", i, "=", str(j * i).rjust(2), end="")
j += 1
i += 1
print()
# 菱形
def rhombus(num=10):
num = num // 2
i = 1
while i <= num:
j = num
while i < j:
print(" ", end="")
j -= 1
j = 1
while j <= i * 2 - 1:
print("*", end="")
j += 1
i += 1
print()
i = 1
while i <= num - 1:
j = 1
while j <= i:
print(" ", end="")
j += 1
j = 1
while j <= (num - i) * 2 - 1:
print("*", end="")
j += 1
i += 1
print()
# 1到n左对齐
def lefJustifying(num=100):
for l in range(1, num + 1):
print(str(l).rjust(str(num + 1).__len__() + 1), end="")
if l % 10 == 0:
print()
def sanJiao(num=6):
for i in range(1, num):
for j in range(1, num - i):
print(" ", end="")
for k in range(1, i + 1):
print("* ", end="")
print("")
def shuLie(len=10):
mlist=[i for i in range(0,len*10)]
for i in mlist:
if(i%10==9 and i!=0):
print(str(i).ljust(5))
else:
print(str(i).ljust(5),end="") | false |
e59b96d2f3400e5f8b52cb8a26ee3e7479913d29 | dhoshya/grokking-algorithms | /quickSort.py | 440 | 4.15625 | 4 | # D&C
def quickSort(arr):
# base case
if len(arr) < 2:
return arr
else:
pivot = arr[0]
# using list comprehension
less = [i for i in arr[1:] if i <= pivot]
# using normal syntax
greater = list()
for i in arr[1:]:
if i >= pivot:
greater.append(i)
return quickSort(less) + [pivot] + quickSort(greater)
print(quickSort([10, 5, 2, 3]))
| true |
c58f7ad55fb459f14ee2d6535fd887063a9850f9 | renato130182/app_python | /aula5.py | 1,243 | 4.21875 | 4 | lista = [1,3,5,7]
listaAnimal = ['cachorro','gato','elefante']
print(type(lista))
print(lista) # pode conter tipos de dados diferentes
print(listaAnimal[0])
for x in listaAnimal: # x assume o valor na possição da lista
print(x)
print(sum(lista))
print(max(lista))
print(min(lista))
print(min(listaAnimal)) # segue a ordem alfabetica
print(max(listaAnimal))
if 'gato' in listaAnimal:
print("gato econtrado")
novaLista = listaAnimal*3 #cria lista com valores triplicados
#adidiocnar intem na lista dinamicamente
listaAnimal.append('lobo')
print(listaAnimal)
# retira o ultima item da lista
listaAnimal.pop()
print(listaAnimal)
#remove pela posição na lista
listaAnimal.pop(0)
print(listaAnimal)
#remove pelo valor na lista
listaAnimal.remove('gato')
print(listaAnimal)
#ordena a lista numerica ou alfabeticamente
lista.sort()
print(lista)
#reverte os valores da lista
lista.reverse()
print(lista)
print(len(lista))
# Tuplas são imutáveis, diferente da lista
print('\n\n\n\n')
tupla = (1,10,12,5,14) # lista adicionada entre parentes e não colchetes
print(tupla)
print(tupla[1])
print(len(tupla))
tuplaAnimal = tuple(listaAnimal) #converte uma tupla em uma lista
listaTupla = list(tupla)
print(tuplaAnimal)
print(listaTupla) | false |
e44f1c6cef22aedc4f5114c69f0260f2a37646a9 | AniketKul/learning-python3 | /ordereddictionaries.py | 849 | 4.3125 | 4 | '''
Ordered dictionaries: they remember the insertion order. So when we iterate over them,
they return values in the order they were inserted.
For normal dictionary, when we test to see whether two dictionaries are equal,
this equality os only based on their K and V.
For ordered dictionary, when we test to see whether two dictionaries are equal,
insertion order is considered as an equality test between two OrderedDicts with
same key and values but different insertion order.
'''
od1 = OrderedDict()
od1['one'] = 1
od1['two'] = 2
od2 = OrderedDict()
od2['two'] = 2
print(od1 == od2) #Output: False
'''
OrderedDict is often used in conjunction with sorted method to create a sorted dictionary.
For example,
'''
od3 = OrderedDict(sorted(od1.items(), key = lambda t : (4*t[1]) - t[1]**2))
od3.values() #Output: odict_values([6, 5, 4, 1, 3, 2])
| true |
b3cfd1cdfbb6800a2b610571b1f720fd5219b8e2 | katherineggs/estructura-datos | /Search Sort/Sort.py | 1,804 | 4.25 | 4 | #INSERTION SORT
def InsertionSort(array):
for i in range(1, len(array)):
key = array[i]
num = i - 1
while (num >= 0) and (key < array[num]):
array[num+1] = array[num]
num -= 1
array[num+1] = key
return array
def MergeSort(array):
if len(array) > 1:
half = len(array) //2
left = array[:half]
right = array[half:]
# indexL = 0
# indexR = 0
# for i in range(0,half-1):
# left[indexL] = array[i]
# indexL += 1
# for i in range(half,len(array)-1):
# right[indexR] = array[i]
# indexR += 1
MergeSort(right)
MergeSort(left)
indexL = 0
indexR = 0
k = 0
while indexL < len(left) and indexR < len(right):
if left[indexL] < right[indexR]:
array[k] = left[indexL]
indexL += 1
else:
array[k] = right[indexR]
indexR += 1
k += 1
while indexL < len(left):
array[k] = left[indexL]
indexL += 1
k += 1
while indexR < len(right):
array[k] = right[indexR]
indexR += 1
k += 1
return array
# def printList(array):
# for i in range(len(array)):
# print(array[i],end=" ")
# print()
if __name__ == '__main__':
array = [15, 22, 1, 9, 6, 67]
print ("Array is")
# printList(array)
print(array)
print("")
print("Inserion Sort array is: ")
print(InsertionSort(array))
# printList(array)
print("")
print("Merge Sort array is: ")
print(MergeSort(array))
# printList(array)
print("")
| false |
f4451ce74fd1b6d16856f09f21f2eee9ae8c8f9a | jorricarter/PythonLab1 | /Lab1Part2.py | 523 | 4.125 | 4 | #todo get input
currentPhrase = input("If you provide me with words, I will convert them into a camelCase variable name.\n")
#todo separate by word
#found .title @stackoverflow while looking for way to make all lowercase
wordList = currentPhrase.title().split()
#todo all lowercase start with uppercase
#found .title() to acheive this
#todo first letter of first word should be lower case
wordList[0] = wordList[0].lower()
#todo join words into single word
newName = ''.join(wordList)
#todo print to screen
print (newName)
| true |
d51e758b43989603f02fc40214a03a970be2d4d1 | KishorP6/PySample | /LC - Decission.py | 1,362 | 4.34375 | 4 | ##Input Format :
##Input consists of 8 integers, where the first 2 integers corresponds to the fare and duration in hours through train, the next 2 integers corresponds to the fare and duration in hours though bus and the next 2 integers similarly for flight, respectively. The last 2 integers corresponds to the fare and duration weightage, respectively.
##Output Format :
## Output is a string that corresponds to the most efficient means of transport. The output string will be one of the 3 strings - "Train Transportation" , "Bus Transportation" or "Flight Transportation".
train_fare = int(input())
train_duration = int(input())
bus_fare = int(input())
bus_duration = int(input())
flight_fare = int(input())
flight_duration = int(input())
fare_weightage = int (input())
duration_weightage = int (input())
train_weightage = int(train_fare*fare_weightage+ train_duration*duration_weightage)
bus_weightage = int(bus_fare*fare_weightage+ bus_duration*duration_weightage)
flight_weightage = int(flight_fare*fare_weightage+ flight_duration*duration_weightage)
if flight_weightage < train_weightage and flight_weightage < bus_weightage :
print ("Flight Transportation")
else:
if bus_weightage < train_weightage and bus_weightage < flight_weightage :
print ( "Bus Transportation")
else :
print ( "Train Transportation")
| true |
ddeadc23b291498c7873533b16bf78c945670b2c | CStage/MIT-Git | /MIT/Lectures/Lecture 8.py | 1,429 | 4.125 | 4 | #Search allows me to search for a key within a sorted list
#s is the list and e is what we search for
#i is the index, and the code basically says that while i is shorter than the the
#length of the list and no answer has been given yet (whether true or false)
#then it should keep looking through s to see if it can find e.
#i=0 means that we START looking at index 0
#For every run-through where we don't find what we need, we look for the key at
#index that is 1 higher than the previous
def Search(s,e):
answer=None
i = 0
numCompares=0
while i < len(s) and answer==None:
numCompares+=1
if e==s[i]:
answer=True
elif e<s[i]:
answer=False
i+=1
print(answer,numCompares)
#If you are working with a sorted list it is a great idea to make the search START
#at the middle of the list. That way you can throw half the list out at each
#run-through. Basically, using a log-function is worth way more for you.
def bSearch(s, e, first, last):
print(first, last)
if (last-first)<2:
return s[int(first)] ==e or s[int(last)]==e
mid=first+(last-first)/2
if s[int(mid)]==e:
return True
if s[int(mid)]>e:
return bSearch(s,e, first, mid-1)
return bSearch(s,e,mid+1,last)
list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
def Search1(s,e):
print(bSearch(s,e,0,len(s)-1))
print("Search complete")
Search1(list,13)
| true |
9e11800cd87f7fa6c523cf6e0f6869e2ce59fb66 | jacobeskin/Moon-Travel | /kuumatka_xv.py | 1,828 | 4.25 | 4 | import itertools
import numpy as np
import matplotlib.pyplot as plot
# Numerical calculation and visualisation of the change in position
# and velocity of a spacecraft when it travels to the moon. Newtons
# law of gravitation and second law of motion are used. Derivative is
# evaluated with simple Euler method. This project was originally
# done in Finnish, the variable names reflect that.
# Define constants and vectors for position and velocity
g = 6.674*(10**(-11)) # Gravitation constant
Maa = 5.974*(10**24) # Earths mass
Kuu = 7.348*(10**22) # Moons mass
X = 376084800 # Target distance, low orbit of moon (Wikipedia)
n = 0 # Keeps tab on how many time steps has gone
r1 = 6578100 # Distance from Earths center in the beginning
v1 = 12012 # Starting velocity + 10%
V = np.array([v1]) # Vector that will house the values of velocity
R = np.array([r1]) # Vector that will house the values of distance
dt = 10 # Length of time step in seconds
# Iterate our way to the moon!
for i in itertools.count():
n = n+1
# New distance
r = r1+v1*dt
R = np.append(R,r)
# Updated acceleration
b = Kuu/((3844*(10**5)-r1)**2)
c = Maa/(r1**2)
A = g*(b-c)
# New velocity
v = v1+A*dt
V = np.append(V,v)
# Update position and velocity
r1 = r
v1 = v
# When arriving to the moon
if r>=X:
break
T = (n*dt)/3600 # Travel time in hours
print(T)
# Plot the graphs of position and velocity as function of time
plot.figure(1)
plot.subplot(211)
plot.plot(R)
plot.xlabel('Aika, s') # "Aika" means time
plot.ylabel('Matka, m') # "Matka" means distance
plot.subplot(212)
plot.plot(V)
plot.xlabel('Aika, s')
plot.ylabel('Nopeus, m/s') # "Nopeus" means velocity
plot.show()
| true |
e050bf9dbde856f206bac59513c3a19e47e23a92 | nwelsh/PythonProjects | /lesson3.py | 408 | 4.28125 | 4 | #Lesson 3 I am learning string formatting. String formatting in python is very similar to C.
#https://www.learnpython.org/en/String_Formatting
name = "Nicole"
print("Hello, %s" % name)
#s is string, d is digit, f is float (like c)
age = 21
print("%s is %d years old" % (name, age))
data = ("Nicole", "Welsh", 21.1)
format_string = "Hello %s %s. Your current balance is $%s."
print(format_string % data)
| true |
05865082b9f165c102b359cd9deb8a53f1e78d87 | nwelsh/PythonProjects | /lesson9.py | 663 | 4.15625 | 4 | # lesson 9: https://www.learnpython.org/en/Dictionaries
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
# prints: {'John': 938477566, 'Jack': 938377264, 'Jill': 947662781}
phonebook2 = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print(phonebook2) #same print
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
del phonebook["John"]
print(phonebook) # just jack and jill
phonebook.pop("Jack") # just jill
print(phonebook)
# add jake and delete jill
phonebook["Jake"] = 938273443
del phonebook["Jill"]
| false |
cad277b1a2ca68f6a4d73edc25c2680120b88137 | tanvirtin/gdrive-sync | /scripts/File.py | 1,380 | 4.125 | 4 | '''
Class Name: File
Purpose: The purpose of this class is represent data of a particular file
in a file system.
'''
class File:
def __init__(self, name = None, directory = None, date = None, fId = None, folderId = None, extension = ""):
self.__name = name
self.__directory = directory
self.__date = date
self.__id = fId
self.__folderId = folderId
self.__mimeType = extension
def __repr__(self):
return self.getName
'''
Name: getName
Purpose: A getter method for the name of the file.
return: private attribute __name
'''
@property
def getName(self):
return self.__name
'''
Name: getDir
Purpose: a getter method for the name of the directory the file is in.
return: private attribute __directory
'''
@property
def getDir(self):
return self.__directory
'''
Name: getLastModified
Purpose: a getter method for the date that the file was last modified at
return: private attribute __date
'''
@property
def getLastModified(self):
return self.__date
'''
Name: getDetails
Purpose: Returns the full file address of a file object.
return: a string representing the full file details
'''
def getDetails(self):
return self.getDir + self.getName
@property
def getFileId(self):
return self.__id
@property
def getFolderId(self):
return self.__folderId
@property
def getMimeType(self):
return self.__mimeType | true |
caa33fdad5d9812eb473d03a497c46d6a0ad71f2 | YasirQR/Interactive-Programming-with-python | /guess_number.py | 1,963 | 4.21875 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import math
import random
import simplegui
num_range = 100
count = 0
stop = 7
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global secret_number
global count
count =0
secret_number = random.randrange(num_range)
print "New Game! Guess a number!"
print ""
# define event handlers for control panel
def range100():
global num_range
global stop
global count
num_range = 100
stop = 7
print ""
new_game()
def range1000():
global num_range
global stop
global count
num_range = 1000
stop = 10
print ""
new_game()
def input_guess(guess):
print ""
print "Guess was " + guess
global count
count +=1
if int(guess) == secret_number:
print "You guessed right!!!"
print ""
new_game()
elif count == stop:
print("GAME OVER! You ran out of guesses")
print ""
new_game()
elif int(guess) > secret_number:
print "Lower!"
print ("You have " +str(stop - count) + " guesses left")
else:
print "Higher!"
print ("You have " +str(stop - count) + " guesses left")
# create frame
f = simplegui.create_frame("GUESSER", 200,200)
f.add_input("Your Guess (Press Enter)", input_guess, 200)
blank = f.add_label('')
label1 = f.add_label('New Game: Change range')
f.add_button("Number (0,100)",range100, 200)
f.add_button("Number (0,1000)", range1000, 200)
# register event handlers for control elements and start frame
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
| true |
1c10a0791d3585aa56a5b6c88d133b7ea98a8b24 | haydenbanting/LawnBot | /Mapping/mapping_functions/matrix_builder.py | 2,029 | 4.25 | 4 | '''
Function for creating matricies for map routing algorithms
Author: Kristian Melo
Version: 15 Jan 2018
'''
########################################################################################################################
##Imports
########################################################################################################################
from Mapping.constants import constants as c
########################################################################################################################
#To use Dijkstras algorithm we need a list of "edges". this is a n x 3 matrix where each row contains the start point,
#end point, and distance.
def build_edges_matrix(lawn):
edges = []
#loop through all nodes in list
for nodes in lawn:
#loop through all the neighbors in a given node
for i in nodes.neighbors:
#add new edge between the given node and its neighbore to the list of edges
#note the length is always gridsize since neighbores are always adjacent squares
edges.append([str(nodes.location), str(i), c.GRIDSIZE])
return edges
########################################################################################################################
'''
#legacy code, keeping in case of future changes
def build_distance_matrix(lawn):
movelist = []
obslist = []
for node in lawn:
if node.type != 9:
movelist.append(node)
else:
obslist.append(node)
distance = np.zeros((len(movelist), len(movelist)))
i,j = 0,1
while i < len(movelist):
while j < len(movelist):
x1 = movelist[i].location[0]
x2 = movelist[j].location[0]
y1 = movelist[i].location[1]
y2 = movelist[j].location[1]
r = m.hypot(x2-x1,y2-y1)
if col.obstacleDetection(obslist, x1, y1, x2, y2) == False:
distance[i, j] = r
j += 1
i += 1
j = i + 1
return distance
''' | true |
22cee07f314c33d643c68081ee0575b51d59f518 | deycyrubi/ProyectoUnidad3 | /DistanciaEuclidea.py | 1,445 | 4.15625 | 4 | """
>>> numero = DistanciaEuclidea(2,2,4,4,)
>>> numero.CalDistancia()
>>> numero.getDistancia()
2.8284271247461903
"""
#Se declara la palabra reservada math para la resolución del problema
import math
#Se declara la clase la cual lleva por nombre el problema a resolver
class DistanciaEuclidea:
"""Se declaran los atributos de la clase DistanciaEuclidea de manera privada
los cuales indicarán las acciones o necesidades del objeto"""""
__x1 = float(0) #Se usa el elemento("__") para indicar que el atributo es privado
__y1 = float(0)
__x2 = float(0)
__y2 = float(0)
__distancia = float(0)
__suma = float(0)
#En esta sección realizamos el metodo constructor el cual será el que utilicen todos los demás métodos
def __init__(self,x1,y1,x2,y2): #def es para declarar un método y _init_es para definir al método constructor
self.__x1 = x1
self.__y1 = y1
self.__x2 = x2
self.__y2 = y2
self.CalDistancia() #Se usa la palabra reservada self seguida del atributo
#para acceder a los atributos privados
def CalDistancia(self):
self.__distancia = math.sqrt((self.__x1 - self.__x2) ** 2 + (self.__y1 - self.__y2) ** 2)
#Se usa get para que pueda mostrar el valor, puesto que está declarado como privado
def getDistancia(self):
return self.__distancia
if __name__ == '__main__':
import doctest
doctest.testmod() | false |
66d85d4d119be319d62c133c1456c91a630291db | 10zink/MyPythonCode | /HotDog/hotdog.py | 1,624 | 4.1875 | 4 | import time
import random
import Epic
# Programmed by Tenzin Khunkhyen
# 3/5/17 for my Python Class
# HotDogContest
#function that checks the user's guess with the actual winner and then returns a prompt.
def correct(guess, winner):
if guess.lower() == winner.lower():
statement = "\nYou gusses right, %s wins!" %winner
else:
statement = "\nYou guess wrong, the winner was %s" %winner
return statement
#main function which runs the program
def main():
tom = 0
sally = 0
fred = 0
guess = Epic.userString("Pick a winnder (Tom, Sally, or Fred: ")
print "Ready, Set, Eat!\n"
keepGoing = True
while keepGoing:
#I created three seperate random number ranges to procduce different numbers for each contestant
tNumber = random.randrange(1,6)
sNumber = random.randrange(1,6)
fNumber = random.randrange(1,6)
tom = tom + tNumber
sally = sally + sNumber
fred = fred + fNumber
time.sleep(2)
print "\nchomp.. chomp... chomp... \n"
print "Tom has eaten %s hot dogs!" %tom
print "Sally has eaten %s hot dogs!" %sally
print "Fred has eaten %s hot dogs!" %fred
#the following if statement then determined the winner
if tom >= 50:
winner = "Tom"
keepGoing = False
elif sally >= 50:
winner = "Sally"
keepGoing = False
elif fred >= 50:
winner = "Fred"
keepGoing = False
print "%s" %correct(guess,winner)
main() | true |
0b18e86b3b5c414604e6cf3e35618770998043a9 | 10zink/MyPythonCode | /Exam5/Store.py | 1,448 | 4.46875 | 4 | import json
import Epic
# Programmed by Tenzin Khunkhyen
# 4/16/17 for my Python Class
# This program is for Exam 5
# This program just reads a json file and then prints information from a dictionary based on either
# a category search or a keyword search.
#This function reads the json file and converts it into a dictionary
def fileReader():
jsonTxt = ""
f = open('PetStore.json')
for line in f:
line = line.strip()
jsonTxt = jsonTxt + line
petStore = json.loads(jsonTxt)
return petStore
#This function takes in a dictionary and also string "a"
def sorter(petStore, a):
answers = ""
#This if statement is for category search
if(a == 'c'):
userInput = Epic.userString("Enter a category: ")
print ""
for cat in petStore:
if(cat["Category"].lower() == userInput):
print "%s - $%s" % (cat["Product"], cat["Price"])
#This if statement is for keyword search
if(a == 'k'):
userInput = Epic.userString("Enter a keyword: ")
print ""
for key in petStore:
if(userInput in key["Product"].lower()):
print "%s - $%s" % (key["Product"], key["Price"])
return answers
def main():
b = Epic.userString("Search by category (c) or keyword (k)?")
a = b.lower()
#This line calls the method
d = sorter(fileReader(), a)
print d
main() | true |
c601c685111500976d62442a4e2be11bb928ee77 | justdave001/Algorithms-and-data-structures | /SelectionSort.py | 524 | 4.1875 | 4 | """
Sort array using brute force (comparing value in array with sucessive values and then picking the lowest value
"""
#Time complexity = O(n^2)
#Space complexity = O(1)
def selection_sort(array):
for i in range(len(array)):
for j in range(i+1, len(array)):
if array[i] > array[j]:
array[i], array[j] = array[j], array[i]
return array
if __name__ == "__main__":
array = list(map(int, input().rstrip().split()))
print(selection_sort(array))
| true |
3c8df58e0135bd806acd5735d66bf42e718cd49d | signoreankit/PythonLearn | /numbers.py | 551 | 4.1875 | 4 | """
Integer - Whole numbers, eg: 0, 43,77 etc.
Floating point numbers - Numbers with a decimal
"""
# Addition
print('Addition', 2+2)
# Subtraction
print('Subtraction', 3-2)
# Division
print('Division', 3/4)
# Multiplication
print('Multiplication', 5*7)
# Modulo or Mod operator - returns the remained after the division
print('Modulo', 97 % 5)
# Exponent - a**b represents a to the power b
print('Exponent', 2 ** 4)
# Floor Division - Returns the left side of the decimal or simple integer if no decimal
print('Floor Division', 9 // 2)
| true |
223070725f14bb3d977bb67a41830942263aacd7 | Hazel-K/Python3 | /code05/main.py | 773 | 4.21875 | 4 | # num_tuple = (1, 2, 3)
# num_tuple[0] = 0
#TypeError: 'tuple' object does not support item assignment
# del num_tuple[0]
#TypeError: 'tuple' object does not support item assignment
# print(num_tuple)
# 튜플 형태의 값은 수정 삭제가 불가능
# num_set = {1, 1, 2, 2, 3, 3} # {1,2,3} 중복 제거됨
# num_set.add(4)
# print(num_set)
# 순서를 갖지 않으므로 인덱싱, 슬라이싱 불가능
# set1 = {1, 2, 3, 4}
# set2 = {1, 2, 3}
# print(set1 & set2) #교집합 연산
# print(set1 | set2) #합집합 연산
# print(set1 - set2) #처집합 연산
test_list = [1, 2 ,3, 1, 2, 3]
# sub_list = [1, 2 ,3]
# print(test_list + sub_list)
# print(test_list * 2)
# list(), dict(), set(), tuple()
print(set(test_list)) #다른 속성값으로 변경 가능 | false |
3b6559c4f2511789a65a458111ba32103cf340a6 | tjrobinson/LeoPython | /codes.py | 2,373 | 4.21875 | 4 | for x in range(0,2):
userchoice = input("Do you want to encrypt or decrypt?")
userchoice = userchoice.lower()
if userchoice == "encrypt":
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
StringToEncrypt = input("Please enter a message to encrypt: ")
StringToEncrypt = StringToEncrypt.upper()
ShiftAmount = int(input("Please enter a number from 1 to 25 to be your key. "))
if 25 < ShiftAmount:
print("Uh Oh, number was too big")
StringToEncrypt = input("Please enter the message to encrypt: ")
StringToEncrypt = StringToEncrypt.upper()
ShiftAmount = int(input("Please enter a number from 1 to 25 to be your key. "))
encryptedString = ""
for currentCharacter in StringToEncrypt:
position = Alphabet.find(currentCharacter)
newPosition = position + ShiftAmount
if currentCharacter in Alphabet:
encryptedString = encryptedString + Alphabet[newPosition]
else:
encryptedString = encryptedString + currentCharacter
print("Your message is", encryptedString)
if userchoice == "decrypt":
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
StringToEncrypt = input("Please enter the message to decrypt: ")
StringToEncrypt = StringToEncrypt.upper()
ShiftAmount = int(input("Please enter the key to decrypt. "))
if 25 < ShiftAmount:
print("Uh Oh, number was too big")
StringToEncrypt = input("Please enter the message to decrypt: ")
StringToEncrypt = StringToEncrypt.upper()
ShiftAmount = int(input("Please enter the key to decrypt. "))
ShiftAmountB = ShiftAmount + ShiftAmount
ShiftAmount = ShiftAmount - ShiftAmountB
encryptedString = ""
for currentCharacter in StringToEncrypt:
position = Alphabet.find(currentCharacter)
newPosition = position - ShiftAmount
if currentCharacter in Alphabet:
encryptedString = encryptedString + Alphabet[newPosition]
else:
encryptedString = encryptedString + currentCharacter
encryptedString = encryptedString.lower()
print("The message is", encryptedString)
nothing = input("")
| true |
44d05ed22e742656562ce9179d63dee9cc2d8980 | redjax/practice-python-exercises | /06-string-lists.py | 567 | 4.375 | 4 | """
Ask the user for a string and print out whether
this string is a palindrome or not.
(A palindrome is a string that reads the same
forwards and backwards.)
"""
test = [0, 1, 2, 3, 4, 5]
# print(test[::-1])
word_input = input("Enter a word, we'll tell you if it's a palindrome: ")
def reverse_word(word):
reversed_word = word[::-1]
return reversed_word
word_reversed = reverse_word(word_input)
if word_input == word_reversed:
print("{} is a palindrome!".format(word_input))
else:
print("{} is not a palindrome. Oh well!".format(word_input))
| true |
d1a6dcf4f6b6600117789e857ad84636cb1788e6 | Deniska10K/stepik | /2.2-print_and_input_commands/4.star_triangle.py | 216 | 4.125 | 4 | """
Напишите программу, которая выводит указанный треугольник, состоящий из звездочек (*).
"""
print('\n'.join(['*' * i for i in range(1, 8)]))
| false |
abde6bffef26afe110d05c19e45f8a4b34b8eb8f | Deniska10K/stepik | /4.3-nested_and_cascading_conditions/5.weighing_ceremony.py | 1,007 | 4.34375 | 4 | """
Известен вес боксера-любителя (целое число). Известно, что вес таков, что боксер может быть отнесён к одной из трех
весовых категорий:
Легкий вес – до 60 кг;
Первый полусредний вес – до 64 кг;
Полусредний вес – до 69 кг.
Напишите программу, определяющую, в какой категории будет выступать данный боксер.
Формат входных данных
На вход программе подаётся одно целое число.
Формат выходных данных
Программа должна вывести текст – название весовой категории.
"""
n = int(input())
print("Легкий вес" if n < 60 else "Первый полусредний вес" if 60 <= n < 64 else "Полусредний вес")
| false |
ec5e93dd759250bef6aa51d6e7cb1d855ac7cd3c | Deniska10K/stepik | /4.2-logical_operations/3.accessory_3.py | 621 | 4.21875 | 4 | """
Напишите программу, которая принимает целое число x и определяет, принадлежит ли данное число указанным промежуткам.
Формат входных данных
На вход программе подаётся целое число x.
Формат выходных данных
Программа должна вывести текст в соответствии с условием задачи.
"""
n = int(input())
print("Принадлежит" if -30 < n <= -2 or 7 < n <= 25 else "Не принадлежит")
| false |
39baba3140cfc6610e60228f6383c2ad3f3e2b6d | Deniska10K/stepik | /6.2-math_module/4.trigonometric_expression.py | 1,172 | 4.21875 | 4 | """
Напишите программу, вычисляющую значение тригонометрического выражения sin(x) + cos(x) + tan(x)^2 по заданному числу
градусов x.
Формат входных данных
На вход программе подается одно вещественное число x измеряемое в градусах.
Формат выходных данных
Программа должна вывести одно число – значение тригонометрического выражения.
Примечание 1. Тригонометрические функции принимают аргумент в радианах. Чтобы перевести градусы в радианы,
воспользуйтесь формулой r = (x * pi) / 180
Примечание 2. Модуль math содержит встроенную функцию radians(), которая переводит угол из градусов в угол в радианах.
"""
from math import sin, cos, tan, radians
x = radians(float(input()))
print(sin(x) + cos(x) + tan(x) ** 2)
| false |
52b709291cc74e7102018d71c409c4c2c0c104df | Deniska10K/stepik | /6.2-math_module/5.floor_and_ceiling.py | 653 | 4.34375 | 4 | """
Напишите программу, вычисляющую значение ⌈x⌉ и ⌊x⌋ по заданному вещественному числу x.
Формат входных данных
На вход программе подается одно вещественное число xxx.
Формат выходных данных
Программа должна вывести одно число – значение указанного выражения.
Примечание. ⌈x⌉ – потолок числа, ⌊x⌋ – пол числа.
"""
from math import ceil, floor
x = float(input())
print(ceil(x) + floor(x))
| false |
44d1a4c1b852cf467408fc42ed5c155bfb5439e9 | Deniska10K/stepik | /6.1-numeric_data_types_int_float/3.reverse_number.py | 877 | 4.375 | 4 | """
Напишите программу, которая считывает с клавиатуры одно число и выводит обратное ему. Если при этом введённое с
клавиатуры число – ноль, то вывести «Обратного числа не существует» (без кавычек).
Формат входных данных
На вход программе подается одно действительное число.
Формат выходных данных
Программа должна вывести действительное число обратное данному, либо текст в соответствии с условием задачи.
"""
n = float(input())
if n == 0:
print("Обратного числа не существует")
else:
print(n ** -1)
| false |
510de01b1b80cc1684faaf2441dd5154bdd52b7c | zaydalameddine/Breast-Cancer-Classifier | /breastCancerClassifier.py | 1,959 | 4.125 | 4 | # importing a binary database from sklearn
from sklearn.datasets import load_breast_cancer
# importing the splitting function
from sklearn.model_selection import train_test_split
# importing the KNeighborsClassifier
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
# loading the databse into that variable
breast_cancer_data = load_breast_cancer()
# get a better understanding of the database
print(breast_cancer_data.target, breast_cancer_data.target_names)
# split data into 80%training and 20% testing sets
breast_cancer_train, breast_cancer_test, target_train, target_test = train_test_split(breast_cancer_data.data, breast_cancer_data.target, test_size = 0.2, random_state = 100)
# printing the len of the data to make sure that the data is the same len as its adjoining labels
print(len(breast_cancer_train), len(breast_cancer_test), len(target_train), len(target_test))
highest_accuracy = 0
index = 0
# finding the best k value using a loop from 1 - 100
for k in range(1, 101):
# creating and training the classifier model
classifier = KNeighborsClassifier(n_neighbors = k)
classifier.fit(breast_cancer_train, target_train)
accuracy = 0
# testing model against test sets and checking if score is higher than previous k
if classifier.score(breast_cancer_test, target_test) > highest_accuracy:
highest_accuracy = classifier.score(breast_cancer_test, target_test)
index = k
#make a model using the best k value and predict the label for the test set
classifier = KNeighborsClassifier(n_neighbors = index)
classifier.fit(breast_cancer_train, target_train)
guesses = classifier.predict(breast_cancer_test.data)
#while not a great graph ot shows that the data is mostly right which is also displayed by the 0.965 R^2 value
plt.scatter(guesses, target_test.data, alpha = 0.1)
plt.xlabel("Classification Guess")
plt.ylabel("Clasification Label")
plt.title("Breast Cancer Classifier")
plt.show() | true |
b0a6d7b51978c4ed6691bc4542e63d63f90fc36a | mirandaday16/intent_chatbot | /formatting.py | 301 | 4.25 | 4 |
# Capitalizes the first letter of every word in a string, e.g. for city names
# Parameters: a place name (string) entered by the user
def cap_first_letters(phrase):
phrase_list = [word[0].upper() + word[1:] for word in phrase.split()]
cap_phrase = " ".join(phrase_list)
return cap_phrase | true |
adc452c82b5e6a0346987e640bcd8364578e0ac6 | MLBott/python-fundamentals-student | /A1/243 assignment 1 Michael Bottom.py | 1,909 | 4.125 | 4 | """
Author: Michael Bottom
Date: 1/14/2019
"""
import math
def lowestNumListSum(firstList, secondList):
"""
This function accepts two lists of numbers and returns the sum of the lowest
numbers from each list.
"""
firstList.sort()
secondList.sort()
sumTwoLowest = firstList[0] + secondList[0]
return sumTwoLowest
def lastNumListAvg(primaryList, secondaryList):
"""
This function accepts two lists of numbers and returns the average of the last
number in each list.
"""
primaryList.sort()
secondaryList.sort()
avgTwoLowest = (primaryList[-1] + secondaryList[-1]) / 2
return avgTwoLowest
def pythagoreanResult(sideOne, sideTwo):
"""
This function accepts two non-hypotenuse side length values of a triangle and returns
the length value of the hypotenuse
"""
sideThree = math.sqrt(sideOne**2 + sideTwo**2)
return sideThree
def lowMidAvg():
"""
This function asks the user to enter three integers, creates a list out of them, and
returns a message for the hightest, lowest, and average numbers of the list.
"""
myList = []
myList.append(int(input("Enter the 1st number: ")))
myList.append(int(input("Enter the 2nd number: ")))
myList.append(int(input("Enter the 3rd number: ")))
myList.sort()
sumList = sum(myList)
avgList = sumList/len(myList)
highestNmbr = "The highest number is: " + str(max(myList)) + "\n"
lowestNmbr = "The lowest number is: " + str(min(myList)) + "\n"
avgNmbr = "The average is: " + str(avgList)
return print(highestNmbr + lowestNmbr + avgNmbr)
def stringConcat(theStringList):
"""
This function accepts a list of strings and returns a single string that is a string
concatenation of the entire list.
"""
swapString = ""
for item in theStringList:
swapString += item
return swapString
help(str.split) | true |
993fc1680d80170a6ddbc8464baae21aa1215c8d | sritar99/Ds-n-algos | /queue.py | 820 | 4.21875 | 4 | #Implementing queue's in python
from exc import Empty
class ArrayQueue:
def __init__(self):
self._data=[]
self._front=0
self._rear=0
def length(self):
return len(self._data)
def is_empty(self):
return self._front and self._rear == 0
def enque(self,n):
self._data.append(n)
self._rear+=1
def deque(self):
if self.is_empty():
raise Empty("Queue is Empty!")
pass
val=self._data[self._front]
self._data[self._front]=None
self._front+=1
return val
def display(self):
print "Queue: ",self._data
print "length: ",len(self._data)
q=ArrayQueue()
q.enque(1)
q.enque(2)
q.enque(3)
q.enque(4)
q.enque(5)
q.display()
print(q.deque())
q.display()
print(q.deque())
q.display()
print(q.deque())
q.display()
print(q.deque())
q.display()
print(q.deque())
q.display()
print(q.length()) | false |
93542a99082c9944497ae78bf2f4589d6985e56c | adithyagonti/pythoncode | /factorial.py | 260 | 4.25 | 4 | num=int(input('enter the value'))
if num<0:
print('no factorial for _ve numbers')
elif num==0:
print('the factorial of 0 is 1')
else:
fact=1
for i in range(1,num+1):
fact= fact*i
print("the factorial of", num,"is",fact)
| true |
b6456f6c87553fab9af92919b1505a90bf675ad8 | geediegram/parsel_tongue | /ozioma/sleep_schedule.py | 651 | 4.15625 | 4 | # Ann inputs the excepted hours of sleep, the excess no of hours and no of sleep hours
# First number is always lesser than the second number
# If sleep hour is less than first number, display "Deficiency"
# If sleep hour is greater than second number, display "Excess"
# If sleep hour is greater than sleep hour and lesser than excess no of hours, display "Normal"
#
print('Enter the required no of sleep hours.')
a = int(input())
b = int(input())
if a < b:
h = int(input())
if h < a:
print('Deficiency!')
elif h > b:
print('Excess!')
elif a < h < b:
print('Normal!')
else:
print('Inputs are not valid')
| true |
2edfabb63a04e58a1987cb9935140691549c1911 | geediegram/parsel_tongue | /goodnew/main.py | 1,443 | 4.46875 | 4 | from functions import exercise
if __name__ == "__main__":
print("""
Kindly choose any of the options to select the operation to perform
1. max_of_three_numbers
2. sum_of_numbers_in_a_list
3. product_of_numbers_in_a_list
4. reverse-string
5. factorial_of_number
6. check_if_a_number-falls_in_the_range
7. check_the_number_of_upper_case_and_lower_case_letters
8. list_of_unique_number
9. write_the_number_number_of_even_number_in_a_list
10.prime_number
""")
user_input = int(input("Kindly select your desired function\n"))
if user_input == 1:
exercise.max_of_three_numbers()
if user_input == 2:
exercise.sum_of_numbers_in_a_list()
if user_input == 3:
exercise.product_of_numbers_in_a_list()
if user_input == 4:
exercise.reverse_a_string()
if user_input == 5:
exercise.factorial_of_a_number()
if user_input == 6:
exercise.check_whether_a_number_falls_in_a_given_range()
if user_input == 7:
exercise.calculate_number_of_uppercase_and_lowercase_letters()
if user_input == 8:
exercise.list_with_unique_element_of_the_first_list([1,2,3,2,1,2,1,1,5,6,1])
if user_input == 9:
exercise.prime_numbers()
if user_input == 10:
exercise.even_number([8, 9, 80, 23, 12])
| true |
9874493316bff21ba4af60b6e245ff793ff65eaf | geediegram/parsel_tongue | /precious/if_elif_else/triangle.py | 425 | 4.34375 | 4 | print("the triangle is valid" if int(input()) + int(input()) + int(input()) == 180 else "invalid triangle")
triangle_angle_one = int(input("Enter first angle \n"))
triangle_angle_two = int(input("Enter second angle \n"))
triangle_angle_three = int(input("Enter third angle \n"))
if triangle_angle_one + triangle_angle_two + triangle_angle_three == 180:
print("the triangle is valid")
else:
print("invalid triangle")
| false |
3d87c8c63add0168a40d51dcc7258dfb2f733b23 | geediegram/parsel_tongue | /solomon/weird_numbers.py | 216 | 4.21875 | 4 | number = int(input("Enter number: "))
if number % 2 == 0 and number > 20 or 2 <= number <= 6:
print("Not weird")
else:
print("Weird")
# if (number % 2 == 0 and number >= 6 and number <= 20):
# print("Weird")
| false |
5f24adb4960ef8fbe41b5659321ef59c1143d2b1 | geediegram/parsel_tongue | /Emmanuel/main.py | 877 | 4.28125 | 4 | from functions import exercise
if __name__== "__main__":
print("""
1. Check for maximum number
2. Sum of numbers in a list
3. Multiple of numbers in a list
4. Reverse strings
5. Factorial of number
6. Number in given range
7. String counter
8. List unique elements
""")
user_input= int(input("Choose which function you wish to make use of:"))
if user_input == 1:
print(exercise.max_of_three_numbers())
elif user_input == 2:
exercise.sum_of_a_list()
elif user_input == 3:
exercise.multiply_numbers_in_a_list()
elif user_input == 4:
print(exercise.reverse_string())
elif user_input == 5:
print(exercise.factorial())
elif user_input == 6:
exercise.number_fall_in_a_given_range()
elif user_input == 7:
exercise.string_counter()
else:
print(exercise.list_unique_elements())
| true |
6e456e8a3206d57ab9041c2cbc00013701ed3345 | geediegram/parsel_tongue | /ozioma/positive_and_negative_integer.py | 363 | 4.5625 | 5 | # take a number as input
# if the number is less than 0, print "Negative!"
# if the number is greater than 0, print "Positive!"
# if the number is equal to 0, print "Zero!"
print('Enter a value: ')
integer_value = int(input())
if integer_value < 0:
print('Negative!')
elif integer_value > 0:
print('Positive!')
elif integer_value == 0:
print('Zero!') | true |
4dfbf66266a20143fc1f3ef6095dbe11b995f3e3 | victorkwak/Projects | /Personal/FizzBuzz.py | 884 | 4.1875 | 4 | # So I heard about this problem while browsing the Internet and how it's notorious for stumping like 99%
# of programmers during interviews. I thought I would try my hand at it. After looking up the specifics,
# I found that FizzBuzz is actually a children's game.
#
# From Wikipedia: Fizz buzz is a group word game for children to teach them about division.[1] Players take
# turns to count incrementally, replacing any number divisible by three with the word "fizz", and any number
# divisible by five with the word "buzz".
#
# The programming problem seems to have added the additional condition of saying "FizzBuzz" if the number
# is divisible by both 3 and 5.
for i in range(1, 101):
if i % 15 == 0: # equivalent to i % 3 == 0 and i % 5 == 0
print "FizzBuzz"
if i % 3 == 0:
print "Fizz"
if i % 5 == 0:
print "Buzz"
else:
print i | true |
b05ab548d4bb352e48135c2a0afd2a4a6251e9ea | whencespence/python | /unit-2/homework/hw-3.py | 282 | 4.25 | 4 | # Write a program that will calculate the number of spaces in the following string: 'Python Programming at General Assembly is Awesome!!'
string = 'Python Programming at General Assembly is Awesome!!'
spaces = 0
for letter in string:
if letter == ' ':
spaces += 1
print(spaces) | true |
67e2747d9d16e1b2ba8137c0d96fc1419a75868e | aryanicosa/praxis-academy | /praxis-academy/novice/05-01/latihan/latihan-serialization.py | 1,396 | 4.21875 | 4 | # serialization, merubah data ke format yang dapat disimpan/dibagikan.
# memungkinkan untuk dikembalikan kembali (deserialization)
# serialization process in python called "pickling"
# dengan pickling kita dapat mengkonversi tingkatan object ke binary format dan dapat disimpan
# contoh
import pickle
class Animal():
def __init__(self, number_of_paws, color):
self.number_of_paws = number_of_paws
self.color = color
class Sheep(Animal):
def __init__(self, color):
Animal.__init__(self, 4, color)
#step 1 create sheep Mary
mary = Sheep("white")
#print(str.format("My sheep mary is {0} and has {1} paws", mary.color, mary.number_of_paws))
# step 2 : pickle Mary
my_pickled_mary = pickle.dumps(mary) # pickling data
'''
# cek data hasil pickling
print("Would you like to see her pickled? Here she is!")
print(my_pickled_mary) # cetak data yang sudah di pickling
'''
'''
# membuat sebuah file binary
binary_file = open('my_pickled_mary.bin', mode='wb')
my_pickled_mary = pickle.dump(mary, binary_file) # akan digunakan untuk cetak file binary
binary_file.close()
'''
# step 3 unpickle Mary and create new instance from clone/pickled data
dolly = pickle.loads(my_pickled_mary)
# create color for dolly to divers with mary
dolly.color = "black"
# step 4, cek hasil
print(str.format("Dolly is {0} ", dolly.color))
print(str.format("Mary is {0} ", mary.color)) | false |
cfeb8cd2427bfac3c448c16eb217e3d01152d005 | bm7at/wd1_2018 | /python_00200_inputs_loops_lists_dicts/example_00920_list_methods_exercise.py | 336 | 4.34375 | 4 | # create an empty list called planets
# append the planet "earth" to this list
# print your list
planet_list = []
# append
planet_list.append("earth")
print planet_list # [1, 2, 3, 4, 5]
# now extend your planets list
# with the planets: "venus", "mars"
# print your list
planet_list.extend(["venus", "mars"])
print planet_list
| true |
c76237f309750c23a148929b45f08b7a34cac668 | jloiola6/cursos | /Alura/Python/Python para Data Science/Python para Data Science Funções, Pacotes e Pandas básico/1.py | 734 | 4.125 | 4 | import pandas as pd # Pandas só esta funcionando na versão 3.6 do python
# pd.set_option('display.max_rows', 100) # Declaramso o numero maximo de linha que sera mostrado
# pd.set_option('display.max_columns', 10) # Declaramso o numero maximo de colunas que serão mostrado
dataset = pd.read_csv('Python_Data_Science\Pandas\data\db.csv', sep= ';') # Fazendo a leitura de um arquivo .csv e declarando um separador
print(dataset)
print(dataset.dtypes) # Descobrir os tipos de dados associado em cada coluna
print(dataset[['Quilometragem', 'Valor']].describe()) # Aqui obtemos um conjunto de destatísticas descritivas dessas variáveis que foram passadas
print(dataset.info) # Adquirie informações sobre a colunas de dados aceitos | false |
863a49bc96fdd2a69ed681d50b83032818e32c05 | hyeonjiseon/introduction-to-software | /coffeereview.py | 1,645 | 4.25 | 4 | #커피샵의 고객 마족도 점 수를 관리하는 프로그램을 사전 리스트를 사용하여 만든다.
#커피샵의 평점을 입력받아 사전에 저장하고 탐색, 삭제하는 프로그램
def print_menu():
print('1. Show all coffeeshop review')
print('2. Add coffee shop review')
print('3. Delete coffeeshop review')
print('4. Search coffeeshop')
print('5. Exit')
def show_review(reviews):
print()
print('Coffee Shop Review')
print()
print('Store \t\t Grade ')
print('='*30)
for store in reviews:
print(store, ' \t ', reviews[store])
print('='*30)
print()
def add_review(reviews):
print("Add new review")
store = input("Store:")
grade = float(input("Grade [1...5] :"))
while (grade < 1 or grade > 5):
print("enter your grade between 1..5")
grade = float(input("Grade [1...5] :"))
reviews[store] = grade
show_review(reviews)
def delete_review(reviews):
print("Delete Store data ")
store = input("Store:")
if store in reviews:
del reviews[store]
show_review(reviews)
def search_store(reviews):
print("Search store review")
store = input("Store:")
if store in reviews:
print(store, " : ", reviews[store])
else:
print(store, " is not found")
reviews = {}
choice = 0
print_menu()
while True:
menu = int(input())
if menu == 1:
show_review(reviews)
elif menu == 2:
add_review(reviews)
elif menu == 3:
delete_review(reviews)
elif menu == 4:
search_store(reviews)
if menu == 5:
break
print_menu()
| false |
dfc679815218037a7d1926ad153c23875d61dd64 | Mwai-jnr/Py_Trials | /class_01/l28.py | 735 | 4.34375 | 4 | #if statements
## start
name = "victor"
if name == "victor":
print("you are welcome")
else:
print('you are not welcome')
# example 2
age = '15'
if age <= '17':
print("you are under age")
else:
print("you can visit the site")
# example 3
# two if statements
age = '17'
if age <='17':
print('you are under age')
if age >= '13' and age < '20':
print('you are a teenager')
else:
print('you can visit the site')
#example 4
age = '20'
if age <='17':
print('you are under age')
if age >= '13' and age < '18':
print('you are a teenager')
else:
if age >= '19' and age < '35':
print("you are an older guy ")
print('you can visit the site') | true |
66948e9a7ce8e8114d8a492300d48506a2e4c30b | Mwai-jnr/Py_Trials | /class_01/L37.py | 854 | 4.46875 | 4 | # Loops.
# For Loop.
#Example 1
#for x in range (0,10):
# print('hello')
#Example 2
#print(list(range(10,20)))
# the last no is not included when looping through a list
#Example 3
#for x in range(0,5):
# print('Hello %s' % x)
# %s acts as a placeholder in strings
#it is used when you want to insert something in a string in our case numbers 0-5.
# while loop
#Example 1
password = 'victor'
enter_pass = ''
pass_count = 0
pass_limit = 3
pass_out_limit = False
while enter_pass != 'victor' and not (pass_out_limit):
if pass_count < pass_limit:
enter_pass = input('Enter Password: ')
pass_count += 1
else:
pass_out_limit = True
if enter_pass == 'victor':
print('welcome to the site')
else:
print('try again later')
| true |
6bbe9e80f879c703b375b52b8e8b3ca5ea16b9f5 | deepakkmr896/nearest_prime_number | /Nearby_Prime.py | 998 | 4.1875 | 4 | input_val = int(input("Input a value\n")) # Get the input from the entered number
nearestPrimeNum = [];
# Define a function to check the prime number
def isPrime(num):
isPrime = True
for i in range(2, (num // 2) + 1):
if(num % i == 0):
isPrime = False
return isPrime
# Assuming 10 as the maximum gap between the successive prime number
for i in range(1, 11):
precVal = input_val - i;
forwVal = input_val + i;
# Check both the preceding and succeeding number for the prime and capture whichever is found first or both (e.g. 3 and 5 for 7)
if (precVal > 1):
if (isPrime(precVal) == True):
nearestPrimeNum.append(precVal)
if (isPrime(forwVal) == True):
nearestPrimeNum.append(forwVal)
if (len(nearestPrimeNum) > 0):
break
if (len(nearestPrimeNum) > 0):
print("Nearest prime no/nos is: {}".format(' and '.join(map(str, nearestPrimeNum))))
else:
print("There is no prime number exists nearby")
| true |
a9067a7adee78d3a72e2cd379d743dd360ed2795 | joelamajors/TreehouseCourses | /Python/Learn Python/2 Collections/4 Tuples/intro_to_tuples.py | 578 | 4.5625 | 5 | my_tuple = (1, 2, 3)
# tuple created
my_second_tuple = 1, 2, 3
# this is a tuple too
# the commas are necesary!
my_third_tuple = (5)
# not a tuple
my_third_tuple = (5,)
# parenthesis are not necessary, but helpful.
dir(my_tuple)
# will give you all the stuff you can do. Not much!
# you can edit _stuff_ within a tuple, but you can't edit the tuple
tuple_with_a_list = (1, "apple", [3, 4, 5])
# can't change [0], [1]. ints and strings are immutable.
# strings are mutable
tuple_with_a_list[2][1] = 7
# gives a list of
[3, 7, 5]
# but you can't remove the list itself!
| true |
8824bf993e2383393d16357e6a318fd27e8e0525 | joelamajors/TreehouseCourses | /Python/Learn Python/2 Collections/5 Sets/set_math_challenge.py | 2,248 | 4.4375 | 4 | # Challenge Task 1 of 2
# Let's write some functions to explore set math a bit more.
# We're going to be using this
# COURSES
# dict in all of the examples.
# _Don't change it, though!_
# So, first, write a function named
# covers
# that accepts a single parameter, a set of topics.
# Have the function return a list of courses from
# COURSES
# where the supplied set and the course's value (also a set) overlap.
# For example,
# covers({"Python"})
# would return
# ["Python Basics"].
COURSES = {
"Python Basics": {"Python", "functions", "variables",
"booleans", "integers", "floats",
"arrays", "strings", "exceptions",
"conditions", "input", "loops"},
"Java Basics": {"Java", "strings", "variables",
"input", "exceptions", "integers",
"booleans", "loops"},
"PHP Basics": {"PHP", "variables", "conditions",
"integers", "floats", "strings",
"booleans", "HTML"},
"Ruby Basics": {"Ruby", "strings", "floats",
"integers", "conditions",
"functions", "input"}
}
# below did not work
# def covers(set_of_topics):
# list_of_courses = []
# for value in COURSES:
# list_of_courses.append(value)
# return list_of_courses
def covers(set_of_topics):
# had to get help
list_of_courses = []
for key, value in COURSES.items():
if value & set_of_topics:
list_of_courses.append(key)
return list_of_courses
# CHALLENGE 2 of 2
# Great work!
# OK, let's create something a bit more refined.
# Create a new function named
# covers_all
# that takes a single set as an argument.
# Return the names of all of the courses, in a list,
# where all of the topics in the supplied set are covered.
# For example,
# covers_all({"conditions", "input"})
# would return
# ["Python Basics", "Ruby Basics"].
# Java Basics and PHP Basics would be exclude because they
# don't include both of those topics
def covers_all(set_of_topics):
course_list = []
for course, value in COURSES.items():
if (set_of_topics & value) == set_of_topics:
course_list.append(course)
return course_list
| true |
135b08e8fbbf31e611e7c8e0e3f0abb4c83f1c71 | Nick-Nch/gb_1lesson_task | /task-1.py | 245 | 4.125 | 4 | a = 'Hello!'
first_name = input('Введите ваше имя:')
last_name = input('Введи вашу фамилию: ')
age = input('Введите ваш возраст: ')
print(a + ' ' + first_name + ' ' + last_name + ' ' + str(age)) | false |
e0dc49212a72b8f58ba69c192bf48e41718d93c5 | brian-sherman/Python | /C859 Intro to Python/Challenges/11 Modules/11_9 Extra Practice/Task1.py | 434 | 4.21875 | 4 | """
Complete the function that takes an integer as input and returns the factorial of that integer
from math import factorial
def calculate(x):
# Student code goes here
print(calculate(3)) #expected outcome: 6
print(calculate(9)) #expected outcome: 362880
"""
from math import factorial
def calculate(x):
f = factorial(x)
return f
print(calculate(3)) #expected outcome: 6
print(calculate(9)) #expected outcome: 362880 | true |
4b775221b8af334d4b2f8b9af0c64ecd2d3c9724 | brian-sherman/Python | /C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_5_1_Multiplication_Table.py | 548 | 4.25 | 4 | """
Print the two-dimensional list mult_table by row and column.
Hint: Use nested loops.
Sample output for the given program:
1 | 2 | 3
2 | 4 | 6
3 | 6 | 9
"""
mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]
for row in mult_table:
for element in row:
list_len = len(row)
current_idx = row.index(element)
list_end = list_len - current_idx
if list_end != 1:
next_idx = current_idx + 1
print(element, end=' | ')
else:
print(element, end='')
print() | true |
fd3d0f0a14900b339535fc94ef21b59619ba66e1 | brian-sherman/Python | /C859 Intro to Python/Challenges/06 Loops/6_8_2_Histogram.py | 797 | 4.96875 | 5 | """
Here is a nested loop example that graphically depicts an integer's magnitude by using asterisks,
creating what is commonly called a histogram:
Run the program below and observe the output.
Modify the program to print one asterisk per 5 units.
So if the user enters 40, print 8 asterisks.
num = 0
while num >= 0:
num = int(input('Enter an integer (negative to quit):\n'))
if num >= 0:
print('Depicted graphically:')
for i in range(num):
print('*', end=' ')
print('\n')
print('Goodbye.')
"""
num = 0
while num >= 0:
num = int(input('Enter an integer (negative to quit):\n'))
if num >= 0:
print('Depicted graphically:')
for i in range(0, num, 5):
print('*', end=' ')
print('\n')
print('Goodbye.') | true |
6da6609432fd57bc89e4097da96dcd60e80cb94c | brian-sherman/Python | /C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_15_1_Nested_Dictionaries.py | 2,843 | 4.96875 | 5 | """
The following example demonstrates a program that uses 3 levels of nested dictionaries to create a simple music library.
The following program uses nested dictionaries to store a small music library.
Extend the program such that a user can add artists, albums, and songs to the library.
First, add a command that adds an artist name to the music dictionary.
Then add commands for adding albums and songs.
Take care to check that an artist exists in the dictionary before adding an album, and that an album exists before adding a song.
"""
music = {
'Pink Floyd': {
'The Dark Side of the Moon': {
'songs': [ 'Speak to Me', 'Breathe', 'On the Run', 'Money'],
'year': 1973,
'platinum': True
},
'The Wall': {
'songs': [ 'Another Brick in the Wall', 'Mother', 'Hey you'],
'year': 1979,
'platinum': True
}
},
'Justin Bieber': {
'My World':{
'songs': ['One Time', 'Bigger', 'Love Me'],
'year': 2010,
'platinum': True
}
}
}
def menu():
print('Select an option from the menu below')
print('0: Quit')
print('1: Add an artist')
print('2: Add an album')
print('3: Add a song')
print('4: Print music')
def add_artist(artist):
music[artist] = {}
print(artist, 'has been added')
def add_album(artist,album):
music[artist][album] = []
print(album, 'has been added')
def add_song(artist,album,song):
music[artist][album].append(song)
print(song, 'has been added')
while True:
menu()
selection = input()
if selection == '0':
break
if selection == '1':
artist = input('Enter an artist\'s name to add: ')
if artist in music:
print(artist, 'already exists')
else:
add_artist(artist)
elif selection == '2':
artist = input('Enter the artist\'s name: ')
album = input('Enter the album name: ')
if artist not in music:
add_artist(artist)
add_album(artist,album)
elif album not in music[artist]:
add_album(artist,album)
else:
print(album, 'already exists')
elif selection == '3':
artist = input('Enter the artist\'s name: ')
album = input('Enter the album name: ')
song = input('Enter the song name: ')
if artist not in music:
add_artist(artist)
add_album(artist,album)
add_song(artist,album,song)
elif album not in music[artist]:
add_album(artist,album)
add_song(artist,album,song)
elif song not in music[artist][album]:
add_song(artist,album,song)
else:
print(song, 'already exists')
elif selection == '4':
print(music)
| true |
ffd50de6b5a8965a8b34db611bd115d2939df135 | brian-sherman/Python | /C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_3_1_Iteration.py | 1,068 | 4.4375 | 4 | """
Here is another example computing the sum of a list of integers.
Note that the code is somewhat different than the code computing the max even value.
For computing the sum, the program initializes a variable sum to 0,
then simply adds the current iteration's list element value to that sum.
Run the program below and observe the output.
Next, modify the program to calculate the following:
Compute the average, as well as the sum.
Hint: You don't actually have to change the loop, but rather change the printed value.
Print each number that is greater than 21.
"""
# User inputs string w/ numbers: '203 12 5 800 -10'
user_input = input('Enter numbers: ')
tokens = user_input.split() # Split into separate strings
# Convert strings to integers
print()
nums = []
for pos, token in enumerate(tokens):
nums.append(int(token))
print('%d: %s' % (pos, token))
sum = 0
count = 0
for num in nums:
sum += num
count += 1
if num > 21:
print('Greater than 21:', num)
average = sum / count
print('Sum:', sum)
print('Average:', average)
| true |
f1b2c6a2815b2621cab190582196521ec04da9e2 | brian-sherman/Python | /C859 Intro to Python/Challenges/07 Functions/7_17_1_Gas_Volume.py | 678 | 4.375 | 4 | """
Define a function compute_gas_volume that returns the volume of a gas given parameters
pressure, temperature, and moles.
Use the gas equation PV = nRT,
where P is pressure in Pascals,
V is volume in cubic meters,
n is number of moles,
R is the gas constant 8.3144621 ( J / (mol*K)), and
T is temperature in Kelvin.
"""
gas_const = 8.3144621
def compute_gas_volume(pressure, temperature, moles):
volume = (moles * gas_const * temperature) / pressure
return volume
gas_pressure = 100.0
gas_moles = 1.0
gas_temperature = 273.0
gas_volume = 0.0
gas_volume = compute_gas_volume(gas_pressure, gas_temperature, gas_moles)
print('Gas volume:', gas_volume, 'm^3') | true |
0c123a95902de5efa3ecb815f22a3d242e376623 | brian-sherman/Python | /C859 Intro to Python/Challenges/06 Loops/6_4_2_Print_Output_Using_Counter.py | 330 | 4.46875 | 4 | """
Retype and run, note incorrect behavior. Then fix errors in the code, which should print num_stars asterisks.
while num_printed != num_stars:
print('*')
Sample output for the correct program when num_stars is 3:
*
*
*
"""
num_stars = 3
num_printed = 0
while num_printed != num_stars:
print('*')
num_printed += 1
| true |
de8809d34f4bd91b00fb0b56d2835b3464c6ce3a | brian-sherman/Python | /C859 Intro to Python/Challenges/08 Strings/8_4_5_Area_Code.py | 256 | 4.21875 | 4 | """
Assign number_segments with phone_number split by the hyphens.
Sample output from given program:
Area code: 977
"""
phone_number = '977-555-3221'
number_segments = phone_number.split('-')
area_code = number_segments[0]
print('Area code:', area_code) | true |
2f13722b0bd4d477768080b375bdd904af9da065 | brian-sherman/Python | /C859 Intro to Python/Challenges/08 Strings/8_6 Additional Practice/Task_2_Reverse.py | 294 | 4.21875 | 4 | # Complete the function to return the last X number of characters
# in the given string
def getLast(mystring, x):
str_x = mystring[-x:]
return str_x
# expected output: IT
print(getLast('WGU College of IT', 2))
# expected output: College of IT
print(getLast('WGU College of IT', 13)) | true |
0416f7bd9af4ef2845a77eb966ab0a21afd7fd64 | brian-sherman/Python | /C859 Intro to Python/Boot Camp/Week 1/2_Calculator.py | 1,871 | 4.4375 | 4 | """
2. Basic Arithmetic Example:
Write a simple calculator program that prints the following menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
The user selects the number of the desired operation from the menu. Prompt the user to enter two numbers and
return the calculation result.
Example One:
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Select 1, 2, 3, 4, or 5: 1
Enter the first number: 4
Enter the second number: 5
The Sum of 4 and 5 is: 9
Example Two:
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Select 1, 2, 3, 4, or 5: 5
GoodBye
"""
while True:
print("Please select operation -")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
selection = input("Select 1, 2, 3, 4, or 5: ")
if selection == '5':
print("GoodBye")
break
elif selection == '1' or selection == '2' or selection == '3' or selection == '4':
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if selection == '1':
sum = num1 + num2
print("The Sum of %d and %d is: %d" % (num1, num2, sum))
elif selection == '2':
difference = num1 - num2
print("The difference of %d and %d is: %d" % (num1, num2, difference))
elif selection == '3':
product = num1 * num2
print("The product of %d and %d is: %d" % (num1, num2, product))
elif selection == '4':
quotient = num1 / num2
print("The product of %d and %d is: %d" % (num1, num2, quotient))
else:
print("Sorry I didn't understand that. Please select an option from the menu.")
| true |
444195237db2c8f053a44b172038335f9d02567e | brian-sherman/Python | /C859 Intro to Python/Challenges/06 Loops/6_8_1_Print_Rectangle.py | 256 | 4.5 | 4 | """
Write nested loops to print a rectangle. Sample output for given program:
* * *
* * *
"""
num_rows = 2
num_cols = 3
for row in range(num_rows):
print('*', end=' ')
for column in range(num_cols - 1):
print('*', end=' ')
print('') | true |
3cf756ebdd38a6a5ff233af1ba998c12f7ed1fa3 | brian-sherman/Python | /C859 Intro to Python/Boot Camp/Week 1/8_Tuple_Example.py | 534 | 4.625 | 5 | """
8. Tuple Example:
Read a tuple from user as input and print another tuple with the first and last item,
and your name in the middle.
For example, if the input tuple is ("this", "is", "input", "tuple"), the return value should be
("this", "Rabor", "tuple")
Example One:
Enter your name to append into the tuple: Rabor
Expected Result: ('this', 'Rabor', 'tuple')
"""
string = input("Enter a tuple seperated by spaces: ")
name = input("Enter your name: ")
list = string.split()
new_t = (list[0], name, list[-1])
print(new_t) | true |
68150df94d2940bb980649e15c56a07194cb59fb | imharrisonlin/Runestone-Data-Structures-and-Algorithms | /Algorithms/Sorting/Quick_Sort.py | 2,138 | 4.21875 | 4 | # Quick sort
# Uses devide and conquer similar to merge sort
# while not using additional storage compared to merge sort (creating left and right half of the list)
# It is possible that the list may not be divided in half
# Recursive call on quicksortHelper
# Base case: first < last (if len(list) <= 1 list is sorted)
#
# The partition function occurs at the middle it will be O(logn) divisions
# Finding the splitpoint requires n items to be checked
# O(nlogn) on average
# Worst case: the split may be skewed to the left or the right
# resulting in dividing the list into 0 items and n-1 items
# the overhead of the recursion required
# O(n^2) time complexity
# ----------------------------------------------------------------------------------------------------------
# Can eleviate the potential of worst case uneven division
# by using different ways of choosing the pivot value (ex. median of three)
# Median of three: consider first, middle, and last element in the list
# pick the median value and use it for the pivot value
def quickSort(nlist):
quickSortHelper(nlist, 0, len(nlist)-1)
def quickSortHelper(nlist, first, last):
if first < last:
splitpoint = partition(nlist, first, last)
quickSortHelper(nlist,first,splitpoint-1)
quickSortHelper(nlist,splitpoint+1,last)
def partition(nlist,first,last):
pivotValue = nlist[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and nlist[leftmark] < pivotValue:
leftmark = leftmark + 1
while nlist[rightmark] > pivotValue and rightmark >= leftmark:
rightmark = rightmark - 1
if rightmark < leftmark:
done = True
else:
temp = nlist[leftmark]
nlist[leftmark] = nlist[rightmark]
nlist[rightmark] = temp
temp = nlist[first]
nlist[first] = nlist[rightmark]
nlist[rightmark] = temp
return rightmark
alist = [54,26,93,17,77,31,44,55,20]
quickSort(alist)
print(alist)
print(partition.__doc__) | true |
47a4339979a4787b4e44cb5e6ff519033bbfe2e3 | avkramarov/gb_python | /lesson 5/Задание 1.py | 600 | 4.25 | 4 | # Создать программно файл в текстовом формате, записать в него построчно данные,
# вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка.
lines = []
new_item = input("Введите значение >>>")
while new_item != "":
lines.append(new_item)
new_item = input("Введите значение >>>")
with open(r"Задание 1.txt", "w") as my_file:
for line in lines:
my_file.write(line + '\n')
| false |
b18daeacb7de198085e4064b05755f63a49bb040 | avkramarov/gb_python | /lesson 4/Задание 7.py | 866 | 4.25 | 4 | # Реализовать генератор с помощью функции с ключевым словом yield,
# создающим очередное значение.
# При вызове функции должен создаваться объект-генератор.
# Функция должна вызываться следующим образом: for el in fact(n).
# Функция отвечает за получение факториала числа,
# а в цикле необходимо выводить только первые n чисел, начиная с 1! и до n!.
def fact(n):
step = 1
for i in range(1, n + 1):
step *= i
yield step
n = int(input("Укажите факториал какого числа Вы хотели бы узнать?"))
for el in fact(n):
print(el)
| false |
ce1e57eb3168263137047a967c2223b65017ec89 | kzmorales92/Level-2 | /M3P2a.py | 250 | 4.3125 | 4 | #Karen Morales
# 04/22/19
#Mod 3.2b
#Write a recursive function to reverse a list.
fruitList = ["apples", "bananas", "oranges", "pears"]
def reverse (lst) :
return [ lst[-1]]+ reverse (lst[:-1]) if lst else []
print (reverse(fruitList))
| true |
85d986e6a42307635cd237b666f0724a27537b16 | claudiogar/learningPython | /problems/ctci/e3_5_sortStack.py | 1,024 | 4.15625 | 4 | # CTCI 3.5: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure. The stack supports the following operations: push, pop, peek, and isEmpty.
class SortedStack:
def __init__(self):
self.stack = []
self.side = []
pass
def push(self, e):
if self.isEmpty():
self.stack.append(e)
pass
p = self.peek()
while p < e:
v = self.pop()
self.side.push(v)
p = self.peek()
self.stack.append(e)
while len(self.side) > 0:
v = self.side.pop()
self.stack.push(v)
def pop(self):
if len(self.stack) > 0:
return self.pop()
return None
def peek(self):
if len(self.stack) == 0:
return None
return self.stack[-1]
def isEmpty(self):
return len(self.stack) == 0 | true |
86fccf5df89eb49af7ab1b269cc9696fe2254291 | nanareyes/CicloUno-Python | /Condicionales/ejercicio6-otraversion_condicional.py | 1,045 | 4.1875 | 4 | '''
Elabora un algoritmo que permita ingresar el monto de la venta alcanzada por un vendedor durante un mes,
se debe calcular la bonificación (%) que tiene derecho de acuerdo a la siguiente tabla:
0 - 1000.000 Bonificación 0
1.000.100 - 2.500.000 Bonificacion 0.04
2.500.100 o más Bonificación 0.08
Imprimir venta realizada en el mes y la bonificación obtenida
'''
'''
ALGORITMO
Inicio
Entradas: el valor de las ventas alcanzadas
Salidas: Valor de la bonificación y Ventas realizadas
Proceso : Valor de la bonificación * Ventas realizadas
'''
print("\n")
ventas = int(input("Digite las ventas del mes: "))
print("\n")
def bonificacion_ventas(mes):
if (ventas <= 1000000):
bono = (ventas * 0)
else:
if (ventas <= 2500000):
bono= (ventas * 0.04)
else:
bono = (ventas * 0.08)
return bono
resultado= bonificacion_ventas(ventas)
print("El valor de las ventas mensuales es: $",ventas)
print ("La bonificacion es: $ %.0f"% resultado)
print("\n")
| false |
3c110c3201336c827c7f7d5809ab36e98696d2b9 | nanareyes/CicloUno-Python | /FuncionesParaColeccionesDatos/ejercicioClase.py | 674 | 4.15625 | 4 | """
1. Crear una función que determine el equipo de futbol, cuyo nombre inicie con la letra “T”, utilizar la función map para iterar en la lista equipos.
equipos = ["América", "Millonarios", "Tolima", "Cali", "Junior"]
Generar una lista de resultado que indique con true los nombres que inicien con
la letra “T” y false para los que no cumplan la condición.
La lista generada es la siguiente:
[False, False, True, False, False]
"""
equipos = ["America", "Millonarios", "Tolima", "Cali", "Junior"]
def nombre_equipo(x):
if x[0] == "T":
return True
else:
return False
result = list(map(nombre_equipo, equipos))
print(result)
| false |
09db9780bc26c56191551748452edf5b31cc3cda | nanareyes/CicloUno-Python | /Nivelacion_1/condicionales_nivelacion.py | 1,375 | 4.3125 | 4 | # Para los condicionales utilizo comparadores de decisión
'''
En los diagramas de flujo el condicional se expresa en rombo
utiliza comparadores de decisión (> < == !=) y operadores lógicos ( y(and) o(or) no(not))
'''
'''
Se necesita saber si el estudiante tuvo alto, medio o bajo rendimiento
[0;3) Rendimiento bajo
[3;4) Rendimiento medio
[4,5] Rendimiento alto
[] el numero va incluido
() No está inclído el número
'''
# if en secuencia
def notas(nota1, nota2, nota3):
promedio = round((nota1 + nota2 + nota3)/3,2)
maximo = max(nota1, nota2,nota3)
minimo = min(nota1,nota2,nota3)
if promedio >= 0 and promedio < 3: # La condición se expresa con variables y operadores ( y siempre debo tener presente lo que voy a comparar)
rendimiento = 'Bajo'
if promedio >= 3 and promedio < 4:
rendimiento = 'Medio'
if promedio >= 4 and promedio <= 5:
rendimiento = 'Alto'
return f'El estudiante tiene una nota promedio de {promedio}, su mayor nota fue {maximo}, su menor nota fue {minimo}, y su rendimiento fue {rendimiento}'
print(notas(3.5,4,4.6)) # con el print llamo la función y coloco los parámetros
print(notas(4,5,5))
print(notas(3,2,1))
print(notas(3,4, 3.6))
# Depuración y ejecución, permite hacer un seguimiento al programa
# buscar como depura
# tambien se puede usar el else entre cada if
| false |
ffebce985975962495b6698d90e759783f4daa5f | nanareyes/CicloUno-Python | /FuncionesParaColeccionesDatos/funciones_anonimas_FilterLambda.py | 1,167 | 4.65625 | 5 | # FUNCIONES ANONIMAS
"""
Habrá ocasiones en las cuales necesitemos crear funciones de manera rápida, en tiempo de ejecución.
Funciones, las cuales realizan una tarea en concreto, regularmente pequeña.
En estos casos haremos uso de funciones lambda.
-------------------------------------------------
lambda argumento : cuerpo de la función
==================================================================
Las expresiones lambda se usan idealmente cuando necesitamos hacer algo simple y estamos más interesados en hacer el trabajo rápidamente en lugar
de nombrar formalmente la función. Las expresiones lambda también se conocen como funciones anónimas.
Las expresiones lambda en Python son una forma corta de declarar funciones pequeñas y anónimas (no es necesario proporcionar un nombre para las funciones
lambda).
==================================================================
"""
def menores_10(numero):
return numero <= 10
lista: list = [1, 2, 3, 4, 8, 9, 10, 11, 12, 14, 15, 16]
# La función de arriba se puede abreviar con lambda de la siguiente forma:
print(list(filter(lambda numero: True if numero <= 10 else False, lista)))
| false |
4bb4253b47123e8791aa1b674881f30da6a4f03c | kongruksiamza/PythonBeginner | /Phase2/EP39.Assignment3.py | 491 | 4.125 | 4 | # Assignment หากลุ่มเลขคู่ / เลขคี่
number=[]
odd=[] #เลขคี่
even=[] #เลขคู่
while True:
x=int(input("ป้อนตัวเลขของคุณ :"))
if x<0:
break
if x%2 == 0:
even.append(x)
else :
odd.append(x)
number.append(x)
print("ตัวเลขทั้งหมด =>" ,number)
print("เลขคู่ => ",even)
print("เลขคี่ => ",odd) | false |
4e9dcaa32b8662fb64d27faa933a01d47cc0caf8 | Harjacober/HackerrankSolvedProblems | /Python/Regex Substitution.py | 311 | 4.15625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import re
def substitution(string):
string = re.sub(r'((?<=\s)&&(?=\s))','and', string)
string = re.sub(r'(?<=\s)\|\|(?=\s)','or', string)
return string
N = int(input())
for i in range(N):
print(substitution(input()))
| true |
45063d790455032ec43c9407c1e71b4453845f5d | adityarsingh/python-blockchain | /backend/util/cryptohash.py | 799 | 4.15625 | 4 | import hashlib #it is library that includes the sha256 function
import json
def crypto_hash(*args):
"""
This function will return SHA-256 hash of the given arguments.
"""
stringed_args = sorted(map(lambda data: json.dumps(data),args)) #Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.
joined_data = ''.join(stringed_args)
return hashlib.sha256(joined_data.encode('utf-8')).hexdigest() #here only encoded data can be hashed so we are encoding it into utf-8
def main():
print(f"crypto_hash(one ,2, 3): {crypto_hash('test',2,3)}")
print(f"crypto_hash(2 ,one, 3): {crypto_hash(2,'test',3)}")
if __name__=='__main__':
main() | true |
968e67c487bc93767de11e74957b8af63e716fe9 | vjishnu/python_101 | /quadratic.py | 591 | 4.15625 | 4 | from math import sqrt #import sqrt function from math
a = int(input("Enter the 1st coifficient")) # read from user
b = int(input("Enter the 2st coifficient")) # read from user
c = int(input("Enter the 3st coifficient")) # read from user
disc = b**2 - 4*a*c # to find the discriminent
disc1 = sqrt(disc)# thn find the square root of discriminent
# in a quadratic equation there are postive and negative solution
post = (-b+disc1) /(2*a) # postive solution
neg = (-b-disc1) / (2*a) # negative solution
print("The postive solution is {} and the negative solution {}".format(post,neg))
| true |
fd7b805579cf158999eebd8cb269c0de1f288b80 | lucasgcb/daily | /challenges/Mai-19-19/Python/solution.py | 815 | 4.15625 | 4 | def number_finder(number_list):
"""
This finds the missing integer using 2O(n) if you count the set operation.
"""
numbers = list(set(number_list)) ## Order the list
# Performance of set is O(n)
# https://www.oreilly.com/library/view/high-performance-python/9781449361747/ch04.html
expected_in_seq = None
# We go through the list again. 2*O(n)
for i in range(0,len(numbers)):
expected_in_seq = numbers[i] + 1
## Check if we are at the end of the list.
try:
next_in_seq = numbers[i+1]
except IndexError:
# Return the next positive expected in sequence if we are.
return 0 if numbers[i] < 0 else expected_in_seq
if expected_in_seq != next_in_seq:
return expected_in_seq
| true |
9fbf85740e7f3aa9f1e438ff0a51c5939294dac4 | Meenawati/competitive-programming | /dict_in_list.py | 522 | 4.40625 | 4 | # Write a Python program to check if all dictionaries in a list are empty or not
def dict_in_list(lst):
for d in lst:
if type(d) is not dict:
print("All Elements of list are not dictionary")
return False
elif d:
return False
return True
print(dict_in_list([{}, {}, {}])) # returns True
print(dict_in_list([{}, {1, 2}, {}])) # prints All Elements of list are not dictionary and returns False
print(dict_in_list([{}, {1: 'one', 2: 'two'}, {}])) # returns False | true |
40d9f9e8e046e5b41d83213bbea3540365d123e0 | alfem/gamespit | /games/crazy-keys/__init__.py | 1,577 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf8 -*-
# Crazy Keys
# My son loves hitting my keyboard.
# So I made this silly program to show random colors on screen.
# And maybe he will learn the letters! :-)
# Author: Alfonso E.M. <alfonso@el-magnifico.org>
# License: Free (GPL2)
# Version: 1.0 - 8/Mar/2013
import random
from Game import Game
class Menu(Game):
def start(self):
self.vowels='aeiou'
def loop(self):
while True:
input_type=self.CONTROLLER.wait_for_user_action()
if input_type == "K": #Keyboard
char=self.CONTROLLER.key_name
if char == "escape": #quit game
break
elif char in self.vowels: #you hit a vowel!
self.SOUNDS['vowel'].play()
elif char.isdigit(): #you hit a number!
self.SOUNDS['number'].play()
elif len(char) == 1: #you hit a consonant!
self.SOUNDS['consonant'].play()
else: #you hit return, tab, or any other special key!
self.SOUNDS['other'].play()
bgcolor=(random.randint(0,255), random.randint(0,255),random.randint(0,255))
charcolor=(random.randint(0,255), random.randint(0,255),random.randint(0,255))
self.fill(bgcolor)
self.DISPLAY.print_textbox(char, self.FONTS["embosst1100"],self.COLORS["text"], self.COLORS["text_background"])
self.DISPLAY.show()
# Main
def main(name, CONF, DISPLAY, CONTROLLER):
menu=Menu(name, CONF,DISPLAY,CONTROLLER)
menu.start()
menu.loop()
| true |
e13468afe2fbfc7c8947e4caf735af756d18d6e6 | ymjrchx/myProject | /pythonStudy/python-demo/Day07/tuple.py | 613 | 4.375 | 4 | """
元组的定义和使用
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
t = ('骆昊', 38, True, '四川成都')
print(t)
print(t[0])
print(t[1])
print(t[2])
print(t[3])
for member in t:
print(member)
# t[0]='王大富'
t = ('王大锤', 20, True, '云南昆明')
print(t)
person = list(t)
print(person)
person[0] = '李小龙'
person[1] = 25
print(person)
fruits_list=['apple','banna',"oarange"]
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)
print(fruits_tuple[1])
if __name__ == '__main__':
main() | false |
28374d28e84a38789ce5810c2ffa642be798d855 | ymjrchx/myProject | /pythonStudy/python-demo/Day09/car2.py | 990 | 4.3125 | 4 | """
属性的使用
- 使用已有方法定义访问器/修改器/删除器
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
class Car(object):
def __init__(self, brand, max_speed):
self.set_brand(brand)
self.set_max_speed(max_speed)
def get_brand(self):
return self._brand
def set_brand(self, brand):
self._brand = brand
def get_max_speed(self):
return self._max_speed
def set_max_speed(self, max_speed):
if max_speed < 0:
raise ValueError('Invalid max speed for car')
self._max_speed = max_speed
def __str__(self):
return 'Car: [品牌=%s, 最高时速=%d]' % (self._brand, self._max_speed)
brand = property(get_brand,set_brand)
max_speed=property(get_max_speed,set_max_speed)
if __name__ == '__main__':
car = Car('QQ',120)
print(car)
car.max_speed=320
car.brand="Benz"
print(car)
print(Car.brand)
print(Car.brand.fget)
print(Car.brand.fset) | false |
da4199473308b99e312b5b542252423592417d85 | nabrink/DailyProgrammer | /challenge_218/challenge_218.py | 342 | 4.15625 | 4 | def to_palindromic(number, step):
if len(number) <= 1 or step > 1000 or is_palindromic(number):
return number
else:
return to_palindromic(str(int(number) + int(number[::-1])), step + 1)
def is_palindromic(number):
return number == number[::-1]
number = input("Enter a number: ")
print(to_palindromic(number, 0))
| true |
fc9ae2f27b799e6c605421e2c01cff6989be0fd5 | txazo/txazodevelop | /python/lession/Python-列表.py | 1,018 | 4.3125 | 4 | # ********************< 列表 >********************
list = [1, 2, 3, 4]
print type(list), list # <type 'list'> [1, 2, 3, 4]
# ********************< list函数 >********************
list = list("1234")
print type(list), list # <type 'list'> [1, 2, 3, 4]
# ********************< 列表元素赋值 >********************
list[0] = 1
# ********************< 删除列表元素 >********************
del list[0]
del list
# ********************< class list(object) >********************
list()
list(iterable)
append(object) # 列表末尾追加新的对象
count(value) # value在列表中出现的次数
extend(iterable) # 列表末尾追加新的列表
index(value, [start, [stop]]) # value在列表中第一次出现的位置
insert(index, object) # 在列表的index位置插入新的对象
pop([index]) # 移除列表中index位置的元素,并返回该元素
remove(value) # 移除列表中value的第一个匹配项
reverse() # 列表倒序
sort(cmp=None, key=None, reverse=False) # 排序列表
| false |
c1f4f21c908dd6c8862868a096e012b77301831e | Teclanat/Curso_Python | /21_Vetores.py | 346 | 4.125 | 4 | __author__ = 'Natanael'
#Trabalhando com Vetores
#Inicializando o vetor
vetor = []
n = int(input('Digite a quantidade de elementos a ser adicionada: '))
i = 0
while i < n:
temp = input('Digite o elemento a ser adicionado: ')
#Uso de append = adiciona um elemento no vetor
vetor.append(temp)
i = i + 1
print('Vetor = ',vetor)
| false |
5c5625cca2c934141df40410f1496302c699da06 | brasqo/pyp-w1-gw-language-detector | /language_detector/main.py | 846 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import defaultdict
import operator
"""This is the entry point of the program."""
def detect_language(text, languages):
"""Returns the detected language of given text."""
# implement your solution here
# create dictionary with same keys as languages
result_languages = defaultdict(int)
for word in text.split():
for lang in languages:
if word in lang['common_words']:
result_languages[lang['name']] += 1
#if so increase count for language
# for result in result_languages:
# if lang['name'] count save count number and name
result = max(result_languages, key=result_languages.get)
return result
# return name
| true |
3f115dc4d77c49f3827e26674bac162ae8613b57 | CodesterBoi/My-complete-works | /File Handling.py | 2,273 | 4.125 | 4 | '''
#Reading from a file:
car_name = input("Which car's stats do you want to display?")
t = open("Car_stats.txt","r")
end_of_file = False
print(car_name)
car_name = True
while True:
car_name = t.readline().strip()
speed = t.readline().strip()
acceleration = t.readline().strip()
handling = t.readline().strip()
nitro = t.readline().strip()
break
if bool(car_name):
print(car_name)
print("speed: ",speed)
print("acceleration: ",acceleration)
print("handling: ",handling)
print("nitro: ",nitro)
t.close()
'''
'''
#Appending from a file:
t = open("Car stats.txt","a")
car_name = input("Enter the name of your chosen car: ")
speed = input("Enter the value of the car's top speed: ")
acceleration = input("Enter the value of your car's acceleration: ")
handling = input("Enter the value of your car's handling: ")
nitro = input("Enter the value of your car's nitro: ")
print("car_name: "+car_name)
print("speed: "+speed)
print("acceleration: "+acceleration)
print("handling: "+handling)
print("nitro: "+nitro)
t.close()
'''
'''
#Writing from a file:
t = open("Car stats.txt","w")
car_name = input("Enter the name of your chosen car: ")
speed = input("Enter the value of the car's top speed: ")
acceleration = input("Enter the value of your car's acceleration: ")
handling = input("Enter the value of your car's handling: ")
nitro = input("Enter the value of your car's nitro: ")
print("car_name: "+car_name)
print("speed: "+speed)
print("acceleration: "+acceleration)
print("handling: "+handling)
print("nitro: "+nitro)
t.close()
'''
'''
#Overwriting a file.
filecontent = open(Car_stats.txt,"w")
filecontent.write("I solemnly swear that these stats are true.")
filecontent.close()
filecontent = open(Car_stats.txt, "r")
print(filecontent.read())
'''
'''
#Creating a file from scratch.
f = open("Python Mechanics.py", "x")
'''
'''
#Current Working Directory and creating a new folder.
import os
curDir = os.getcwd()
print(curDir)
os.mkdir('Asphalt9')
'''
'''
#Deleting a file
import os
if os.path.exists("12 days of christmas.txt"):
os.remove("12 days of christmas.txt")
else:
print("This file doesn't exist.")
'''
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.