blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0234a44bcffd297313a83b1e413bc4e8207e96c9 | harshalms/python | /learn_python/dictionary.py | 166 | 3.546875 | 4 | A = [5, 3, 7, 7, 1, 2, 1, 1]
dicti={}
for i in A:
if i in dicti:
dicti[i]+=1
else:
dicti[i]=1
for key in dicti:
print(dicti[key]) |
6fee506e0b4918c75483c1bb18072744dd612a44 | johnguolex/tonyg_freechips | /pokerbot/gamestate/table.py | 870 | 3.953125 | 4 | class Table:
"""
A class representing the public state of the poker game.
Attributes
----------
opponents : list Opponent
a list of Opponents at the Poker Table
round : int
an int representing which stage of the hand we are at
sharedcards : list Card
... |
e73ea28524e23676214c8d65f8ca575a8520df30 | daniel-reich/turbo-robot | /k87ztfzqrpPHvgNWR_8.py | 1,342 | 3.8125 | 4 | """
Given a list of strings _depicting a row of buildings_ , create a function
which **sets the gap between buildings** as a given amount.
### Examples
widen_streets([
"### ## #",
"### # ## #",
"### # ## #",
"### # ## #",
"### # ## #"
], 3) ➞
[
"### ## #",
... |
57c866e183c3c4999be805420223d4bf5586a915 | azake-stud/python_learning | /chapter 1.5.py | 4,539 | 3.921875 | 4 | # >>> (Вопрос 1) Проверка слово на палиндром
# soz = input('Введите слово: ')
# if soz == soz[::-1]:
# print('True')
# else:
# print('False')
#
# >>> (Вопрос 2)
# soz = input('input a word: ')
# bukva = input('input a bukva: ')
# cc = int(soz.count(bukva))
# print(f'в слове "{soz}" есть {cc} букв "{bukva}"')
# ... |
e91115fa4a8e5bf76484a8a536c49884d323e1b6 | kevinjzheng/CS-UY-1114 | /Labs/Lab4/test.py | 95 | 3.5 | 4 | for i in range(1,6):
for j in range(1,11):
print(j**i, "\t", end= " ")
print()
|
d02fbb955ee23b8f13355074b6e80e892baa1ba0 | laippmiles/Leetcode | /217_存在重复元素.py | 568 | 3.90625 | 4 | '''
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 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
'''
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
""... |
0ae1f3e3576828afb137457626b5fde060b64eba | sdivakarrajesh/Interview-Prep-questions | /Service Based company - Fit1/3/answer-py.py | 220 | 3.796875 | 4 | count = int(input())
for i in range(count):
n,str = input().split(maxsplit=1)
n= int(n)
vowels = ['a','e','i','o','u','A','E','I','O','U']
str = [c for c in str if c not in vowels]
print("".join(str)) |
8d11c71b83e23f88e894f8b077d7d6dcf314ea19 | Rosthouse/AdventOfCode2019 | /challenge1_part2.py | 659 | 3.703125 | 4 | # Advent of Code 2019: Day 1, Part 2
# https://adventofcode.com/2019/day/1
import math
def calc_fuel(mass):
fuel = math.floor( mass / 3) - 2
if(fuel > 0):
addedFuel = calc_fuel(fuel)
if(addedFuel >= 0):
fuel += addedFuel
return fuel
fuel = calc_fuel(14)
print(fuel)
assert(fuel... |
5ad4f1f5e21e69086b34e076f1513508e352482a | LIUUL/f_to_c | /f_to_c.py | 96 | 3.5625 | 4 | F = input('請輸入華氏溫度:')
F = float(F)
C = (F - 32) * 5 / 9
print('攝氏溫度: ',C)
|
6e6020003c73bd2e810b378a430619c1126795a8 | v-ivanko/QAlight_Online_G7_ | /7-string analysis.py | 268 | 3.609375 | 4 | s = input("\nВведите предложение: ")
m = input("Введите символ: ")
count = 0
for i in range(0, len(s), 1):
if m == s[i]:
count += 1
print("\nКоличество символов в предложении: ", count)
|
396406203c1ff0af5007e58e616ce1f9f161351f | MauroBraga/python | /funcao.py | 142 | 3.734375 | 4 | def soma(x, y):
return x + y
def multiplicacao(x, y):
return x * y
s = soma(2,3)
print(s)
m = multiplicacao(2,3)
print(soma(s,m)) |
ad27ee62ce798550ba8a66a1bf3f809720bc4ad3 | marco-bom-amigo/Programming-AI-in-Python | /basics/Rand Range.py | 565 | 3.78125 | 4 | from random import randrange
numero_secreto = randrange(0,11)
def check_hunt(num, num_secreto):
if num == num_secreto:
print("Parabéns, o número secreto é %s"%num_secreto)
return True
elif num > num_secreto:
print("O número secreto é menor")
else:
print("O número secreto é ... |
b126276deff6115f33cd973fe7c3dc3f59feca5b | khanhdodang/automation-training-python | /python_basics/exercises/38_multiply_two_matrices.py | 1,152 | 4.75 | 5 | '''
In Python, we can implement a matrix as nested list (list inside a list).
We can treat each element as a row of the matrix.
For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix.
The first row can be selected as X[0].
And, the element in first row, first column can be selected as X[0][0].
Multi... |
896bdb871182b9b2661514ccdce85aa3074864d4 | driellevvieira/ProgISD20202 | /Mouhamed/Atividades/Atividade 4/Exemplos_aula4.py | 3,971 | 4.0625 | 4 | logicValue = int(input('Você é uma pessoa inteligente? \n'))
if(logicValue):
print('Não deixe o trabalho para depois! \n')
print ( "Fim do programa")
botao1Apertado = int(input("O rato apertou o botão 1? (Responda 0 para não e 1 para sim) "))
botao2Apertado = int(input("O rato apertou o botão 2? (Responda 0 para... |
7e6048d30d7c45c7cf7e3cd93d90b627ef3feed7 | dennisdela/my_first | /day3.py | 385 | 3.59375 | 4 |
import this
def myFunction():
pass
def stars():
d=0
for d in range (1,5):
print ("*"*4)
stars()
"""
def stars2():
to_print = 1
going_down = False
for i in range (0,7):
for j in range(0, to_print):
print("*", end="")
print("")
if to_print ==4:
going_down = True
if going_down:
to_print -... |
111ee7ad99536b8c40c5dd041b0492299ab73802 | rvaccari/uri-judge | /01-iniciante/1005.py | 1,189 | 3.765625 | 4 | """
Média 1
Leia 2 valores de ponto flutuante de dupla precisão A e B, que correspondem a 2 notas de
um aluno. A seguir, calcule a média do aluno, sabendo que a nota A tem peso 3.5 e a nota
B tem peso 7.5 (A soma dos pesos portanto é 11). Assuma que cada nota pode ir de 0 até
10.0, sempre com uma casa decimal.
Entrad... |
699720c12a3379bc459b8b6ea0d20ffb7eb544df | kevinjzheng/Data-Structures | /Classwork/countDown.py | 1,921 | 4.1875 | 4 | def count_down(start,end): #assume that when calling count_down on a smaller range it would print the
#numbers of that range in a decreasing order
if (start == end):
print(start)
else:
count_down(start+1,end) #this is print the entire range in decreasing order from e... |
810261cba507a88ca38c37d2633c9d9ca03919cf | Adrian0207/-LetsGo_Python | /Ejercicios_Diccionarios/Ejercicio5.py | 2,150 | 4.375 | 4 | '''Escribir un programa que implemente una agenda. En la agenda se podrán guardar nombres y números de teléfono. El programa nos dará el siguiente menú:
> Añadir/modificar: Nos pide un nombre. Si el nombre se encuentra en la agenda, debe mostrar el teléfono y, opcionalmente, permitir modificarlo si no es correcto.
Si ... |
c5b0f9b99d4a591997a49557fbff6b7525f19433 | meganindya/btech-assignments | /computer-networks/assg-5/geo-location.py | 2,510 | 3.8125 | 4 | # File: geo-location.py
# Author: Anindya Kundu <anindya.k22@outlook.com>
# Date: 2020-06-15
# Reference: https://docs.python.org/3/library/
"""
Finds the geographic loaction of a client connecting to this
server. Opens the location in a Google Map in default browser.
Functions:
- `_map_geo()`: maps g... |
d8dce9c29b1e00d1869da01e2d031bb2890b6b20 | prajwal041/ProblemSolving | /Leetcode/pairSum.py | 517 | 4 | 4 | """
Write a function that returns the indices of an array Arr for
elements that add up to a given number K
For example:
Given an array: [1,1,2,23,4,9,13,6,9] and K = 10, returns [[0,8],[1,5]
"""
def pairSum(arr, k):
ans = []
check = []
for i,val in enumerate(arr):
if k-val in set(arr) and val not in... |
bb90d6113308cde125b8df0d52cc43b05e6fd2d4 | BackToTheSchool/YMC | /Desktop/SummerVacation/0710/num_eleven.py | 185 | 3.609375 | 4 | numbers = input("Input the 4 binary numbers: ")
numbers = numbers.split(",")
for i in numbers :
token = int(i)
if int(bin(token),2) % 5 ==0 :#why 0100 % 5 is 0?
print(i) |
942892d556f27a68f82dab3e4f5b5c557811587d | laloparkour/pildoras_informaticas_python | /46 - Interfaces Gráficas - Widget Text & Button/main.py | 2,777 | 3.890625 | 4 | #Widget text: sirve para introducir texto largo.
#Widget button: botones para interactuar con la interfaz
from tkinter import *
raiz = Tk()
miFrame=Frame(raiz, width=1200, height=600)
miFrame.pack()
#Variables
miNombre = StringVar()
#Nombre
labelNombre = Label(miFrame, text="Nombre:")
labelNombre.grid(row=0, colum... |
0a0d014ddf2b69d4ca373bab72e4635d46873ba0 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2099/60870/258228.py | 360 | 3.703125 | 4 | dict_excel = {'A':1, 'B':2, 'C':3, 'D':4, 'E':5, 'F':6, 'G':7, 'H':8, 'I':9, 'J':10, 'K':11, 'L':12, 'M':13, 'N':14, 'O':15, 'P':16, 'Q':17, 'R':18, 'S':19, 'T':20, 'U':21, 'V':22, 'W':23, 'X':24, 'Y':25, 'Z':26}
str_test = input()
str_test = str_test[::-1]
res = 0
for i in range(len(str_test)):
res = res + pow(26,... |
f74e7a2ef2a7f22830f25f927f3344780b042b6c | zhangli709/python_note | /day10/student.py | 3,179 | 4.5625 | 5 | """
类名,每个单词首字母大写
类,属性和行为都要有!
类的定义:
1.类是对象的蓝图和模板,有了类就可以创建对象
2.定义类需要做两件事情:数据抽象和行为抽象
3.数据抽象:抽取对象共同的静态特征(找名词)- 属性
4,行为抽象:抽取对象共同的动态特征(找动词)- 方法
定义类的关键字- color-类名(每个单词首字母大写)
class Student(object): # Python3 中的规范写法
# 构造方法(构造器/构造子)constructor
# 调用该方法的时候不是直接使用方法的名字,而是使用类的名字
def __init__(self, name, age... |
1161d8730af6f91c418f899c591ca2160fb70ef9 | ATromp1/CountdownPython | /listcombinations.py | 1,646 | 3.78125 | 4 | from itertools import permutations
from collections import OrderedDict
cards = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 25, 50, 75, 100]
perm = list(permutations(cards, r=5)) # Every permutation from the list Card... |
c67f807fe2af8d9996f85a9ef493271698de3bb4 | dgwozdz/rudimentary_ml | /ordinary_least_squares.py | 1,208 | 3.625 | 4 | #==============================================================================
### Rudimentary ML: Ordinary Least Squares
### Author: Damian Gwóźdź
### Date: 31JAN2018
### Last modified: -
#==============================================================================
# 0. Loading libraries
import numpy as np
from s... |
473ab76481686c79b7b95fc1cf429474549519b0 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/mayc4t/hw3/strformat_lab.py | 3,870 | 4.25 | 4 | #!/usr/bin/env python3
# ###############################################################################
# Written by: Mayc4t
# March 19, 2018
def task_3_dynamic_formatter(seq):
""" Dynamically Building up Format Strings. """
# this is just note to myself
# hint build from the video
# list of a item... |
9b95418d0fcd9b9e63435eeadb09663f1c6ea0eb | chittoorking/Top_questions_in_data_structures_in_python | /python_progarm_to_create_a_list_of_tuples_from_given_list.py | 84 | 3.515625 | 4 | input_list=[1,2,3,4,5]
output_list=list()
print([(k,k**3) for k in input_list ])
|
5faa832a444756ca9edbc0bfcd5f2e568afbf0d2 | elu3/Python | /tangent.py | 951 | 3.734375 | 4 | from math import *
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return cos(x/2)
def solution(a,b,eps):
while ((f(a)*f(b)<0) and (abs(a-b)>=eps)):
c=(a+b)/2
if f(c)==0:
return c
elif (f(a)*f(c)<0):
b=c
elif f(b)*f(c)<0:
a=c
... |
4baa08f0e5d3977101a3faff4f3313296a0de743 | MananDesai54/028_MananDesai | /Lab1/lab1Pandas.py | 845 | 3.65625 | 4 | #!/usr/bin/env python3
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('../Lab2/Data/Datasets/Exercise-CarData.csv')
d = pd.crosstab(index=data['Index'], columns="Price", dropna=True)
print(d)
print(data.info())
# Count Total Null values in each column
print("Total Null Data:", data.isnull().... |
fe46b9242feacd0b328f7651a28f2612a1e67be5 | AlexQianYi/N_puzzle | /utility.py | 902 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 4 11:52:30 2018
@author: yiqian
"""
from collections import deque
import queue
class PriorityQueue:
def __init__(self):
self.queue = queue.PriorityQueue()
def __contains__(self, item):
for element in self.que... |
b5a954ea00fc2c189c6e6cdab8b3144a84cd1e3f | Eric-Wonbin-Sang/SalaryTracker | /Classes/Salary.py | 511 | 3.609375 | 4 |
class Salary:
def __init__(self, annual_salary):
self.annual_salary = annual_salary
self.hourly_rate = round(self.annual_salary / 52 / 5 / 8, 2)
self.overtime_rate = round(self.hourly_rate * 1.5, 2)
def __str__(self):
ret_str = "Salary:\n"
ret_str += "\tannual_salary:... |
5687256bccf8f35fcd50dae9053d0f57d5d0ed82 | ikemous/learningPython | /player.py | 2,624 | 3.515625 | 4 | import pygame;
from pygame.sprite import Sprite;
from math import sqrt, acos, degrees, hypot, atan2;
from settings import Settings;
class Player(Sprite):
''' A Class To Manage The Player '''
def __init__(self, app):
''' Initialize the player and its starting position '''
super().__init__();
... |
e432709dfe26fffc09585e0db74bda52d7412755 | dcragusa/LeetCode | /100-199/120-129/121.py | 1,301 | 4.46875 | 4 | """
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your
profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve... |
596e0e3a65dbaa11e69032d936be621a8c5c9ad2 | stheakanath/GoogleGames2015 | /problem8.py | 567 | 3.53125 | 4 | import string
fname = "wordlist"
words = []
with open(fname) as f:
words = f.readlines()
words = [x.strip('\n') for x in words]
fname = "soup"
needtofind = []
with open(fname) as f:
needtofind = f.readlines()
needtofind = [x.strip('\n') for x in needtofind]
alphabet = list(string.ascii_uppercase)
total = 0
... |
baafa22d7a51077a72ab012aab0f06d4a15ee99f | bielabades/Bootcamp-dados-Itau | /Listas/Funcoes/07.py | 316 | 3.765625 | 4 | # Faça uma função que sorteia 10 números aleatórios entre 0 e 100 e retorna o maior entre eles.
from random import randint
lista = []
count = 0
while count < 11:
num = randint(0,100)
lista.append(num)
count += 1
def aleatorio(lista):
maximo = max(lista)
print(num)
aleatorio(lista)
|
32cd09efb118604e0d5c2e521046e64e8ad1c33f | solcra/pythonEstudio | /cadenas.py | 524 | 4.15625 | 4 | texto = "Prueba dos dos"
print("Upper")
print(texto.upper())
print("Lower")
print(texto.lower())
print("Capitalize")
print(texto.capitalize())
print("Count")
#print(texto.count())
print("Fing")
#print(texto.fing())
print("Isdigit")
print(texto.isdigit())
print("Isalnum")
print(texto.isalnum ())
print("Isalpha")
print(t... |
8f3bb229ba5e963e7590ebf4582defbfeb7503f3 | tappasarn/string_dataset_generator | /src/distances/jaccard.py | 450 | 3.5 | 4 | """
This module calculate Jaccard's distance score
parameters:
x : (numpy array) first string sequence
y : (numpy array) second string sequence
return:
(float) : Jaccard's distance socre (1 - Jaccard's similarlity)
"""
def jaccard_seq(x, y):
len_x = len(x)
len_y = len(y)
fst, snd = (x, y) if len_x < len_... |
b46349b51c1e126221df9839a440e39fc8e1fd34 | alfoquial/algoritmos | /sequentialsearch.py | 811 | 3.921875 | 4 | # Search unordered lists
def search_unordered_1(alist, item):
found = False
for value in alist:
if value == item:
found = True
return found
def search_unordered_2(alist, item):
found = False
position = 0
while not found and position < len(alist):
if alist[position... |
fd9fc99e18a0b7cd264567ec38ca90a6aff6de6a | YaniraHagstrom/PY-111-Intro_to_Python | /Day11_Modules.py | 4,029 | 4.34375 | 4 | '''
User Input: '''
# userinput = input("Enter your age:") #this prompts the user to input a value in the terminal and stores the value.
# print(userinput)
#This returns a string...
#Casting is when you return a data type and wrap it or "cast" it into another. Ex: using the list construct method to change a string i... |
da36ba318ef961963e9420b79dc1fc49948fe63c | rpparas/LeetCode-Programming-Problems | /Matrices/CountIslands.py | 2,348 | 3.625 | 4 | # Problem Statement: https://leetcode.com/problems/number-of-islands/
class Solution:
def count_islands(self, grid: 'List[List[str]]') -> 'int':
if len(grid) == 0:
return 0
num_contiguous_islands = 0
modifiers = [(-1,0), (1,0), (0,-1), (0,1)]
for r, row in enumerate(gr... |
d2252bf85a516d2a77a0650e5f66937ba4aa8052 | lixiang2017/leetcode | /explore/2021/march/Short_Encoding_of_Words.py | 4,675 | 3.609375 | 4 | '''
approach: Reverse + Sort
Time: O(NlogN)
Space: O(1)
You are here!
Your memory usage beats 93.33 % of python submissions.
'''
class Solution(object):
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
words = sorted([word[:: -1] for word ... |
4456d41821875ad908fcd662ca54ffd32fee2ce2 | afsanehshu/python-project | /User Input/1.User_Input.py | 162 | 4.03125 | 4 | username = input("Enter username:")
Mobile =str(input("Please Enter Your Mobile Number :"))
print("Username is: " + username)
print("Mobile Numner is: " + Mobile) |
931bc6d51e60c4dbe374ce515ed0017232834c97 | Park-Jiho20/MSE_Python | /ex210.py | 889 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
# message1() 라는 입력값을 받으면 A를 출력하도록 함수를 만든다.
def message1():
print("A")
# message2() 라는 입력값을 받으면 B를 출력하도록 함수를 만든다.
def message2():
print("B")
# message3() 라는 입력값을 받으면 message2() 에 해당하는 B를 출력하고, 연달아 다음줄에 C를 출력하도록 한다.
# 이때 message2() 와 print("C") 는 for문에 포함되어 있으... |
73e20578d35db7233fbd3091cadcfac939be018a | Konstantinospil/SimulationConstitution | /Python Codes/Classes.py | 851 | 4.15625 | 4 | # Class Population
class Population(object):
"""
The object contains information about a population in the simulation
:arg size: number of members
:param get_size(): getter for the size (int)
:param populate(): a function that generates a number of Individuals equal to the size of the population.
... |
06a803be2855b7c34a15730ea1999e73de5d458a | imranali18/Edifytech-C- | /CS1010Fall2019-master/Homeworks/Homework 2/HW2Q4.py | 223 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 20 16:06:40 2019
@author: uzma
"""
str1=str(input('Input the string '))
char = str1[0]
str1 = str1.replace(char, '&')
str1 = char + str1[1:]
print(str1) |
14e5b67290c88fd55a05f8fe992ca4d346e73e47 | mfguerreiro/Python | /lista2/EXTRA/ex2.py | 571 | 3.796875 | 4 | import math
raiz1=0
raiz2=0
a = float(input("Valor a:"))
b = float(input("Valor b:"))
c = float(input("Valor c:"))
delta = (b**2) -(4 * a * c)
if(delta < 0):
print("esta equação não possui raízes reais")
elif(delta == 0):
raizUni = (- b) / (2 * a)
print("a raiz desta equação é", raiz1)
else:
raiz1 = (- b + ma... |
b60eee328aa97fc7f68979417c91175b01692968 | jianhui-ben/leetcode_python | /915. Partition Array into Disjoint Intervals.py | 1,602 | 3.78125 | 4 | #915. Partition Array into Disjoint Intervals
#Given an array nums, partition it into two (contiguous) subarrays left and right so that:
#Every element in left is less than or equal to every element in right.
#left and right are non-empty.
#left has the smallest possible size.
#Return the length of left after such a p... |
e4f0dcfc435ea53e785104c105aed389f54efe51 | Dhruv1956/learning_python | /Chapter1/4_Listofnumbers.py | 1,486 | 3.9375 | 4 | def CreateList(count):
aList = []
i=0
while(i<count):
print("Enter a number: ")
n= int(input())
aList.append(n)
i=i+1
return aList
def PrintList(list):
i=0
while(i<len(list)):
print(list[i])
i=i+1
def FindBiggestNumber(alist):
i=1
big=al... |
94137224b1db5586e8e8f13c6f6cd30f327e7c1f | vnpavlukov/Study | /Coursera/2_Coursers/Basic_progr_in_Py/Week_2/Test_27_list_squares.py | 133 | 3.515625 | 4 | limitation = int(input())
max_num = 1
b = 1
while max_num <= limitation:
print(b ** 2, end=' ')
b += 1
max_num = b ** 2
|
d4268e5317eedcca3d63c7ae04ecc21f5ee7a337 | KULDEEPMALIKM41/Practices | /Python/Python Basics/51.fectorial.py | 108 | 3.765625 | 4 | #fectorial number.
n=int(input('enter any number'))
a=n
i=1
while i<n:
a=a*i
i+=1
print('factprial is',a) |
6c2ee624e46ecc321be000c7c71b8d234f8ba175 | s-ruby/uxr_spring_2021 | /challenges/03_bootcamp_strings_booleans/03_strings_boolean_challenge.py | 2,313 | 4.4375 | 4 | # You run a startup media company called Ripple Media
# It's typical when you hire a new employee in your company, to setup an email id for them
print('Question 1')
employee_first_name = "Your first name"
employee_last_name = "Your last name"
# You have decided the format of the email should be: Serena Killion -> se... |
1446a9aead543a48ecf0184effd5b8c56aac04ea | EricksonSiqueira/curso-em-video-python-3 | /Mundo 1 fundamentos basicos/Aula 7 (operadores aritmeticos)/Desafio 014.py | 227 | 4.1875 | 4 | #Escreva um programa que converta gruas celcios para fahrenheit
c = float(input('Digite a temperatura em celcios:'))
f = (c*9/5)+32
print(f'A temperatura digitada foi: {c:.2f}°C.\nA temperatura em fahrenheit é: {f:.2f}°F')
|
f0b8636231eca11ee441924c4bf168317f673cdb | shreyakapadia10/PythonProjects | /Python Programs/fstrings.py | 289 | 4.1875 | 4 | name = "Shreya"
bdate = 10
# Way 1
print("This is %s, my birthdate is %s" % (name, bdate))
# Way 2
print("This is {}, my birthdate is {}".format(name, bdate))
print("My Birthdate is {1}, this is {0}".format(name, bdate))
# Efficient way
print(f'This is {name}, my birthdate is {bdate}') |
2b22408eb5495b8a8a9a347876e18ac21362e273 | CrABonzz/SmartAuthentication | /Screens/login.py | 3,318 | 3.75 | 4 | from tkinter import StringVar, Label, Button, END
from Utils.common import AUTH_METHODS
from Utils.tkinter_utils import add_screen, destroy_screens, add_entry, info_screen
login_success = True
class Login(object):
""" The login screen, presents the user all the passwords he needs to pass """
def __init__(se... |
ef587e1fef38879e4c0d0f71a5495e712c0e57b6 | lopez1941/PythonMasterClassRepo | /HelloWorld/HelloWorld.py | 1,101 | 4.3125 | 4 | # print('Hello, World!')
# print(1 + 2)
# print()
# print("Python's strings are easy to use.")
# print("The end.")
# """There's no difference between single and double quotes"""
# print("Hello" + " World")
# greeting = "Hello"
# name = "Donnie"
# print(greeting + ' ' + name)
# This is a comment, get some comments sucka... |
f8ceab1768605df33513cc5f0f531d15c0f431cf | codereport/LeetCode | /0321_Problem_1.py | 586 | 3.59375 | 4 | # Problem Link: https://leetcode.com/problems/find-the-pivot-integer
# Solution 1
def pivotInteger(n):
a, b = 0, n * (n + 1) / 2
for i in range(1, n + 1):
a += i
if a == b: return i
b -= i
return -1
# Solution 2 (BQN inspired)
from operator import add
from itertools import accumul... |
164e76586ea200b3ca9a92eb1ac801ec059d4e62 | timurridjanovic/data-structures | /python_problems/steps_problem.py | 724 | 4.125 | 4 | #we have 10 stairs. We can climb those stairs going one step at a time,
#two steps at a time, or three steps at a time, or any permutation of those
#possibilities. Calculate all possible ways of climbing those stairs.
#It's a permutation with repetition problem.
def ways_of_climbing(steps_list, num_stairs):
resul... |
572bd6f5846dfdfdc20e6862468c9f467ac1ec3e | C-CCM-TC1028-102-2113/tarea-3-programas-que-usan-funciones-Esteban-Garcia-Gonzalez | /assignments/10Bisiesto/src/exercise.py | 230 | 3.5625 | 4 | def es_bisiesto(a,b):
if (a%4==0 or a%400==0):
b=True
return b
else:
b=False
return b
def main():
a=int(input())
b=0
print(es_bisiesto(a,b))
if __name__=='__main__':
main()
|
cb149aba9eaa5fa8d9a22d73f7567b5d96f135e1 | prefrontal/project-euler | /Answers-Python/039.py | 1,470 | 3.53125 | 4 | #!/usr/bin/python
# Project Euler Problem 39
#
# If p is the perimeter of a right angle triangle with integral
# length sides, {a,b,c}, there are exactly three solutions for p = 120.
#
# {20,48,52}, {24,45,51}, {30,40,50}
#
# For which value of p <= 1000, is the number of solutions maximised?
#
# Answer: 840
MAXIMUM... |
a1ca6a9b825198b16385b70b4b7fc61056c0454b | justinbarak/2020_Advent_of_Code | /Day18A.py | 1,922 | 3.796875 | 4 |
import re
import copy
def load(filename: str) -> list:
"""Open a text file & return a list of lowercase strings."""
try:
with open(filename) as in_file:
loaded_txt = in_file.read().strip().split("\n")
loaded_txt = [x.lower() for x in loaded_txt]
return loaded_txt
... |
cb1a05bf4075b034c5838c6af8d125ddb8339e18 | sharanyaa/coursera_python | /1/quiz1 q6.py | 349 | 4.03125 | 4 | def f(x):
"""
Implement the mathematical function
f(x) = -5 x5 + 69 x2 - 47 as a Python function.
Then use Python to compute the function values
f(0), f(1), f(2), and f(3).
Enter the maximum of these four numbers.
"""
return (( -5 * (x**5)) + (69 * (x**2)) - 47 )
print f(0)
pri... |
9b35d2ac25bf33a2676b36c97ccc5ec60e88fe10 | villamormjd/data-science | /NumpyCourse/NumpyArray.py | 299 | 3.65625 | 4 | import numpy as np
from numpy.random import rand
my_list = [1, 2, 3]
arr = np.array(my_list)
print(arr)
"""
my_mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mat_array = np.array(my_mat)
print(mat_array)
print(np.zeros((3, 3)))
print(np.eye(5))
print(np.random.randint(1,100))
"""
print(rand(5,5))
|
60d551d48e461f7d3d5b45323d1a92d1c7ffcfc9 | geiza12/Python-Projects | /while-soma-positivos.py | 246 | 4.03125 | 4 | # Este software aceita 3 entradas e acumula os valores positivos
numero = 0
somatoria = 0
k = 1
while k < 4:
numero = int(input("Valor: "))
if numero > 0:
somatoria += numero
k = k + 1
print(k)
print("Soma: ", somatoria)
|
39ca221d458f342162af8487e0f60482e3624827 | geovanemelo/exercicios-py | /26.py | 316 | 3.90625 | 4 | #Programa que leia uma frase e diga quantas vezes aparece A
#onde apareceu primeiro e por ultimo
frase=str(input("Digite a frase a ser Analisada:")).lower().strip()
aparecimentoA=frase.count('a')
primeiravezA=frase.find('a')
ultimavezA=frase.rfind('a')
print(aparecimentoA)
print(primeiravezA)
print(ultimavezA) |
918b0ea8e46bb913815a54c8f46729329dd52259 | larsg153/florin | /florin/closure.py | 2,255 | 3.65625 | 4 | """Closure decorator for delayed processing.
Functions
---------
florinate
Decorator to wrap arbitrary functions and enable delayed evaluation.
"""
from collections import Sequence
from itertools import count
import functools
from florin.context import FlorinMetadata
from florin.graph import FlorinNode
def fl... |
2f6f382baca56991bd304098af0830fd2454a463 | caiosainvallio/estudos_programacao | /curso_em_video/exe096.py | 506 | 4.3125 | 4 | """Exercício criado por: https://www.cursoemvideo.com/
096: Faça um programa que tenha uma função chamada área(), que receba as
dimensões de um terreno retangular (largura e comprimento) e mostre a área
do terreno."""
def area(largura, comprimento):
print(f'A área de um terreno de {largura:.1f}x{comprimento:.1f} ... |
2729e1e46cb57a471ce0fd80ec0382eead3bfed5 | LuanadBraz/LoginUsuario | /login_usuario.py | 513 | 3.796875 | 4 | import time
print('-------------------------------')
print('######## LOGIN USUÁRIO ########')
print('-------------------------------')
nome = str(input('Digite seu nome: '))
senha = str(input('Digite sua senha: '))
print('Carregando...')
time.sleep(1.9)
while (senha == nome):
senha = str(input('Senha Inválida! Di... |
c065112e38927602ebd1521756c6331b602e784b | JulyKikuAkita/PythonPrac | /cs15211/PopulatingNextRightPointersinEachNode.py | 5,148 | 4.03125 | 4 | __source__ = 'https://leetcode.com/problems/populating-next-right-pointers-in-each-node/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/populating-next-right-pointers-in-each-node.py
# Time: O(n)
# Space: O(1)
# Divide and conquer
#
# Description: Leetcode # 116. Populating Next Right Pointers in Each Node... |
a133ad258d84cd9483457674255985bce0aece52 | mercifulking/shiyanlou_project | /calculator.py | 796 | 3.84375 | 4 | #!/usr/bin/env python3
import sys
def main():
if len(sys.argv) != 2:
print('Parameter Error')
exit()
try:
income = int(sys.argv[1])
except ValueError:
print('Parameter Error')
exit()
value = income - 3500
if value <= 0:
result = income
elif valu... |
0a9c6facb075effdd98196d83aa5ff195a9202af | binitamaity/fair-clustering-fairlets | /utils.py | 1,851 | 3.78125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def distance(a, b, order=2):
"""
Calculates the specified norm between two vectors.
Args:
a (list) : First vector
b (list) : Second vector
order (int) : Order of the norm to be calculated as distance
Returns:
Resultant norm value
"""
assert len(a) ==... |
c9fa1af86687c09700044954471c8fb5cbb93799 | MrYurchik/MainHW | /3-5.py | 374 | 3.703125 | 4 | name2 = 0
users = {
'karas': 'karas',
'arnold': 'arnold.',
'bozdan': 'bozdan1.',
'korchma': 'korchma1.'
}
name = input('Please enter your name: ')
name1 = name in users
if name1:
pas1 = users[name]
pas = input('Please enter your pass: ')
if pas1 == pas:
print("welldone")
else:
... |
fdfe674afb28fb4519f0f7503aa4f62475607355 | vincent-kangzhou/LeetCode-Python | /281. Zigzag Iterator.py | 942 | 3.796875 | 4 | class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
if len(v1)==0:
v1, v2 = v2, v1
self.currVec = v1
self.nextVec = v2
self.currIdx = 0
... |
7655ccb0855ab8506e3f91eca51648f28ab0ef33 | syurskyi/Python_Topics | /045_functions/008_built_in_functions/map/examples/06-map.py | 148 | 3.796875 | 4 | """Пример использования функции map"""
string = '2 4 8 15 42'
numbers = map(int, string.split())
print(list(numbers))
|
d27e829ae670ec4e7543b2860e7ee6b101238698 | HaydenTheDev/pythonnewpractice | /dictionaries2.py | 474 | 3.609375 | 4 | games = {"WoW": "Best game ever back then",
"Runescape": "I Still like to play this game occasionally",
"RocketLeague": "When I want a good challenge",
"7 Days to Die": "If you like survival check this one out.",
"Heroes of the Storm": "Is more for strategy nerds, but great."}
f_tup... |
0a7ba72cf63969bd677eb529c96f746583eb9401 | kisgitter/hello | /xiecheng.py | 670 | 3.734375 | 4 | def consumer():
r = ''
while True:
m = yield r #yield r 返回 r ,上一次执行到yield r 终止,再次开启从 m 开始,同时m的值等于produce中发送过来的n
if not m:
return
print('[CONSUMER] Consuming %s...' % m)
r = '200 OK'
def produce(c):
#启动生成器,也可以写作next(c),效果一样i
c.send(None)
n = 0
while n ... |
b9398b38e151297d8bb66d0f8bc6f9455c08977b | stavanmehta/leetcode | /python_submission/33.search-in-rotated-sorted-array.198369584.ac.py | 1,111 | 3.5 | 4 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums)==0:
return -1
L = 0
R = len(nums) - 1
while True:
if L>R: return -1
tmpVar = ... |
c08f39352a733e3b4570db6a1df4e318dd5d1e14 | ZodiacSyndicate/leet-code-solutions | /medium/98.验证二叉搜索树/98.验证二叉搜索树.py | 1,477 | 3.765625 | 4 | #
# @lc app=leetcode.cn id=98 lang=python3
#
# [98] 验证二叉搜索树
#
# https://leetcode-cn.com/problems/validate-binary-search-tree/description/
#
# algorithms
# Medium (25.22%)
# Likes: 189
# Dislikes: 0
# Total Accepted: 22.6K
# Total Submissions: 87.7K
# Testcase Example: '[2,1,3]'
#
# 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
#
# ... |
cc99c16a07add6eaf33012e06f0a634c01954951 | Jayashree24/code-practice | /interviewbit/BinarySearch.py | 898 | 3.9375 | 4 | """
Implement Binary Search
https://www.interviewbit.com/courses/programming/topics/binary-search/
"""
def binary_search(arr, target):
start = 0
end = len(arr) - 1
l = len(arr)
mid = int(l/2) + start
#while l >= 1:
while start <= end:
#mid = int(l/2) + start
mid = int((start+end)/2)
#print ("MID len=%s ... |
0dcf8a6a5a7ab92fe53e8660309d7e20c4154d64 | Simochenko/Generation_Python_Advanced_Course | /Module_15/15.2_functions_with_a_variable_number_of_arguments.py | 26,758 | 3.734375 | 4 | '''Тема урока: функции с переменным количеством аргументов
Аргументы *args
Аргументы **kwargs
Keyword-only аргументы
Аннотация. Урок посвящен функциям с переменным количеством аргументов.
Переменное количество аргументов
Вспомним функцию print(), которой мы пользуемся почти в каждой задаче.
Приведенный ниже код:
pri... |
2012e2262b1d242281fd53502e96d892b07d0252 | ze-dev/Educational_Tasks | /Asterisk it.py | 964 | 4.375 | 4 | '''Asterisk it
https://www.codewars.com/kata/5888cba35194f7f5a800008b/train/python
Task
You are given a function that should insert an asterisk (*) between every pair of even digits in the given input,
and return it as a string. If the input is a sequence, concat the elements first as a string.
Input
The input c... |
2b586de4cf57c5cea9060af113a9d97d047952b4 | Ziles131/PyCourseStepik | /1.6_inheritance_class_3.py | 321 | 3.625 | 4 | import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
class LoggableList(list, Loggable):
def append(self, v):
super(LoggableList, self).append(v)
super(LoggableList, self).log(v)
l = LoggableList()
print(l)
l.append(17)
l.append(1)
l.append(89)
l.append(9)
l.append(35)... |
2e9a4bff0b6f4e5e06933a13b8c6d133e207b449 | Ikkjo/python-data-structures | /binary_tree.py | 3,738 | 3.671875 | 4 | from queue import Queue
class BTNodeException(Exception):
"""Base class for BTNode Exceptions"""
pass
def check_if_btnode(obj):
if not isinstance(obj, BTNode):
raise TypeError("Object must be BTNode data type!")
class BTNode(object):
def __init__(self, data, parent=None, l_child=None, r_ch... |
ae148af4e68969a7b7e8778dea800ddecac2dac6 | Crismaria11/Proyecto2_Graficas | /Final/cone.py | 1,271 | 3.5 | 4 | from lib import *
from sphere import *
import math
class Cone(object):
def __init__(self, radius, height, position, material):
self.radius = radius
self.height = height
self.position = position
self.material = material
def ray_intersect(self, origin, direction):
A = origin.x - self.position.x
... |
c7c5630d175eba8f3c9d690ac1cbb7407181f27c | rishikanthc/competitive-programming | /303.py | 919 | 3.640625 | 4 | """
303. Range Sum Query - Immutable
Easy
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
"""
class NumArray:
def __init__(self, nums):
self.arr = nu... |
da31cd9b97640a8d3bee423e34c848a8f55b15a7 | ValmorMachado/Python_Diversos | /SUBNETTING_C.py | 2,727 | 3.671875 | 4 | # SUBNETTING CLASSE C
# Algoritmo desenvolvido por Natalia Oliveira
# Alterações 15/03/2021
subnetting = [255,255,255]
mascaras = [128,192,224,240,248,252,254,255]
pesos = [128,64,32,16,8,4,2,1]
expoentes_pesos = [7,6,5,4,3,2,1,0]
bits = [0,0,0,0,0,0,0,0]
bits_emprestados = 0
num_subredes = int(input(f"Dig... |
ead5b5486beda8d06957a77a928a7024692f0720 | YazanAhmad18/data-structures-and-algorithms-python | /data_structures/merge_Sort/merge_sort/merge_sort.py | 1,174 | 4.3125 | 4 | def merge_sort(array):
if len(array)>1:
middle_of_array=len(array)//2
left_side=array[:middle_of_array]
right_side=array[middle_of_array:]
merge_sort(left_side)
merge_sort(right_side)
merge(left_side,right_side,array)
return(array)
def merge(left_side,... |
a805d487d6ecca689d9b634e9daa1f24b3b1ed4b | sotsoguk/hackerrank | /interview_prep/strings/morganandastring.py | 471 | 3.78125 | 4 | def morgan(a,b):
output = []
a += 'z'
b += 'z'
for _ in range(len(a) + len(b) - 2):
if a < b:
output.append(a[0])
a = a[1:]
else:
output.append(b[0])
b = b[1:]
# print(output)
return "".join(output)
def main():
t = "JACK"
... |
4bd1ee67be64c4aeec679f37dda47e5d142c61b8 | Pcamerer/School | /MIS407HW/FinalExam/final01_01.py | 313 | 4 | 4 | import itertools
def anagram(text):
for w in itertools.permutations(word):
yield ''.join(w)
text = input("Enter word to search: ")
with open('dictionary_words.txt', 'r') as f:
for line in f:
word = line.rstrip('\n')
for w in anagram(text):
if w in line:
print(w)
|
7e369f2a1d39a76f33bea059ab17c8af6cce285f | Fulvio7/curso-python-guppe | /guppe/exercicios_secao_6/ex_24.py | 325 | 3.84375 | 4 | """
24- Leia um número inteiro e calcule a soma de todos os divisores
desse número, com excessão dele próprio.
"""
number, soma = -1, 0
while number <= 0:
number = int(input('Digite um número positivo: '))
for i in range(1, number):
if number % i == 0:
soma += i
print(f'Soma dos divisores: {soma}')
|
de83c8fd12f71de6a54f64e20d0b33087d94ee17 | paulbmouton/LPHW | /ex13.py | 620 | 4.0625 | 4 | # this adds modules (libraries) to python. needed to be imported in order to keep programs as small as possible. also acts as documentation for future reading by other programmers.
# argv is the "argument variable"
# assigning variables to argv tells it to pring them in that order
from sys import argv
# the first var... |
008099ef6f6f533c869c6c552183861263f686ea | revanth96/coding | /noofwordoccuring.py | 155 | 3.578125 | 4 | mystring =input()
result={}
value=mystring.split(" ")
for i in value:
if i in result:
result[i]+=1
else:
result[i]=1
print(result)
|
6894b1d125cabc83fab39e7ff91b918652d31535 | Jeongm1n/DKU_Class | /오픈소스활용SW/Problem_Final/Problem7.py | 846 | 4.09375 | 4 | """
Problem #7
"""
class Letter:
def __init__(self, letterfrom, letterto):
self.letterfrom = letterfrom
self.letterto = letterto
self.text = ""
def addLine(self, line):
self.text += line + "\n"
def get_text(self):
print("----------------------------... |
9ea66e2d36aef16b52895e76df10269e1cc657b0 | vokeven/CourseraPythonHSE | /Week5/Наименьший нечетный.py | 515 | 3.984375 | 4 | # Выведите значение наименьшего нечетного элемента списка,
# гарантируется, что хотя бы один нечётный элемент в списке есть.
def isMin(xList):
i = 0
while xList[i] % 2 == 0:
i += 1
minX = xList[i]
for j in range(i, len(xList)):
if xList[j] % 2 != 0 and minX > xList[j]:
min... |
82dca33ca0427a4ab6ec01e329228967f101ff88 | richardmanasseh/hort503 | /lpthw/ex18a.py | 4,309 | 4.375 | 4 | # Example of a program split into small logical functional units, each perfroming a task
# Case: program to calculate and display the net pay and name of every employee in a company
# Algorithm:
# Step 1 Define your problem (as above).
# Step 2 Algorithms input(s): employee record
# Step 3 Define the algorithm's (in... |
584cda4751d0fa72beca1c47889ec7a2dab7f767 | gabrielspires/Busca-em-espaco-de-estados | /ids.py | 1,575 | 3.640625 | 4 | from funcs import find_start_points, find_neighbors
paths_found = []
def dls(mapa, graph, max_passos, node, path, max_depth, visited):
if node not in visited:
visited.append(node)
# Max_passos--
path[0] -= 1
if mapa[node[0]][node[1]] == "#":
path[1] += 1
... |
6ccdb073cf16a6f8126d624bfc478be0a917f89b | cesaralmeida93/programacao-treino | /URIOnlineJudge/iniciante/1051.py | 1,577 | 3.734375 | 4 | '''Em um país imaginário denominado Lisarb, todos os habitantes ficam felizes em pagar seus impostos, pois sabem que nele não existem políticos corruptos e os recursos arrecadados são utilizados em benefício da população, sem qualquer desvio. A moeda deste país é o Rombus, cujo símbolo é o R$.
Leia um valor com duas c... |
a117e86364921e8eeee1190071315bcf71fa41ca | Shabarna/guvi | /code kata/line.py | 121 | 3.65625 | 4 | num=input()
b = num.count('.')
if(b==0):
print(1)
elif(b==1):
print(2)
elif(b==2):
print(3)
elif(b==3):
print(4)
|
618766e2b7b2a36c152b880884265def8678ecf8 | shrirangmhalgi/Python-Bootcamp | /17. Functions/args_unpacking.py | 168 | 3.53125 | 4 | def sum(*args):
total = 0
for i in args:
total += i
print(total)
sum(*[1, 2, 3, 4, 5])
sum(*(1, 2, 3, 4, 5))
'''works for both list and tuple '''
|
447960757ed107e40587b5fa38001d71a25297cb | shreykhare/LeetCodeSolutions | /LeetCode/InterviewQuestions/sorocco-ba/ba-ques.py | 916 | 3.75 | 4 | from typing import List, Tuple
def gcd(a: int, b: int):
if a < b:
a, b = b, a
if b == a == 0:
raise Exception("Invalid input")
if b == 0:
return a
return gcd(a % b, b)
def numberExtractor(s: str) -> Tuple[int, int, int, int]:
"""
Input would be like `10/21 + 21/30`
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.