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 |
|---|---|---|---|---|---|---|
3c17aa036156abb1b9f3b7c83464b2258cb8ea41 | janetschel/exercises | /week_02/01_loop_revision/08_total-of-list.py | 353 | 3.765625 | 4 | """
Schreibt eine Funktion, welche die Summe einer Liste aus Nummern ermittelt.
Beispiel:
[1, 2, 3] -> 6
[-1, 1, 0] -> 0
"""
from typing import List
def sumOfList(numbers: List[int]) -> int:
result: int = 0
for number in numbers:
result += number
return result
print(sumOfList([1, 2, 3])) # 6
... |
c9c577f7d5baf683a83f77d31b72841e897afcd5 | janetschel/exercises | /week_01/04_arrays-list-strings/05_is-palindrome.py | 475 | 3.9375 | 4 | """
Schreibt eine Funktion, welche ermittelt, ob das eingegebene Wort ein Palindrom ist.
Beispiel:
Otto -> True
Peter -> False
"""
def isPalindrome(word):
lowerCasedWord = word.lower()
# return lowerCasedWord[::-1] == lowerCasedWord
length = len(lowerCasedWord)
for i in range(0, length):
if... |
614057bca46ef8582910c737f1bc3e55a0f9bb3e | gerritvanos/ATP-interpreter | /token_class.py | 447 | 3.78125 | 4 | """
class to store a token
"""
class token():
def __init__(self,token_type,value):
self.token_type = token_type
self.value = value
def __str__(self):
if callable(self.value):
return "(type: {} , value: {})".format(self.token_type.name ,self.value.__name__)
r... |
aa4d1e8e167031b5cf5637c76e25cc61e82a5fb0 | r0ckyyr0cks/PycharmProjects | /Automation/PythonCode/LoopSyntax1.py | 252 | 4.21875 | 4 | # For loop with final range
for i in range(10):
print(i)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# For loop with user input
num = input("Please enter a number => ")
for i in range(int(num)):
print(i)
|
948d539c3ac65477fd419f1aa8d73277c9a500e9 | Beatriz-GFPereira/Forecast_SmartFactory4.0 | /data_processing_prototype/data_loader.py | 64,380 | 3.640625 | 4 | import os
import pandas as pd
class DataLoad:
"""
Class collecting all necessary data for demand forecasting, including: demand (signal), all the sets of
exogenous variables in use (sales, external demand forecasts, stock, marketing, macroeconomics, other), the list of
product codes (sku) for which fo... |
032a4f616c3d6bf5b5293a58265332226f2783ec | npavanel/PHY407-Computational-Physics | /Lab 2/lab2q2b | 2,404 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 09:59:49 2020
@author: HayleyAgler
"""
#lab2 q2 b)
#Import necessary modules
import numpy as np
import matplotlib.pyplot as plt
from scipy import special
from matplotlib import cm
#define arrays for the values of m and x
m=np.array([0, 1, 2])
x... |
08ca3159b114f9a31f5cb0930160ab89de70862e | mjsh635/Non_Commutative_Matrices | /Matrices.py | 5,623 | 4.15625 | 4 | # required for the operation of this class
import random
import numpy as np
# used in the printing
import time
import os
class Matrix:
"""create a matrix of size row/columns
create and return all the random values for the matrix
populate that matrix with random values
return the matrix
... |
3b5121e732e623a7bf3a733b9f9c1961c0cc19c0 | gcdsss/Python_Script | /book_example/GuessNumber.py | 492 | 4.03125 | 4 | import random
secretnumber = random.randint(1,20)
print('I am thinking of a number between 1 and 20.')
for i in range(1,6):
print('Take a guess.')
number = int(input())
if number > secretnumber:
print('Your guess is too high.')
elif number < secretnumber:
print('Your guess is too low')
else:
br... |
a57165fc407cc8acb1adf5217cfabc1cf4502b88 | gercaballero/U2-EJERCICIO-8 | /main.py | 939 | 3.78125 | 4 | from classConjunto import Conjunto
from menu import Menu
import test
import os
if __name__=='__main__':
os.system('cls')
t=str(input('DESEA PROBAR EL TEST (S/N) : '))
if t.lower()=='s':
test.testar()
menu= Menu()
salir= False
while not salir:
print("\... |
f33784c91db03ff075c56bdc558f5f19793f727a | k15z/foenix | /2016_10_18/code.py | 3,609 | 4.03125 | 4 | """
Author: Kevin Zhang <kevz@mit.edu>
Date: October 15th, 2016
"""
def normalize(dist):
"""
This function takes a dictionary object and normalizes it so that it adds
up to 1.0, making it a valid probability distribution. It should not
mutate the dictionary object - instead, it should create a copy and return
a ... |
5eef82336a8dc5d6e449cebf3ec0a5ab7fdade3b | FinTecher-code/TestGitProject | /Chapter2/Numpy/array_operation.py | 129 | 3.515625 | 4 | import numpy as np
arr = np.array(np.arange(10))
arr1 = np.array(np.arange(1,11))
#数组的运算
print(arr*2)
print(arr + arr1) |
0ddafedefbba514aa065349fcf3ba7023bfb2762 | reddyimr/Mallikarjunaa | /reverse string.py | 186 | 4.21875 | 4 | #a=input("enter the string")
#b=a[::-1]
#print (b)
#to reverse an array
n=int(input("enter the size of an array"))
a=[]
for i in range(n):
a.append(int(input()))
b=a[::-1]
print (b)
|
2fd67ff46f25ea84c5841a3b288b259cb21bc085 | kr-amitsinha/hackerrank_10days_stats | /Day0/day_0_problem.py | 691 | 3.6875 | 4 | #Taking the inputs
length = int(input())
arrays = list(map(int, str(input()).split(' ')))
#Sort the array
arrays.sort()
#mean
mean = sum(arrays)/length
#median
mid_point = int(length/2)
if length%2==0:
median = (arrays[mid_point]+arrays[ mid_point-1])/2
else:
median = arrays[mid_point]
#mode
freq_dic = {}
m... |
c1a5e589fec922d847c1e80644cd4684490a1639 | ua-snap/atm | /read_control (homer's conflicted copy 2015-10-27).py | 3,958 | 4.1875 | 4 | def read_control(self):
"""
The purpose of this module is to open and read the control file into a
control dictionary. The control file contains information such as Input
directory, Output directory, file names, etc.
The name of the control file is specified at the command line as
the first op... |
648ab7c2152fc5e8b5b6a03ce15b69faf2efcd16 | KONAPAVANKUMAR/code-library | /search_range.py | 401 | 3.5 | 4 | def search_range(nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if target < nums[mid]:
high = mid - 1
elif target > nums[mid]:
low = mid + 1
else:
break
for j in range(len(nums) - 1, -1, -1... |
e9dffd88a950fe12e80a579473e424d217a29eb7 | KONAPAVANKUMAR/code-library | /longest_increasing_subsequence.py | 326 | 3.5 | 4 | def longest_increasing_subsequence(sequence):
length = len(sequence)
counts = [1 for _ in range(length)]
for i in range(1, length):
for j in range(0, i):
if sequence[i] > sequence[j]:
counts[i] = max(counts[i], counts[j] + 1)
print(counts)
return max(c... |
8f95fe4136fd2f2a6d273b158a8055cf8849c8a0 | KONAPAVANKUMAR/code-library | /word_break.py | 254 | 3.625 | 4 | def word_break(s, word_dict):
dp = [False] * (len(s)+1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(0, i):
if dp[j] and s[j:i] in word_dict:
dp[i] = True
break
return dp[-1] |
d143b18e5b21610481559ca00905ad2d9caf236a | Carpe-liam/python | /fundamentals/fundamentals/function_intermeidate_Ia.py | 1,314 | 3.8125 | 4 | """
1 Update values in Dictionaries and Lists
"""
x = [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo... |
9225433ff5b0a4e2b974dc8df4534eb23b9b493f | Carpe-liam/python | /fundamentals/oop/dojo-pets/ninja.py | 764 | 3.546875 | 4 | import pet
class Ninja:
def __init__(self, first_name, last_name, pet, treats, pet_food):
self.first_name = first_name
self.last_name = last_name
self.treats = treats
self.pet_food = pet_food
self.pet = pet
def walk(self):
self.pet.play()
return self
... |
aa5e7f52c89cdf69892b965862c94db2dce98848 | Carpe-liam/python | /fundamentals/oop/selection_sort.py | 541 | 3.890625 | 4 | thing = [4,2,7,1,4,8,9,3,0]
def selection_sort(list):
for i in range(len(list)):
print(f'list[i] = {list[i]} at index {i} - iteration~{i}')
for x in range(len(list)-1):
print(f"comparing I=val {list[i]} with X=val {list[x]}")
if list[i] < list[x]:
list[i], li... |
5cd192e823e7df66a895aef22934f474da05a547 | cathylefebvre/dice-game | /app.py | 1,172 | 3.890625 | 4 | import player as p
numPlayers = -1
while not 0 <= numPlayers <= 4:
try:
numPlayers = int(raw_input("How many human players are there? (choose a number 0-4)"))
except ValueError:
print "Error must type in a number value"
else:
if not 0 <= numPlayers <= 4:
print "Please e... |
6c6cc62f94c3c84de3b4522e719e0accd71478bf | cheungsingyi/predictive_punter | /predictive_punter/date_utils.py | 416 | 3.6875 | 4 | from datetime import timedelta
def dates(date_from, date_to):
"""Iterate over all dates from date_from to date_to (inclusive)"""
time_delta = timedelta(days=1)
if date_from > date_to:
time_delta *= -1
next_date = date_from
while (date_from <= date_to and next_date <= date_to) or (date_fr... |
9d45319a34f7e3c728bee402992bb20c58ae2204 | malloryeastburn/Learning-Tkinter-PY | /calculator.py | 3,239 | 4.03125 | 4 | #Purpose: Create a calculator
from tkinter import *
root = Tk()
#change title
root.title("Simple Calculator")
e=Entry(root, width=60, borderwidth=5)
e.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
def clear_click():
e.delete(0,END)
def add_click():
firstNum = e.get()
global num1
global butto... |
5679ec5a303df88b7bfc3874f2876b3b3a5a4a9b | Bellzinho/Pycharm | /Exercicio 13.py | 371 | 3.921875 | 4 | contador = 1;
a = 0;
while contador <= 20:
n = int(input(f'Digite o {contador}° valor: '));
if (n >= 0 and n <= 100):
a = a + 1;
contador += 1;
if a == 0:
print(f'Não foram digitados nenhum entre 0 e 100!')
elif a == 1:
print(f'Apenas um numero digitado está entre 0 e 100!')
else:
print(... |
2c907b20dfd589ddf327ce04df99df5cb4796ab5 | itsharshgandhi-ub/UdemyPythonDS | /QueueImplementation.py | 598 | 3.578125 | 4 | '''
Created on Dec 21, 2018
@author: harsh
'''
class QueueImplementation(object):
def __init__(self):
self.queue = []
def isEmpty(self):
return self.queue ==[]
def queueSize(self):
return len(self.queue)
def queuePeek(self):
return self.queue[-1]
def dequeue(se... |
6aab36cea6fc5d96992c964dbd6583dd0c6f6a17 | vamsivijay2021/MarletteFunding-data-engineer-sample-2020-07 | /main.py | 1,320 | 3.734375 | 4 | """
This is the entrypoint to the program. "python main.py" will be executed and the
expected csv file should exist in ../data/destination/ after the execution is complete.
"""
from src.some_storage_library import SomeStorageLibrary, project_root
import os
if __name__ == "__main__":
"""Entrypoint"""
print("Be... |
b90615f14da6ce3bacbf8210648d0ca48bb71092 | hussein-esmail7/ffmpeg_subtitle | /sub.py | 1,301 | 3.78125 | 4 |
"""
Subtitle Adder
Author: Hussein Esmail
Description: This program adds a subtitle file to a movie. Note that this can only
be done once to a movie (the second time would override the first).
Feel free to contribute to this to make it better!
"""
import os # Used to change directory, list the directory... |
ac5f3db25ad77c00c62db5f2c7852e08a6f41fee | Tomaltach/Tutorials | /Python/Algorithms/find_peak.py | 1,192 | 4.125 | 4 | #demonstrate how to use a class with Tkinter
class Application:
""" Algorithms """
def __init__(self):
""" Initialize the Program """
self.get_input()
def get_input(self):
""" Get user input """
input = raw_input('Enter numbers to be put into array using , to seperate numbers: ')
self.numbers = map(int, i... |
2e63b8d8a94213976d909c4a695c0fdc720c0e5e | megahertz66/HGC | /Myexercise/NO13_CalcTax/CalcTax.py | 386 | 4.09375 | 4 | """
What is the order amount? 10
What is the state? WI
The subtotal is $10.00.
The tax is $0.55.
The total is $10.55.
"""
amount = float(input("What is the order amount? :"))
state = input("What is the state? :")
state = state.upper()
tax = 1
if ("WI" == state) or ("Wisconsin" == state):
tax = 1.055
print("The ta... |
38bee967611ac4997918173e2720ab870e981c32 | KarmaComputing/website-word-frequency-counter | /main.py | 4,601 | 3.765625 | 4 | # 'i' is a word
# 'j' is the document
# Fij is the frequency (number of occurrences) of the term (word) i
# in document j.
# Term frequency is: TFij = Fij/max k Fkj
# Term frequency with inverse document frequency is:
# TFij X IDFi or:
# The term frequency X Inverse of the frequecy of a given term accross all
# do... |
08f811590b5263551341f14dc8341720d8266c10 | mnetrwal-tgm/A9 | /Musikstueck.py | 338 | 3.5 | 4 | from abc import ABCMeta, abstractmethod
__author__ = 'DD'
class Musikstueck(metaclass=ABCMeta):
""" Die basisklasse fuer alle Musikstuecke
"""
def __init__(self, path):
self.path=path
self.meta()
@abstractmethod
def meta(self):
pass
@abstractmethod
def abspielen(s... |
5d55cf36088806f30232586d6c04ba4d1b7f1758 | summitkumarsharma/pythontutorials | /tut10.py | 443 | 4.03125 | 4 | # Dictionary is nothing but key value pairs . it uses symbol={}
d1 = {}
print(type(d1))
d2 = {"Sumit": "Burger",
"Rohan": "Fish",
"SkillF": "Roti",
"Shubham": {"B": "maggie", "L": "roti", "D": "Chicken"}}
print(d2["Sumit"])
d2["Ankit"] = "Junk Food"
d2[420] = "Kebabs"
print(d2)
del d2[420]
# print(d2... |
7562da63409e44a8a4a77032f0ad5a2bb611b1ca | summitkumarsharma/pythontutorials | /tut21.py | 1,003 | 4.65625 | 5 | # operators in python
# 1.Arithmetic operators
# 2.Assignment operators
# 3.Comparison operators
# 4.logical operators
# 5.Identity operators
# 6.Membership operators
# 7.Bitwise operators
# 1.Arithmetic operators
# print("5 + 6 is =", 5+6)
# print("5 - 6 is =", 5-6)
# print("5 * 6 is =", 5*6)
# print("5 / 6 is =", ... |
18b3a779a6f144bf679eb47b8438b997e87f04ba | summitkumarsharma/pythontutorials | /tut28.py | 752 | 4.1875 | 4 | # file handling - write operation
# f = open("test-write.txt", "w")
# content = "To write to an existing file, you must add a parameter to the open()function" \
# "\n1.a - Append - will append to the end of the file \n2.w - Write - will overwrite any existing content"
# no_of_chars = f.write(content)
# print... |
957c37acc8c6a1c6211aba327df21de9aa4bd499 | summitkumarsharma/pythontutorials | /tut23.py | 515 | 3.96875 | 4 | # Functions in python
a = 7
b = 8
c = sum((a, b)) # built in functions
# print(c)
# user defined function
def function1():
print("we are in function 1")
# print(function1())
# function1()
def function2(a, b):
print("sum of a and b", a+b)
# function2(2, 6)
def function3(a, b):
"""This is a funct... |
e83ccf9c8148239a1407b7c243c54eaf8a1c9c73 | sumit-porwal/mySender | /user.py | 558 | 3.578125 | 4 | import socket
port = 3000
c = socket.socket()
c.connect(('localhost',port))
name = input('enter your name')
c.send(bytes(name,'utf-8'))
# import socket
# import sys
# import time
# x=socket.socket()
# h_name = input(str("Enter the hostname of the server "))
# port = 8080
# x.connect((h_name,port))
# print("Co... |
f07bddfa311a3cf735afe4d7e7f139a0bbe94c6c | KiikiTinna/Python_programming_exercises | /41to45.py | 1,684 | 4.15625 | 4 | #Question 41: Create a function that takes a word from user and translates it using a dictionary of three words,
#returning a message when the word is not in the dict,
# considering user may enter different letter cases
d = dict(weather = "clima", earth = "terra", rain = "chuva")
#Question 42: Print out the ... |
2653880ea9174d601ea8347dcc3e6cfc0a5bcc3c | Telmo465/AI-B | /aplic8.py | 241 | 3.578125 | 4 | import random
s=1
n = int(input("Número de elementos"))
a = [0 for i in range (n)]
for i in range(n):
a[i]=random.randint(0,1000)
if i%2 == 0:
s*= a[i]
print(a)
if s != 1:
print("Produto dos números de indice par:", s)
|
45a5a4477235f156a13ac60e56f09422bd74a85d | Telmo465/AI-B | /aplic7.py | 236 | 3.59375 | 4 | import random
s=1
n = int(input("Número de elementos"))
a = [0 for i in range (n)]
for i in range(n):
a[i]=random.randint(0,1000)
if a[i]%2 == 0:
s*= a[i]
print(a)
if s != 1:
print("Produto dos números pares:", s)
|
1b0d780a83a217d9bbb30b27770e6c0c7753c1a2 | Shreya-Raut/Virtual-Assistant | /Code.py | 767 | 3.859375 | 4 | import wikipedia
import wolframalpha
from tkinter import *
root = Tk()
top_frame = Frame(root)
top_frame.pack()
bottom_frame = Frame(root)
bottom_frame.pack(side = BOTTOM)
label1 = Label(top_frame , text = "Question" )
nm = Entry(top_frame)
def printAnswer():
try:
answer = wikipedia.summary(nm)
ex... |
649ba1f7946f3768b863bf52d9edc6f3ef1bdd6c | jmajorNRELgit/Tkinter-projects | /sentdex_program/temp.py | 313 | 3.609375 | 4 | import tkinter as tk
root = tk.Tk()
a = 0
def change():
global a
if a == 0:
btn_text.set("b")
a = 1
else:
btn_text.set("a")
a = 0
btn_text = tk.StringVar()
btn = tk.Button(root, textvariable=btn_text, command=change)
btn_text.set("a")
btn.pack()
root.mainloop() |
c54d7949ec7f3ca0032c580e0a2e283c5b4e5945 | SahSanjeev/SahSanjeev.github.io | /02_02_weather_forecast/end/dd_content.py | 3,540 | 3.640625 | 4 | import csv
import random
from urllib import request
import json
import datetime
"""
Retrieve a random quote from the specified CSV file.
"""
def get_random_quote(quotes_file='quotes.csv'):
try: # load motivational quotes from csv file
with open(quotes_file) as csvfile:
quotes = [{'au... |
ff165d3e0745531c7792c2e174fcaacd3cfc05ac | ADSCPYTHON/PYTHON-NIT-7AMAM | /DataTypes/Strings/isdigit.py | 227 | 3.96875 | 4 | #!/usr/bin/python
str = "2020" # No space in this string
print (str.isdigit())
str = "Python world....wow!!!";
print (str.isdigit())
"""
12 isdigit()
Returns true if string contains only digits and false otherwise.
"""
|
74ecfe357b3a3fa4bec27eff79a7cb7ea2d3aa8d | ADSCPYTHON/PYTHON-NIT-7AMAM | /DataTypes/Strings/Encoded_Method.py | 556 | 3.59375 | 4 | #!/usr/bin/python
#Str = ":-d"
Str = "redhat"
Str = Str.encode('cp1252','strict')
#Str = Str.encode('UTF-8','strict')
print ("Encoded String: ", Str)
print ("Decoded String: ", Str.decode('UTF-8','strict'))
'''
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding.
e... |
14ff56e9719ef156595e8869a1095c475a3203fd | ADSCPYTHON/PYTHON-NIT-7AMAM | /DataTypes/Strings/STRING_METHODS_isdecimal_isdigit_isnumeric.py | 1,550 | 4.09375 | 4 | '''
str.isdecimal()
Return true if all characters in the string are decimal characters
and there is at least one character, false otherwise. Decimal characters
are those from general category “Nd”. This category includes digit
characters, and all characters that can be used to form decimal-radix
numbers, e.g. U... |
9b141a24fd206e0048d1c9912313fd8484724800 | danieldiasm/Python_PostgreSQL_Udemy | /Refresher/S2E24/E24.py | 383 | 3.8125 | 4 | def greeting():
print("Welcome to the age in seconds program!");
def user_age_in_seconds():
user_age = int(input("Insert your age:"))
user_age_in_seconds = user_age * 365 * 24 * 60 * 60
print(f'Your age in seconds is: {user_age_in_seconds}')
# Yes, I've just did it. Just for the lolz!
print(f'{greetin... |
bd7a96e36266309124764b625ae845f758df502c | danieldiasm/Python_PostgreSQL_Udemy | /Sec3_Journal_w_Python_SQLite/database.py | 992 | 4.09375 | 4 | import sqlite3
connection = sqlite3.connect("data.db")
# We can change the way SQLite assemble the returning results
# connection.row_factory = sqlite3.Row
# Then the print results from a cursor will look like this:
# print(f"{entry['date']}\n{entry['content']}\n\n")
# getting as a dict we can look for a K:V pair, but... |
e33098027d5d81e360ab6bfa59e21518b60fafb5 | simarjeetsingh/Python | /Ejercicios Python/ej_06.py | 780 | 4.34375 | 4 | '''Escribe un programa que pida por teclado dos valores de tipo numérico que se han de
guardar en sendas variables. ¿Qué instrucciones habría que utilizar para intercambiar su
contenido? (es necesario utilizar una variable auxiliar). Para comprobar que el algoritmo
ideado es correcto, muestra en pantalla el... |
43b161e2538c0dc6a7d419dc0aee35378a958474 | simarjeetsingh/Python | /Ejercicios Python/ej_13.py | 576 | 3.890625 | 4 | ''' Diseña un programa que calcule el importe final de una venta considerando que sobre el
valor bruto se hace un descuento según la siguiente tabla:
a. Valores <=20 implican un descuento del 0%
b. Valores >20 y <=100 implican un descuento descuento del 5%
c. Valores >100 implican un descuento 10%.'''
valor ... |
8b51095d7754e62ba2af57f55a619e0f87ab8564 | gustavscholin/advent_of_code_2020 | /task_04/task_4_1.py | 588 | 3.546875 | 4 | def read_input(path):
output = []
with open(path, 'r') as f:
input_lines = f.read().split('\n\n')
for line in input_lines:
line = line.split()
output.append({i.split(':')[0]: i.split(':')[1] for i in line})
return output
if __name__ == '__main__':
credentials = read_input('... |
e51eb1823da80b14128e2f0dd01ca72a68d1e37e | ShydowLi/data_processing | /分类变量,顺序变量标志转换(哑变量处理)/Sort_data.py | 1,212 | 3.65625 | 4 | #将分类数据和顺序数据转换为标志变量
#1、分类数据的处理
#2、顺序数据的处理
#运用标志方法处理分类和顺序数据
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df=pd.DataFrame({
'id':[3566841,6541227,3512441],
'sex':['male','female','female'],
'level':['high','low','middle']
})
print(df)
#自定义转换过程
df_new=df.copy()
for col_num,col_name in... |
97403961cc908e197b4be16b5aba6ff75741ecf0 | Jeevan1351/pythonLevel1 | /Activity6.py | 683 | 3.921875 | 4 | import math
def read():
nums = input("Enter a few numbers").split()
ints = [int(n) for n in nums]
return ints
def is_prime(n):
if n <= 1:
return 0
elif n == 2:
return 2
elif n % 2 == 0:
return 0
else:
for i in range(3, int(math.sqrt(n)) + 1, 2):
... |
1a1534f4c01d5001a7deefa53e313bb6fe530016 | 1Magnus/pythonProject19_07_2021 | /lesson_3/hw_9.py | 618 | 3.859375 | 4 | # Найти максимальный элемент среди минимальных элементов столбцов матрицы
import random
random.seed(7)
N = 5
a = []
for str in range(N):
b = []
for row in range(N):
b.append(random.randint(0, 99))
a.append(b)
for i in range(N):
print(a[i])
print('*' * 20)
d = []
for row in range(N):
c =... |
b3a98b16474442b4f12dc647514db6fd9b80f63e | 1Magnus/pythonProject19_07_2021 | /lesson_3/hw_5.py | 644 | 4.25 | 4 | # В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве.
import random
def rand_mass(N):
a = [0] * N
for i in range(N):
a[i] = random.randint(-99, 99)
return a
def main():
N = 10
a = rand_mass(N)
print(a)
b = []
for i in a:
... |
75fcbdc0d721cffaaa0c355cc526a64d8fe679ae | 1Magnus/pythonProject19_07_2021 | /hw_6.py | 265 | 3.984375 | 4 | # Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
a = int(input('Введите номер буквы в алфавите: '))
print(f'Это буква: {chr(a + ord("a") - 1)}') |
3d06d8fb2180e9b3fc24671cbd93708b2f66b1b2 | montdev/xware | /file.py | 716 | 3.515625 | 4 | import os
Path = os.path.dirname(os.path.abspath(__file__))
print(__name__, Path)
#print(os.path.abspath("."))
# ================================================
# Get the Xware Path..
# ================================================
def xwarePath():
"""Where is our Application?"""
return os.path.d... |
b2a5d47a56393cd1c3f196f33670fc6b7af71b6b | Prakruthi94/Pylearning | /Name, age and location.py | 482 | 3.703125 | 4 | #def print_personal_details(name,age,loc):
# print("My name is",name)
# print("My age is",age)
# print("My location is",loc)
#return None
def print_personal_details(*args):
print("My name is",args[0])
print("My age is",args[1])
print("My location is",args[2])
return None
def main():
n... |
d23b9cadd1d595cc1c9bde96d01ac51baff9bd82 | Prakruthi94/Pylearning | /vowels.py | 220 | 3.703125 | 4 | s1=['a','e','i','o','u']
sum=0
s2=input("Enter the string")
sum=sum+s2.count(s1[0])
sum=sum+s2.count(s1[1])
sum=sum+s2.count(s1[2])
sum=sum+s2.count(s1[3])
sum=sum+s2.count(s1[4])
print("The number of vowels is", sum)
|
3d1d12ea77cfab289f17635dc7d1618149e326cb | ThomasB123/ecc | /bits.py | 246 | 3.890625 | 4 | def binary(num): # convert denary number to binary
out = []
while num > 0:
if num % 2 == 1:
num -= 1
out.append(1)
else:
out.append(0)
num /= 2
return out
print(binary(151)) |
182671b68d10432a1538a3a52c59ec64ff88ff7d | ayank540/CP | /Tree/dfs.py | 1,469 | 3.859375 | 4 | from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
self.df = []
# def dfs(self, root):
# dfs = deque()
# if not root:
# ... |
31eb10aa5ed3523676352cf91a983788ab1ab499 | 99003770/Python_practice1 | /_init.py | 217 | 3.765625 | 4 | # A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Danish')
p.say_hi()
|
09f694cd9b2aec187e7ab89aaa6de444eebf1fc4 | mathews19/projetoPython | /ex15.py | 660 | 4.0625 | 4 | from sys import argv
script = argv # file_name = argv Nessa linha recebemos/descompactamos os parametros recebidos
file_name = input("Digitev aqui o nome do arquivo")
txt = open(file_name) # Nessa linha abrimos o arquivo que recebemos como parametro no command line
print(f"Here\'s your file {file_name}: ")
print(txt.... |
ce7403b301e32b07d1902b72121e7d2ea699de82 | nitya108/leetcode | /vertical_order_traversal.py | 1,171 | 3.625 | 4 | # Input: [3,9,20,null,null,15,7]
# Output: [[9],[3,15],[20],[7]]
# Explanation:
# Without loss of generality, we can assume the root node is at position (0, 0):
# Then, the node with value 9 occurs at position (-1, -1);
# The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
# The node with value 20 oc... |
9b9f35fa2c1c77ca093469e4181ec499129df7c7 | mdyounusali/api_doc | /gg.py | 3,442 | 3.9375 | 4 | daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
import turtle
#pixel pra
myPen = turtle.Turtle()
myPen.speed(0)
myPen.color("#000000")
# This function draws a box by drawing each side of the square and using the fill function
def box(intDim):
myPen.begin_fill()
... |
e67a6e716981fd50f29efae284080290a86751f0 | chekol1/live-N-living | /demo2.py | 204 | 3.921875 | 4 |
def show_love(num):
if num%2 == 0:
print("is even")
else:
print("is not even----")
if __name__ == "__main__":
input1 = int(input("write your number"))
show_love(input1) |
d4be3d34f0528b17000bc3ea9357b7439337e262 | amanverma15/programing | /Aman/OldWork/big game.py | 5,579 | 3.953125 | 4 | import random
import time
tries = 10
while True:
print("Hi I am Coputer and I would like you to test my ten games")
print("Do you want to play")
a = random.randint(1,100)
print(a)
b = input(" ")
if b == "yes":
print("Great")
print("1st game")
print("guessing game")
... |
6218d9ca2319404fb646e45c62e7d7ab65e5bc84 | amanverma15/programing | /Aman/OldWork/Projects/class10.py | 363 | 3.984375 | 4 |
list1 = ["physics", "chemistry", 1997, 2000]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
print(list1)
print(list2)
print(list3)
list1[3] = "biology"
list2[3] = 6
list3[3] = "e"
list1.remove(1997)
list2.remove(5)
list3.remove('a')
print(list1)
print(list2)
print(list3)
len(list1)
len(list2)
len(list3)
... |
288a6222b5646b665e4481227413ed22def9cd75 | amanverma15/programing | /Aman/OldWork/comma.py | 960 | 3.953125 | 4 | """Write a Python program that accepts a comma separated sequence of words
as input and prints the unique words in sorted form (alphanumerically). Sample
Words : red, white, black, red, green, black
Expected Result : black, green, red, white,red"""
a = input("Enter multiple words")
words = a.split(",")
print(words)
wo... |
47498ff38b5c055977582b455c8f36e9948574ad | amanverma15/programing | /Aman/Function.py | 367 | 4.03125 | 4 | """Write a Python function that takes a list and returns a new list with unique elements of the first list.
"""
list1 = ['a','b','c','d','e','a','b','a','b','d','f']
def unqie(list2):
list3 = []
for i in list2:
if i in list3:
continue
else:
list3.append(i)
return lis... |
81b80b01cbfd150a5c05cc258cb48fed4f127924 | justineschabel/Python | /Practice_and_learn/distance.py | 292 | 3.828125 | 4 | #This program calculates the distance between two points
import math
import sys
def dist(x1 ,x2, y1, y2):
a = (x2 - x1)**2
b = (y2 - y1)**2
c = math.sqrt(a + b)
print c
x = int(sys.argv[1])
y = int(sys.argv[2])
x_ = int(sys.argv[3])
y_ = int(sys.argv[4])
dist(x,x_,y,y_)
|
b878710a1e80355e01500b6a10601bf03f8c4f8b | LuckyDima/Geekbrains_DB_0607 | /GeekBrains_local/Основы языка Python. Интерактивный курс/05 Модули и библиотеки/Lesson2.py | 844 | 4.15625 | 4 | # 2: Создайте модуль. В нем создайте функцию, которая принимает список и возвращает из него случайный элемент.
# Если список пустой функция должна вернуть None. Проверьте работу функций в этом же модуле.
# Примечание: Список для проверки введите вручную. Или возьмите этот: [1, 2, 3, 4]
from random import choice, randi... |
da64e8206095a235dc4ddcb082d5cc8820c8632d | LuckyDima/Geekbrains_DB_0607 | /GeekBrains_local/Основы языка Python. Интерактивный курс/02 Встроенные типы и операции с ними/Встроенные типы и операции с ними.py | 3,476 | 4.3125 | 4 | # 1: Даны два произвольные списка. Удалите из первого списка элементы присутствующие во втором списке.
# Примечание. Списки создайте вручную, например так:
# my_list_1 = [2, 5, 8, 2, 12, 12, 4]
# my_list_2 = [2, 7, 12, 3]
# Предполагаю, что задание должно быть решено при помощи функции set, но это не верное решение
# ... |
e82287afa6b5f5d50c2ea330549dd8ecafaeb635 | LuckyDima/Geekbrains_DB_0607 | /GeekBrains_local/test/test.py | 1,002 | 3.75 | 4 | x = 2
result = x * 10 if x < 10 else x / 10
print (result)
from pynput import keyboard as k
import random as r
number = r.randint(1, 100)
finish = 0
print(f'Моё число {number}')
def on_release(key,finish=finish):
if key == k.Key.esc:
print('Вы закончили игру.')
return False
elif key == k.K... |
2d608e5524d28fd841cb6c902d1af98f1cfb8743 | kshah17/PythonAssessment2 | /Code/blank.py | 104 | 3.828125 | 4 | input = "THE"
def one(input):
word = ' '
for char in input:
word = word + char + char
return word |
0656000a14dcf90dd7233b72073a190862c8aeba | seebrand/spoofnet-tensorflow | /data/helpers.py | 1,223 | 3.546875 | 4 | """
Helping functions called by the pipeline modules.
"""
########################################################
def get_lines_in_file(file_path, read=False):
"""
Reads file lines and returns number of lines, and optionally the lines list
:param file_path
:param read: boolean to alloe=w return of li... |
fb961e9bcd3f9a62c1c60c5c0eb26235a215d7b6 | ram-marwaha123/Decision-Tree | /Decision Tree/tree.py | 640 | 3.703125 | 4 | class node:
def __init__(self, value = ""):
self.value = value
self.branches = []
def add_node(self, node):
self.branches.append(node)
class Leaf(node):
def __init__(self, p, q):
self.p = p
self.q = q
def add_node(self, node):
raise
... |
074ef01424865ce88dd820c1879af476f5ea820a | alexander-held/advent-of-code-2019 | /02/puzzle.py | 2,564 | 3.796875 | 4 | import copy
opcodes = [1, 2, 99]
# 1: read values at the two following indices, save to third index
# 2: same but multiply
# 99: stop program
# after processing: move forward 4 positions
def process_code(code):
i = 0 # position in code, "instruction pointer"
while i < len(code):
if code[i] == 1:
... |
1baa97766bac53cd7cf5cd4d1527b01320f3704f | TimothyBergstrom/DD1324 | /Exercise_1/Exercise_1.2.py | 1,012 | 3.859375 | 4 | import time
n = input('Fibnumber: ')
if not n.isdigit():
print('Not a digit, quitting')
quit()
elif int(n) <= 0:
print('0 or less is not permitted')
quit()
else:
n = int(n)
def fib_sequence(n):
if n == 1 or n == 2:
return 1
else:
return fib_sequence(n - 2) + fib_sequence(n ... |
799b9039040410801c89cd794e02f7587e83611e | oldwai/guest | /guest/learn_unittest/calculator.py | 546 | 3.578125 | 4 | # -*- coding:utf-8 -*-
'''
@author:oldwai
简单计算器功能
'''
# email: frankandrew@163.com
class Calculator():
'''
实现两个数的加、减、乘、除
'''
#
def __init__(self,a,b):
self.a = int(a)
self.b = int(b)
#Addition
def add(self):
return self.a + self.b
#subtracti... |
c65bc508a10563fa6a391cdfdd1997db19569b7a | bsamaha/hackerrank_coding_challenges | /Sock Merchant.py | 761 | 4.125 | 4 | # %%
from collections import defaultdict
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
"""[Find how many pairs can be made from a list of integers]
Args:
n ([int]): [nymber of socks]
ar ([list of integers]): [inventory of socks]
Returns:
[type]: [description... |
917df75887ad40506539bc69da84036eb31b8004 | xoltia/consolecalc | /consolecalc/defaults.py | 2,235 | 3.578125 | 4 | from .expressions import Grouping, Operator, Precedence
from importlib import import_module
@Operator.new('+', Precedence.Addition)
def add(x, y):
return x.evaluate() + y.evaluate()
@Operator.new('-', Precedence.Addition)
def sub(x, y):
return x.evaluate() - y.evaluate()
@Operator.new('*', Precedence.Multipl... |
07c41ccd7a966c32929d29e6186e329f39fd6086 | kxz18/JapanK | /core/display.py | 2,243 | 3.90625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
def myPrint(target, width, _end='\n', hideOverLen=False):
'''special format print for non-English
first decide the size of the string, then judge the overlength(if hideOverLen is true) and decide what to return'''
size = 0
target = str(target)
#decide size o... |
afbca40d25947b547a95386467f259dbace88dca | viad00/uts_march_2016_py | /17.3.16/G.py | 496 | 3.515625 | 4 | import math
import sys
sys.stdin = open("twoc.in")
sys.stdout = open("twoc.out", "w")
x, y, x1, y1, R, R1 = map(float, input().split())
d = math.sqrt((x1 - x) * (x1 - x) + (y1 - y) * (y1 - y))
if R + R1 == d:
print('Tangent: outside')
elif R + R1 < d:
print('Too far')
elif R1 == d + R:
print('Tangent: 1 in... |
c27029337d0f7cacc5256deb578d6433ce081f08 | frederickm13/data-science | /CsvSplitter/Python-CommandLine/CSV_Splitter.py | 2,936 | 3.828125 | 4 | import csv
import os
import numpy as np
import CSV_Splitter_Functions
print(os.getcwd())
#####
#Get/check directory of .csv file
#####
counter = 1
while counter == 1:
filePath = input("Please input the path for your .csv file:")
if os.path.isfile(filePath) == True:
input("File confirmed to exist... Pl... |
4d33b0686c38979cd59a79b0ec3f8463cff40684 | haoyanjun21/AI_demo | /demo/linear_demo.py | 591 | 3.78125 | 4 | import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def runplt():
plt.figure()
plt.title('price and inch')
plt.xlabel('inch')
plt.ylabel('price')
plt.axis([0, 25, 0, 25])
plt.grid(True)
return plt
X = [[6], [8], [10], [14], [18]]
y = [[7], [9], [13], [17.5]... |
e064d9a951cc77879be234b921f3712a4782652e | jz1611/python-codewars | /squareDigits.py | 377 | 4.1875 | 4 | # Welcome. In this kata, you are asked to square every digit of a number.
# For example, if we run 9119 through the function, 811181 will come out,
# because 92 is 81 and 12 is 1.
# Note: The function accepts an integer and returns an integer
def square_digits(num):
new = []
for num in list(str(num)):
new.ap... |
b6a57d249c42f823a3a2129917e187cd90226b78 | NinjaKemuri/adventofcode | /day_02/question_2.py | 905 | 3.984375 | 4 | def check_password(password, char, f_min, f_max):
string_list = list(password)
# Check both positions are not the same character
if string_list[f_min - 1] == char and string_list[f_max - 1] == char:
return False
else:
if string_list[f_min - 1] == char or string_list[f_max - 1] == char:
... |
ac67c89904dc7c87380b73a7c51372427b1b0f19 | NinjaKemuri/adventofcode | /day_02/password_policy.py | 633 | 3.796875 | 4 | def check_password(password, char, f_min, f_max):
# Check occurrences of character in password
if f_min <= list(password).count(char) <= f_max:
return True
return False
pass_obj = []
with open("input.txt") as f:
for line in f:
print(line.split())
pass_obj.append(line.split())
... |
f8765716f08a4c3d0fa79234da22e3dddea089d9 | decarb/python-cards | /card_collection.py | 1,012 | 3.640625 | 4 | import random
import itertools
from card import Suit, Rank, Card
class CardCollection:
def __init__(self, cards):
self.cards = cards
def push(self, card):
self.cards.append(card)
def pop(self):
return self.cards.pop()
def is_empty(self):
return (self.cards == [])
... |
1504429ab43eb7b50a9321285884b95971aea937 | Mohammadmosin/Hacker-rank-solutions | /Connected Cells in a Grid | 1,333 | 3.71875 | 4 | #!/bin/python3
#hacker ran link: https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem
import math
import os
import random
import re
import sys
# Complete the connectedCell function below.
def dfs(row, column, l, v):
d = 1
leng=len(l[0])
v.append([row, column])
row_vector = [0,1,-1,0,1... |
4ba98f192d5edace667c5a4b3b66db0b47e1ba15 | Zeki-Souza/Comp_1-Python-_UFRJ_2020 | /Módulo 5/Machine Teaching/L5MT.py | 3,578 | 4.21875 | 4 | ##Machine Teaching Lab 5
##1)Quantidade de palavras
def quant_palavras(frase):
"""Função que, dada uma frase, retorna o numero de palavras da frase,
considerando que a mesma pode ter espaços no início e no final.
Entrada: list (str) ; Saida: int"""
spl = str.split(frase)
return len(spl)
... |
8a6d907f43d5dfab43ec715a01cb30a8138b0ed7 | Zeki-Souza/Comp_1-Python-_UFRJ_2020 | /Módulo 2/Lista 2 Idle.py | 5,217 | 3.609375 | 4 |
import math
##Questão 1:
##a):
def media3(n1,n2,n3):
'''funcao que retorna a media de tres numeros inteiros, dados por n1,n2 e n3
float, float, float -> float'''
return (n1 + n2 + n3)/3
##b):
def difmair(n1,n2,n3):
'''funcao que retorna, dados os numeros n1,n2 e n3, a diferença do maior
d... |
b60c3f606910f03063a7a03e7ec1b2c630af2e9d | wwuhn/wwuhn.github.io | /notes/VC/排序算法/buble/buble.py | 320 | 3.890625 | 4 | def bubble_sort(nums):
for i in range(len(nums) - 1):
for j in range(len(nums) - i - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
return nums
print(bubble_sort([45, 32, 8.3, 33, 12, 22.1, 19, 97]))
# 输出:[8.3, 12, 19, 22.1, 32, 33, 45, 97]
|
280152ea248f3c1fdf5238b0856c2952d6fb1906 | Intern-Trial/answers-andrada0801 | /cond_ex1.py | 432 | 3.859375 | 4 | # Name: cond_ex1.py
#
# Description:
#
# This program prints prices of tickets depending on age.
def main():
age=int(input("\nEnter your age: "))
if age<=16:
print("Your ticket costs {0:1} pounds".format(6/2))
elif age>=60:
print("Your ticket costs {0:1} pounds".format(6/3))
else:
... |
32d01319b4f77b6aae3ab33368beca864b02dcd0 | mynamesjaff/Complete-Python-3-Bootcamp | /04-Milestone Project - 1/Project1_tic_tac_toe.py | 6,377 | 4.5 | 4 | #TicTacToe Project - Milestone #1
#Step 1: Write a function that can print out a board. Set up your board as a list, where each index
#1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.
def display_board(board):
print('| | | |')
print(f'| {board... |
061c6c80dddfce1510e69b6bba56d8018abcd466 | YevheniiM/TwitterFriendsMapForConsole | /helpers/map_creation.py | 1,809 | 3.71875 | 4 | """map_creation.py
The module provides functions to create map of friends
"""
import folium
import requests
from data.tokens import API_KEY
def get_coordinates(address):
"""(string) -> (tuple[float, float])
The functions finds actual coordinates of
the place, which is given as a string and
returns... |
1b15a144d8a314f3054bf9de484f531c1cc58be3 | 1769778682/python11 | /class1/c08para2.py | 548 | 3.765625 | 4 | import unittest
def add(x, y):
return x + y
class Test(unittest.TestCase):
# 整理测试数据
def test_add(self):
# 用一个测试方法将所有测试数据全部使用一遍
test_list = [(0, 1, 1), (1, 1, 1), (1, 2, 3)]
for i, j, expect in test_list:
print(i, j, expect)
result = add(i, j)
... |
a304f6a85cbfdcd24a67dd75b8c17817e77928b9 | 1769778682/python11 | /class1/c07para.py | 495 | 3.828125 | 4 | import unittest
def add(x, y):
return x + y
class Test(unittest.TestCase):
def test_add01(self):
result = add(1, 0)
self.assertEqual(1, result)
def test_add02(self):
result = add(1, 1)
self.assertEqual(1, result)
def test_add03(self):
result = add(1, 2)
... |
859c35e8a4e8f511f5000b89f8f95f7e24a0689b | pris0213/udemy-qa-1 | /2-python-recap/decorators.py | 763 | 3.765625 | 4 | import functools
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func():
print("Inside the decorator!")
func()
print("After the decorator!")
return function_that_runs_func
@my_decorator
def my_function():
print("Inside the function!")
# my_function()
## Complex decorators
def decora... |
7ec134f3dfe4ccd1dabff39bc53069ea7fedd66c | shatmanyu/cp_shed | /Trees/Zigzag or Spiral Traversal.py | 1,547 | 3.921875 | 4 | class newNode:
def __init__(self,val):
self.val=val
self.right=None
self.left=None
## ZigZag or spiral level order traversal of binary tree
## DS used -> Queue
## Algo used -> Level order traversal
## Concept -> Do Simple Level order Traversal + change directon at each level thro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.