blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
61db95632e65ef487112a89a830e348a39ac7047 | HuangJingGitHub/PracMakePert_py | /leetcode/leetcode_2.py | 797 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
sumDigit = 0;
headNode = ListNode(-1)
res = headNode # shallow copy, res is... |
cab33918f62b39c397b74a94c172691e89196815 | HuangJingGitHub/PracMakePert_py | /leetcode/leetcode_82.py | 826 | 3.625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None:
return head
newNode = None
... |
55327754a4c7c4412bddd9892fc330e1c12cd78f | HuangJingGitHub/PracMakePert_py | /leetcode/leetcode_77.py | 583 | 3.59375 | 4 | class Solution:
res = []
def combine(self, n: int, k: int) -> List[List[int]]:
self.res = []
path = []
self.trackback(n, k, 1, path)
return self.res
def trackback(self, n: int, k: int, begin: int, path: List[int]) -> None:
if len(path) == k:
self.res.... |
b380dd9e05d124e13721135076306c90dcf1870e | Danica-Tuckova/PythonBible | /pig_latin.py | 790 | 4.0625 | 4 | original = input("Please enter a sentence").strip().lower()
words = original.split()
new_words = []
for word in words:
# if the first letter of the word is vowel
if word[0] in "aeiou":
new_word = word + "yay"
new_words.append(new_word)
# if the fisrt letter of the word isn`t vowel
els... |
54f958d5402945d3f7afff2a39570ded3028f557 | Danica-Tuckova/PythonBible | /all_coins.py | 1,598 | 3.59375 | 4 | import random
# make general abstract class called Coin
class Coin:
def __init__(self, rare = False, clean = True, heads = True, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
self.is_rare = rare
self.is_clean = clean
self.heads = heads
# r... |
032ca9e3d4c4357c747c4a388a98cfb4a8e98910 | Danica-Tuckova/PythonBible | /list_comprehesions.py | 313 | 4.1875 | 4 | # go through all the numbers between 1 and 100 and create a list of even numbers
even_numbers = [x for x in range(1, 101) if x % 2 == 0]
print(even_numbers)
# go through all the numbers between 1 and 100 and create a list of odd numbers
odd_numbers = [y for y in range(1,101) if y % 3 == 0]
print(odd_numbers)
|
8836aa6b272074d07a497f9300653d6db6d9fc3e | Danica-Tuckova/PythonBible | /del.py | 305 | 3.8125 | 4 | from random import choice
list = []
while len(list) < 5:
new_member = input("add new name").strip()
list.append(new_member)
print("We are full")
print(list)
random_name = choice(list)
print(new_member)
for new_member in list:
if "a" in new_member:
print(new_member) |
c0b3e85af63e5f73734519306ea1a225128f67ee | hughdbrown/units_thing | /src/units_thing.py | 2,076 | 3.546875 | 4 |
from collections import Counter
class UnitsThing(object):
UNITS = ["kg", "km", "m", "s"]
def __init__(self, measure, units):
self.measure = measure
if type(units) is str:
if "/" not in units:
over, under = units, ""
else:
over, under = un... |
86b14034c1df8d394997505d369afec2846378a0 | NUDelta/affordanceaware | /weather.py | 2,145 | 3.5625 | 4 | """
This module is a class wrapper for the OpenWeatherMap API and time-based affordances.
"""
from __future__ import print_function
from __future__ import absolute_import
import requests
class Weather(object):
"""
Manages queries to the OpenWeatherMap API (https://openweathermap.org/api) for weather affordan... |
a8bf20d63cd02f67fb48048971bb6a2383936bc8 | ludoge/phonetoque | /Syllables_Stats.py | 4,789 | 3.5 | 4 | from collections import defaultdict
import json
import logging
import requests
api_url = 'http://127.0.0.1:5000'
class Syllables(object):
"""
This class is used to calculate the correspondance between
the phonetical syllables and the orthographical syllables
in a specific language according to the w... |
8b6025bb5ce823642ffe43accf1a19d90885336b | vinay2810/my-work | /1234.py | 1,051 | 3.71875 | 4 | # import time
# start_time = time.time()
# main()
# print("--- %s seconds ---" % (time.time() - start_time))
import random
# a = int(input("enter your no: "))
# n = 0
# for i in range (a+1):
# n = n*10+i
# print(n)
str1 = str(input("enter your first word: "))
str2 = str(input("enter your second word: "))
if len(str... |
d4519df880857d07ccb6c3e3d0280244ace2cfef | ryanjwise/Example_Code | /python/hello.py | 214 | 4.1875 | 4 | def say_hi(name):
if name == '':
print("You didn't enter your name!")
else:
print("Hi there ...")
for letter in name:
print(letter)
print("Please input your name")
name = input()
say_hi(name) |
d4b8fcae4c3ad7378d9193e77ab80d7ef59c978c | ledzerck/devf | /descuento.py | 244 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
precio = 30
articulos = 6
if articulos >= 5:
print("Tienes descuento")
descuento = (precio*articulos)*.95
print("Tienes que pagar", int(descuento))
else:
print("No tienes descuento")
|
30aabcf5103d92de2bc788b91cd78e174e7a48f7 | ledzerck/devf | /funciones.py | 962 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
separador = "------------------------------------"
def mi_funcion():
print("Baia baia")
mi_funcion()
########################################
print(separador)
# Parámetro y parámetro con un valor por default
def sumando(num1,num2):
suma = num1 + num2
print(str(... |
98d4c801f481b3a8b46b0b9d7b22a1f6f82c06a0 | ledzerck/devf | /for.py | 594 | 3.96875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# itera elementos como (listas, cadenas, range)
'''
var = "HOLA"
for i in var:
print("La letras que representa i es: " + i)
print ("Se acabó")
for i in range(1,10):
print(i)
print ("Se acabó")
'''
# Cuantos múltiplos de 2 hay en una cuenta del 1 al 100
print(... |
0e65c593810edacb20bad8e0707c3cbf2a8478c9 | MalikMehr/Mehr | /assignment 1 Q12.py | 206 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 15:36:10 2019
@author: MalikMehrKhan
"""
h = input("Enter height in feet ")
h = int(h)
cm = (h * 152.4) / 5
print ("height in cm is " + str(cm))
|
4445415df2b87b9c47ae573489459f2d6a355846 | gcmerz/shuttleLED | /minutes.py | 4,221 | 3.78125 | 4 | """ Contains functions that define how to write numbers to the seven segment
display we hooked up to the Pi. Contains lots of extra functions that were
written for testing. """
import RPi.GPIO as GPIO
import time
# Please find a visual of the mapping for pins the following link:
# https://www.dropbox.com/s... |
fed53f6c696da088ccb60efd9e737a0d0a194d75 | gregueiras/advent-of-code | /2021/18/script_1.py | 5,119 | 3.515625 | 4 | import sys
import math
debug = True or len(sys.argv) >= 2
class Node:
id = 0
def __init__(self, value='', parent=None) -> None:
self.value = value
self.parent = parent
self.left = self.right = None
self.id = Node.id
Node.id += 1
def hasChildren(self) -> bool:
... |
4ff9c8db7c587f0351b10ad8269f2891b2a798d0 | gregueiras/advent-of-code | /2022/3/1.py | 503 | 3.5 | 4 | import os
PATH = os.path.join(os.path.dirname(__file__), 'input.txt')
with open(PATH) as file_in:
lines: "list[str]" = []
for line in file_in:
lines.append(line.strip())
acc = 0
for line in lines:
size = int(len(line) / 2)
first: "set[str]" = set(line[size:])
second: "set[str]" = set(line... |
cab2d145dc399c6bf22343177a9afe287a607ecc | EnmanuelEstrella22/MiniProyectoAjedrez | /board.py | 3,456 | 3.765625 | 4 | from utilities import *
# class board which inherits from the utilities class
# in this class are the methods where the bacio board is generated and then a method where it is
# assign the pieces
# We also have the method of changing the piece, the method of changing the pawn for a queen
# method of validating if the ... |
8af45c17a94e2516fdfce41fc35caf25c6347926 | gnursk/F1M1PYT | /PYTB1L1PlayWIthPython/test12.py | 107 | 3.765625 | 4 | name = input ("Your name: ")
name2 = input ("Your name: ")
print ("Hello " + name)
print ("Hello " + name2) |
b7f4c24e291f5b52bac34c7ed017fbdd0c6f292b | Rajasekhar29/pythonExpertLevelBref | /Decorators.py | 3,035 | 4.78125 | 5 | """
Decorators is used to change the behaiour of the function with out changing the code in it.
[extended_summary]
"""
def func(string):
def wrapper():
print("Started")
print(string)
print("Ended")
return wrapper()
# return wrapper # {}
x = func("Hello")
"""
# Enable afte... |
20185ccc48e54081316b59044b424b96de4c853d | antokon/chessapi | /chessApi/database.py | 19,364 | 3.515625 | 4 | """
Created on 19.02.2018
Provides the database API to access the forum persistent data.
@author: lorinc
"""
from datetime import datetime
import sqlite3
import os
import time
DEFAULT_DB_PATH = 'db/chessApi.db'
DEFAULT_SCHEMA = "db/chessApi_schema_dump.sql"
DEFAULT_DATA_DUMP = "db/chessApi_data_dump.sql"
class Eng... |
54e415aa088a6a899e82c8deaf528be89577f9af | adp1002/practica-dms-2019-2020 | /src/components/game-server/juego/datos/tablero_abstracto.py | 1,468 | 3.953125 | 4 | from abc import ABC
class TableroAbstracto(ABC):
""" Clase abstracta que representa un tablero.
---
La clase proporciona la estructura de una tablero.
"""
def __init__(self, alto, ancho):
self.__tablero = [[None] * ancho for _ in range(alto)]
self.__piezas = 0
self.__max_p... |
505bb403730d8e01f48feda88a5ec03f84b92d95 | adp1002/practica-dms-2019-2020 | /src/components/game-server/juego/datos/pieza_abstracta.py | 670 | 4.09375 | 4 | from abc import ABC, abstractmethod
class PiezaAbstracta(ABC):
""" Clase abstracta que representa un pieza.
---
La clase proporciona la estructura de una pieza.
"""
def __init__(self, tipo):
"""Constructor.
---
Parámetros:
- tipo: String del tipo de piez... |
8b4f816a2978a006bc83f1d300090fd96e427c78 | OlgaFimbresMorales/Computacional1 | /Actividad3/Actividad3.py | 2,735 | 3.765625 | 4 |
# coding: utf-8
# In[32]:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from math import sin
# Original "data set" --- 21 random numbers between 0 and 1.
x0 = np.random.random(10)
x00 = 3*x0
#y0 = np.random.random(10)
y0 = np.sin(2*x00)
plt.plot(x00, y0, 'o', label='Dato... |
daa25e2c3aae9d512ce5e8bf8c827725abca9101 | rchekalov/hhpractice_async | /example/cpu_bound_example/thread_counter.py | 401 | 3.8125 | 4 | import time
from threading import Thread
COUNT = 90000000
def countdown(n):
while n>0:
n -= 1
t1 = Thread(target=countdown, args=(COUNT//3,))
t2 = Thread(target=countdown, args=(COUNT//3,))
t3 = Thread(target=countdown, args=(COUNT//3,))
start = time.time()
t1.start()
t2.start()
t3.start()
t1.join()
t2.... |
9ee45ea1b311db5d0c6090034f33cad7482be31e | JcForget/L06_PR01_20B | /partie_3.py | 358 | 3.5 | 4 | # Initilisation des variables
capital = 300000
taux_interet = 0.08
jours_par_annee = 365
nombre_annee = 20
annee = 1
# Calcul du capital au bout de 20 années
while annee < nombre_annee:
capital += capital * taux_interet
annee += 1
# Affichage du capital au bout de 20 années
print(f"\n Après 20 ans, le capi... |
9a04e957d0c1f595c53ee4718a94df5bafb2ce4f | martasnchz/HOMEWORK | /homework11.py | 1,077 | 4 | 4 | a = b = c = 0
read_line = input("Give me 3 numbers separated by , and space (like this example): 5.1, 4, 7 ")
read_line = read_line.replace(",", "")
list_num = read_line.split()
if len(list_num) != 3:
print("That is not 3 numbers")
exit()
print(list_num)
try:
a = float(list_num[0])
b = float(list_num[... |
566b41e84bab038c6db862857cab6f251a99e5cd | martasnchz/HOMEWORK | /homework1.py | 95 | 3.546875 | 4 | prompt = ("Hello!! Please, enter your name")
name = input(prompt)
print("Good morning,", name)
|
cf51ded10e4a81431cc9b33d742e0cca22e692e6 | leis1801/Intro-to-Python | /3_Functions.py | 5,533 | 5 | 5 | ###Introduction to Python - Nackademin
## Session 3 - Functions
## Based on Chapter 3 of AtBS
#we've seen some built-in functions already, but we can define our own functions to accomplish
#tasks that we need to do repeatedly in our code.
#the purpose of writing custom functions is therefore to prevent code duplicati... |
87519ff770c712a873e56a3216c81506764199f5 | sofiasackett/Basic-Python | /creditBrand.py | 901 | 4.09375 | 4 | # This program will determine the brand of credit card given the card number
#input number and get first number of card
card = (input("Enter your 16-digit credit card number: "))
first_number = card[0]
first_number = int(first_number)
if len(card) ==16:
try:
first_number >=3 and first_number <= 5
excep... |
97f3a74260f2284b43d3ffdd5d3337e9e8324a3b | sofiasackett/Basic-Python | /studentLogin.py | 690 | 4.375 | 4 | #This program will generate a UAlbany system login name given a users first and last names and birth year
#program greetings and inputs
print("We are going to generate a UAlbany system login name. \n")
first_name = input("Enter your first name here: ")
last_name = input("Enter your last name here: ")
birth_year = inpu... |
1d98a8206e2fc6892a6c395641f346b8db1b2fc9 | sofiasackett/Basic-Python | /areaCylinder.py | 517 | 4.53125 | 5 | #Compute the surface area of a cylinder given radius and height in cm
#get inputs from user
radius = input("Enter radius (in centimeters) here: ")
radius = float(radius)
height = input("Enter height (in centimeters) here: ")
height = float(height)
#calculate surface area
pi = float(3.14159)
surface_area = (2*pi*radiu... |
d5e55b2406a61ecc0f1d37365c623a957836dd68 | sofiasackett/Basic-Python | /tic-tac-toe.py | 774 | 3.96875 | 4 | #program using coordinate transformation
from graphics import *
def main():
win = GraphWin ("Tic-Tac-Toe", 500, 500)
#set coordinates to go from (0, 0) in the lower left corner to (3, 3) in the upper right
win.setCoords (0.0, 0.0, 5.0, 5.0)
#draw the vertical lines
Line (Point (1, 0), Point (1, 5)... |
94222f971338213e5a56212b0c810c66521afa31 | sofiasackett/Basic-Python | /Magic8Ball.py | 1,016 | 4.0625 | 4 | # Sofia Sackett
# This program acts as a magic-8 ball, and replies with one of ten original responses
# Import necessary modules
import random
import time
# Get user input
print("To begin using this Magic 8-ball, think of a yes or no question.")
ready = input("When you're ready, press enter to receive your answer!")
... |
13dfd5735f98acef0194635ade2ccb584b4363a3 | sofiasackett/Basic-Python | /SackettTest1.py | 834 | 4.3125 | 4 | # Sofia Sackett
# This program calculates how many digits are in a number between 1 and 1000
# This program also outputs the last digit of the number entered
# Input
inp = input('Please enter a number between 1 and 1000: ')
# Try/except
try:
num = int(inp)
except:
print('Something went wrong. Please enter a v... |
db4f57f81beca5c98140aae6350dcccd1aafbd06 | sofiasackett/Basic-Python | /highwayTax2.py | 727 | 4.25 | 4 | #This program will calculate the highway tax given a full market house value using conditionals
#program greetings and input house value
print("This program finds the highway tax given a full market house value. \n")
market_value = input("Enter a house value here: ")
market_value = float(market_value)
#calculate asse... |
1272772418b334e673329b31cabd83719ca95261 | alfredotp/pythonstudy | /reto.py | 496 | 3.859375 | 4 | # Examen
# Realiza un examen con 3 preguntas que tu desees, el usuario deberá responder "SI" o "NO" y al final otorgarle una calificación (La calificación se logra con una variable que inicia en 0 y por cada respuesta correcta incrementa en 1)
preguntas={"¿2+2? = 4": "SI", "¿3+5=8?" : "SI","¿7+7=15?" : "NO"}
resultado... |
e66b215057020b7806434c26f89075c59b829fa6 | yeomko22/TIL | /algorithm/programmers/numbers/124world.py | 254 | 3.71875 | 4 | def solution(n):
answer = ''
while (n):
cur_value = n % 3
if cur_value==0:
answer += '4'
else:
answer += str(cur_value)
n -= 1
n = n // 3
answer = answer[::-1]
return answer
|
e7f4a5adb585f9be26e8a67aef051cff9327feda | yeomko22/TIL | /algorithm/codility/etc/longestPassword.py | 787 | 3.59375 | 4 | # 너무 기초적인 실수함. 역시 졸린 상태에서 푸는 알고리즘이 한번에 맞을리가 없음
# 역시 정규표현식과 문자열 처리 문제는 파이썬으로 푸는게 제일 깔끔한거 같다.
import re
def solution(S):
words = S.split(' ')
answer = -1
re_num = re.compile(r'[0-9]')
re_char = re.compile(r'[a-zA-Z]')
for word in words:
num_cnt = 0
char_cnt = 0
flag = True
... |
665f6e45d72306cb1eadd40ffbd0b9bd54d64fd1 | dyclone/NLP-HW3 | /Questions/Q2/Q2.py | 1,228 | 3.90625 | 4 | import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk import ne_chunk, pos_tag
def entities(a_text):
'''
:param a_text: A sentence of type string
:return: Takes a sentence and first creates word tokens out of it. Those tokens are then assigned POS tags.
Last ne_chunk() is used o... |
c632660b769e11250023dcb1f0d88fe402b96b7e | zhaiworld/basicPython | /matrixmul.py | 617 | 3.984375 | 4 | #!/usr/bin/env python
# coding=UTF-8
from __future__ import print_function
#计算两个矩阵的乘积
n = int(input("Enter the value of n:"))
print ("Enter the value of the Matrix A")
a = []
for i in range(n):
a.append([int(x) for x in input().split()])
print ("Enter the value of the Matrix B")
b = []
for i in range(n):
b.... |
1b95868eb5443a144dac0d77c3dd2b924de6d089 | Hargun-singhh/Python_course | /Covid19 Daily Basis.py | 1,655 | 3.59375 | 4 | import requests
import json
import matplotlib.pyplot as plt
url = "https://api.covid19india.org/data.json"
response = requests.get(url)
covid_data = json.loads(response.text)
covid_cases_cases= []
for i in range(0, len(covid_data["cases_time_series"])):
covid_cases_cases.append(
{
"date": covi... |
5093179442d1418078c7796ffec354a9ed7c7933 | Hargun-singhh/Python_course | /Covid19 USER.py | 1,584 | 3.515625 | 4 | import requests
import json
import matplotlib.pyplot as plt
url = "https://api.covid19india.org/data.json"
response = requests.get(url)
covid_data = json.loads(response.text)
covid_cases_india = []
for i in range(0, len(covid_data["statewise"])):
covid_cases_india.append(
{
"state": covid_data... |
9b60df8c18a2ee6f7cbcb3606e3d68ef8a91e6ef | arnabdut14/Algorithms | /Week2/fibonacci_huge.py | 477 | 3.703125 | 4 | #uses python3
def fib_mod(n,m):
fib_list =[0,1]
count = 1
index = 0
remainder = 0
i = 2
while count < 2:
fib_list.append((fib_list[i - 1] + fib_list[i - 2]) % m)
if fib_list[i] == 1 and fib_list[i-1] == 0:
count += 1
index = i -1
i += 1
if coun... |
2ff550554a5fd33ebc5b247d9f49ede811ea5ffa | dd-code-immersives/py-112-code | /code-snippets/ci_sqlnosql__lesson_02.py | 5,335 | 3.84375 | 4 | # Enter your code here
import csv, sqlite3
#con = sqlite3.connect("hardware_store.db") # change to 'sqlite:///your_filename.db'
#cur = con.cursor()
with open('inventory.csv','r') as fin:
dr = csv.DictReader(fin)
#you are going to use executemany
import sqlite3
import os
# MAKE SURE YOU ARE IN TH... |
f066817decf82d1fb1a7f1b23bb6ebb24140c0ad | dd-code-immersives/py-112-code | /exercises/g7_hw_solution.py | 1,209 | 3.8125 | 4 | import sqlite3
work_dir = r"../sql-data/"
fn = "World_country_populations.csv"
conn = sqlite3.connect(work_dir+"world_populations.db")
c = conn.cursor()
countries = ('Canada', 'France','Germany','Italy','United States','United Kingdom','Japan')
c.execute("""select sum(migrants) from pop_data where country in {0} and... |
82f7d1ee7315aecc1c452493bc98db833c1fa594 | dd-code-immersives/py-112-code | /exercises/in_class_assignment.py | 2,116 | 3.515625 | 4 | import csv
from pprint import pprint
from collections import Counter
with open('MOCK_DATA.csv', newline='') as csvfile:
data = csv.DictReader(csvfile)
all_ip_addresses = []
all_emails = []
for row in data:
all_ip_addresses.append(row['ip_address'])
all_emails.append(row['email'])
#... |
b64553593e478957be2268e8194d3e17b0292491 | dd-code-immersives/py-112-code | /exercises/py_mongo_world_data_solution.py | 2,259 | 4.03125 | 4 | """
use pymongo to write a find statement that finds countries that have a population greater than 500,000
use pymongo to write a find statement to calculate the total populations of the following countries [mexico, canada, us, brazil]
use pymongo to write a find statement to find all countries that have a landmass les... |
b0cd1a796df90dfe198a889aceb12189fc73ed6c | srinivasansakthivel/BasicPrograms | /BasicPrograms/ReverseAStringUsingLoop.py | 245 | 4.4375 | 4 | def reversing_string(string):
reverse_string = ""
for i in string:
reverse_string = i + reverse_string
return reverse_string
string1 = input("Enter the string : ")
rev_string1 = reversing_string(string1)
print(rev_string1)
|
50b4ab48a6f7834c1e7864092139b014cc143953 | srinivasansakthivel/BasicPrograms | /BasicPrograms/SelectionSort2.py | 266 | 3.828125 | 4 | list1 = [56, 5, 10, 23, 46, 10]
print("Unsorted List", list1)
for i in range(len(list1)-1):
min_val = min(list1[i:])
min_ind = list1.index(min_val, i)
if list[i] != list1[min_ind]:
list1[i], list1[min_ind] = list1[min_ind], list1[i]
print(list1) |
d1d605959dd57e58424dac84b111daf5d1bc8b04 | srinivasansakthivel/BasicPrograms | /BasicPrograms/PalindromeStringCheck.py | 416 | 4.3125 | 4 | user_str = input("Enter the String : ")
# rev_str = user_str[::-1]
# if user_str == rev_str:
# print("It is palindrome")
# else:
# print("Not a palindrome")
# without using reverse func
rev_str = ""
for i in range(len(user_str)-1, -1, -1):
rev_str = user_str[i] + rev_str
print("Reversed String : ", rev_st... |
2c7990dffb0e225d5192da4934b844e8df7a420e | guilhermehenriquesantos/calculadora | /lacos.py | 1,058 | 4.0625 | 4 | # Laços
# Laço for: sempre que preciso de executar uma tarefa por determinadas vezes eu posso usar o for
# por exemplo, eu quero imprimir uma mensagem 5 vezes na tela, para isso eu faço:
for indicador in range(0, 5):
print("Enviando mensagem:", indicador)
# Também posso usar o laço while (enquanto), ou seja, enqu... |
3f861213224449580b8008bd4bc852fa6ca621d3 | Thilagaa22/python-codes | /fib.py | 284 | 3.953125 | 4 | x = int(input("Enter limits of numbers:"))
n1 = 0
n2 = 1
count = 0
elif x == 1:
print("Fibonacci sequance upto",x,":")
print(n1)
else:
print("Fibonacci sequance upto",x,":")
while count < x:
print(n1,end=',')
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
|
cfc710f8211ef7486ae5d087c5d22877c7a2fea4 | Thilagaa22/python-codes | /83.py | 92 | 3.796875 | 4 | a,b,c = input().split()
a = int(a)
c = int(c)
if b == '/':
print(a//c)
else:
print(a%c)
|
f503ea6af7030e78ab8dcebc060697a04175613e | Thilagaa22/python-codes | /71.py | 168 | 3.796875 | 4 | def palin(str):
rev = ''.join(reversed(str))
if (str == rev):
return True
return False
n = input()
ans = palin(n)
if(ans):
print("yes")
else:
print("No")
|
345a723e5d764b9c5242a67c7c66b75db8789a94 | Thilagaa22/python-codes | /oddprime.py | 293 | 4.09375 | 4 | lower = int(input("Enter a lower limit:"))
upper = int(input("Enter a upper limit:"))
print("prime numbers are between", lower, "and",upper, "are:")
for num in range(lower,upper +1):
if num > 1:
for i in range(2,num):
if( num % i )==0:
break
else:
print(num)
|
64331688ab6451395a283894359ad9b737708ffa | Thilagaa22/python-codes | /swap.py | 197 | 3.96875 | 4 | x = int(input("Enter first number:"))
y = int(input("Enter second number:"))
temp = x
x = y
y = temp
print('The value of x after swap:{}',format(x))
print('The value of y after swap:{}',format(y))
|
6a79a324ed0808b714df0790849f3834f5a5bc0e | Thilagaa22/python-codes | /60.py | 77 | 3.625 | 4 | n = int(input())
sum = 0
while (n>0):
sum = sum + n
n = n - 1
print(sum)
|
e41a3dd82186360dfe4f1f6e6055e414f9e1669c | Thilagaa22/python-codes | /70.py | 102 | 3.703125 | 4 | import math
a = int(input())
for i in range(a):
if 2 ** i == a:
f = i
break
print(2**(f+1))
|
31b0966ac36a50fcb9bc331fd018a3ef7a351d45 | Thilagaa22/python-codes | /25.py | 142 | 3.53125 | 4 | num = [1,2,3,4,5]
n = len(num)
num.sort()
if n %2==0:
m1 = num[n//2]
m2 = num[n//2-1]
m = (m1+m2)/2
else:
m = num[n//2]
print(m)
|
0ea92b29633438e682c48981b9e2612a1b02c44a | Thilagaa22/python-codes | /102.py | 128 | 3.71875 | 4 | import math
def div(n):
if n % 2 == 0:
return div(n/2)
else:
return math.ceil(n)
n = int(input())
print(div(n))
|
c3d1e67071fb8756318b5772fb4afdbe1267c96e | anthonykawa/Intro-Python-I | /src/17_all_prime.py | 459 | 3.734375 | 4 | import sys
import datetime
def all_prime(num):
p = 2
num_list = list(range(p, num + 1))
for p in num_list:
for i in range(p, num + 1):
try:
num_list.remove(i*p)
except:
pass
return num_list
num = int(sys.argv[1])
date = datetime.datetime
... |
226ee0ce2913e73882e12f8a6b9771bec7bf4169 | msaaksjarvi/opentable_scraping_analysis | /scraper/opentablescraper.py | 14,125 | 3.578125 | 4 | from selenium import webdriver
from bs4 import BeautifulSoup as soup
import re
import time
import csv
def nyc_opentable_scraper(borough, date, starting_page):
"""
nyc_opentable_scraper: given a borough and date, scrapes the OpenTable search results front page to see how many pages of
results there are for ... |
d65d7738457df3611842e7cd9f7b08a76f054dcc | learsixela/logica2021 | /python/ejercicio_python3.py | 429 | 3.890625 | 4 |
#ejercicio 3
mensaje="""
Esto es un obj
mensaje de
prueba
"""
print(mensaje)
mensaje2= "ewfewf \
wefwef \ mas texto"
print(mensaje2)
#ejercicio 4
numero1= 5
numero2= 7
resultado= numero1+numero2
print(resultado)
print (numero1 + numero2)
#calculo de iva
valor_producto = 1423
iva = 19
iva_porcentaje = iva / ... |
7eaa0b1ade75b1b91bb15d2a25a144cb6f8de13c | awharkrider/CPSC_3320_Cybersecurity_Lab | /Bithday_Paradox_Lab/birthday_paradox.py | 1,465 | 3.921875 | 4 | """
Aaron Harkrider
"""
import argparse
import random
import math
def main():
print("Starting the Birthday paradox program")
# Parse in arguments from the cmd line
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--t_people', type=int, default=23,
help="number o... |
a203387c5a4b1bfe7a581bee845bbab0f97046c5 | Atramekes/Snake | /SnakeEditor.py | 5,996 | 3.703125 | 4 | from tkinter import *
from random import randint
class Grid(object):
#这个对象不是个实体对象,它用来布置所有物体(蛇的身体或者食物等)
def __init__(self,master=None,window_width=800,window_height=600,grid_width=40,offset=20):
#window是整个游戏画面的长度和宽度,master=None表示每个物体都是顶层窗口,offset表示窗口边缘留出的空间
self.height = window_height
... |
9a01ffeaa099f89044a04ab07f29b51ae2d8baca | defibull/leetcode | /pow_even.py | 117 | 3.515625 | 4 | def pow_e(x,n):
s = x
while n/2:
s*=s
n/=2
return s
print pow_e(3,4)
|
41640b07780133a7c1d683754f8379ded3540380 | defibull/leetcode | /7_reverse_integer.py | 429 | 3.625 | 4 | def reverse(self, x):
"""
:type x: int
:rtype: int
"""
negative = False
ans = 0
if x < 0:
negative = True
x = abs(x)
while x != 0:
supplement = x%10
x = x/10
ans = ans*10 + supplement
if... |
c71bc1b6b781f50503f5b6a62450843a28512ed6 | ahaoao/PySpider | /Pc_01_urllib/pc_01_parse/pc_03_urlencode.py | 420 | 3.5625 | 4 | from urllib import request
from urllib import parse
# urlencode 函数可以将url参数进行编码, 将参数字典转换为字符串
# params = {"name": "张三", "age": 19, "greet": "hello world"}
# result = params.urlencode(params)
# print(result)
url = "http://www.baidu.com/s"
params = {"wd": "刘德华"}
qs = parse.urlencode(params)
url = url + "?" + qs
resp = req... |
9caef1774caeda0c5f35e260c2991919e40b1ade | alexandernzach/Student-UWL | /session7 code/ex9.py | 376 | 3.578125 | 4 | def f(a) :
if a < 0 :
return -1
n = a
while n > 0 :
if n % 2 == 0:
n = n // 2
return n
elif n == 1 :
return 1
else :
n = 3 * n + 1
return 0
a=[-1, 0, 1, 2, 10, 100]
def main():
for i in a:
... |
0c71a821be0a5d454858ea2b0442e67b02eb60dd | LucasDiasTavares/TavaresForum | /core/utils.py | 249 | 3.578125 | 4 | import random
import string
ALPHANUMERIC_CHARS = string.ascii_lowercase + string.digits
STRING_LENGHT = 6
def generate_random_string(chars=ALPHANUMERIC_CHARS, lenght=STRING_LENGHT):
return "".join(random.choice(chars) for _ in range(lenght))
|
4568bed592ed5aa530588630f70d9f7c209a3ea2 | pawan-nirpal-031/DeepLearning | /fstNeuNet.py | 2,243 | 3.765625 | 4 | import numpy as np
from matplotlib import pyplot as plt
# each data point is [x,y,z] x is length , y is width z is {0,1} 1 if red 0 if blue
data = [[3, 1.5, 1],
[2, 1, 0],
[4, 1.5, 1],
[3, 1, 0],
[3.5, 0.5, 1],
[2, 0.5, 0],
[5.5, 1, 1],
[1, 1, 0]]
... |
2df5bc2e87e429542e67e76a72f0f4647e614e8c | TimurKhakimyanov/catet_solution | /catet_solution.py | 1,040 | 3.921875 | 4 | #code to calculate the lengths of the legs and the hypotenuse of a triangle
#values are entered in order a then b then C
#if the value is unknown and you need to find it, enter 0 instead
#July 2020
#код для вычисления катетов и гипотенузы прямоугольного треугольника
#значения вводятся в порядке а потом b потом ... |
cc8b67c96fc681c107397379da63098b2d3cb6f4 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/2. Streamlined Data Ingestion with pandas/28_joining_filtering_aggregating.py | 1,459 | 3.71875 | 4 | # Query to get heat/hot water call counts by created_date
query = """
SELECT hpd311calls.created_date,
COUNT(*)
FROM hpd311calls
WHERE hpd311calls.complaint_type = 'HEAT/HOT WATER'
GROUP BY hpd311calls.created_date;"""
# Query database and save results as df
df = pd.read_sql(query, engine)
# View first... |
17bb687282d322c2e6f06e1694bc257c631badaa | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/2. Streamlined Data Ingestion with pandas/32_set_api_params.py | 2,389 | 3.703125 | 4 | import pandas as pd
import requests
api_url = "https://api.yelp.com/v3/businesses/search"
headers = {'Authorization': 'Bearer {}'.format('api_key')}
# Create dictionary to query API for cafes in NYC
parameters = {'term': 'cafe',
'location': 'NYC'}
# Query the Yelp API with headers and params set
respon... |
252308d84d163f00365a18aa0aabd4be54b06d09 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/NLP Skills Track/1. NLP Fundamentals/4_nltk_regex.py | 1,285 | 3.609375 | 4 | # Unlike the syntax for the regex library, with nltk_tokenize() you pass the pattern as the second argument.
# Import the necessary modules
from nltk.tokenize import regexp_tokenize
from nltk.tokenize import TweetTokenizer
# Define a regex pattern to find hashtags: pattern1
pattern1 = r"#\w+"
# Use the pattern on the ... |
08a73add8babc9bcf1b49ff37d8ddbe45015cb36 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Science Track/16. Statistical Thinking in Python/3_number_of_bins.py | 722 | 4.28125 | 4 | # Adjusting the number of bins in a histogram
# Thehistogramyoujustmadehadtenbins.This is thedefaultofmatplotlib.
# The"square root rule" is acommonly - usedruleofthumb for choosingnumber
# of bins: choose the number of bins to be the square root of the number of samples.
# Import numpy
import numpy as np
# Compute ... |
df35708999a154e79805c068a07c36c860141b94 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/4. Writing Efficient Python Code/18_using_combinations.py | 1,418 | 4 | 4 | # Import combinations from itertools
from itertools import combinations
pokemon = ['Geodude', 'Cubone', 'Lickitung', 'Persian', 'Diglett']
# Create a combination object with pairs of Pokémon
combos_obj = combinations(iter(pokemon), 2)
print(type(combos_obj), '\n')
'''
class 'itertools.combinations'>
'''
# Convert c... |
41d7004013e27992102cd3a37e510011c8f717d5 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/3. Software Engineering & Data Science/21_writing_good_comments.py | 353 | 3.828125 | 4 | import re
def extract_0(text):
# match and extract dollar amounts from the text
return re.findall(r'\$\d+\.\d\d', text)
def extract_1(text):
# return all matches to regex pattern
return re.findall(r'\$\d+\.\d\d', text)
# Print the text
print(text)
# Print the results of the function with better c... |
df6c8ea9225fa98733bd68ea697f417e4e65174a | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/7. Command Line Automation in Python/33_click_open_file.py | 626 | 3.8125 | 4 | # Take a few random words that come to mind and
# write them out via click.
# Setup
import click
words = ["Asset", "Bubble", "10", "Year"]
filename = "words.txt"
# Write with click.open()
with click.open_file(filename, 'w') as f:
# Loop over words with a for loop
for word in words:
f.write(f'{word}\n')... |
d535406fa15b3193b03b9eff2af387cef7e02d3b | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/2. Streamlined Data Ingestion with pandas/20_selecting_columns_sql.py | 858 | 4.4375 | 4 | # Create database engine for data.db
engine = create_engine('sqlite:///data.db')
# Write query to get date, tmax, and tmin from weather
query = """
SELECT date,
tmax,
tmin
FROM weather;
"""
# Make a data frame by passing query and engine to read_sql()
temperatures = pd.read_sql(query, engine)
# Vie... |
c74d662ee88e6beb99d18ff013266b5febe772d1 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/NLP Skills Track/1. NLP Fundamentals/1_re.py | 942 | 4.0625 | 4 | # Write a pattern to match sentence endings: sentence_endings
sentence_endings = r"[.?!]"
# Split my_string on sentence endings and print the result
print(re.split(sentence_endings, my_string))
# Find all capitalized words in my_string and print the result
capitalized_words = r"[A-Z]\w+"
print(re.findall(capitalized_... |
f8874258e2c944c6cc4ef21a92bd97cec0d7cb62 | Ali-Parandeh/Data_Science_Playground | /pyimagesearch gurus/Module 1/lesson_1_4_4/flipping.py | 1,402 | 3.890625 | 4 | # import the necessary packages
import argparse
import cv2
import imutils
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help = "Path to the image")
args = vars(ap.parse_args())
# load the image and show it
image = cv2.imread(args... |
7247d5d7106baf4f6c9eecc46bd1a431c4de276d | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/4. Writing Efficient Python Code/17_using_counter.py | 1,386 | 4 | 4 | from collections import Counter
# Collect the count of primary types
type_count = Counter(primary_types)
print(type_count, '\n')
'''
Counter({'Water': 66, 'Normal': 64, 'Bug': 51, 'Grass': 47, 'Psychic': 31, 'Rock': 29,
'Fire': 27, 'Electric': 25, 'Ground': 23, 'Fighting': 23, 'Poison': 22, 'Steel': 18,
'Ice': 16, ... |
245ac6bdcd4e37f959819e7154dc6c3756fd4e99 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/4. Writing Efficient Python Code/2_builtin_range.py | 637 | 4.40625 | 4 | # Create a range object that goes from 0 to 5
nums = range(6)
print(type(nums))
# Convert nums to a list
nums_list = list(nums)
print(nums_list)
# Create a new list of odd numbers from 1 to 11 by unpacking a range object
nums_list2 = [*range(1,12, 2)]
print(nums_list2)
'''
<script.py> output:
<class 'range'>
... |
c3bbc82712c2a9cbf83ba1a689b539dbf803c3bc | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/7. Command Line Automation in Python/9_subprocess_Popen.py | 2,396 | 3.96875 | 4 | # Reading a creepy AI poem
# As a mad scientists working on AGI (Artificial General Intelligence)
# in your underground bunker in Siberia, you have come up with a program
# that appears to show signs of human level intelligence. Your program was
# trained to write poems and initially showed signs of true brilliance... |
7d59f703e797ceec8f64f8f508baf403d4d05731 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/2. Streamlined Data Ingestion with pandas/33_set_request_headers.py | 1,457 | 3.71875 | 4 | import pandas as pd
import requests
api_url = "https://api.yelp.com/v3/businesses/search"
# Create dictionary that passes Authorization and key string
headers = {'Authorization': "Bearer {}".format(api_key)}
# Query the Yelp API with headers and params set
response = requests.get(api_url, params = params, headers = ... |
de202b8b9ae298ebd02313ab0628540704f62d35 | Ali-Parandeh/Data_Science_Playground | /Datacamp Assignments/Data Engineer Track/3. Software Engineering & Data Science/5_pep8_documentation.py | 1,214 | 3.796875 | 4 | def print_phrase(phrase, polite=True, shout=False):
if polite:# It's generally polite to say please
phrase = 'Please ' + phrase
if shout: #All caps looks like a written shout
phrase = phrase.upper() + '!!'
print(phrase)
#Politely ask for help
print_phrase('help me', polite=True)
# Shou... |
f439c13e060dcf06ca27704b381c95bf4a2c69cb | kkaranoraon/Python19 | /dtouch.py | 426 | 3.796875 | 4 | #!/usr/bin/env python2
# import the os module
import os
# detect the current working directory and print it
path = os.getcwd()
print ("The current working directory is %s" % path)
folder = raw_input("enter folder name : ")
file = path + '/'+ folder
try:
os.mkdir(file)
except OSError:
print ("Creation ... |
023f2de62be9097b7e8e9a58ba3031f4d1612f75 | nptit/python-snippets | /quiz1.py | 3,025 | 3.890625 | 4 | def Square(x):
return SquareHelper(abs(x), abs(x))
def SquareHelper(n, x):
if n == 0:
return 0
return SquareHelper(n-1, x) + x
def isPalindrome(aString):
'''
aString: a string
'''
# Your code here
n = len(aString)
return all(aString[i] == aString[n -i -1] for i in range(n)... |
36f65ed5ab2488cd839228171dcfeafb1d8e6a6a | nptit/python-snippets | /checkio/box-probability.py | 1,272 | 3.71875 | 4 | def prob_white(marbles):
"given the marbles, calculate the probability of getting white"
lenf = float(len(marbles))
return len([m for m in marbles if m == 'w'])/lenf
def checkio(marbles, step):
'non recusive using a temp array'
results = []
results.append(tuple([marbles, 1.0]))
for i in ra... |
07a141d82249a173767c610f382a903cfe325e14 | nptit/python-snippets | /backtracking-cryptarithmeticPuzzles.py | 4,211 | 3.90625 | 4 |
'''
Solving cryptarithmetic puzzles
Newspapers and magazines often have cryptarithmetic puzzles of the form:
SEND
+ MORE
MONEY
The goal here is to assign each letter a digit from 0 to 9 so that the arithmetic works out
correctly. The rules are that all occurrences of a letter must be assigned the same digit, and n... |
7dc87a5a6450385f78d44b95e29873906df80ddf | nptit/python-snippets | /twosum-coursera.py | 2,485 | 3.578125 | 4 | from timeit import timeit, Timer
from bisect import bisect_left
def binary_search(a, x, lo=0, hi=None):
hi = hi or len(a)
# find insertion position
pos = bisect_left(a, x, lo, hi)
return (pos if pos != hi and a[pos] == x else -1)
def twosum_bisearch(nums,t):
'''about 5 time slower than set lookup'... |
4011b8304e54f3114814e76c42c7107b24aedd0e | nptit/python-snippets | /insertionSort.py | 269 | 3.984375 | 4 | def insertionSort(l):
''' sort a list by insertion sort'''
n = len(l)
for i in range(1, n):
j = i
while j > 0 and l[j-1] > l[j]:
l[j-1], l[j] = l[j], l[j-1]
j -= 1
return l
print insertionSort([2, 0.5, 1,2,-1])
|
cb1bd401c4ca8242ceea3104bb4b413e71c4e4a2 | nptit/python-snippets | /BFS-DFS.py | 3,457 | 3.828125 | 4 | # http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/
def DFS_recursive(graph, start, visited=None):
if not visited:
visited = [start]
print 'visit: ', start
for v in graph[start]:
if v not in visited:
visited.append(v)
print "visit: ", v
DFS_recursive(graph, v, visited)
... |
8532fda139db1dec49e95df31a1cf2da1111ea84 | nptit/python-snippets | /checkio/clock-angle.py | 735 | 3.75 | 4 | def clock_angle(time):
h, m = time.split(':')
hr_angle = (int(h) % 12 + float(m) / 60 ) * 30
mn_angle = float(m) * 6
angle = (mn_angle - hr_angle)
if angle < 0:
angle = 360 + angle
if angle > 180:
angle = 360 - angle
return angle
if __name__ == '__main__':
#These "ass... |
d7983fe5c241e43231107d2ceaceac395962bf1e | nptit/python-snippets | /powerN.py | 810 | 4.09375 | 4 |
def power(x, n):
if n == 0:
return 1
half = power(x, n//2)
result = half*half
return result if n % 2 == 0 else x*result
def power(x, n):
if n < 0:
return power(x, -n)
if n == 0:
return 1
product = power(x*x, n//2)
return product if n % 2 == 0 else x*product
... |
b54a38e40d48cbda20f15e40af998505a4496ac4 | nptit/python-snippets | /checkio/super-root.py | 1,228 | 3.90625 | 4 | from math import log, sqrt
def super_root(number):
'solve log N - x log x = 0, note x log x is monotonically increasing'
'so we can use binary search between 1 and N'
l, r = 1.0, number
cycles, maxcycles = 0, 10**6
while cycles < maxcycles:
cycles += 1
guess = (l + r) / 2
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.