blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
f5090b41b7e5cb5e98c4dc3ac85f092df79000bd | iyoussou/CAAP-CS | /hw1/fibonacci.py | 469 | 4.28125 | 4 | #Prints a specific value of the Fibonacci Sequence.
def main():
print("This program prints a specific term of the Fibonacci Sequence.")
term = eval(input("Which term of the Fibonacci Sequence would you like?: "))
current = 1
previous = 0
old_previous = 0
for i in range(0, term-1):
old_previous = previous
... |
9b0fac24e2bcb32eef20b015d760677dcf8fd4e1 | INNOMIGHT/problem_solving | /CTCI/linked_lists/is_palindrome_2.6.py | 602 | 4.0625 | 4 | class Solution:
def is_palindrome(self, l1):
# Method 1 Using Stacks
if l1.head is None: return False
stack = []
compare_stack = []
pointer = l1.head
while pointer is not None:
stack.append(pointer.val)
pointer = pointer.next
... |
2f0118e6be4135e57e3f1f8a92c5b3a5a78fe65b | INNOMIGHT/problem_solving | /leetcode_problems/3sum_15.py | 662 | 3.640625 | 4 | # Given an integer array nums,
# return all the triplets [nums[i], nums[j], nums[k]]
# such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
#
# Notice that the solution set must not contain duplicate triplets.
class Solution:
def three_sum(self, nums):
subsets = [[]]
result ... |
f88ecba2c69a6ec7fae1af9484a4fa33d75169fb | INNOMIGHT/problem_solving | /nagarro/longest_common_subsequence.py | 1,222 | 3.578125 | 4 | # Recursion for longest common subsequence
# def lcs(string_1, string_2, n, m):
# # base condition
# if n == 0 or m == 0:
# return 0
# # choices
# else:
# if string_1[n-1] == string_2[m-1]:
# return 1 + lcs(string_1, string_2, n-1, m-1)
# else:
# return ... |
d3950015bec0b842bc99390ea9b516ee5acf7a16 | INNOMIGHT/problem_solving | /leetcode_problems/weekly_contest_may23.py | 2,108 | 4 | 4 | # Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise.
# For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3.
# Note th... |
4862297347e3f9a218fab80d726083d68f0e1c53 | INNOMIGHT/problem_solving | /leetcode_problems/rotate_string_796.py | 601 | 4.03125 | 4 | """ We are given two strings, A and B. A shift on A consists of taking string A
and moving the leftmost character to the rightmost position.
For example, if A = 'abcde', then it will be 'bcdea' after one shift on A.
Return True if and only if A can become B after some number of shifts on A."""
class Solution:
de... |
b35189d10e4b3592eb93556e28e57f7fb06fb19e | INNOMIGHT/problem_solving | /CTCI/trees_and_graphs/validate_bst_4.5.py | 571 | 3.71875 | 4 | import sys
class Node:
def __init__(self, value=None):
self.value = value
self.left_child = None
self.right_child = None
def validate_bst(root, min_=-sys.maxsize, max_=sys.maxsize):
if root is None:
return True
if(
min_ <= root.value <= max_ and
validate_bs... |
4e689538257ed2bf96cf598e45f168c4124d2051 | INNOMIGHT/problem_solving | /nagarro/character_frequency.py | 319 | 4.0625 | 4 | def char_frequency(string):
result = ""
i = 1
while i < len(string):
if string[i-1] != string[i]:
result += string[i-1] + str(string.count(string[i-1]))
i += 1
result += string[-1] + str(string.count(string[-1]))
return result
print(char_frequency("prepinsta"))
|
ba9e7f423b945085dc454edc1658dbe25086b33a | INNOMIGHT/problem_solving | /nagarro/remainder_eleven.py | 651 | 4.03125 | 4 | # return the remainder when a large number is divided by 11.
# divisibility rule of 11:
# sum all the odd digits and sum all the even digits and the difference of these sum
# if 0 or divisible by 11 then div by eleven
from typing import final
def divisibility_by_eleven(string):
even = []
odd = []
counte... |
847aa1af14c82ef07c92060c59ffc52ffd96e3da | INNOMIGHT/problem_solving | /nagarro/ways_to_pay.py | 316 | 3.5 | 4 | def ways_to_pay(n, count):
# types of coins = 1, 2, 5, 10
# base case
if n < 0:
return 0
if n == 0:
count += 1
return count
else:
return ways_to_pay(n-1,count), ways_to_pay(n-2, count), ways_to_pay(n-5, count), ways_to_pay(n-10, count)
print(ways_to_pay(4, 0))
|
783004dbee056549524a60b758399744e48b63fb | INNOMIGHT/problem_solving | /CTCI/trees_and_graphs/implementations/all_implementations.py | 2,829 | 3.84375 | 4 | # Binary Tree Implementation
# class BinaryTree:
# def __init__(self, root_obj):
# self.key = root_obj
# self.left_child = None
# self.right_child = None
# def insert_left(self, val):
# if self.left_child == None:
# self.left_child = BinaryTree(val)
# else:
... |
2212f3aa40b95de35bb686d7462c95119bc865be | idealgupta/pyhon-basic | /matrix1.py | 310 | 4.1875 | 4 | matrix =[
[3,4,5],
[5,7,8],
[4,9,7]
]
print(matrix)
transposed=[]
#for colem
for i in range(3):
list=[]
for row in matrix:
list.append(row[i])
transposed.append(list)
print(transposed)
#same
trans =[[row[i] for row in matrix] for i in range(3)]
print(trans) |
21050df0cc7af2375f8baa9905d6d57dd4db743c | idealgupta/pyhon-basic | /sodh 2 pe.py | 221 | 3.703125 | 4 | num =int (input("2 ki gand mero : "))
count = 0
for i in range (2,num):
if (num%i)==0 :
count = count+1
break
if (count==1):
print("not prime ")
else :
print("prmr")
|
e418a4eb59c778acf17936a28d01c86b3d1a5c32 | idealgupta/pyhon-basic | /form.py | 191 | 4.125 | 4 | mat =[
[1,2,3],
[4,5,6],
[7,8,9]
]
print(mat)
trans=[]
for i in range(3):
x=[]
for row in mat:
x.append(row[i])
trans.append(x)
print(trans)
|
60204cc0f87a3226aca9b9dca85333ece2453333 | disklosr/adventofcode | /2019/4-part2.py | 1,039 | 3.59375 | 4 | def get_num_possible_passwords(start, end):
counter = 0
for x1 in range(0,10):
for x2 in range(x1,10):
for x3 in range(x2, 10):
for x4 in range(x3, 10):
for x5 in range(x4, 10):
for x6 in range(x5, 10):
... |
2636f9016936422d6ec9dbd16cecdc6c8ffe8807 | adarsh434/SELabAssignment | /19C5103_Assignment2_AdarshHondadakatti.py | 1,071 | 3.984375 | 4 | from tkinter import *
import sqlite3
root = Tk()
root.geometry('600x500')
root.title("Registration Page")
Username = StringVar()
Password = StringVar()
def database():
name = Username.get()
password = Password.get()
conn = sqlite3.connect('Form.db')
with conn:
cursor = conn.cursor()
curso... |
b4ac74f6fc08883bc460ed2ecfcd4e1bfd3b368b | StephaneAcode/Python | /threadLock.py | 3,502 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
import random
import sys
import time
def myProc():
# Repete 20 fois
i = 0
while i < 20:
sys.stdout.write("1")
sys.stdout.flush()
attente = 0.2
attente += random.randint(1, 60) / 100
# attente est a present entre 0.2 et 0.8
... |
d4ee2df15e46a8d13eaaf48d287a0e095549cc14 | andrevictor17/aulasRenzoEd | /balanceamento.py | 3,640 | 3.8125 | 4 | import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.pilha = []
def topo(self):
try:
return self.pilha[-1]
except:
raise PilhaVaziaErro()
def vazia(self):
if len(self.pilha) == 0:
return Tru... |
88bbd1a7cf97c95b7c72d8b8e62e49c7464e242a | Warwick1156/DDPG | /OUP.py | 1,411 | 3.53125 | 4 | # Based on https://en.wikipedia.org/wiki/Ornstein–Uhlenbeck_process
# Adds noise for exploration purposes
import numpy as np
# class Noise:
# def __init__(self, mean, std, theta=0.15, dt=1e-2, initial_noise=None):
# self.theta = theta
# self.mean = mean
# self.std = std
# self.dt =... |
1ad01ea99cb8e907c40ad8bb044a8294b45970a7 | Number0000009/playpen | /1337(0d3/celeb/celeb.py | 1,068 | 3.734375 | 4 | #!/usr/bin/env python3
"""
Given a party when someone knows someone = pleb;
celeb doesn't know anyone, but everyone know celeb;
Find celeb
Given O(1) func knows find celeb in O(N)
"""
N = 4
connections = [
[0, 1, 1, 0], # knows 1 and 2
[0, 0, 1, 0], # knows 3
[0, 0, 0, 0], # doesn't know anyone (celeb)
... |
0548afaa637c97901e402e67dd8a1fb32c436094 | pyrius/gt | /tws.py | 524 | 3.9375 | 4 | # ===Program to find whether sum of two elements of array is equal to an entered value
# ===Version with difference
def twoSum(nums, target):
seen = {}
for i, v in enumerate(nums):
remaining = target - v
if remaining in seen:
print(f"i = {i}, v = {v}")
print(f"remaining =... |
1981ab80bfc04eb1c2cf9672477778cf7cebdc0a | sjyn/LahTech | /cs_foundations/printnbrs.py | 111 | 3.9375 | 4 | #Steven Rosendahl
print("Enter a postivie integer")
num = int(input())
i = 0
while i <= num:
print(i)
i = i + 1
|
8668393ffae71e441dd43017ae06b5b9208b6b23 | sjyn/LahTech | /cs_foundations/grade.py | 309 | 3.9375 | 4 | #Steven Rosendahl
def getGrade(num):
if num <= 50:
return 'F'
else:
letter = 'F'
for x in range(50,num):
if x % 10 == 0:
letter = chr(ord(letter) - 1)
return letter
print("Enter your number grade:")
print("Your Grade is %s" % getGrade(int(input())))
|
498c476277aa58243c9951b2231d8f32d9df69fb | NasipCOM/Python-4-Me | /largest.py | 317 | 3.890625 | 4 |
def largest_product(series, size):
largest = 0
for i in range(len(series)-size+1):
temp = 1
for j in range(size):
temp *= int(series[i+j])
if temp > largest:
largest = temp
return largest
number = input().strip()
number, length = number.split(' ')
print(largest_product(number, int(length)))
|
ff57fae92ff7cc208e2d5f33c73a81d2130e53f2 | NasipCOM/Python-4-Me | /abc.py | 229 | 3.796875 | 4 | def sum_of(str1):
sum_digit = 0
for x in str1:
if x.isdigit() == True:
z = int(x)
sum_digit = sum_digit + z
return sum_digit
print(sum_of("12243660"))
print(sum_of("1111112223"))
|
547ce4f4d147f9e54c88dcc4ad4e9ef75b6a6b24 | NasipCOM/Python-4-Me | /durontu.py | 830 | 3.578125 | 4 |
global cases
cases = int(input())
def duronto_eagle():
planets_list = []
for i in range(cases):
num_of_planets = number_of_planets_inputs()
farthest_planet = -1
planet_index = -1
for j in range(num_of_planets):
x, y = inputs()
distance = x ** 2 + y ** 2... |
38fa12bb089d62f76120c49953c8b0b359368281 | forzen-fish/python-notes | /1.简单介绍/5简单操作.py | 1,186 | 4.25 | 4 | #语句与函数
#赋值语句:由辅助符号构成的一行代码
#赋值语句用来给变量赋予新的数据值
#赋值语句右侧的数据类型同时作用于变量
#如:
#代码:
# a = 10
# b = "10"
# c = str(a)
# print(type(a))
# print(type(b))
# print(type(c))
#输出结果:
# <class 'int'>
# <class 'str'>
# <class 'str'>
#分支结构语句
#作用:根据判断条件决定运行方向的语句
# 由if elif else 构成
#格式:
"""
if 条件:
成立语句
elif 条件:
el... |
4bb1f08be42cd7249b668f40e707a79cfca25477 | forzen-fish/python-notes | /4.元组列表&字典/3列表排序与元祖.py | 768 | 4.53125 | 5 | """
列表的排序操作
sort从小到大,如需大到小排序,利用reverse翻转
num = [1,5,61,7,8,5]
num.sort()
print(num)
[1, 5, 5, 7, 8, 61]
num = [1,5,61,7,8,5]
num.sort()
num.reverse()
print(num)
[61, 8, 7, 5, 5, 1]
"""
"""
列表的嵌套
列表中还有列表:
[[1,2],[2,3],[3,4]]
"""
"""
元组
与列表类似但是元组不能修改,使用圆括号
a = (1,2,3,4)
索引从零开始
a[0]--》1
...
"""
"""
修改元组
元组的值是不允许修改的,但... |
a8ecb7ed69b8c98aaa0aee2306a69ccec257126e | forzen-fish/python-notes | /1.简单介绍/1计算机与计算机程序简介.py | 1,336 | 3.609375 | 4 | #不知道叫啥了,自己取名字吧
#计算机与程序设计
#计算机:功能性、可编程性
#功能性:对数据操作,表现为计算,输入出,处理,结果存储
#可变成性:根据指令自动的,可预测的准确的完成任务
#计算机根据摩尔定律预测 指数发展
#程序设计是计算机可编程性的体现
#程序设计语言:程序设计的具体方式,计算机语言不具备二义性
#1972年c语言诞生,1990年python诞生
#编程语言的执行方式
#编译与解释
#源代码:采用某种编程语言编写的计算机程序,人类可读 如:a = 1 + 1
#目标代码:计算机可直接执行 “普通人类”不可读 如:0101 0011
#程序执行的两种方式
#1.编译:将源代码一次性转换成目标代码... |
8249a1941baa2436b60eb2c17ddce264cf335c7d | forzen-fish/python-notes | /3.字符串与其操作/2字符串操作与函数.py | 1,188 | 3.625 | 4 | """
字符串输入
input():从标准输入中读取一行文本,默认标准输入为键盘
"""
"""
字符串的存储方式:
python不支持单字符,‘a’,同样作为字符串使用
访问字符串中的值,需要通过访问字符串下标
如:
当:name='chenlu'
访问name[0]时,就会返回c
字符串从0开始排序
"""
"""
字符串切片
[起始:结束:间隔]
name='chenlu'
name[0:3] 取0到2--->che
name[3:5] 取3到4--->nl
name[1:-1] 取1到倒数第二个--->henl
name[2:] 取2到最后一个--->enlu
name[::-2] 从后往前,间隔2,... |
dea33f93aa99d41717a9199a80ea5309d4f660bc | forzen-fish/python-notes | /4.元组列表&字典/1列表.py | 969 | 3.84375 | 4 | #元组列表&字典
"""
列表:python中的一种数据结构,可以存储不同类型的数据
创建方式: 列表名 = [变量1,变量2,...,变量n]
列表的索引也是从0开始
列表可以套娃
如:
list_a = ['a',1,[1,'a']]
list_a[0]--->'a'
"""
"""
列表的循环遍历
使用for和while循环遍历列表
代码1(使用for):
name = ['c','h','e','n','l','u']
for a in name:
print(a)
代码2(使用while):
i=0
name = ['c','h','e','n','l','u']
while i<len(name):
... |
8646d28c0880d9b3851d0ec49e97ef259031bec3 | akshitshah702/Akshit_Task_5 | /# Task 5 Q3.py | 436 | 4.21875 | 4 | # Task 5 Q3
def mult_digits():
x = input("Enter number ")
while type(x) is not int:
try:
while int(x) <= 1:
x = input("Please enter a number greater than 1: ")
x = int(x)
except ValueError:
x = input("P... |
8374d1dc56bce80b7f1b62b07e3e99571f8c44ca | elvis-alexander/StonyBrookCS | /cse307/cse307/tpg/datatypes.py | 1,110 | 3.6875 | 4 | import tpg
# these are the nodes of the abstract syntax tree.
class Node(object):
"""
A base class for nodes. Can be used to superclass different nodes
"""
def evaluate(self):
"""
Called on children of Node to evaluate that child.
"""
raise Exception("Not Implemented... |
93e4b9ff0b31ab6864e2fbfeeab8933faf600df7 | elvis-alexander/StonyBrookCS | /cse307/cse307/tpg/test.py | 3,213 | 4.3125 | 4 | class SemanticError(Exception):
"""
This is the class of the exception that os raised when a semantic error occurs
"""
# these are the nodes of the abstract syntax tree
class Node(object):
"""
A base class for nodes. Can be used to superclass different nodes
"""
def evaluate(self):
... |
58a8b9c439ac379a4154f0fbced6937215be1fd2 | drayoden/ccurry | /015listdelslice.py | 424 | 4 | 4 | stuff = ['mooses', 'puppies', 'unicorn', 'wombat','kitties','squirrels']
print(stuff)
del stuff[2] # deletes 'unicorn'
print(stuff)
stuff.insert(2,'monkey')
print(stuff)
del stuff[-1] # removes last element
print(stuff)
stuff.insert(2,'gremlin')
print(stuff)
del stuff[1:] # removes everything starting at [1]: 'pu... |
3d50ef3d4cd1ddc511ff29ce06cd408c86b92e1d | drayoden/ccurry | /011counter.py | 177 | 3.65625 | 4 | from collections import Counter
bp1 = ['one', 'two', 'one', 'three', 'four', 'two', 'seven', 'two', 'one', 'three']
# returns a dictionary of 'value':count
print(Counter(bp1)) |
154b92734fbf9f37cb90712f7f9d023296862654 | MachineDragon/ReplaceVowelsWithG | /ReplaceVowelsWithg.py | 271 | 3.921875 | 4 | # function replaces vowels with the letter "g"
def translate(phrase):
new_word = ""
for i in phrase:
if i in "AEIOUaeiou":
new_word += "g"
else:
new_word += i
return new_word
print(translate(input("enter a word: ")))
|
183b9a7d439dca14510d9257712d90d1adc8a515 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/QuickSort.py | 801 | 4.125 | 4 | def partition(array, low, high):
i = (low - 1)
pivot = array[high]
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
array[i], array[j] = array[j], array[i]
array[i+1], array[high] = array[high], array[i+1]
return (i + 1)
def quickSort(array, low, high)... |
c4f2ba0d605988bfcfb046c42e92b4ef216c0534 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Merge_sort.py | 916 | 4.28125 | 4 | def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Finding the middle point and partitioning the array into two halves
middle = len(unsorted_list) // 2
left = unsorted_list[:middle]
right = unsorted_list[middle:]
left = merge_sort(left)
right = merge_s... |
8b73c09f85bb34d2331621e8db75013909455bf7 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Projects/findingLeastPosiitveNumber.py | 941 | 3.953125 | 4 | # finding least positive number
# Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
# find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
# code contributed by devanshi katy... |
678c35594c3f41a0afc0b8e8b48386e37ab4386b | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Projects/Color Game.py | 5,671 | 4.03125 | 4 | # import needed modules
from tkinter import *
import random
# define Score label
score = 0
# list of colors
colors = ['white', 'blue', 'green', 'yellow', 'orange', 'red', 'brown', 'black']
# Timer
timer = 60
# main game function
def startGame(event):
if timer == 60:
countdown()
nextColor()
# func... |
6e3235205388258659eb7ac63925152e52267ed9 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Insertion_sort.py | 305 | 4.21875 | 4 | def insertionSort(array):
for index in range(1,len(array)):
currentvalue = array[index]
position = index
while position>0 and array[position-1]>currentvalue:
array[position]=array[position-1]
position = position-1
array[position]=currentvalue
return array
|
9f39e95b9c161587fc815127b502929cb429c89b | CodeDummy/Python_Learning | /syntax.py | 845 | 4.0625 | 4 | #syntax.py
#function definition
def Whtnum (List1):
#Learning if Else
if List1[1] != 13:
print ('Not 13')
elif List1[2]==14:
print('14')
else :
print('13')
#Variable assignment
loop=5
#Raw input example
#name= raw_input('What is your name\n')
#print ('Hello %s' %name)
#for loop... |
a805bd08f69684c2cf96a9c71fc109a149568c8b | Himanshu-L2/Decimal-to-Binary-calc | /binary to decimal.py | 398 | 3.984375 | 4 | x=input('Press x to exit OR Press any other key to restart.')
while(x!='x'):
op=int(input('\t1.Binary to Decimal \n\t2.Decimal to Binary'))
n=int(input('Please Enter number:'))
if (op==1):
deci1 =int(n,2)
print('Your answer is',deci1)
elif(op==2):
print('Your answer is',(... |
f16f9e65b27f801012bf6f955b7ee03f5fc5fa98 | jtleider/uisalaries | /processData.py | 7,000 | 3.828125 | 4 | import time
import pandas as pd
import numpy as np
import requests
pd.set_option('display.max_rows', None)
debug = False
def collegeSalaries(campus, code, sleep=30):
"""Return pandas DataFrame with 2017-2018 Gray Book Information for given college of the University of Illinois.
Args:
campus (str): Campus of whic... |
b75c3d95b8a1e0ae5d610591821636a639d765db | felixgomez/adventofcode2017 | /day1/1_1.py | 669 | 3.546875 | 4 | import pytest
def calculate_sum(code):
code_list = [int(digit) for digit in list(code)]
sum = 0
for index, digit in enumerate(code_list):
next_index = (index + 1) if (index + 1) < len(code_list) else (index + 1) % len(code_list)
if digit == code_list[next_index]:
sum += digit
... |
8b50ff7d208debe57d919ff3eb696d0308e32b87 | ManuelXI/Credit-Scoring-Module | /Twitter_Analysis.py | 2,041 | 3.5625 | 4 | import GetOldTweets3 as got
import string
from nltk.sentiment.vader import SentimentIntensityAnalyzer
tw_username = ''
while True:
try:
choice_tw = int(input('''
Do you have a Twitter account:
1. Yes
2. No
'''))
if choice_tw < 0 or choice_tw > 2:
... |
d65a820aabe2a9f8bd01729fef72c9c2c19fc8d3 | 616353553/MovieStars | /src/DataReader.py | 2,501 | 3.625 | 4 | from Actor import Actor
from Movie import Movie
from Starring import Starring
import json
from pprint import pprint
actors = []
movies = []
starrings = []
def gross_value(movie_name):
for movie in movies:
if movie.movie_name == movie_name:
return movie.gross_value
return "N/A"
def part... |
b238fd9a5af1f7d68a9ed44428f57a11a1d87e8a | ClaytonCKOB/validacao_cpf_python | /validar_cpf.py | 1,964 | 3.796875 | 4 | # O cálculo do cadastro de pessoa física (cpf) é padronizado. Logo,
# as linhas de código a seguir buscam executá-lo para verificar sua
# validade.
class Cpf:
def __init__(self, cpf): #Módulo Construtor
self.cpf = cpf
def filtro_de_valores(self, cpf):
if len(cpf) > 14:
print(... |
642efec882cdf5e9a7c4e1e2151d5e0b95b68631 | SaibersysTesting/HARSHITHA-VAAS-.NET | /recruitement.py | 711 | 3.9375 | 4 | #!/usr/bin/python
class Jobs:
'Common base class for all Job seekers'
JseekerCount = 0
def __init__(self, name, tech):
self.name = name
self.tech = tech
Jobs.JseekerCount += 1
def displayCount(self):
print ("Total Job Seekers %d" % Jobs.JseekerCount)
def displa... |
85951385adac5b895720e369d43a63de1489a82e | rodrigobn/Python | /Lista de exercício 3 (if, elif, else)/ex05.py | 563 | 4.0625 | 4 | # 5. Faça um Programa que leia três números e mostre o maior deles.
numero1 = float(input("Digite o primeiro numero: "))
numero2 = float(input("Digite o segundo numero: "))
numero3 = float(input("Digite o terceiro numero: "))
if numero1 > numero2 and numero1 > numero3:
print("O numero maior é o {}".format(numero1)... |
ca1a75914b4cf61c03b242de254143f880c0458c | rodrigobn/Python | /Lista de exercício 4 (laços)/ex14.py | 237 | 3.953125 | 4 | """
14 - Faça um programa para:
a) Ler um valor x qualquer
b) Calcular Y = (x+1)+(x+2)+(x+3)+(x+4)+(x+5)+…(x+100).
"""
x = float(input("Digite o valor de X: "))
y = 0
for i in range(1, 101):
y += (x+i)
print("{:.2f}".format(y)) |
0d842964ec7ceecba7e10a4bef65b812a63a0e0f | rodrigobn/Python | /Lista de exercício 4 (laços)/ex50.py | 1,469 | 4 | 4 | """
50 - Em uma competição de ginástica, cada atleta recebe votos de sete jurados. A melhor e a pior nota são eliminadas. A sua nota fica sendo a média dos votos restantes. Você deve fazer um programa que receba o nome do ginasta e as notas dos sete jurados alcançadas pelo atleta em sua apresentação e depois informe a ... |
ae381fafbaee7cdd89c5f4078229c1693b4504ea | rodrigobn/Python | /Lista de exercício 3 (if, elif, else)/ex09.py | 2,381 | 4.03125 | 4 | """ 9. Faça um programa para o cálculo de uma folha de pagamento, sabendo que os descontos são do Imposto de Renda, que depende do salário bruto (conforme tabela abaixo) e 3% para o Sindicato e que o FGTS corresponde a 11% do Salário Bruto, mas não é descontado (é a empresa que deposita). O Salário Líquido corresponde ... |
04994935faa67526f4588d98d22ca235e993285d | rodrigobn/Python | /Lista de exercício 4 (laços)/ex09.py | 275 | 4.21875 | 4 | """
9 - Faça um programa para calcular a área de N quadriláteros. Fórmula: Área = Lado * Lado.
"""
quadrados = int(input("Informe quantos quadrados: "))
for i in range(quadrados):
lado = float(input("Informe o lado do quadrado: "))
area = lado * lado
print(area) |
c4b2736ddd4f1672c1423c90298befe5c6ed71cb | rodrigobn/Python | /Lista de exercicio 2 (print, input, tipos primitivos)/ex14.py | 414 | 3.828125 | 4 | #14. Escrever um algoritmo para determinar o consumo médio de um automóvel
#sendo fornecida a distância total percorrida pelo automóvel e o total de
#combustível gasto.
distancia = float(input("Distancia percorrida em km: "))
combustiveGasto = float(input("Quantidade de combustivel gasto em L: "))
resultado = dista... |
9713106449a94348367e55fdb503a0508a74ae03 | rodrigobn/Python | /Lista de exercício 4 (laços)/ex15.py | 282 | 3.703125 | 4 | """
15 - Fazer um programa que calcule e escreva a soma dos 50 primeiros termos da seguinte série:
(1000/1) + (997/2) + (994/3) + (991/4) + ...
"""
numerador = 1000
resultado = 0
for i in range(1, 51):
resultado += numerador/i
numerador -= 3
print("{:.2f}".format(resultado)) |
c2b759bb13e094290557153d12bb221a97b9718a | rodrigobn/Python | /Lista de exercício 3 (if, elif, else)/ex13.py | 1,252 | 4.375 | 4 | """
13. Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações:
• Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa ... |
86a771a75b4872377aaab4b9be84b208d8792cd5 | rodrigobn/Python | /Lista de exercicio 2 (print, input, tipos primitivos)/ex4.py | 157 | 4.28125 | 4 | #4.Faça um Programa que converta metros para centímetros.
metro = float(input('Digite o numero em metros: '))
cm = metro * 100
print(metro,"m = ",cm,"cm") |
4b974df000fc347992e1cf94bde59a217fd55dfd | rodrigobn/Python | /Lista de exercício 4 (laços)/ex07.py | 278 | 4.15625 | 4 | """
7 - Escreva um programa que calcula o fatorial de um dado número N.
"""
num = int(input("Digite o valor: "))
while num < 0:
num = int(input("Digite o valor: "))
fatorial = 1; #O valor neutro da multiplicação
for i in range(num, 1, -1):
fatorial *= i
print(fatorial) |
acca982f9e942c4bfc76cf4efbe9fc7e2e55474b | rodrigobn/Python | /Lista de exercício 3 (if, elif, else)/ex23.py | 715 | 3.9375 | 4 | """
23. Tendo como dados de entrada a altura e o sexo de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: para homens: (72.7*h) – 58 e para mulheres: (62.1*h) - 44.7 (h = altura)
"""
altura = float(input("Digite a altura em m: "))
while altura <= 0:
altura = float(inpu... |
3633225f705e1e30ca8d56a034f2c6161ff7f8df | rodrigobn/Python | /Lista de exercício 4 (laços)/ex21.py | 616 | 4.03125 | 4 | """
21 - Faça um programa que peça um número inteiro e determine se ele é ou não um número primo. Um número primo é aquele que é divisível somente por ele mesmo e por 1.
"""
numero = int(input("Digite um numero inteiro: "))
while numero < 0:
numero = int(input("Digite um numero inteiro: "))
divisivelPorOutros = ... |
27cb3413018e8caa819fbf341dcd708a74505a55 | rodrigobn/Python | /Lista de exercicio 5 (Lista e Matrizes)/ex12.py | 799 | 3.8125 | 4 | """
12 - Foram anotadas as idades e alturas de 30 alunos. Faça um Programa que determine quantos alunos com mais de 13 anos possuem altura inferior à média de altura desses alunos.
"""
import random
idades = []
alturas = []
alturaTotal = mediaAltura = contadorMais13 = 0
# Povoa a lista randomicamente
for i in range(... |
250dba542c95de2089a84ab5a0b9a3687bf51bb4 | willwiz/caputo_derivatives | /src/py/tools/ProgressBar/ProgressBar.py | 1,507 | 3.875 | 4 | #!/usr/bin/env python3
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '*', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (I... |
b00f9dd57b7e0bd7d1067b93a3f56819398ef9bb | sQu4rks/se-for-ase-sample_code | /02_unit_testing_lab/models.py | 1,186 | 3.59375 | 4 | import json
class Car:
def __init__(self, color, top_speed, gear_box, average_speed, hours_driven):
self.color = color
self.top_speed = top_speed
self.gear_box = gear_box
self.average_speed = average_speed
self.hours_driven = hours_driven
# For the more advanced python ... |
3c89ce2383b4396771648c1cd3cd652e76f2ec8e | yangjufo/LeetCode | /Python/297. Serialize and Deserialize Binary Tree.py | 1,229 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def __init__(self):
self.str = ""
def serialize(self, root):
"""Encodes a tree to a single string.
:... |
12cc1c0bc76686030a47b64a2c191c3372a7fa2f | yangjufo/LeetCode | /Python/1032. Stream of Characters.py | 821 | 3.53125 | 4 |
class StreamChecker:
def __init__(self, words: List[str]):
self.waitlist = []
self.trie = dict()
for word in words:
tmp_dict = self.trie
for letter in word:
tmp_dict = tmp_dict.setdefault(letter, dict())
tmp_dict['#'] = '... |
77afe5bbb59a96c6c034363002686d484bb941e5 | yangjufo/LeetCode | /Python/247. Strobogrammatic Number II.py | 596 | 3.5 | 4 | class Solution:
def findStrobogrammatic(self, n: int) -> List[str]:
def helper(n, m):
if n == 0:
return [""]
if n == 1:
return ["0", "1", "8"]
sublist = helper(n - 2, m)
res = list()
for s in sublist:
... |
6ef451c6ff968e2aef35b907a2a5fefb461d5816 | yangjufo/LeetCode | /Python/288. Unique Word Abbreviation.py | 775 | 3.546875 | 4 | class ValidWordAbbr:
def __init__(self, dictionary: List[str]):
self.abbr = collections.defaultdict(int)
self.dictionary = set(dictionary)
for word in self.dictionary:
if len(word) <= 2:
self.abbr[word] += 1
else:
self.abbr[word[0] + s... |
8140813caa7ece737bef03e3a15010ca5b74fd2c | yangjufo/LeetCode | /Python/212. Word Search II.py | 1,307 | 3.671875 | 4 | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
WORD_KEY = '$'
trie = {}
for word in words:
node = trie
for c in word:
node = node.setdefault(c, {})
node[WORD_KEY] = word
rowNum =... |
e7c652fc7922897c40dae9cae0856c0b07aabef5 | jacobsny/Semester_Project | /src/serverBackEnd/backEnd.py | 7,143 | 3.765625 | 4 | from random import randint
import json
import math
#python object orientated programming
#location is a class that takes x and y
#player class that takes location, size and kill state
class Location:
def __init__(self, xcor, ycor):
self.x = xcor
self.y = ycor
def distance(self, other):
... |
970d9c88ae8b94072b9fe44dda83bfba5b13195e | redclazz2/LogicaDeProgramacion | /Quizzes/Quiz23Abril/Punto6.py | 282 | 4.125 | 4 | palabra = input("Ingrese una palabra para verificar si es un palíndromo: ")
palabraLista = list(palabra.lower())
palabraInver = list(palabra.lower())
palabraInver.reverse()
if palabraLista == palabraInver:
print("Es un palíndromo!")
else:
print("No es un palíndromo!")
|
34102a0ed93b688e3c76986f09f5cdc10f2c9774 | redclazz2/LogicaDeProgramacion | /Quizzes/Quiz16Abril/Punto7.py | 1,354 | 4 | 4 | #Esta función se encarga de retornar la sumatoria de los digitos introducidos
def sumaDigitos(numero):
suma = 0
while numero != 0:
digito = numero % 10
suma = suma + digito
numero = numero // 10
return suma
cantidadSumatoriaMenora10 = 0
mayor = -1
n_mayorsuma = 0
numero = int(input(... |
87d5f8e6d2656644ab4ef47d5cafed97bf65f3c6 | redclazz2/LogicaDeProgramacion | /Laboratorios/Lab23_0504/Punto4.py | 427 | 3.8125 | 4 | entrada = 0
ArrayNumeros = []
i = True
while(i):
entrada = input("Ingrese un número real para añadir a una lista, ingrese FIN para terminar: ")
if entrada != "FIN":
entrada = float(entrada)
ArrayNumeros.append(entrada)
elif entrada == "FIN":
i = False
ArrayNumeros.sort()
print("Se in... |
10ecf195aa78aa5e5d9d45903db5e552cfa3f918 | redclazz2/LogicaDeProgramacion | /Talleres/Taller30Abril/Punto19.py | 258 | 3.75 | 4 | segundos = float(input("Ingrese la cantidad de segundos: "))
horas = segundos/3600
horasFin = horas//1
minutos = (horas-horasFin)*60
minutosEnt= minutos//1
segundos = (minutos-minutosEnt)*60
print("{0}:{1}:{2}".format(int(horasFin),int(minutosEnt),segundos)) |
6eed8259d5648e2b21a4bb9aa2f80f10d37feb1a | redclazz2/LogicaDeProgramacion | /Talleres/Taller12Mayo/Ejercicio2.1.py | 742 | 3.96875 | 4 | import pandas as pd
inicio = int(input("Ingrese el año inicial: "))
fin = int(input("Ingrese el año final: "))
ventas = {}
for i in range(inicio,fin + 1):
ventas[i]= float(input('Introduce las ventas del año ' + str(i) + ': ')) #Funciona de manera que i es el año y se le añade como valor
#es lo mismo que tene... |
276fbf877d1c662407fa49320af4e645a0d0d5dd | redclazz2/LogicaDeProgramacion | /Talleres/Taller30Abril/Punto25.py | 289 | 3.671875 | 4 | compra = float(input("Ingrese el valor de la compra: "))
iva = compra * 0.19
desc = 0
if compra >= 150000:
desc = compra * 0.05
print("Valor original {0}, valor del iva {1}, compra + iva {2}, descuento {3}, valor con descuento {4}".format(compra,iva,compra + iva,desc,compra+iva-desc)) |
689d6486bd0a0e3d36a1f40449dab6d62ae26daf | redclazz2/LogicaDeProgramacion | /Talleres/Taller30Abril/Punto49.py | 166 | 3.765625 | 4 | i = 0
sum = 0
while i<10:
numero = float(input("Ingrese un número para la sumatoria: "))
sum += numero
i+=1
prom= sum / 10
print("La sumatoria es:",prom) |
a9de5f2c37a847395d2fff2e842246b3d3f25c10 | redclazz2/LogicaDeProgramacion | /Laboratorios/Lab23_0504/Punto3.py | 303 | 3.921875 | 4 | nota1 = float(input("Ingrese la primera nota: "))
nota2 = float(input("Ingrese la segunda nota: "))
nota3 = float(input("Ingrese la tercera nota: "))
promedio = (nota1+nota2+nota3)/3
if promedio >= 7:
print("Promocionado")
if 4<=promedio<7:
print("Regular")
if promedio<4:
print("Reprobado") |
9d63c8ef977b16886ae52ed88b8e627796d95a9e | redclazz2/LogicaDeProgramacion | /Talleres/Taller30Abril/Punto56.py | 299 | 3.796875 | 4 | contador,arrayNumeros = 0,[]
numero = int(input("Ingrese el número para evaluar sus factores"))
for i in range(1,numero+1):
if numero % i == 0:
contador += 1
arrayNumeros.append(i)
print("Se encontraron un total de: {0} factores, resaltando: {1}".format(contador,arrayNumeros))
|
1f77fa491cc685359bfad11472df1b8128221367 | redclazz2/LogicaDeProgramacion | /Talleres/Taller30Abril/Punto2.py | 94 | 3.84375 | 4 | num1 = float(input("Ingrese un número real: "))
res = num1 ** 2
print("El cuadrado es:",res) |
1952e3f1b905bcdcd2a969da1413d80678365e38 | redclazz2/LogicaDeProgramacion | /Talleres/Taller30Abril/Punto54.py | 684 | 3.84375 | 4 | w,n,mayor,menor,impar,par,mulocho = True,0,0,0,0,0,0
while w:
n = int(input("Ingrese un número cualquiera tenga en cuenta que el 0 es para terminar el programa:"))
if n>0:
mayor+=1
elif n==0:
w = False
break;
else:
menor+=1
if n%2 == 0:
par +=1
else:
... |
e16deb0fef29c10993c93b1957d30986cee0ac7f | redclazz2/LogicaDeProgramacion | /Talleres/Taller30Abril/Punto37.py | 259 | 3.859375 | 4 | numero = input("Ingrese un número entero menor a 100000 para calcular la cantidad de dígitos que tiene: ")
if int(numero)<100000:
print("El número tiene:",len(numero),"digitos.")
else:
print("El número es mayor a 100000, la entrada es inválida.") |
73f20b637dc2b6cf39f4455722c5056e9f80daec | redclazz2/LogicaDeProgramacion | /Quizzes/Quiz16Abril/Punto1.py | 297 | 3.90625 | 4 | def validar():
direccion = input("Para validar el email, este debe contener @, de otra manera saldrá error \nTu email: ")
if direccion.find("@")<0:
print("Dirección no válida, debe contener @")
validar()
else:
print("Dirección de correo válida")
validar() |
9ed002459e345e00ad9013eb70965bd0640639f4 | DrunkCynicalUnicorn/training_tests_python | /PL's exercices/exercices_cartes.py | 6,757 | 3.8125 | 4 | import random
from math import ceil, floor
def maze(size=10):
"""
Créer une carte de labyrinthe en console de largeur et de hauteur size
Le labyrinthe est encadré par des murs et les murs sont disposés aléatoirement dans la carte comme ceci :
wwwwwww
w..w..W
ww..WWW
WWW.WWW
W... |
ac64b60d214a64cd3aea7b90de2e50f96848646a | AlexAlestra100/Alexander-College-Projects | /Databases/pythonDB.py | 1,035 | 3.625 | 4 | import sqlite3
import csv
conn = sqlite3.connect('forTaxPurposes.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS stocks(date text, trans text, symbol text, qty real, price real)''')
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
conn.commit()
t = ('RHAT',)... |
d4b14540013b3f2effb087234b7333aae6559b0c | chapman-cpsc-230/hw1-abouc101 | /Seconds2Years.py | 290 | 3.84375 | 4 | x=1
while x>0:
Seconds = input ('Please enter any amount of seconds')
Y=Seconds/60.0000/60/24/365
if Y>100:
print "No the baby won't live"
else:
print "Yes the baby will live"
print "There are %d years in %d Seconds" % (Y, Seconds)
name = input ('')
|
f48416b78c2e6a29a4b041b843cd8de5d280a2b0 | anilgeorge04/cs50harvard | /python-intro/credit.py | 1,958 | 4.25 | 4 | # This software validates a credit card number entered by the user
# Validity checks: Format, Luhn's checksum algorithm*, Number of digits, Starting digit(s) with RegEx
# Output: It reports whether the card is Amex, Mastercard, Visa or Invalid
# *Luhn's checksum algorithm: https:#en.wikipedia.org/wiki/Luhn_algorithm
im... |
afa2349ffe2a829689ff05ef146cf2380a27e6d5 | israelmarcelino/Python_codes | /2_Delay.py | 1,006 | 3.953125 | 4 | '''
- EXEMPLO DE FUNÇÕES
def hello(meu_nome,idade):
print('Olá',meu_nome,'\nSua idade é:',idade)
def calcular_pagamento(qtd_horas, valor_hora):
horas = float(qtd_horas)
taxa = float(valor_hora)
if horas <= 40:
salario=horas*taxa
else:
h_excd = horas - 40
salario = 40*taxa+(h_excd*(1.5*taxa))... |
0cf8dabae652848b5d0ac46fd753e0ee977630ee | AjayMistry29/pythonTraining | /Extra_Task_Data_Structure/ETQ8.py | 831 | 4.1875 | 4 | even_list=[]
odd_list=[]
while True:
enter_input = int(input("Enter a number from from 1 to 50: "))
if enter_input>=1 and enter_input<=50 and (enter_input % 2) != 0 and len(odd_list)<5:
odd_list.append(enter_input)
print("Odd List :" ,odd_list)
continue
elif enter_input>=... |
ea3c024d8cf79f697fcf4bffe6951487d3e401e9 | AjayMistry29/pythonTraining | /Task4/T4Q6.py | 213 | 4.0625 | 4 | def calculateSum (a,b):
s = int(a) + int(b)
return s
num1 = input("Enter number one :" )
num2 = input("Enter number two :" )
# calculate sum
sum = calculateSum (num1, num2)
# print sum
print ("Sum = ", sum) |
d2c7eb76a23802e46178e6f21d86848b2381d970 | AjayMistry29/pythonTraining | /Task4/T4Q4.py | 114 | 3.828125 | 4 | items=[n for n in input("Type the words with hyphen saprated: " ).split('-')]
items.sort()
print('-'.join(items))
|
b86c042cbb31c5a3ebe00322619d6a32ae5d09ea | AjayMistry29/pythonTraining | /Task3/T3Q6.py | 321 | 3.75 | 4 | list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
print("List : ",list)
modified_list = [list[0],list[25],list[27],list[28],list[29]]
print(modified_list)
result_list = []
for i in modified_list:
i = i*i
result_list.append(i)
print("Requeted List is : ", result_list)
... |
b7497ea31a107328ecb0242600df34d808483353 | AjayMistry29/pythonTraining | /Task4/T4Q2.py | 359 | 4.3125 | 4 | def upperlower(string):
upper = 0
lower = 0
for i in string:
if (i>='a'and i<='z'):
lower=lower+1
if (i>='A'and i<='Z'):
upper=upper+1
print('Lower case characters = %s' %lower,
'Upper case characters = %s' %upper)
string = input("E... |
9abf1bd0f4e972b8a79c0a39fc11b34ec5897c32 | poojansoni/Codes | /python/lab7.py | 1,141 | 3.875 | 4 | #%%
from sklearn.cluster import KMeans
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot as plt
df = pd.read_csv(r'C:\Users\sonip\OneDrive\Documents\Codes\python\kmeans.csv')
df.head()
# USING N = 3
km = KMeans(n_clusters=3)
y_predicted = km.fit_predict(df[['Age','Income... |
3fab33ec2b0ec5d95bcfefbab6c1b878d0c81daf | mrodzlgd/dc-ds-071519 | /Warm_Ups/number_finder.py | 766 | 4.25 | 4 | def prime_finder(numbers):
import numpy as np
prime=np.array([])
"""will select only the prime #'s from a given numpy array"""
for n in np.nditer(numbers):
if (n%2)>0:
prime = np.append(prime,n)
return prime
#a series of numbers in which each number ( Fibonacci number ) ... |
730decdf2bc9cc977be63e0d9b98255597f7b332 | nathanielwichman/nlpproject | /prepare_wino.py | 933 | 3.59375 | 4 | import csv
from random import shuffle
def process(num_examples):
data = list()
# get pre-printed data from file
wino = open("test_output2", 'r')
wino_count = 0
for line in wino:
if wino_count > num_examples:
wino_count = num_examples
break
data.append((line... |
19366ff7276c57d6a4a02557269793fb5f1d818b | Frans-L/Algorithm-Challenge-Heaps | /fibonacci_heap.py | 7,249 | 4.0625 | 4 | import math
import abstract_heap as heap
class _Node(heap.HeapNode):
def __init__(self, key, val):
self.key = key
self.val = val
self.parent = self.child = None
self.left = self.right = self
self.degree = 0
self.flag = False
# Implementation of FibonacciHeap.
# ht... |
e78d5f3b2fab1bcd1ec737519c4ae2e36e72b1a0 | LeeThomas13/data-structures-and-algorithms | /python/code_challenges/tree_intersection/tree_intersection.py | 2,459 | 3.9375 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.next_ = None
self.front = None
self.back = None
class BinaryTree:
def __init__(self):
self.root = None
def pre_order(self):
values = []
... |
b25ceff695a38347221a7c8c1935ab59b801d1b2 | js4683/CS172 | /Homework 3/hw3.py | 3,697 | 4.03125 | 4 | #Author: Jashanpreet Singh
#Id: js4683
#Date: 05/17/19
#Purpose: CS172 Homework 3
#NOTE: The program requires two fingers for the drag to work on Macbooks and maybe Windows.
import pygame
#importing all the classes
from Ball import Ball
from Text import Text
from Block import Block
#intiailizing the environment in th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.