blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e9a4e032b838bc88c312fa530eb8a6a8d2787589 | dom-0/python | /RandomCode/passwd.py | 584 | 3.515625 | 4 | with open("/etc/passwd", 'r') as passwd:
string = passwd.read()
print(string[0:2])
print('-=' * 40)
with open("/etc/passwd", 'r') as passwd:
string = passwd.readlines()
print(string[0:2])
print('-=' * 40)
with open("/etc/passwd", 'r') as passwd:
string = passwd.readline()
print(string[0:2], flush=True)
... |
3f7913c2fe0b7be07cd2d9e963d24e94965d6871 | dom-0/python | /PyFlow/ifprogramflow.py | 238 | 4.25 | 4 | name = input("Please enter your name: ")
age = int(input("How old are you, {0}? ".format(name)))
if age >= 18:
print("You are old enough to vote")
elif age < 18:
print("Please wait for another {0} years to vote".format(18 - age)) |
e884be2ed00a2a3314d30e9bbd0bbc26656e90c2 | dom-0/python | /Challenges/fibo.py | 249 | 3.859375 | 4 |
temp = 0
initial = 0
second = 1
listofnumbers= []
listofnumbers.append(initial)
listofnumbers.append(second)
for i in range(0, 28):
temp = initial + second
initial, second = second, temp
listofnumbers.append(temp)
print(listofnumbers) |
99dbb7ea7ad608ddc38c9105cd81633e97397553 | dom-0/python | /Jammer/cavemap.py | 951 | 3.984375 | 4 | place = {0: "You are sitting in front of a computer",
1: "You are on a dark deserted road",
2: "You are on top of a hill",
3: "You are in front of a huge glass building",
4: "You landed up in a valley",
5: "You are in a dense forest"}
exits = [{"Q": 0},
{"W": 2, "E... |
5ffd29ee8c44f092510bd320fd431df80f4f1b2a | dom-0/python | /oldstuff/mod_username.py | 561 | 3.59375 | 4 | class User(object):
import json
"""User data"""
def __init__(self, **more):
for key, value in more.items():
self.fname = key
self.lname = value
self.fullname = self.fname + " " + self.lname
def storeuser (self, filename="../files/userfile.txt"):
with open (filename, 'w') as FWH:
self.json... |
a19cafa6b7d1561c29220b1f5a6eacea4169ad20 | dom-0/python | /ohwell/pic.py | 388 | 3.78125 | 4 | #!/usr/bin/env python3
import pickle
file_Name = "dict.txt"
# open the file for writing
fileObject = open(file_Name,'r')
# load the object from the file into var b
b = fileObject.read()
fileObject.close()
print(b)
with open ("./dict1.txt", "wb") as fwrite:
pickle.dump(b,fwrite)
with open ("./dict1.txt", "rb"... |
f440953129f547d5c693b9165a57fea51a7c9a53 | dom-0/python | /random/iterator1.py | 93 | 3.734375 | 4 | arr = [1, 2, 3, 4]
my_iter = iter(arr)
for i in range(0, len(arr)):
print(next(my_iter)) |
3c11a8a94314699c1e3ace14c68b4ce454a40762 | dom-0/python | /Straplez/Quotes.py | 439 | 3.859375 | 4 | # greeting = "Hello"
# name = input ('Enter your name please ')
#
# print (greeting + ' ' + name)
splitString = "This string\nhas been split\nover several lines"
print (splitString)
anotherSplitString = """This string \
has been
split over
several lines"""
print (anotherSplitString)
print ('''There is a "quote" and... |
4895085d3121675ccb71c5b752f367eef404bdc7 | dom-0/python | /Challenges/tosolve1.py | 942 | 3.703125 | 4 |
names = ["Luis", "Hector", "Selena", "Emmanuel", "Amish"]
cyclicnames = {}
startwith = ""
depth = 1
for i in range(len(names)):
for j in range(len(names)):
if i == j:
continue
if names[i][-1].lower() == names[j][0].lower():
cyclicnames[names[i]] = names[j]
break... |
b64a11ea82ae6cd710b04bcb20cbdb8a23335fad | mikeleppane/AlgoExpert | /smallest_difference.py | 1,143 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List
def absolute_difference(num1: int, num2: int) -> int:
return abs(num1 - num2)
def smallest_difference(array_one: List[int], array_two: List[int]):
array_one.sort()
array_two.sort()
array_one_index = 0
array_two_index = 0
... |
165f1528107db3755327bdbe05cec79777ae4a27 | mikeleppane/AlgoExpert | /nth_fibonacci.py | 273 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List
def getNthFib(n: int):
if n == 1:
return 0
if n == 2:
return 1
return sum([getNthFib(n-1), getNthFib(n-2)])
if __name__ == "__main__":
n = 8
print(getNthFib(n))
|
f6098cf1ed77e3ec67aec8bd5507db4d441229a6 | mikeleppane/AlgoExpert | /depth_first_search.py | 1,082 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List
class Node:
def __init__(self, name):
self.children: List[Node] = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return self
def depthFirstSearch(self, array: List[str]... |
296a23aa58ffffa16c393e72300b064232310b21 | mikeleppane/AlgoExpert | /levenshtein_distance.py | 783 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List
def levenshteinDistance(str1: str, str2: str):
chars_1 = list(str1)
chars_2 = list(str2)
edits = 0
if not chars_1:
return len(chars_2)
if not chars_2:
return len(chars_1)
for index, char in enumerate(chars_... |
199d2ca82042e346eab502382cc2ef50e5273693 | zuosc/PythonCode | /OOP/ooptest.py | 356 | 3.796875 | 4 | # !/usr/bin/env python3
# _*_ coding:utf8 _*_
'oop demo'
__author__ = 'zuosc'
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
bart = Student('Bart', 59)
lisa = Stud... |
da4094381e8985f3dc08f682d428c6afdd816491 | Abdulrahman2k/udacity-project | /Project/audit.py | 4,364 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This the first program used for cleaning of Data, we are cleaning following values
a. Names with unexpected Values
b. Phone Number in proper Syntax
"""
import xml.etree.cElementTree as ET
from collections import defaultdict
import re
import pprint
##from sets i... |
5210abaa5b4d39e50f7761d19209503d15585e11 | ErenBtrk/PythonDictionaryExercises | /Exercise12.py | 188 | 4.3125 | 4 | '''
12. Write a Python program to remove a key from a dictionary.
'''
my_dict = {"ali":1,"veli":2,"isa":3,"musa":4}
key = input("Please enter a key : ")
del my_dict[key]
print(my_dict) |
6258638b9c51b8141d51fe91279f56e729151b39 | ErenBtrk/PythonDictionaryExercises | /Exercise11.py | 200 | 4.21875 | 4 | '''
11. Write a Python program to multiply all the items in a dictionary
'''
my_dict = {'data1':5,'data2':-5,'data3':3}
total = 1
for key,value in my_dict.items():
total *= value
print(total) |
bfd33fcb08e152a31b8e18e4c3eee9b09f3379f0 | Priyanshu729/hacktoberfest-2020 | /python/even_odd.py | 241 | 4.40625 | 4 | # Function to check if a number is even or odd
def even_odd(x):
# Todo: Code to determine & print even or odd
if(x % 2 == 0):
print("The number is Even")
else:
print("The number is Odd")
even_odd(5)
even_odd(6)
|
5745d050a0e7eabcedeaa0fbf6794fd14e20f863 | SmasterZheng/leetcode | /力扣刷题/217存在重复元素.py | 584 | 4.09375 | 4 | """
217 简单
给定一个整数数组,判断是否存在重复元素。
如果任意- -值在数组中出现至少两次,函数返回true。如果数组中每个元素都不相同,则返回false。
示例1:
输入: [1,2,3,1]输出: true
示例2:
输入: [1,2,3,4]输出: false
示例3:
输入: [1,1,1,3,3,4,3,2,4,2]输出: true
"""
def repeat(listdata):
"""思路:
利用set函数去重,对比列表长度
"""
return False if len(set(listdata))==len(listdata) else True
... |
d701744e6acb309d8ec4aefeec2bbb345710c379 | SmasterZheng/leetcode | /力扣刷题/1365有多少小于当前数字的数字.py | 1,613 | 3.90625 | 4 | """给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。
换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。
以数组形式返回答案。
示例 1:
输入:nums = [8,1,2,2,3]
输出:[4,0,1,1,3]
解释:
对于 nums[0]=8 存在四个比它小的数字:(1,2,2 和 3)。
对于 nums[1]=1 不存在比它小的数字。
对于 nums[2]=2 存在一个比它小的数字:(1)。
对于 nums[3]=2 存在一个比它小的数字:(1)。
对于 nums[4]=3 存在三个比它... |
f099f118568cd674e8b09081aa6ad148c322d755 | SmasterZheng/leetcode | /Tencent/合并两个有序数组.py | 729 | 4.28125 | 4 | """
给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
"""
class Solution:
def merge(self, nums1 , m, nums2, n):
... |
050a28d46cb0e4198e2fc40f91aa91914930dd1d | SmasterZheng/leetcode | /work/返回月末.py | 913 | 3.953125 | 4 | """
输入一个日期,判断它和月中的一个日期,然后大于等于的话则返回月末,小于则正常输出
如:月中的日期为'20200516'
输入:'20200512'
输出:'20200512'
输入:'20200518'
输出:'20200531'
"""
import datetime
import calendar
class Solution:
def get_the_last_month_day(self, date,ndate):
'''
:param date: 输入日期
:param ndate: 指定月中的日期
:return: 月末
... |
a04fb2dbf08fbe15d2798d0d716c24e9d4b3b0a5 | SmasterZheng/leetcode | /力扣刷题/5428重新排列数组.py | 945 | 4.28125 | 4 | """
给你一个数组 nums ,数组中有 2n 个元素,按 [x1,x2,...,xn,y1,y2,...,yn] 的格式排列。
请你将数组按 [x1,y1,x2,y2,...,xn,yn] 格式重新排列,返回重排后的数组。
示例 1:
输入:nums = [2,5,1,3,4,7], n = 3
输出:[2,3,5,4,1,7]
解释:由于 x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 ,所以答案为 [2,3,5,4,1,7]
示例 2:
输入:nums = [1,2,3,4,4,3,2,1], n = 4
输出:[1,4,2,3,3,2,4,1]
示例 3:
输入:nums = [1,1... |
e51a392fd298c7c02b2f70a9f1e76e2d940a1ee6 | gagigante/Python-exercises | /List 02/07.py | 594 | 3.90625 | 4 | # Faça um programa para calcular e exibir a valor dos juros de um empréstimo bancário, conforme o valor emprestado e o número de parcelas digitado pelo usuário (incluindo centavos – cuidado com o uso do tipo de dados correto).
value = float(input('Digite o valor do empréstimo ').replace(',', '.'))
installmentQtt = int... |
b3af159653819c630ba489efb751b4a284293f92 | gagigante/Python-exercises | /List 03/05.py | 178 | 3.828125 | 4 | # Faça um programa que apresente os quadrados de números inteiros existentes na faixa de valores de 15 a 200
for i in range(15, 201):
print(f'O quadrado de {i} é {i ** 2}') |
dbffdd2f4215c5a8e72a6c1bb7322ec3d2d66565 | gagigante/Python-exercises | /List 05/06.py | 1,173 | 4.28125 | 4 | # Questão 6. Elabore um programa que utilize uma função que converta da
# notação de 24 horas para a notação de 12 horas. Por exemplo, o programa
# deve converter 14:25 em 2:25 P.M. A entrada é dada em dois inteiros.
# Deve haver pelo menos duas funções: uma para fazer a conversão e uma
# para a saída. Registre a i... |
2ca5ebaf713e1edd9cd1163b3ddf5e7bd024f061 | gagigante/Python-exercises | /List 01/10.py | 633 | 3.71875 | 4 | # Pedro comprou um saco de ração com peso em quilos.
# Pedro possui dois gatos para os quais fornece a quantidade de ração em gramas.
# Faça um programa que receba o peso do saco de ração e a quantidade de ração fornecida para cada gato.
# Calcule e mostre quanto restará de ração no saco após cinco dias.
SackWeight... |
513326a7ea0fe09b4bc7a173dcbd9e8d7822108a | gagigante/Python-exercises | /List 02/16.py | 440 | 3.921875 | 4 | # Dado um ano d.C. (depois de Cristo), identifique se este é um ano bissexto ou não.
# Considere que para o ano ser bissexto basta que seja divisível por 400.
# Caso contrário, este precisará ser divisível por 4 e não ser divisível por 100.
value = int(input('Digite um ano '))
if value % 400 == 0 or (value % 4 == 0... |
b91789fab9aedbda81a7d7126a2f8f1ec1507cef | gagigante/Python-exercises | /List 03/11.py | 163 | 3.703125 | 4 | # Faça um algoritmo que apresente todos os valores numéricos divisíveis por 4 e menores que 200.
i = 1
while i <= 200:
if i % 4 == 0:
print(i)
i += 1
|
ade853e50347020d9e3ecb44757f36b437ac248d | gagigante/Python-exercises | /List 02/19.py | 348 | 4.0625 | 4 | # Efetuar a leitura de um valor numérico inteiro positivo ou negativo representado pela variável
# N e apresentar o valor lido como sendo positivo. Dica: se o valor lido for menor que zero,
# o mesmo deve ser multiplicado por -1.
number = int(input('Digite um valor '))
if number < 0:
number = number * -1
print(f... |
13b5b82aa953e5c513d73738a26cad01889e395b | gagigante/Python-exercises | /List 04/08.py | 259 | 4.21875 | 4 | # Elabore um programa que efetue a leitura de quinze números inteiros,
# adicione-os a uma data e mostre-a de forma invertida, do último para o primeiro.
data = []
for i in range(15):
data.append(int(input('Adicione um número: ')))
print(data[::-1]) |
5999d12a57f4863d7b6278cac35de99dbf8a37a0 | gagigante/Python-exercises | /List 05/09.py | 251 | 4.21875 | 4 | # Questão 9. Elabore um programa que utilize uma função que retorne
# o reverso de um número inteiro informado. Por exemplo: 127 -> 721.
def reverse(number):
print(str(number)[::-1])
number = int(input('Digite um número: '))
reverse(number) |
33a53191f4f2820af611886125f7fcc53a6c9f69 | gagigante/Python-exercises | /List 02/03.py | 645 | 3.90625 | 4 | # Faça um programa para calcular e exibir a valor do imposto de ICMS de um produto, conforme a classificação do tipo de produto e do valor de custo do mesmo digitado pelo usuário (incluindo centavos – cuidado com o uso do tipo de dados correto).
value = float(input('Digite o valor do produto ').replace(',', '.'))
prod... |
24fa8cb110e3d71c77084b68d8fa95aa54888756 | gagigante/Python-exercises | /List 02/02.py | 611 | 3.84375 | 4 | # Faça um programa para calcular e exibir a porcentagem de comissão de vendas de um vendedor, conforme o volume mensal de vendas do mesmo digitado pelo usuário (incluindo centavos – cuidado com o uso do tipo de dados correto).
salesValue = float(input('Digite o salesValue de vendas ').replace(',', '.'))
if salesValue... |
f35857e5dd4628e86d9ca2715c4a2d4a5e41ea59 | Jiaoma/fileStr | /traverseMultiList.py | 709 | 4.1875 | 4 | '''
Traverse a multi-list is a recurrence problem, and is widely needed in python world, in order to simplify it, I write
some method here. In the future, I will create more methods that can be applied to more data structure to meet the
demand in developing deep learning method
'''
def search_multi_list(source,target)... |
14d7b22bb670cb96f2e9b19d944be00aca7f5365 | stan-andrei/python_upskilling | /exercices/assessment1/part4/practice2.py | 638 | 4.28125 | 4 | import random
'''
Write a Python program to guess a number between 1 to 9.
User is prompted to enter a guess.
If the user guesses wrong then the prompt appears again until the guess is correct,
on successful guess, user will get a "Well guessed!" message, and the program will exit.
'''
if __name__ == "__main__":
... |
e9e3df790e58eb8d2a709cea9fa2f0b66d23bd45 | stan-andrei/python_upskilling | /exercices/assessment1/part5/practice2.py | 674 | 4.25 | 4 |
'''
Create a program that computes the sum of all float and integer numbers from a list.
The given list contains other data types as well: strings, tuples, list of lists, etc.
(e.g: at least one list element from each data type + combinations
(e.g: one element with list of numbers))
'''
if __name__ == "__main__":
... |
4cd8c5415079df9786d4a89442cfb211ee8ea550 | bgreni/CMPUT403Sols | /Week2/grandpa_bernie.py | 1,158 | 3.6875 | 4 | import sys
"""
Brian Grenier
1545276
bgrenier
List any resources you used below (eg. urls, name of the algorithm from our code archive).
Remember, you are permitted to get help with general concepts about algorithms
and problem solving, but you are not permitted to hunt down solutions to
these particular... |
c39c59115c27c754beb58a680e17a748f9b32da2 | bgreni/CMPUT403Sols | /Week5/getshorty.py | 1,711 | 3.625 | 4 | """
Brian Grenier
1545276
bgrenier
List any resources you used below (eg. urls, name of the algorithm from our code archive).
Remember, you are permitted to get help with general concepts about algorithms
and problem solving, but you are not permitted to hunt down solutions to
these particular problems!
... |
57b45754a9431046158e8e122e02442ddf64df16 | dpmald/euler | /euler4.py | 488 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
i = 0;
for a in xrange(999,100,-1):
for b in xrange(a,100,-1):
... |
52d058580dc4f6b2ca50da136f191ad374318b1c | yzw1102/study_python | /partone/test11.py | 583 | 4.125 | 4 | # 1.
# for char in 'iterator':
# print(char,end = ' | ')
# 2.
# list1 = [1,2,3,4,5]
# for num in list1:
# print(num,end = ' | ')
# 3.
# dict1 = {'name':'ye','age':20}
# for key in dict1:
# print(key,end = ' | ')
#
# for value in dict1.values():
# print(value,end = ' | ')
# 4.
# list1 = [(1,'a'),(2,... |
8dcebff8e77cd05ed52ee648adc82788910039de | yzw1102/study_python | /partone/test2.py | 1,107 | 3.828125 | 4 | # 1.
# list1 = ['a','b','c',123]
# print(list1[0])
# print(list1[0:2])
# print(list1[0:])
# print(list1[:2])
# print(list1)
# list1[2] = 456
# print(list1)
# list1.append(789)
# print(list1)
# del(list1[4])
# print(list1)
# 2.
# list1 = ['a','b','c',123]
# print(list1)
# print(len(list1))
# list2 = ['d','e','f',456]
#... |
b668d29096563112db9bbe2fb4adc91d5dcac26e | yzw1102/study_python | /partsix/TestQueue.py | 528 | 3.5 | 4 | from queue import Queue
from threading import Thread
import time
isRead = True
def write(q):
for value in ['ye1','ye2','ye3']:
print('the value write in queue is : {0} '.format(value))
q.put(value)
time.sleep(1)
def read(q):
while isRead:
value = q.get(True)
print('the... |
c42fc0ec5ad8e683cfea8305dcb274fccb3f4e1e | luanloose/branch-and-bound | /aestrela.py | 6,701 | 3.5 | 4 | # -*- coding: utf8 -*-
# Este código implementa a busca A* para o exemplo da seção
# "3.5.2: A* search", do livro "Artificial Intelligence: A Modern
# Approach", 4ª edição, de Russell e Norvig (pág. 103-107). Neste
# exemplo utiliza-se o A* para encontrar o caminho ótimo entre as
# cidades de Arad e Bucareste (na verd... |
fb7f23bdb7ff18c9777b67cb6b00b550d03d13ff | alisonbelow/closed_loop_robot_sim | /sim/src/pose.py | 751 | 3.96875 | 4 | """
Defines simple Pose class (3D coord) to be used for sim
"""
class Pose():
def __init__(self, x = 0.0, y = 0.0, z = 0.0):
self.x = x
self.y = y
self.z = z
# Define basic operators for Pose
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.... |
d624d8f8b043aa4b92bd411b5a01cf1aa4f48e0f | Notinfrequently/python2021 | /omd/omd.py | 3,191 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class Game:
def __init__(self, start_step):
self.start_step = start_step
def start(self):
step = self.start_step.next_step()
while step is not None:
step = step.next_step()
class GameStep:
def __init__(self, question, next_steps, description='')... |
a655513d29da4b9b5e41b64e4d8cf033bbfdcfb4 | lyunardo/lpthw | /ex6.py | 745 | 4.15625 | 4 | types_of_people = 10
# this variable is a string that accepts a variable
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
# string inside of a string twice
y = f"Those who know {binary} and those who {do_not}"
print(x)
print(y)
# string inside of a string
# 'f' allows you to pas... |
4f8f14d84e448983b3f6b0c25d90d3d527830c37 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Introdução à programação com python/Exercícicios/Exercício 5.5.py | 104 | 3.78125 | 4 | x = 0
mult = 1
while x < 9:
print('{:2}º - {}'.format(x+1, mult))
mult = mult * 3
x = x + 1 |
4ec052523006785d08d1ae9d049e04cba56a8898 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Curso em Vídeo/7.6 - Desafio 008.py | 496 | 4.28125 | 4 | #Desafio 8 - Converter de m para cm e mm
medidam = float(input("Digite um valor em metros: "))
print(
'{:.2f} m = \n'
'[{:.5f} km]\n'
'[{:.2f} hm]\n'
'[{:.2f} dam]\n'
'[{:.0f} dm]\n'
'[{:.0f} cm]\n'
'[{:.0f} mm]\n'
.format(
medidam,
medidam / 1000,
... |
d182ec60500710e45d07fb38fa579094bf8cec64 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Curso em Vídeo/8.4 - Desafio 017.py | 302 | 3.84375 | 4 | #calcular hipotenusa dado cateto oposto e adjacente
import math
catOposto = float(input('Cateto oposto: '))
catAdjacente = float(input('Cateto adjacente: '))
hipotenusa = math.sqrt(math.pow(catOposto, 2) + math.pow(catAdjacente, 2))
print("Hipostenusa vale {}".format(hipotenusa))
#a² + b² = c² |
146252a0131f714661e56b018b2484a1f8019364 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Curso em Vídeo/5-Soma.py | 391 | 3.921875 | 4 | #Entrada de dados e soma
##Para strings o recomendado são as aspas simples
###N1 e N2 não tem tipo primitivo, são interpretados como strings
n1 = input('Digite um número: ')
n2 = input('Digite outro número: ')
print(type(n1))
print(type(n2))
###Convertendo para float
sum = float(n1) + float(n2)
print(type(sum))
... |
32b4ff7d49a4cdf5e5cd96a97e50208c3f4f8d15 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Introdução à programação com python/Exercícicios/Exercício 3.14.py | 228 | 3.671875 | 4 | percorrido = float(input("Km percorridos: "))
diasAlugado = int(input("Dias alugados: "))
print("Carro percorreu {}km durante {}dia(s) \nTotal a pagar R${}".format(percorrido, diasAlugado, 60 * diasAlugado + 0.15 * percorrido)) |
a90d79756c9758821e94eb71e7119c0597125875 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Resolução de problemas II/oo.py | 1,187 | 3.6875 | 4 | '''
class <NomeDaClasse>:
"""Descição da classe""" # acessada por print NomeDaClasse__.doc__
CONSTRUTOR
def __init__(self):
"""..."""
...
Time.__init__.__doc__
Atributos começando com _, indica que não devem ser acessados diretamente
self._hour = 0
pois existe setHour(...):
... |
401dd73f2d8443b7c7d07720e3e97f8ae08fb5e1 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Curso em Vídeo/9.4 - Desafio 025.py | 165 | 4.0625 | 4 | #Pessoa possui silva no nome?
findWord = 'Silva'
nome = str(input('Seu nome: '))
print('Possui "{}" no nome? : {}'.format(findWord, nome.find(findWord) >= 0)) |
c4782c5eee365757f5712fc9e14ba0bb9554e9e4 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Curso em Vídeo/10.4 - Desafio 28.py | 247 | 3.765625 | 4 | from random import randint
print('Pensando num número entre 0 e 5...')
num = randint(0, 5)
print('Pensei!')
tent = int(input('Tente advinhar: '))
if tent == num:
print('**** Acertou. ****')
else:
print('Perdeu, era {}'.format(num))
|
e853b7aa27b1b3ea01c1610d69112331944b0e0d | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Resolução de problemas II/liersDice/HumanPlayer.py | 1,612 | 3.734375 | 4 | from Player import *
from Dices import *
class HumanPlayer(Player):
def __init__(self):
"""Class player implements general methods to simulate a human player"""
self.playerType = Player.playerTypes[0]
self.playerID = 0
self.playerName = str(input('What\'s your name, player? '))
... |
863789a159ae47e193f5d9c9219f53ac384ba5f2 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Curso em Vídeo/8.3 - Desafio 016.py | 171 | 3.890625 | 4 | #ler número real e mostrar parte inteira
from math import trunc
num = float(input('Digite um número real: '))
print('Parte inteira de {} é {}'.format(num, trunc(num))) |
17280d847e8d39daf10072ba9d301f1b184c2f09 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Curso em Vídeo/7.5 - Desafio 007.py | 168 | 3.96875 | 4 | #Desafio 7 - Média
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
print('Média: {:.2f}'.format((nota1 + nota2)/2)) |
ec33629ab223e336818e7aa63b7bc489f1cabe15 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Resolução de problemas II/NumeroRacional.py | 5,286 | 3.703125 | 4 |
###########################################################
class Fracao:
def __init__(self, a = 0, b = 0):
self.num = a
self.den = b
def getNumerador(self):
return self.num
def getDenominador(self):
return self.den
def printAB(self):
print('{}/{} '.format(s... |
93d71a2f08c73e416fdf89e15b4d066345ead20e | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Resolução de problemas II/exCarlos drummond.py | 1,764 | 4.34375 | 4 | '''
• Contar quantas vezes aparece ‘amava’.
• Encontrar o primeiro e o último índice em que
aparece ‘amava’.
• Encontrar todos os índices em que aparece
‘amava’.
• Substituir ‘amava’ por ‘treinava’.
• Indique quais linhas começam com ‘que’.
'''
strOrig = '''João amava Teresa que amava Raimundo
que amava Maria que amav... |
3a3df51a70ea3c985f600ab9c4a636859a50f288 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Curso em Vídeo/6.2 - Desafio 003.py | 157 | 4.0625 | 4 | #Desafio 3
n1 = float(input('Digite um número: '))
n2 = float(input('Digite outro número: '))
sum = n1 + n2
print('{0} + {1} = {2}'.format(n1, n2, sum)) |
1571800fdbf889f5e746e7d16e53cc0c48c36389 | tcgoudoe/Vitenskapelige_beregninger | /Newtons_method_fixpoint_nice_and_tidy.py | 1,033 | 3.5 | 4 | import numpy as np
x0 = 0
tol = 1E-10
def type_of_iteraton(fN,fF, x0,tol, method):
NMAX = 100
assert tol>0
difference = 2*tol
xn = x0
iter = 0
print("iter x")
while difference>tol:
iter = iter+1
if method == "Newtons":
x = fN(xn)
... |
8ecf8798f351a9bf355f8cfdba2d93d646c52ca1 | danny2549/python_project | /rock, paper, scissors.py | 1,554 | 3.9375 | 4 | from random import randint
player = input("Player, make your move: ").lower()
random_number = randint(0,2)
#computer logic str----------------------------------
if random_number ==0:
computer ="rock"
elif random_number==1:
computer ="paper"
elif random_number==2:
computer ="scissors"
#computer logic end--... |
073c111138ec1aa5389483dfa1d1e6e2f1552782 | SanLatkar/codewayy_python_series | /Python-Task1/Marksheet.py | 1,649 | 4.3125 | 4 | # Declaring variables
# Personal Details
first_name = "Sanket"
middle_name = "Santosh"
last_name = "Latkar"
marks_Atharvaveda = 78
marks_Rigveda = 97
marks_Yajurveda = 91
marks_Samveda = 96
marks_Vedant = 84
#College Deatails
college_name = "Yeshwantrao Chavan College of Engineering"
college_address = "Wanadongri,Nagp... |
f3335ff13008aaf42c79ab6d728881b939d46471 | nicolas47360/chesstournament | /chesstournaments/views/homemenuview.py | 452 | 3.5625 | 4 | class HomeMenuView:
def __init__(self, menu):
self.menu = menu
def _display_menu(self):
print("\n-------PRÊT A GÉRER VOS TOURNOIS------\n")
for key, entry in self.menu.items():
print(f"{key}: {entry.option}")
def get_user_choice(self):
while True:
se... |
5283a0a94faf9d425792dd9f59a9ae356c1c6b72 | Kuval999/ML-AI | /Test 1/test1-1.py | 1,172 | 3.890625 | 4 | str1=input("enter the string: ")
print(str1)
v=u=l=s=0
str1=str1.split('.')
for i in str1:
print(i)
str1[2]="UST Global specializes in Healthcare, Retail & Consumer Goods, Banking and Financial Services, Telecom, Media, & Technology, Insurance, Transportation & Logistics, and Manufacturing & Utilities."... |
828d08ef0dc22ff849a7bc01d5d6c82e615e399c | Kuval999/ML-AI | /Exercise 3 -Week 1/exer3-10.py | 255 | 3.828125 | 4 | a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
e=list(input("Enter element: "))
e=list(map(int,e))
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print("The original list is: ",a)
print("The new list is: ",b)
|
b46d5837d0e62eda9ec664214eb6dffd1ab9d9d5 | Kuval999/ML-AI | /Exercise 3 -Week 1/exer3-6.py | 173 | 3.671875 | 4 | l1=list(input("enter list: "))
l1=list(map(int,l1))
l2=list()
for i in range(len(l1)):
l2.append(l1[i]**2)
print(l2)
tup=list(zip(l1,l2))
tup.sort()
print(tup)
|
a8a28782e43e0ee6ece5ae931a00dd0c50af48c0 | Kuval999/ML-AI | /Exercise 3 -Week 1/exer3-1.py | 178 | 3.734375 | 4 | n=[1,2,3,40,5,6,10,3]
n.sort()
l=len(n)
print("First largest: ",n[l-1])
print("Second largest: ",n[l-2])
temp=n[0]
n[0]=n[l-1]
n[l-1]=temp
print("After swapping: ",n)
|
4a521d7b6a217eb8bbb50d061fc51165445ebbdd | Kuval999/ML-AI | /Exercise 3 -Week 1/exer3-4.py | 200 | 3.796875 | 4 | l1=list(input("enter list: "))
print("3rd element: ",l1[2])
print("6th element: ",l1[5])
len1=len(l1)
print(l1[:4])
print(l1[6:len1])
l1[1]='x'
l1[4]='y'
l1.pop(4)
print(l1)
print(len(l1))
|
52b960012bd4a4167277ef89220dde095bf10a8b | vikaskanderai/python-programming | /student information.py | 1,424 | 3.921875 | 4 | print("Enter student information in the order NAME AGE CONTACT-NUMBER EMAIL-ID")
import csv
def write_into_csv(info_list):
with open('student_info.csv', 'a', newline='') as csv_file:
writer = csv.writer(csv_file)
if csv_file.tell()== 0:
writer.writerow(["Name","Age","Contact-n... |
b8440b714bf8a5aee9975fac9e1bbf18290dc519 | cplusProgrammer/forfun | /ccEnc.py | 379 | 3.921875 | 4 | import string
LETTERS = string.ascii_lowercase
mod = 'e'
key = 3
msg = input('Enter your message: ')
def encrypt(key, mod):
global key
encryptedMsg = ''
for letter in msg:
shift = LETTERS.find(letter) + key
if shift > 25:
shift = key
if shift != 2:
encryptedMsg += LETTERS[shift]
else:
encrypted... |
96cd68c0efda0372d3c0b1baf780c7fd2f581ceb | DiceChrisChang/UdacityDataAnalysisProgram | /part2/udacity_bikeshare-new/filter_data.py | 7,993 | 3.859375 | 4 | import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
# how to use seaborn
from matplotlib.figure import Figure
# for the plot visualization
def filter_data(city,month,weekday):
'''function to get data from csv files devided by city
return
data... |
bf73f15fd64c63a020bdc397c0162ac3b14e2f47 | ashu2496/simple-Language-Model-and-Sentiment-Classifier | /sentiment_classifier.py | 3,153 | 3.5 | 4 | import numpy as np
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import CountVectorizer
# Loading training/validation data and labels from files
train_sents = []
train_labels = []
with open("sentiment-data/train.txt") as f:
fo... |
80c1fdf94d70a44d055f7630573ad13d88deacbd | apon-if4104-a/APON | /LatihanCoding/cobaMax.py | 188 | 3.5 | 4 | a = 3
b = 4
c = 5
ans = pow(a,2)
ans1 = pow(b,2)
ans2 = pow(c,2)
max = 0
i = 0
arr = [ans,ans1,ans2]
while (i <= 2):
if (max < arr[i]):
max = arr[i]
i = i + 1
print(max) |
7c339d3287bf7c13fcdf7e158022d35302058a39 | SherryYeh/Python-HW | /004.py | 97 | 3.859375 | 4 | def identify(num):
num=int(input())
return num
if(num%2==0):
print("even")
else:
print("odd") |
d9fbd8de56c4b49b8519796a9852608bd39ddb61 | SherryYeh/Python-HW | /033.py | 2,912 | 3.5625 | 4 | def compute(all):
for i in range(10):
for j in range(10):
if(all[i][j]=="0"):
if(right(i,j,all) or down(i,j,all) or slide1(i,j,all) or slide2(i,j,all)):
print(i,j)
def right(i,j,all):
a=int(j)
count=0
while(True):
if(a-1<0):
... |
71dae813b268c71c0ebb1191e13f34b8344086dc | SherryYeh/Python-HW | /008-3.py | 684 | 3.5 | 4 | import math
def compute(a,b,c):
d=float(b*b-4*a*c)
#T=float(math.sqrt(b*b-4*a*c))
x1=float((-b)/(2*a))
x2=float((math.sqrt(-d))/(2*a))
x3=float(((-b)+math.sqrt(d))/(2*a))
x4=float(((-b)-math.sqrt(d))/(2*a))
#x3=float((-b+T)/(2*a))
#x4=float((-b-T)/(2*a))
if(d>=0):
... |
a028e2f6a08842eba9ddf92f5b5778da1dc5a104 | SherryYeh/Python-HW | /014.py | 1,482 | 3.546875 | 4 | import math
def compute(total):
sum=0
if(total>=120):
sum+=120
total-=120
if(total>=120):
sum+=160
total-=120
return sum+math.ceil(total/30)*60
else:
return sum+math.ceil(total/30)*40
else:
return sum+(total//30)*30 ... |
e3b3aff8e6de92ca1cc5ad0cf1fc3837d6392b40 | SherryYeh/Python-HW | /024.py | 8,981 | 3.796875 | 4 | #from fractions import Fraction
n=d=0
def add(n1,d1,n2,d2):
"""x=Fraction(n1,d1)
y=Fraction(n2,d2)
i=0
if(x+y>1):
i+=1
s=(x+y)-1*i
print(str(i)+"("+str(s)+")")
else:
print(x+y)"""
A=abs(n1*d2+n2*d1)
B=abs(d1*d2)
min1=min(A,B)
for i in range(min1,0,... |
7933c711fc73eba8f9cc4134b0c76fee88009a6d | 5l1v3r1/rest-api-goat | /routes.py | 9,608 | 3.5625 | 4 | import json
import server
def row2dict(row):
"""Takes sqlite3.Row objects and converts them to dictionaries.
This is important for JSON serialization because otherwise
Python has no idea how to turn a sqlite3.Row into JSON."""
x = {}
for col in row.keys():
x[col] = row[col]
return x
def check_token(api_token)... |
42ac92651ca9618e0c94aacffcc18655954421c5 | tirth1/python-examples | /multiplication_table.py | 252 | 4.09375 | 4 | for i in range(1,11):
print(f"1*{i}={1*i}")
def print_multiplication_table(a,b):
for i in range(1,b+1):
print(f"{a}*{i}={a*i}")
def print_multiplication(a,b):
for i in range(1,b+1):
print("{0}*{1}={2}".format(a,i,a*i))
|
982d800879d6d29855098713d83e560efa23546f | peterhusisian/Mosaicer-2.0 | /ImageOp/Paste.py | 467 | 3.515625 | 4 |
def paste_image_onto_image_at_bbox(base_image, paste_image, bbox):
base_copy = base_image.copy()
base_copy[bbox[1] : bbox[1] + bbox[3], bbox[0] : bbox[0] + bbox[2]] = paste_image
return base_copy
'''pastes a value into the image at all pixels contained by the bbox'''
def set_bbox_in_image_to_value(image, ... |
52217fa7962065009d7c8338ce3df625df54747a | Alba126/Laba6 | /individual2.2.py | 1,099 | 3.515625 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
# Преобразовать список состоящий из целых элементов таким образом,
# чтобы в первой его половине располагались элементы,
# стоявшие в нечетных позициях, а во второй половине - элементы, стоявшие в четных позициях.
if __name__ == '__main__':
a = list... |
001e0644c5f8d07ca66327f70e6547469eeac3a6 | HarrietHarchy/Project_Work | /Pupils_Ages.py | 721 | 3.75 | 4 | #find the oldest and youngest pupil in the class of 4, namely:Sharon, John,Grace,Emmanuel.
#Sharon is 12years old, John is 7 years old, Grace is 10 years old and Emmanuel is 6years old.s
def biggest(a,y,z,w):
Max = a
if y > Max:
Max = y
if z > Max:
Max = z
if w > Max:
Max = w
return Max
print(biggest(1... |
792120fb8ba2102bb37f683580b1e06c746a12a0 | abhip999/encoding_categorical_feature | /Encoder_function.py | 1,916 | 4 | 4 | import pandas as pd
from sklearn.preprocessing import LabelEncoder
class Encoding:
"""
To handle conversion of categorical variables to numerical values
"""
def __init__(self, df):
"""
Constructor of the class
:param df: Dataframe for encoding
"""
... |
b55d4f7276f46d06c7ae9fce385bf9ffe3d2dbe8 | JVuns/Assignments | /Class Exercise 2 Composite/num1.py | 1,558 | 3.65625 | 4 | class Author():
def __init__(self, auAuthor, email, gender):
self.__name = auAuthor
self.__email = email
self.__gender = gender
if self.__gender not in ['M', 'F']:
raise ValueError(gender)
if "@gmail.com" not in self.__email:
raise ValueError(email)
... |
f99a97db81ff0fe96db44a99243d9f07df84f093 | kajal8512/IF_ELSE.PY | /divisble8.py | 166 | 4.0625 | 4 | user = int(input("enter any no."))
if user%5==0:
print("it is divisble by 5")
if user%15==0:
print("it is divisble by 15")
else:
print("nothing")
|
c2849c3b27d4ef8ac5e2de2282c93f58278f6aa7 | kajal8512/IF_ELSE.PY | /nested if-else.py | 200 | 4.0625 | 4 | user=int(input("enter the no"))
if user>10 and user<=20:
user=10
print("assign 10 value")
elif user>20:
user=20
print("assign 20 value")
else:
user=15
print("greater than 20")
|
1e6fbd1d1052137cf1fc2fd971b58437cac3636b | kajal8512/IF_ELSE.PY | /hackathon.test1.py | 1,076 | 4.15625 | 4 | day = input("enter any day")
menu = input("breakfast,lunch,dinner")
if day=="monday":
if menu=="breakfast":
print("phoha")
elif menu=="lunch":
print("rotti sabji")
else:
print("dal chaval")
elif day=="tuesday":
if menu=="breakfast":
print("halva")
elif menu=="lunch":
... |
a7e7f68a96ec3dcc58f93362ef157001db6dcae0 | Lilowl06/pythonFormationCloud | /tuple.py | 544 | 4.03125 | 4 | t = ()
print(type(t)) # <class 'tuple'> vide
# lat = 45.9632
# lng = 21.7891
coordGPS = (45.9632,21.7891) # chaque élément d'un tuple est un membre
print("Latitude :", coordGPS[0])
# print("Longitude :", coordGPS[2]) # error : tuple index out of range
print("Longitude :", coordGPS[1])
lat, lng = coordGPS #tuple unpa... |
ccc0f033bf8d5116dc537d5988ae15862650d033 | Lilowl06/pythonFormationCloud | /conditions.py | 1,313 | 4.28125 | 4 | '''
if 2 > 1 :
print("2 est supérieur à 1")
if 2 > 3 :
print("2 est supérieur à 3")
'''
isEarthRound = True
message = "2 est strictement supérieur à 1"
condition = 2 > 1 # cette variable vaut True
# version courte
if isEarthRound :
print("La terre est ronde")
# version longue
if isEarthRound == True:
... |
610566899f939d9ee798c61c3e40156723f52e88 | Jiganesh/Problems | /ProblemZR.py | 585 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
self.current ... |
86bcd44cbe0824a0dd9e6b8490e62e15459186a7 | idontcaro/pythonintro | /Scripts/multby2.py | 492 | 4.4375 | 4 | #create a program that asks the user to input a number
#output to the CONSOLE the number multiplied by two (2)
#QUICK REFERENCE TYPES
#string type = '' or "" Example -> 'HI WORLD' or "HELLO WORLD"
#int type = 1234
#float type = 1.0f
#bool type = true or false
# aString = 'String'
# aInt = 1234
# aFloat = 1.0
# aBool =... |
bd724aea221b7304e036b94607d1f11d9eda87d7 | curiousguy13/project_euler | /pe23.py | 733 | 3.703125 | 4 | def sumOfFactors(x):
'''return the sum of all the factors of a number x'''
import math
sum=0
for i in range(1,int(math.sqrt(x)+1)):
if x%i==0:
sum+=i+x/i
return sum-x
def abundant(x):
'''return a list of abundant numbers till x'''
abundantNos=[]
for i in range(1,x+1):
if sumOfFactors(i)>i:
abundantNo... |
2db2d9b5de7429e6b0b84d989cdb8e4af1d07092 | curiousguy13/project_euler | /pe4.py | 372 | 3.515625 | 4 |
def isPalindrome(n):
s=str(n)
for i in range(len(s)/2+1):
if(s[i]!=s[-i-1]):
return False
return True
#print isPalindrome(0)
def findPal():
max=0
for i in range(999,99,-1):
for j in range(999,99,-1):
if(isPalindrome(i*j)):
if(max<i*j):
... |
3d18f2ca4c3b3691b501eaea0f3698c35927b637 | mauro40ar/segundo_a-o_2018 | /practica_1/ejercicio1B.py | 254 | 3.984375 | 4 | #I
summers=input("ingrese una oracion: ")
summer=summers.upper()
print(summer)
#II
sky="HOLA"
skys=sky.lower()
print (skys)
#III
grey=" esto es un ejercicio"
greys=grey.replace("ejercicio","prueba")
print (greys)
#IV
rey=grey.index("un")
print(rey) |
d47732b4a718a2612ca5135a8bc5acd387ff0457 | pomfy113/CS-3-Core-Data-Structures | /source/sandbox.py | 2,077 | 4.40625 | 4 | def insertion_sort(items, key):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order."""
# if order == "reverse":
# compare = operator.lt
# elif order == "normal":
# compare = operator.gt
global ... |
b4caae60c873e583b0f641a0366f8ca8289da3ea | singh4jitendra/NeuralNetworks | /Ex-2/softmax.py | 1,232 | 3.75 | 4 | """ @author: kmario23
Fast & stable implementation of Softmax function to ensure numerical stability.
"""
import numpy as np
def stable_softmax(x):
"""
Input : some vector 'x'
Output: a vector with entries that sum to 1;
Intuitively, it converts a vector of real entries to a vector of probabilities, t... |
58889ba29780ef81250ea396ec7037b2ce6a8915 | jeevers/onetimepass | /db.py | 1,353 | 3.578125 | 4 | """
DB Model and Helper functions to create/get users
"""
from peewee import *
import pyotp
import auth
USERSDB = 'users.db'
db = SqliteDatabase(USERSDB)
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
username = CharField(unique=True)
email = CharField()
passwdhash ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.