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 |
|---|---|---|---|---|---|---|
c1993d62bac5084c7dd45875deded6296f9e6272 | a22616/Python | /12_Inheritance.py | 1,200 | 3.796875 | 4 | '''
30 what is inheritance ?
ans : Inheritance is a way of exeating a new class from an
existing class.
31 TYPE OF INHERITANCE
ans : Single inheritance
single inheritance occure when child class inherits only
a "single" parent class
Multiple inhertance
Multiple inheritance occu... |
e25d7e6057bcc01d086207a6655741bd1658e2ba | sebastiandro/advent-of-code | /day1/1.py | 458 | 3.59375 | 4 | # Advent of Code Day 1
# Part A
input_file = open("1-input.txt", "r")
input_data = input_file.read()
nums = list(map(int, input_data.split()))
totalFreq = sum(nums)
print("Total frequency: {}".format(totalFreq))
# Part B
currFreq = 0
freqs = {}
while True:
for num in nums:
currFreq = currFreq + num
... |
661627a12dc195ee9a2c9b26fc340d7e0a2099be | LavanyaBashyagaru/letsupgrade- | /day3assigment.py | 539 | 4.21875 | 4 | '''You all are pilots, you have to land a plane,
the altitude required for landing a plane is 1000ft,
if it is less than that tell pilot to land the plane,
or it is more than that but less than 5000 ft
ask the pilot to come down to 1000 ft,
else if it is more than 5000ft ask the pilot togo around and try later'''
... |
dd982408aa70bfc988b53bc60935adb2bc4f261a | felipesantos10/Python | /mundoUM/ex033.py | 621 | 4.09375 | 4 | #Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
n1 = int(input('Informe o primeiro numero: '))
n2 = int(input('Informe o segundo numero: '))
n3 = int(input('Informe o terceiro numero: '))
if n1>n2 and n1>n3:
print('{} é o maior numero'.format(n1))
if n2>n1 and n2>n3:
print('{}... |
755dace85dfc7180b5e208f7ba5ce5691a742e1f | felipesantos10/Python | /mundoDois/ex045.py | 1,313 | 3.765625 | 4 | #Crie um programa que faça o computador jogar Jokenpô com você.
inicio = str(input('''Bem vindo ao jokenpô!!!
Vamos começar? sim/não
'''))
if inicio == 'sim':
import random
from time import sleep
itens = ( 'pedra','papel','tesoura')
maquina = random.randint(0,2)
humano = int(input('''Escolha ... |
895c942ce32f3e4eff983cbe258e9fce04215e03 | felipesantos10/Python | /mundoUM/ex018.py | 388 | 4.09375 | 4 | 3#Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
import math
ang = float (input('Valor do angulo: '))
sen = math.sin(math.radians(ang))
cos = math.cos(math.radians(ang))
tan = math.tan(math.radians(ang))
print('O angulo {} apresenta seno de {:.2f} cosse... |
70d43485cecbf81e32017c8ebfde6720de099f9a | felipesantos10/Python | /mundoUM/aula8.py | 693 | 4.125 | 4 | #Utilizando módulos
#import math ( importando toda a biblioteca de matematica)
#from math import sin( importante apenas as informações que eu necessito da biblioteca)
#funcionalidades do match
#Funcionalidade do match
#ceil (arrendomamento pra cima)
#floor (arredodamento pra baixo)
#trunc ( quebrar o numero)
#pow (pot... |
1a21c71cde5540e648e26126a3d52c7a68ad137e | felipesantos10/Python | /mundoUM/ex019.py | 498 | 4.03125 | 4 | #Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.
import random
aluno1 = str(input('Nome do primeiro aluno: '))
aluno2 = str(input('Nome do segundo aluno: '))
aluno3 = str(input('Nome do terceir... |
c61b8d10b26b658b8299c691de760b7ab6eb1249 | felipesantos10/Python | /mundoUM/ex022.py | 384 | 4.15625 | 4 | #Crie um programa que lei o nome completo de uma pessoa e mostre
#O nome com todas as letras em maisculas
#O nome com todas minusculas
#Quantas letras ao todo(sem considerar os espaços vazios)
#quantas letras tem o primeiro nome
nome = str(input('Digite o seu nome completo? ')).strip()
print(nome.upper())
print(nome.l... |
2f42a1b11a33b0a5623c40c2700c8777a741afff | DottaPaperella/TALight | /example_problems/tutorial/bit_edit_to_zero/old/att/template_sol.py | 633 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Soluzione di bit_edit_to_zero
from __future__ import print_function
import sys
if sys.version_info < (3, 0):
input = raw_input # in python2, l'equivalente di input è raw_input
#################################################
# BEGIN: parte di tua competenza
def ... |
a2b2700b0505eb19db95e02d0514d4ee7420ecbd | dimosp/grades-report | /grades_report/stats.py | 6,655 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 KAUTH
"""
from statistics import mean, stdev
def mean_grade(parsed_list, passing_grade, overall_mean=True):
"""
This function calculates the arithmetic mean of the given grades.
:param parsed_list: the parsed list of the grades
:pa... |
033cb6cf2e391a6eb629e4910c6229ad0ad212f7 | rachit-k/packet-trace-analysis | /networks_A3/q7.py | 1,632 | 3.8125 | 4 | import csv
import statistics
filename = "file3.csv"
# initializing the titles and rows list
fields = []
rows = []
f= open("q7_3.csv","w+")
#f= open("temp.txt","w+")
# reading csv file
with open(filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
# extrac... |
d30d3b933242b725bf6312575bc36f35e12d97d5 | MarsForever/python_kids | /do15-2.py | 187 | 3.578125 | 4 | import my_module
from my_module import c_to_f
celsius = float (input("Enter a temperatur in Celsius:"))
fahrenheit =c_to_f(celsius)
print "That's ", fahrenheit ,"degress fahrenheit"
|
b38bb1c062e5c1623d11c68af7de45f2deb8ae11 | MarsForever/python_kids | /test5-3.py | 146 | 3.859375 | 4 | print("How long is length:")
long = float(input());
print("How long is wide:")
wide = float(input());
print("You need ",long*wide,"square meter")
|
953b47f0be6a1c46f7c75b888dccf5d9e484f920 | MarsForever/python_kids | /7-1.py | 316 | 4.125 | 4 | num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if num1 < num2:
print (num1, "is less than",num2)
if num1 > num2:
print (num2, "is more than",num2)
if num1 == num2:
print (num1,"is equal to",num2)
if num1 != num2:
print (num1,"is not equal to", num2)
|
69ab8d1b2593f44099b0514e9b824f070af324f2 | syurskyi/100DaysOfCode_i_Python | /01-03-datetimes/datetime_date.py | 667 | 4.25 | 4 | #!python3
from datetime import datetime
from datetime import date
datetime.today()
# datetime.datetime(2018, 2, 19, 14, 38, 52, 133483)
today = datetime.today()
print(type(today))
# <class 'datetime.datetime'>
todaydate = date.today()
print(todaydate)
# datetime.date(2018, 2, 19)
print(type(todaydate))
# <class... |
7c03bd449b0b79bea193584dd957de1f1df66e78 | hbostangi/py-todo | /nameSpaces.py | 1,485 | 3.8125 | 4 | # A namespace is therefore a mapping from names to objects.
# Examples are the set of built-in names
# (containing functions that are always accessible for free in any Python program),
# the global names in a module, and the local names in a function.
# --> Even the set of attributes of an object can be considered a ... |
c362bea760b33b665fc61225f8d1bfc1894be696 | akim-ruslanov/cracking_the_coding_interview | /chapter1/isPermutation.py | 655 | 3.90625 | 4 | '''
Ask what kind of strings (ASCII vs Unicode). Are two strings always the same size? Are spaces allowed? upper case vs lower case? '''
def isPermutation(str1, str2):
letter_dict = {}
if (len(str1) != len(str2)):
return False
for x in str1:
if x in letter_dict:
letter_dict[x]+=... |
9c990d0e80f171bffc30fe375e58c35688cf3ba5 | tanjowen/python-challenge | /PyPoll/main.py | 2,529 | 3.734375 | 4 | #import os and csv and path to the resources
import os
import csv
csvpath = os.path.join("Resources", "election_data.csv")
#add a list and zero variables
total_votes = []
past_id = 0
winning_vote = 0
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvrea... |
c60dc853a33dbdfab3cce7bebe9b9a7585a47ab8 | athd33/Pendu-exercice | /pendu.py | 1,295 | 3.71875 | 4 | #coding:utf-8
from fonctions import *
game = True
good_letter = []
tentatives = 8
word = ""
compte = 1
print("Recherche de mot en cours...")
random_word = get_random_word()
print(f"Random word : {random_word}")
score = init_score()
user_name = get_user_name()
print(f"Bienvenu {user_name}, nous allons commencer.... |
5a0592c2451fac1e71a8c1a79df9f66da38f34b0 | leosooter/LeoSooter-1 | /Week1/names.py | 1,947 | 3.765625 | 4 | students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
fullName = ""
for student in students:
for name in student.values():
fullNa... |
ff369f9b9581837c041504e9e325545f4fcd2854 | Kaikaine/Intro-Python | /src/python-example/rock_paper_scissors.py | 4,266 | 3.8125 | 4 | #import module we need
import random
#file i/o functions for historical results
def load_results():
text_file = open("history.txt", "r")
history = text_file.read().split(",")
text_file.close()
return history
def save_results( w, t, l):
text_file = open("history.txt", "w")
text_file.write( str(... |
b96fc765a2038432f6d7128cf7159eedd53302f9 | hafizmau/LearnPython | /python_loop.py | 260 | 3.984375 | 4 | #latihan python
name = int(input("banyak baris = "))
for i in range(1,name+1):
#print(i)
for j in range(name-i,0,-1):
print("#", end="")
for j in range(0,2*i-1):
print("*", end="")
print()
# for i in range(1,2):
# print(i)
|
ebf9b32cd934eec6287bf0c9960d1b159ae2cf0c | OrSGar/Learning-Python | /Mini Projects/RPS2.py | 1,243 | 4.09375 | 4 | from random import choice
""" Rock paper scissors extended to use CP """
print("Rock Paper Scissors Game\n\n")
rock_paper_scissors = ["rock", "paper", "scissors"]
p1_choice = input("Enter Player 1's choice: ")
comp_choice = choice(rock_paper_scissors)
print("The computer plays " + comp_choice + "\n")
# Rock pape... |
6461becb3ef2198b34feba0797459c22ec886e4c | OrSGar/Learning-Python | /FileIO/FileIO.py | 2,953 | 4.40625 | 4 | # Exercise 95
# In colts solution, he first read the contents of the first file with a with
# He the used another with and wrote to the new file
def copy(file1, file2):
"""
Copy contents of one file to another
:param file1: Path of file to be copied
:param file2: Path of destination file
"""
des... |
22855a356181d21593e45a66fa769a3cb4ae40e3 | k-koech/flask-blog | /tests/test_user.py | 413 | 3.546875 | 4 | import unittest
from app.models import User
class UserModelTest(unittest.TestCase):
"""
Test User class to test behaviour of User model
"""
def setUp(self):
self.new_user = User(id=1,username='triplek',email='triplek901@gmail.com',image_file="default.png",date_joined="2021-08-23", password = ... |
76b1318afa7d537da72ca535268913176efce562 | Sim-1122/s-project | /스크립트프로그래밍 Homework #1.py | 7,677 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# 2020136078_심재규
# ================
# ### 스크립트프로그래밍 Homework #1
# 1번 문제
# =======
# #### a="Hello Python" 문자열을 Slicing과 연결 연산자 (+)를 사용하여 "Python Hello"로 변경하시오.
# ##### [주의] a 변수 자체에 "Python Hello" 문자열이 저장되어야 함
# In[26]:
a = "Hello Python"
a = a[6:] + a[5] + a[0:5]
a
# #### 슬... |
d0870e32fd0fdb1f7c8fd637c9dc8ad55c76a7bc | code-is-here/python-topics | /zip.py | 306 | 4.03125 | 4 | for i in zip([1,2,3], ['a','b','c']):
print(i)
print("=========")
for i in zip([1,2,3]):
print(i)
print("========")
for i in zip([1,2,3],['a','b','c'],['#','!','@']):
print(i)
print(set(zip([1,2],[3,4,5])))
print("========")
z=zip([1,2,3],['a','b','c'],['#','*','$'])
a,b,c = zip(*z)
print(a,b) |
dfe5fd906b50b130aa81a57724262e8fffdce418 | moazmuha/small-projects | /Python/tryExcept.py | 1,490 | 3.890625 | 4 | class StudentGrade:
def __init__(self, num):
self.set_num(num)
def set_num(self, num):
if num < 0:
raise NegativeGradeException
elif num > 100:
raise TooSmartStudentException
else:
self._num = num
self._set_letter(num)
... |
a5dffff0ebf2ee4ce365678778c064d4546f1805 | Covax84/Snippets | /GCD.py | 457 | 3.78125 | 4 | def gcd(a: int, b: int) -> int:
""" алгоритм Евклида для 2-х целых положительных чисел """
if a % b != 0:
return gcd(b, a % b)
return b
def reduce_fraction(n: int, m: int) -> int:
""" сокращение дроби n/m алгоритмом Евклида """
return n // gcd(n, m), m // gcd(n, m)
# x = int(... |
0d256e167152d9e5e5e0e8a616c7d992e5133899 | joseph-aylor/adventofcode | /2.py | 1,143 | 3.609375 | 4 | class Package:
def __init__(self, length, width, height):
self.length = int(length)
self.width = int(width)
self.height = int(height)
def wrapping_paper_area(self):
sides = [(self.length * self.width), (self.width * self.height), (self.height * self.length)]
slack = min(... |
14b8d8e64aec3b1d8d2b69947c7b12efa57326a3 | rohanasthana/Neural-Network | /Train.py | 1,285 | 4.0625 | 4 | #n_x=Number of input features
#m is the number of training examples
import numpy as np
w=np.array([[1],
[2],
[3]])
b=3
#Randomly Initialise w and b
X=np.array([[2,4,6,3],
[3,5,8,6],
[7,9,10,11]]) #Here you can replace X with your desired matrix
#Create train... |
2bf9843a806d08e58c2bc7d33188557a695ae59b | kanhirun/UserName | /lib/user_name.py | 690 | 3.59375 | 4 | class UserName(object):
def __init__(self, existingNames):
self.existingNames = existingNames
def newMember(self, newName):
if self.isNameTaken(newName):
suggestedName = self.suggestName(newName)
return suggestedName
else:
return newName
def suggestName(self, oldName):
var... |
eac8aaadf7ff4d0f9e9ce46fbfe740092919f173 | davidxbuck/playground | /src/HeapSort.py | 3,021 | 3.640625 | 4 | '''
HEAPSORT Algorithm
Directly following the pseudocode from CLRS
'''
from math import floor
#
# Because Python indexing starts from 0, not 1, the values of :LEFT, RIGHT and PARENT need to be modified according.y
# 0
# 1 2
# 3 4 5 6
#
#
class Heap:
def __init__(self, values=[]):
... |
bbf8df97d15acc5e668188d0e5e4d71d31e52a30 | davidxbuck/playground | /src/InsertionSort.py | 905 | 3.65625 | 4 | '''
INSERTION SORT Algorithm
Directly following the pseudocode from CLRS
'''
class Array:
def __init__(self, values=[]):
self.A = values
def alen(self):
return len(self.A)
length = property(alen)
# INSERTION-SORT(A)
# for j = 2 to A.length
# key = A[j]
# // Inse... |
6773ac78031821ac372fbef367ba5de87331011c | davidxbuck/playground | /src/TicTacToe.py | 4,414 | 3.515625 | 4 | import random
import numpy as np
def print_grid(grid):
print(" " + grid[0, 0] + " | " + grid[0, 1] + " | " + grid[0, 2])
print(" ---+---+---")
print(" " + grid[1, 0] + " | " + grid[1, 1] + " | " + grid[1, 2])
print(" ---+---+---")
print(" " + grid[2, 0] + " | " + grid[2, 1] + " | " + grid... |
382ec0cf195cf9ab27e6d25f9564ee6a9c302dc0 | bondinthepond/PythonPractice | /LIstArrayAlgorithms/ArrayRotation.py | 256 | 3.84375 | 4 | array1 = ['a','b','c','d','e','f','g','h','i','j']
def rotateArrayOnce(list):
list = list[1:]+list[:1]
print list
def rotateArrayByN(list, n):
list = list[n:] + list[:n]
print list
rotateArrayOnce(array1)
rotateArrayByN(array1, 5)
|
246df80149d6b6dc44a21b66d3ea37dd479a198e | dragosstefanov/Python-Scripts | /download_file.py | 660 | 3.625 | 4 | # Note that pip is required to install the requests library
import requests
def download(url):
get_response = requests.get(url) # Sending a get request for the specified url which returns a response
file_name = url.split("/")[-1] # Splitting our URL by / and accessing the last element
# Opening ... |
5a7b8942440b0e09640e88480dacb3620fb95a81 | Mrabear79/DungeonMaster | /dungeonescape.py | 6,313 | 4.0625 | 4 | from random import randint
import time
def main():
word = "a"
sword = 5
intro()
while True:
sword, word, finished = TakeTurn(word, sword)
if finished:
break
if sword == 1:
word1 = "sword"
else:
word1 = "swords"
print("You have... |
f1e5e7bd782e2d12f1329219dd1fbc8c1541a4f0 | DevinEBrown/PythonArrays | /myFavoriteCars.py | 351 | 3.796875 | 4 | # Program Name: myFavoriteCars.py
# Program Description: This program outputs a list of info using tuples
# Programmer Name: Devin Brown
cars = (('1965', 'Pontiac', 'GTO', 'Blue'),
('1969', 'Plymouth', 'Roadrunner', 'Yellow'),
('2002', 'Chevrolet', 'Z-28 Camaro', 'Black'))
for car in cars:
print(car[0] + ' ' + c... |
9211eee360d84cae480320b839e339265dd14f54 | Ashishb21/PythonCourse | /Lec8.py | 308 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 12 13:26:40 2021
@author: ashishbansal
"""
de nd
def add(x=100,y=10):
return (x+y)
s=add(y=10,x=20)
s
x=10
def sum():
x=20
y=10
return y
print(x)
x1=sum()
print(x)
print(x1) 10
|
fe4415ab7692b3e39918ff03ca2e3898ee48e6a1 | amfei/PyProgrms | /find_duplicate.py | 737 | 3.640625 | 4 | # Auto detect text files and perform LF normalization
ssn_name_pairs= {"555-1234": "Bob",
"555-1239": "Bob",
"555-2345": "Matthew",
"555-3456": "Luke",
"555-11222": "Bob",
"003-9929": "Luke"}
def find_duplicated(ssn_name_dictio... |
0d8a10505c222227fa53bd2a0b10b5bfb206e510 | calebeof/NumericalMethods | /ROOTS/incrementalSearch.py | 1,175 | 3.90625 | 4 | '''
Author: Calebe Oliveira
May, 2019.
'''
import numpy as np
#Simple function that we will use as an example
def sen10_cos3(x):
return np.sin(10*x)+np.cos(3*x)
def incrementalSearch(function, xMin, xMax, jump = 0.1):
'''
The Incremental Search is an iterative method which use the following property:
... |
c59290256d35c84be417d53f908eeba3751521a2 | fullstackenviormentss/ATPBetting | /Python/utilities.py | 898 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
def basic_horizontal_barplot(values,labels,xaxis_label,title,xlim=None,figsize=None):
"""
Please provide the labels corresponding to the values, the plot title, and
the xaxis label.
"""
# Possible colors to use - if not... |
e1522e3393ee3750cdc6169781cc88490b039238 | ysun232/piethon | /list1.py | 349 | 3.96875 | 4 | list1 = ["apple", "banana", "cherry", "banana", "watermelon", "blueberry"]
print(list1.count("banana"))
print(len(list1))
#with bracketes its a list[], elements can be moved around
#with tuples, created with (), elements cannot be moved around. TO USE A TUPLE, YOU NEED TO INCLUDE A COMMA AT THE END
t1=(5,)
t2=(5)
pr... |
503e22dcf0c6622b8a4babae69b90da872700e3d | Jizishuo/LEETCODE_LOG_BY_PY_AND_GO | /data_2020_07/Convert_to_lowercase_letters_709/code.py | 565 | 3.59375 | 4 | class Solution:
def toLowerCase(self, str: str) -> str:
dic = {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd', 'E': 'e', 'F': 'f',
'G': 'g', 'H': 'h', 'I': 'i', 'J': 'j', 'K': 'k', 'L': 'l',
'M': 'm', 'N': 'n', 'O': 'o', 'P': 'p', 'Q': 'q', 'R': 'r',
'S': 's', 'T': 't', ... |
10903a515690b6d08677cb0251529510aa02f6ed | Jizishuo/LEETCODE_LOG_BY_PY_AND_GO | /data_2020_05/Verify_the_reply_string_680/code.py | 496 | 3.5625 | 4 | class Solution:
def validPalindrome(self, s: str) -> bool:
def search(chars, times):
begin, end = 0, len(chars)-1
while begin<end:
if chars[begin] != chars[end]:
if times == 0:
return False
return search... |
b6831b3356af22dc18b769f41bb2966e03f2e255 | Jizishuo/LEETCODE_LOG_BY_PY_AND_GO | /data_2020_05/Minimum_depth_of_a_binary_tree_111/code.py | 512 | 3.765625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if root == None:
return 0
queue = [(1, root)]
while queue:
d, n = queue.pop(0)
... |
609d035b6024a80041d9b600d780e39200ff74d9 | Jizishuo/LEETCODE_LOG_BY_PY_AND_GO | /data_2020_04/Using_queue_to_implement_stack_225/code.py | 894 | 4.03125 | 4 | class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.q.append(x)
q_len = len(self.q)
while q_len > 1:
self... |
60ce089cbbc612632e6e249227e3cac374e59ad1 | MNJetter/aly_python_study | /diceroller.py | 1,396 | 4.15625 | 4 | ##################################################
## Begin DICEROLLER. ##
##################################################
## This script is a d20-style dice roller. It ##
## requires the user to input numbers for a ##
## multiplier, dice type, and modifier, and ##
## displays re... |
a425af412c404ebbef4e634ce335c58b75b7cee1 | RhettWimmer/Scripting-for-Animation-and-Games-DGM-3670- | /Python Assignments/scripts(old)2/Calculator.py | 2,452 | 4.21875 | 4 | '''
Enter a list of values for the calculator to solve in "Values"
Enter a value in to "Power" to calculate the power of "Values"
Define "userInput" to tell the calculator what function to solve for.
1 = Add
2 = Subtract
3 = Multiply
4 = Divide
5 = Power
6 = Mean
7 = Median
8 ... |
0f6fe95108c73df1a306d09cc232944d5e19671c | billlaw6/python_utils | /professional_python/ch3_generator.py | 729 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding=utf-8 -*-
#
# File Name: ".expand("%:t"))
# Copyright(c) 2015-2024 Beijing Carryon.top Corp.
#
# Author LiuBin on: Fri Oct 27 13:46:46 CST 2017
#
# @desc:
#
# @history
#
# 最简生成器示例
def generator():
yield 1
yield 1
yield 2
yield 3
yield 5
yield 8
def fibonacc... |
1fef7130aea0f5c87348d661106c16ef725834bd | harikrishnankv/Python_HackerRank | /migratoryBirds2.py | 1,265 | 3.828125 | 4 |
def leapYear(daysumWithoutFeb,programmersDay):
leapfebDays = 29
daysum = daysumWithoutFeb + leapfebDays
day = programmersDay - daysum
return day
def nomalYear(nonleapfebDays,daysumWithoutFeb,programmersDay):
daysum = daysumWithoutFeb + nonleapfebDays
day = programmersDay - daysum
return day... |
4835bf9f78677700a448722acc71e56eca97fb6a | AHETESHAMS/git-github | /Palindrome.py | 303 | 3.96875 | 4 | num=int(input('Enter the number:='))
originalNum=num
n=num
reverseNum=0
while(n!=0):
remainder=int(num%10)
reverseNum=reverseNum*10+remainder
n=int(n/10)
if(originalNum==reverseNum):
print(originalNum,' is a palindrome number')
else:
print(originalNum,' is not a palindrome number')
|
79c2110452a61eeeb374fb66099bb6d5c6f0a046 | lucasdutraf/competitive-programming | /codeforces/PPC/Contest-2/a.py | 514 | 3.6875 | 4 | def main():
n_chars = int(input())
chars = input()
n_s = int(input())
ans = []
for i in range(n_s):
flag = 0
a = input()
for char in chars:
if char in a or char.capitalize() in a:
ans.append('Mensagem #{}: Carlos'.format(i+1))
break... |
e0cfff0b22a3b3933c09e4e902d689c370ff80e6 | lucasdutraf/competitive-programming | /codeforces/TEP/SumOfRoundNumbers.py | 281 | 3.9375 | 4 | from typing import Iterable
def replace_first(items: list) -> Iterable:
if len(items) == 1 or len(items) == 0:
return items
else:
aux = items[0]
items.pop(0)
items.append(aux)
return items
print(list(replace_first([1, 2, 3, 4])))
|
48974ce5bc1a575b6daa0a7f7a0287c943f71f5d | GlauberFerreiraAngelo/aprendendo_python | /programas/soma_e_subtracao.py | 227 | 3.859375 | 4 | a = 10
b = 5
soma = a + b
subtracao = a - b
print('soma: {}, subtração: {}' .format(soma, subtracao))
print('soma: {soma}, \nsubtração: {subtracao}' .format(soma=soma, subtracao=subtracao))
#esse \n quebra de linha. |
357d590d183a78d7ba42c12dead156877594c987 | GlauberFerreiraAngelo/aprendendo_python | /programas/analisar_par.py | 298 | 3.921875 | 4 | b = int(input('Entre com o primeiro valor: '))
c = int(input('Entre com o segundo valor: '))
resto_b = b % 2
resto_c = c % 2
#if(resto_b == 0 or not resto_c > 0):
if(resto_b == 0 or resto_c == 0):
print('foi digitado um número par')
else:
print('nenhum número par foi digitado') |
501481f1144cd59d5bfcde3c1882dc4c904c5322 | alexminnaar/PyDS | /tests/StackTest.py | 718 | 3.671875 | 4 | import unittest
from stack.Stack import Stack
class StackTest(unittest.TestCase):
def test_empty(self):
empty_stack = Stack(5)
is_empty = empty_stack.stack_empty()
self.assertEqual(is_empty, True, "should be true")
def test_push(self):
my_stack = Stack(5)
my_stack.push... |
bfd415ff430d3508421c04dc3139a6a2438719a2 | anatu/CS221-Fall2018 | /1_foundations/submission_v3.py | 6,120 | 4.03125 | 4 | import collections
import math
############################################################
# Problem 3a
def findAlphabeticallyLastWord(text):
"""
Given a string |text|, return the word in |text| that comes last
alphabetically (that is, the word that would appear last in a dictionary).
A word is defin... |
60d132a96739d55738600c2454bcc5f3224abd4f | luciasucunza/unsam_python | /ejercicios_python/Clase_10/larenga.py | 1,107 | 3.984375 | 4 | # larenga.py
def pascal(n, k):
'''
Precondición: n y k deben ser enteros positivos, k menor o igual a n para
estar dentro del triangulo.
Devuelve: El número en el triangulo de pascal alojado en fila n,
columna k.
'''
# Caso base, los bordes del tri... |
92e9ab5217cde483b7c9671c11c87771d92841e6 | luciasucunza/unsam_python | /ejercicios_python/Clase_11/comparaciones_ordenamiento.py | 7,338 | 3.75 | 4 | # comparaciones_ordenamiento.py
# Ejercicio 11.5 +11.7
#%%
import random
def generar_lista(N):
'''
Precondicion: N debe ser un entero positivo
Devuelve: Una lista de N números aleatorios del 1 al 1000, con repeticion.
'''
lista = []
for i in range(N):
lista.append(r... |
14431ca64f10832267a4b748072d91d89b8835fb | luciasucunza/unsam_python | /ejercicios_python/generala.py | 2,503 | 3.90625 | 4 | import random
'''
Para ver que funcione correctamente descomentar los prints y colocar un N menor, por ejemplo de 10
Para que los cometarios del funcionamiento resalten por sobre los prints comentados
'''
def tirar (n):
tirada = []
for i in range(n):
tirada.append(random.randint(1, 6))
... |
03ce2926ecc50927b9139ea2a28205ba9dd07d61 | kokamapc/min | /min.py | 115 | 3.65625 | 4 | A = [3,4,2,1,0,8,9,-1,100,0]
min = A.pop()
while A:
a = A.pop()
if a < min:
min = a
print(min)
|
a3aca6f4f5a2c7b6482db7a1097ccbaa6cf47544 | MarkoGodra/PA-HT | /open_addresing/open_addresing/open_addresing.py | 2,607 | 3.640625 | 4 | import sys
import random
import math
def random_list(min, max, no_el) :
list = random.sample(range(min, max), no_el)
return list
class Data :
def __init__(self, key) :
self.key = key
self.literal = str(key)
class HashTable :
def __init__(self, size, c1 = 0.5, c2 = 0.5) :
self.... |
97a5fc06b41ab8ff28e8179b3de335f9d1abee55 | nalo26/CodinGame-Solutions | /Onboarding.py | 316 | 3.875 | 4 | # https://www.codingame.com/training/easy/onboarding
while 1:
enemy_1 = input() # name of enemy 1
dist_1 = int(input()) # distance to enemy 1
enemy_2 = input() # name of enemy 2
dist_2 = int(input()) # distance to enemy 2
if dist_1 < dist_2: print(enemy_1)
else: print(enemy_2)
|
3a75c905a3831727c8152674d1daa3c81f2be4d0 | sharly2012/wechat-applet-test | /testcase/0001.py | 1,598 | 4.25 | 4 | def bubble_sort(array):
length = len(array)
if length < 2:
return array
else:
for i in range(length - 1):
for j in range(length - 1 - i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
def qui... |
217abed83b7959399c960f4ab220fb43bd0d0393 | aptiko/hk-climate | /other/combine | 1,711 | 3.640625 | 4 | #!/usr/bin/python
# Takes the r2w input and combines it into one rest file, so that it can
# then be used to provide a pdf.
def find_what_to_combine():
"""Read index.txt, get section names from there, and return list of
filenames to be combined."""
import os.path
index = os.path.join('input', 'en', 'in... |
a97adcbfe4398941c32dcdc8b16b6855a268f0cf | shalvinpshaji/dataStructures | /LinkedList.py | 1,262 | 3.9375 | 4 | class Node:
def __init__(self,value=None):
self.value = value
self.next = None
class Linked:
def __init__(self):
self.head = Node()
self.len=0
def insert(self,value):
self.len+=1
if self.head.value==None:
self.head.value=value
else:
temp = self.head
while temp.next!=N... |
69cee4a253e72b782a3b4f99a58f72cd75b09e35 | mihailruskevich/rosalind | /bioinformatics_textbook_track/median_string/median_string.py | 819 | 3.703125 | 4 | def hamming(p, line, i):
h = 0
for index in range(0, len(p)):
if p[index] != line[index + i]:
h += 1
return h
def d_line(p, line):
min_d = len(p)
for i in range(0, len(line) - len(p) + 1):
d = hamming(p, line, i)
if d == 0:
return 0
elif d < ... |
d0abfc79db4304c89edfba70ea681316cbf06807 | mihailruskevich/rosalind | /algorithmic_heights/insertion_sort/sort.py | 360 | 3.84375 | 4 | from utils.common import int_list
def insertion_sort(a):
swap_count = 0
for i in range(2, len(a)):
j = i
while j > 0 and a[j] < a[j - 1]:
a[j - 1], a[j] = a[j], a[j - 1]
j -= 1
swap_count += i - j
return swap_count
arr = int_list(next(open('array.txt')))
s... |
7b6ffc348b2b67eeeb362cace4fcb9be3166f260 | mihailruskevich/rosalind | /bioinformatics_stronghold/completing_tree/tree.py | 186 | 3.59375 | 4 |
def tree_missing_edges(lines):
n, *graph_lines = lines
return int(n) - len(graph_lines) - 1
file = open('graph.txt')
edges_count = tree_missing_edges(file)
print(edges_count)
|
dd7eda7eee5a1f01b57d8cff157a27cefd8519d1 | mihailruskevich/rosalind | /bioinformatics_textbook_track/count_pattern/count_pattern.py | 237 | 3.578125 | 4 | def count_pattern(seq, p):
return len([1 for i in range(0, len(seq) - len(p) + 1) if seq[i: i + len(p)] == p])
with open('dna.txt') as file:
dna, patten = file.read().split()
res = count_pattern(dna, patten)
print(res)
|
20b51c3b2f8da7ad0407c6bce693d5cd362006b0 | adhikara13/Simple_Chatty_Bot | /Problems/Leap Year/main.py | 132 | 3.875 | 4 | year = input()
if int(year) % 4 == 0 and int(year) % 100 != 0 or int(year) % 400 == 0:
print("Leap")
else:
print("Ordinary") |
7492b4edeae90b3e075b5aac9341fe1db34e6822 | Rexzy/phyton | /1.py | 138 | 3.625 | 4 | print "Selamat Datang"
nama = raw_input ("masukkan nama anda:")
umur = input("masukkan umur anda")
print "Haiii {0}, umur {1}". format(nama,umur)
|
9277fb45f6ae86999fe0d8ac55e747575f795250 | hxl163630/practice | /44. Wildcard Matching.py | 681 | 3.625 | 4 | class Solution:
def isMatch(self, s: 'str', p: 'str') -> 'bool':
si = pi = match = 0
starIdx = -1
while si < len(s):
if pi < len(p) and (p[pi] == "?" or p[pi] == s[si]):
si += 1
pi += 1
elif pi < len(p) and p[pi] =="*":
... |
170ab06e67fcba9007fdc994663f05b9faa310b3 | hxl163630/practice | /almost sorted array.py | 302 | 3.984375 | 4 | def insertionSort(nums, size):
for i in range(1, size):
key = nums[i]
j = i-1
while j >= 0 and nums[j] > key:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = key
return nums
nums = [6, 5, 3, 2, 8, 10, 9]
size = len(nums)
insertionSort(nums, size) |
5850e178942c6c1462215f7c2ee41ee4195d8092 | hxl163630/practice | /97. Interleaving String.py | 511 | 3.734375 | 4 | class Solution:
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
i = j = 0
for char in s3:
if i < len(s1) and s1[i] == char:
i+=1
continue
if j < ... |
04b7e2d12522f52c296d0dca0244ca9fed8c1073 | hxl163630/practice | /269. Alien Dictionary.py | 699 | 3.640625 | 4 |
def alienOrder(words):
"""
:type words: List[str]
:rtype: str
"""
if not words or len(words) == 1: return ""
order = []
for pair in zip(words, words[1:]):
for a, b in zip(*pair):
if a != b:
order.append(a + b)
break
output = []
ch... |
51e43d41e2f3593ea57a6c36153b727188fa5f3a | hxl163630/practice | /505.py | 1,254 | 3.609375 | 4 | class Solution(object):
def shortestDistance(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int
"""
import heapq
heap = [(2, start[0], start[1])]
dx = [0, 0, 1, -1]
... |
bab232f0b83ed96b939a9fa53ec86b360f3cd6ef | gus07ven/Networking | /testRequest.py | 2,141 | 3.609375 | 4 | # # imported the requests library
# import requests
#
# image_url = "http://192.168.56.1:8000/arepa.jpg"
#
# # URL of the image to be downloaded is defined as image_url
# r = requests.get(image_url) # create HTTP response object
#
# # send a HTTP request to the server and save
# # the HTTP response in a response objec... |
db95ed4eccce222cea4b4326ab5e4586f2916ac3 | JimGeist/sb_18-02-20_Python_Data_Structures_Exercise | /17_mode/mode.py | 856 | 4.28125 | 4 | def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
... |
cce0a73b95333ca1cdb18857403a41ede3cdb6a4 | JimGeist/sb_18-02-20_Python_Data_Structures_Exercise | /12_multiply_even_numbers/multiply_even_numbers.py | 589 | 4.375 | 4 | def multiply_even_numbers(nums):
"""Multiply the even numbers.
>>> multiply_even_numbers([2, 3, 4, 5, 6])
48
>>> multiply_even_numbers([3, 4, 5])
4
If there are no even numbers, return 1.
>>> multiply_even_numbers([1, 3, 5])
1
If the list is empty, return... |
f320f52b98025d0edfb543da612d28752ec6f579 | JimGeist/sb_18-02-20_Python_Data_Structures_Exercise | /06_single_letter_count/single_letter_count.py | 587 | 4.28125 | 4 | def single_letter_count(word, letter):
"""How many times does letter appear in word (case-insensitively)?
>>> single_letter_count('Hello World', 'h')
1
>>> single_letter_count('Hello World', 'z')
0
>>> single_letter_count("Hello World", 'l')
3
"""
# letter... |
0506b09086df7f69d180748741b2921e73711f67 | huine/compiladores | /analisador_sintatico.py | 2,153 | 3.578125 | 4 | # Gabriel Diniz Gisoldo RA: 22214007-1
class AnalisadorSintatico(object):
"""Analisador sintatico."""
def __init__(self, string, idx=0):
self.string = string
self.idx = idx
self.pilha = 0
def print_log(self):
"""."""
print(vars(self))
def up_index(self):
... |
76bf1a4e27575f7ee5b5c5926fd47a2a423645d1 | PatrickArthur/Python_fibonacci | /python_fib.py | 101 | 3.78125 | 4 | def fib(n):
if (n==1) or (n==2):
return 1
else:
return fib(n-1) + fib(n-2)
print fib(8)
|
0cbf97bb28837d7b3b60cdf0f0bcda7467544627 | julysses/itp-u4-c2-hangman-game | /hangman/game.py | 2,258 | 3.546875 | 4 | from .exceptions import *
import random
# Complete with your own, just for fun :)
LIST_OF_WORDS = ['starbucks', 'latte','book', 'sandwhich','chocolate', 'carmel','ginger']
def _get_random_word(list_of_words):
if list_of_words == []:
raise InvalidListOfWordsException('Cmon bruh')
else:
return ... |
75919d324164a8e65441d210dcbcf6bd5927fdb7 | Silentsoul04/PythonCode | /exceptions.py | 1,305 | 3.5 | 4 | import random
def f1():
try:
# 1/0
{}['key']
except ZeroDivisionError:
print("division by zero error")
except Exception:
print("Unknown error")
raise
def f2():
class MyException(Exception):
def __init__(self, message="Custom message"):
self... |
90707b2e54d15dcf7ecdcf4286a2409b271968a4 | ibrahimuslu/udacity-p0 | /Task4.py | 1,555 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
count =0
textPhoneDict = {}
callingPhoneDict = {}
receiveingPhoneDict = {}
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
for text in texts:
if text[0] not in tex... |
1911a47655624966750fc2df8525648c46ff4a7d | Gustavosmc/uri | /uri_1024.py | 386 | 3.8125 | 4 | n = int(input())
for i in range(n):
palavra = input()
palavra = list(palavra)
for i in range(len(palavra)):
if palavra[i].isalpha():
palavra[i] = chr(ord(palavra[i]) + 3)
palavra = palavra[::-1]
for l in range(int(len(palavra) / 2), len(palavra)):
palavra[l] = chr(ord(pala... |
6c30f1b802aac2f8d91919db469f7c8fd043e7e3 | angie1015/Py_Primer | /Built-in-datatypes/Strings/string_1.py | 83 | 3.65625 | 4 | str a = " this is a string"
print(a)
#there is an error in this program correct it
|
d7a7e67eaf251b651d29527e55f6f8d1cd0e23d0 | bes-1/lessons_python | /dz_3_2_berezin.py | 824 | 4.03125 | 4 | def info_man(name, surname, year_of_birth, city, email, phone_number):
list_info = []
list_info.append(name)
list_info.append(surname)
list_info.append(year_of_birth)
list_info.append(city)
list_info.append(email)
list_info.append(phone_number)
return list_info
name = input('Введите им... |
bceb4060029f4c84663e16d4d488c95b57698123 | bes-1/lessons_python | /dz_2_4_berezin.py | 435 | 3.546875 | 4 | enter_str = input('Введите строку из нескольких слов через пробел: ')
list_str = enter_str.split()
enter = '\n'
for i in range(len(list_str)):
if len(list_str[i]) > 10:
print(f"Значение {i + 1} слова больше 10 символов, первые 10 символов = {list_str[i][:10]}")
else:
print(f"Значение {i + 1} сло... |
4c94ff18d71c873061cf37a994af8f6bd6a4dd00 | trustdark/lessons | /6.py | 1,698 | 3.78125 | 4 | def caesarCipher(str, key):
new_list = []
for index, value in enumerate(str):
new_num = ord(value) + key
if ord(value) == 32:
new_list = new_list + [" "]
elif 96 < ord(value) < 123:
if new_num < 122:
new_list = new_list + [chr(new_num)]
... |
967cd2b4d83f099624d43292a8d37fc5d9528944 | oscaarpina/pysunlight | /sunlight/city.py | 1,525 | 3.5 | 4 | from .neighborhood import Neighborhood
from .exceptions.not_in_exception import NotInCityException
class City:
"""
def __init__(self, desc):
self.__neighborhoods = dict()
for n in desc:
Neighborhood.is_description_correct(n)
neighborhood = Neighborhood(n)
self.__neighborhoods[neighborhood.get_name()] = ... |
3a57497942dd80cc3f0da1be2da38d65d70eaf74 | martinee300/Python-Code-Martinee300 | /w3resource/Python Basic I/Qn7_PythonBasicPart1_SplitFilename.py | 613 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 12:21:49 2018
@author: dsiow
"""
# =============================================================================
# 7. Write a Python program to accept a filename from the user and print the extension of that.
# Sample filename : abc.java
# Output : java
# ===========... |
35c53757e5669ad24a4b61aa6878b722de8636e1 | martinee300/Python-Code-Martinee300 | /w3resource/Python Numpy/Qn3_PythonNumpy_CreateReshapeMatrix.py | 508 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 14:24:51 2018
@author: dsiow
"""
# =============================================================================
# 3. Create a 3x3 matrix with values ranging from 2 to 10.
# Expected Output:
# [[ 2 3 4]
# [ 5 6 7]
# [ 8 9 10]]
# ===================================... |
55016b7647b2bd5b8bc61707d71faf5313ad3808 | martinee300/Python-Code-Martinee300 | /w3resource/Python Numpy/Qn14_PythonNumPy_CelsiusToFahrenheit.py | 815 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 21:31:11 2018
@author: dsiow
"""
# =============================================================================
# 14. Write a Python program to convert the values of Centigrade degrees into Fahrenheit degrees. Centigrade values are stored into a NumPy array. Go to th... |
c5418968a3523cbbfc687e2c76c0e9c36bfbe198 | martinee300/Python-Code-Martinee300 | /w3resource/Python Pandas/Qn4_PythonPandas_SeriesElementComparison.py | 797 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 28 19:27:27 2018
@author: dsiow
"""
# =============================================================================
# 4. Write a Python program to compare the elements of the two Pandas Series.
# Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]
# ========================... |
08d000f314c10736546925c28dc98fc75d37336c | zelazna/freshdesk_to_gorgias | /gorgias/api/http_client.py | 685 | 3.53125 | 4 | import requests
class HTTPClient:
"""The HTTP client, define the basics http methods"""
def __init__(self, username=None, password=None, base_url=None):
self._username = username
self._password = password
self._base_url = base_url
def get(self, path):
url = f"{self._base_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.