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 |
|---|---|---|---|---|---|---|
5c5435cc6d4ca75a391fa40d5c5488cf7f600799 | Rameesa/training | /Python progrmng/ass6.py | 150 | 3.625 | 4 | list1=[1,20,33,5,44]
list2=[12,43,1,33,56]
def diff(li1,li2):
return(list(set(li1)-set(li2)))
print(list1)
print(list2)
print(diff(list1,list2))
|
2d9d107e17038844c1533227d696fee1c34c1c04 | malienko/projecteuler_python | /problem7.py | 706 | 3.78125 | 4 | '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
import numpy as np
import math
from datetime import datetime
start = datetime.now()
top_limit = 200000
total = 0
arr = np.zeros((top_limit,1), dtype=bool)
for num in rang... |
fa350dfcbb8a3ae3c4d585fb215ec12cdacde992 | malienko/projecteuler_python | /problem30.py | 775 | 4 | 4 | '''
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1**4 + 6**4 + 3**4 + 4**4
8208 = 8**4 + 2**4 + 0**4 + 8**4
9474 = 9**4 + 4**4 + 7**4 + 4**4
As 1 = 1**4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 1... |
0a0e377ff207f57bafb2cd622c772080d4559fe4 | AvyanshKatiyar/megapython | /app4/app4_code/backend.py | 2,190 | 4.3125 | 4 | import sqlite3
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)")
conn.commit()
conn.close()
#id checks how many entries
def insert(title, author, ye... |
eb740ea5b08d9f8b1cec289512d993ec5093ea42 | AvyanshKatiyar/megapython | /Not_app_code/the_basics/forloops.py | 889 | 4.1875 | 4 | monday_temperatures=[9.1, 9.7, 7.6]
#rounding
print(round(monday_temperatures[0]))
for temperature in monday_temperatures:
print(round(temperature))
#loop goes through all the variables
#looping through a dictionary
student_grades={"Marry": 9.1, "Sim": 8.8, "John": 7.5}
#chose what you want to iterate o... |
574a7fbd43b7f673945f5a09c76c4233312d6db2 | PengchengAi/udp_ctl | /gpio_test.py | 250 | 3.5 | 4 | from gpiozero import LED, Button
import time
btn = Button(21)
led = LED(20)
while True:
if btn.is_pressed:
print("is pressed, led on")
led.on()
else:
print("is released, led off")
led.off()
time.sleep(1)
|
9d3a49d2a2510a06c0f5ed7a03581a592babeb31 | fenda88/Earthquake-Induced-Landslide-Prediction- | /ML models/Logistic Regression/logistic_regression.py | 3,648 | 3.5 | 4 | # Logistic Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('/home/btpbatch3/Desktop/BTP3/April/dataset_250m.csv')
X = dataset.iloc[:, 2:8].values
y = dataset.iloc[:, 8].values
# var = 0
# for i in range(0, len(y)... |
a343e09ca1dbbbce570d17da43ddc7854e4e2f08 | cpe202fall2018/lab0-bjgrabow | /planets.py | 336 | 4 | 4 | def weight_on_planets():
# write your code here
#weight is an integer to be input by the user
weight = int(input('What do you weigh on earth? '))
print('\nOn Mars you would weigh %.2f pounds.\nOn Jupiter you would weigh %.2f pounds.' % ((weight * 0.38),(weight * 2.34)))
if __name__ == '__main__':
weig... |
cff76b384deb0743ab50974e3e6993b7598d9be8 | JoePittsy/AdventOfCode | /Day 15/main.py | 1,017 | 3.578125 | 4 | #!/usr/bin/python3
# Joseph Pitts 15th of December 2020
def tasks(numbers, limit):
memory = {num: [index + 1] for index, num in enumerate(numbers)}
turn = len(numbers)
last_spoken = numbers[-1]
memory[last_spoken] = [None]
# for _ in range(10):
while turn < limit:
turn += 1
# F... |
e758af020457f6f4f332d8e6d80ac6afff89bbdd | JoePittsy/AdventOfCode | /Day 13/main.py | 1,468 | 3.671875 | 4 | #!/usr/bin/python3
# Joseph Pitts 13th of December 2020
from itertools import count
def read_data(path):
with open(path) as f:
lines = f.readlines()
time = int(lines[0].rstrip())
dataset = lines[1].strip().split(",")
return time, dataset
def task_one(time, dataset):
bus_timetab... |
cecf188d0a3425dbc83dac4b9caf56f1f428b4d2 | meetashwin/python-play | /basic/countsetbits.py | 392 | 4.5 | 4 | # Program to count the set bits in an integer
# Examples:
# n=6, binary=110 => Set bits = 2 (number of 1's)
# n=12, binary=1100 => Set bits = 2
# n=7, binary=111 => Set bits = 3
def countsetbits(n):
count = 0
while(n):
count += n & 1
n >>= 1
return count
print("Enter the number to find set bits for:")
n = ... |
cd90a62bd121172d081c4687a886e76c47c7a1c2 | aks789/python-code-basics-to-expert | /advanced_concepts/reg_expr_part1.py | 449 | 3.84375 | 4 | import re
text = "The agent's phone number is 408-555-1234. Call soon!"
print('phone' in text)
pattern = 'phone'
print(re.search(pattern,text))
match = re.search(pattern,text)
print(match.span())
text = 'My phone once, my phone twice'
match = re.search(pattern,text)
print(match)
matches = re.findall(pattern,t... |
cdabebbea670189f34d20c56c0655e5e16101993 | aks789/python-code-basics-to-expert | /advanced_concepts/time_code.py | 749 | 3.71875 | 4 | import time
import timeit
def func_one(n):
return [str(num) for num in range(n)]
def func_two(n):
return list(map(str,range(n)))
start_time = time.time()
res = func_one(10000)
end_time = time.time()
elapsed_time = end_time - start_time
print(elapsed_time)
start_time = time.time()
res = func_two(10000)
... |
9ed79315a5265e8c80f53b6c78fd3cb4d377623b | aks789/python-code-basics-to-expert | /advanced_data_Structure/adv_dict_list.py | 710 | 3.984375 | 4 | d = {'k1':1,'k2':2}
d1 = {x:x**2 for x in range(10)}
print(d1)
## zip creates an iterator which will aggregate two or more iterables
d2 = {k:v**2 for k,v in zip(['a','b'],range(2))}
print(d2)
for k in d1.values():
print(k)
## ADVANCED LISTS ##
l = [1,2,3,4]
l.append(5)
print(l)
print(l.count(10))
print(l.e... |
40bd72c0b2458e416ec6e67cd0397e5bf35cd878 | gopig494/Learn-Python | /python3.py | 1,208 | 3.5625 | 4 | #split and Reverse a String
#1
intp="gopi python java india"
l=intp.split()
j=0
li=[]
for i in range(1,len(l),2):
ab=l[j]
j+=2
li.append(ab)
bc=l[i]
li.append(bc[::-1])
print(li)
#2
intp="gopi python java india"
l=intp.split()
j=0
li=[]
while j<len(l):
if j%2!=0:
a=l[j]
li.append(a[::-1])
j+=1
else:
b... |
2c7b868ebd02ab81ee13cf4abda1cb65e759e2e4 | gopig494/Learn-Python | /regex_21.py | 9,198 | 3.796875 | 4 | #regex #regular expression
#meta characters
#search
import re
print(re.compile(r'\d\d\d\d\d\d\d\d\d\d').search('9000000049'))
#1
#method 1
strr=re.compile(r'\d\d\d\d\d\d\d\d\d\d')
res=strr.search('9000000049')
print(res)
#method 2
res='9000000049'
strr=re.search(r'\d\d\d\d\d\d\d\d\d\d',res)
print(strr)
#... |
75f7809d09ea4f751cde3f6be2171515e6b5a82c | gopig494/Learn-Python | /multithreading_24.py | 388 | 3.640625 | 4 | from threading import Thread
class Multi(Thread):
def fun(self):
for i in range(10):
print('i am child')
def callme():
for i in range(10):
print("call me")
a=Multi()
ac=Thread(target=a.fun)
ac.start()
bc=Thread(target=callme)
bc.start()
ac.join()
bc.join()
for i in range(10):
... |
73f987e79d108ae2993999e00488096fed70db57 | gopig494/Learn-Python | /python12.py | 2,253 | 4.0625 | 4 | #function
#Variables
#1
phone='iphone,xiomi' #phone_variable
print(phone)
#types of variables
#Global variables
#1
phone='iphone,xiomi'
def ph():
print(phone)
def sm():
print(phone)
def call():
sub_variable=phone
print(sub_variable)
ph()
sm()
call()
#2
phone='iphone,xiomi',100,[10,20,30,40]
def ph... |
5212f2d72f6162d1d169b7b583f4ff83fdf85781 | dannko97/python_github | /Algorithmic illustration_算法图解/divide and conguer_sum.py | 606 | 4.15625 | 4 |
# recursion
def DaC_sum(list):
"""sum of the elements of a list"""
if list == []:
return 0
else:
x = list[0]
return x + DaC_sum(list[1:])
def DaC_len(list):
"""number of the elements of a list"""
if list == []:
return 0
else:
return 1 + DaC_len(list[1:... |
6b674887d7d590d12016e60aed03cce67d284b9d | remcous/Python-Crash-Course | /Ch04/squares.py | 452 | 4.5625 | 5 | #initialize an empty list to hold squared numbers
squares = []
for value in range(1,11):
# ** acts as exponent operator in python
square = value**2
# appends the square into the list of squares
squares.append(square)
print(squares)
# more concise approach
squares = []
for value in range(1,11):
squares.append(va... |
5b11fb3d65ad33bd6b11957cb7a222793278f368 | hotshot07/Scripts | /scrape.py | 910 | 3.578125 | 4 | from bs4 import BeautifulSoup
import requests
url="https://tutsgalaxy.com"
data=requests.get(url)
url2="https://www.yify-torrent.org/popular.html"
data2=requests.get(url2)
url3="https://www.yify-torrent.org/latest.html"
data3=requests.get(url3)
print("---------------Courses---------------")
print()
soup=Beautif... |
348a61cf4af7a6c8813914c40de873a3154cd6fe | shekharkarna/SnakeLadder | /main.py | 1,346 | 3.796875 | 4 | # random module to simulate dice flow
import random
# reference for snake and ladders
grid = [i for i in range(101)]
grid[2] = 23
grid[8] = 12
grid[17] = 93
grid[29] = 54
grid[31] = 14
grid[32] = 51
grid[39] = 80
grid[41] = 20
grid[59] = 37
grid[62] = 78
grid[67] = 50
grid[70] = 89
grid[75] = 96
grid[83] = 80
grid[9... |
3571534be7351e91f9b7e7e039a31865b51d0d6c | sol20-meet/tal3a | /ball.py | 1,376 | 3.953125 | 4 | from turtle import *
import turtle
class Ball(Turtle):
def __init__(self,x,y,dx,dy,r,color):
Turtle.__init__(self)
self.pu()
self.goto(x,y)
self.dx = dx
self.dy = dy
self.r = r
self.shape("circle")
self.shapesize(r/10)
self.color(color)
... |
4ff2b09c4e15e21b4c2e85ac473f4d082f6611b0 | TarsilaaSouza/MaquinaDeTuring | /turing-machine/code/maquina/Maquina.py | 2,319 | 3.5 | 4 | from Arquivo import lerArquivo
from Operacao import Operacao
from Fita import Fita
#codificao dos simbolos
ESTADO_INICIAL = '0'
ACEITACAO = 'halt-accept'
REJEICAO = 'halt-reject'
class Maquina:
def __init__(self, Fita=Fita(), Operacao=Operacao()):
self.Fita = Fita
self.Operacao = Operacao
... |
2fd212a71a709469e6b152c7aab4e51d3fb9e1b3 | gokulrajganesan2000/python_assignment2 | /sqlite3_connectivity.py | 649 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 21:27:25 2020
@author: Gokulraj
"""
import sqlite3
def creatTable(con,cur):
cur.execute(""" CREATE TABLE student( regno integer,name text)""")
con.commit()
def insertValuesInTable(con,cur):
cur.execute("INSERT INTO student VALUES (1721118,'go... |
9c898178c5fb6ed2b379b6d2fae63b90a5116c7e | VolodkoUra/HomeWork1 | /task_1_3.py | 210 | 3.578125 | 4 | #Дана длина ребра куба. Найти объем куба и площадь его боковойповерхности
d = 2
v = d ** 3
print("Объем: ", v)
print("Площадь: ", d ** 2) |
5c40f579d70385457f67841913373237baf85152 | pipkamv/freeje1 | /d10.py | 377 | 4 | 4 | # a = input('Введи 1 число: ')
# b = input('Введи 2 число: ')
# if a < b :
# print('Результат: ', a + ' < ' + b)
# # '<' - фунция в кавычках, потому - что оно что-то выполняет
# elif a > b:
# print('Результат: ', a + ' > '+ b)
# else:
# print( 'Результат: ', a + '=' + b )
|
481d7a2f38d082aebf28a09f0b44e3a845627f7d | pipkamv/freeje1 | /d8.py | 180 | 3.890625 | 4 | # 8
# a = input('Input: ')
# if len(a) == 2:
# print(a * 2)
# elif len(a) == 2:
# print(a)
# elif len(a) < 2:
# print('Error!')
#
# print(a[0:2:] )
# print(a[-2:])
|
6ec8008adacf753c5eee0702e8d31bac8d5c6b71 | blackantywj/Leetcode_coding_everyday | /number_of_1_bits.py | 439 | 3.75 | 4 | # class Solution:
# def hammingWeight(self, n: int) -> int:
# total = 0
# while n != 0:
# crc = n % 2
# n = n / 2
# if crc == 1:
# total += 1
# return total
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
... |
cc88b9f62aa630e7c1359fa786fa374bc09a9d84 | blackantywj/Leetcode_coding_everyday | /convert_sorted_array_to_binary_search_tree.py | 880 | 3.78125 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param num, a list of integers
# @return a tree node
# 12:37
def sortedArrayToBST(self, num):
if not num:
... |
c9bb56551f82834eca2baffc422ee59b06c436b5 | blackantywj/Leetcode_coding_everyday | /balanced_binary.py | 752 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def ch(root):
if(root==None):
... |
21ac3efa0c0929a9904ca3d9d3e6549dc003e575 | blackantywj/Leetcode_coding_everyday | /swap_node.py | 1,224 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# def swapPairs(self, head: ListNode) -> ListNode:
# p = head
# listresult = []
# result = ListNode()
# i=0
# ... |
2b8356442660989550a87609d593e11db2eb83ad | k-kengo-0507/study_python | /read_csv01.py | 509 | 3.9375 | 4 | import csv
f = open("kimetsu.csv","r")
reader = csv.reader(f)
for row in reader:
for col in row:
print(col,end=",")
f.close()
def search():
word=input("鬼滅の登場人物を入力してください>>>")
# for word in source:
if word in reader:
print("{}が見つかりました".format(word))
else:
print("{}が見つかりませんでした".format(wo... |
aad101a6ace09f3dd4a6b48cd93c17e793f18f0c | laurens777/Advent-of-Code-2020 | /day1/part2.py | 1,717 | 3.671875 | 4 | import time
# A simple n^3 algorithm
# Can be improved slightly using while loops and ensuring j > i and k > j
def bruteForce(input):
for i in input:
for j in input:
for k in input:
if i+j+k == 2020:
return (i, j, k)
# this is the standard 3SUM algorithm
# ... |
e89755dac4e68ebfe3eb92fc97732285581327c9 | laurens777/Advent-of-Code-2020 | /day3/part1.py | 263 | 3.6875 | 4 | def main():
tree1 = 0
s1 = 0
with open("input.txt") as input:
for line in input:
if line[s1 % len(line.strip('\n'))] == "#":
tree1 += 1
s1 += 3
print(tree1)
if __name__ == '__main__':
main() |
78c35400491736d57bb5ee628906c145cf2f3e60 | levan92/poker_sort | /hand.py | 639 | 3.734375 | 4 | import random
from sorts import bubble_sort
class Hand(object):
def __init__(self, init_draw = [], sort_algo='bubble'):
self.cards = init_draw
if sort_algo == 'bubble':
self.sort = bubble_sort
else:
raise Exception('Sort algo {} not implemented yet'.format(sort_al... |
ae546a9858f3f37c2936dad101949db8d22554d1 | hunterx12932/hi | /casting型別轉換練習.py | 188 | 3.75 | 4 | # casting 型別轉換練習
age = input("請輸入年齡")
#型別轉換
age = int(age)
#下判斷式
if age >= 20:
print("你可以投票了")
else:
print("你還沒有投票權")
|
f801eac2b3ec53d372842b70893eb3ff5cceab7b | sujerry/Python | /11-RegularExpression.py | 1,094 | 3.875 | 4 | #!/usr/bin/python3
#coding: utf-8
#正则表达式是一种用来匹配字符串的强有力的武器。它的设计思想是用一种描述性的语言来给字符串定义一个规则,凡是符合规则的字符串,我们就认为它“匹配”了,否则,该字符串就是不合法的。
#1--- re模块
#Python提供re模块,包含所有正则表达式的功能。由于Python的字符串本身也用\转义,所以要特别注意:
s = 'ABC\\-001' # Python的字符串
# 对应的正则表达式字符串变成:
# 'ABC\-001'
#因此我们强烈建议使用Python的r前缀,就不用考虑转义的问题了:
s = r'ABC\-001' # Python的字符串
# 对应... |
e1b7e201e6fd5fc830454ba3a7a13f0f2f2afd79 | Chenyouchao/Algorithm | /foundation/5_heap_sort.py | 834 | 3.75 | 4 | # 下潜性
def sift(li, low, high):
'''
:param li: 待调整列表
:param low: 堆的根节点位置
:param high: 堆的最后一个位置
:return:
'''
i = low
j = 2 * i + 1
tmp = li[low]
while j <= high:
# 寻找i的位置 (待插入位置)
if j + 1 <= high and li[j+1] > li[j]:
j += 1
if li[j] > tmp:
... |
1da5cf06ad68df28e8e1be33ec8553c747bcbbe4 | BD20171998/holbertonschool-higher_level_programming | /0x10-python-network_0/6-peak.py | 519 | 3.8125 | 4 | #!/usr/bin/python3
def find_peak(list_of_integers):
if list_of_integers == [] or list_of_integers is None:
return None
def binarySearch(arr, l, r):
if l == r:
return l
mid = (r + l) / 2
mid = int(mid)
if arr[mid] > arr[mid + 1]:
return binar... |
b9854e8781e6261b6919999f85e782205aab07d1 | BD20171998/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 686 | 4.46875 | 4 | #!/usr/bin/python3
"""
This is an example of the is_same_class function
>>> a = 1
>>> if is_same_class(a, int):
... print("{} is an instance of the class {}".format(a, int.__name__))
>>> if is_same_class(a, float):
... print("{} is an instance of the class {}".format(a, float.__name__))
>>> if is_same_class(a, object... |
d6e710a407e39e9362e932a57f0e72acf01e3515 | BD20171998/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/rectangle.py | 4,682 | 3.84375 | 4 | #!/usr/bin/python3
"""Importing Base class"""
from models.base import Base
class Rectangle(Base):
"""Class that defines a rectangle"""
def __init__(self, width, height, x=0, y=0, id=None):
"""Class constructor"""
self.width = width
self.height = height
self.x = x
self... |
24a74a601581375eb9b9198dedbf07c2d2dac2fe | BD20171998/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,371 | 3.8125 | 4 | #!/usr/bin/python3
"""Importing Rectangle class"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""Class that defines a square"""
def __init__(self, size, x=0, y=0, id=None):
"""Class constructor"""
super().__init__(size, size, x, y, id)
@property
def size(self)... |
36bcd1fc0ec00f9ca1da87c053a7813973b4d23d | BD20171998/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 624 | 4.25 | 4 | #!/usr/bin/python3
"""This is an example of the append_write function
>>> append_write = __import__('4-append_write').append_write
>>> nb_characters_added = append_write("file_append.txt", "Holberton School \
... is so cool!\n")
>>> print(nb_characters_added)
29
"""
def append_write(filename="", text=""):
"""
... |
69320271e69304529b706aaa3249512af8fee7cc | diileeaan/Ejersicios- | /10.-FloataInt.py | 139 | 3.96875 | 4 | y = float(input("Escriba un número con decimal: "))
print(y)
entero = round(y)
print("Este es el número convertido a entero:", entero) |
f77c648a97d7da3276f0064d6c37bc9c3fd396ce | navyad/python-labs | /var_scoping.py | 679 | 3.734375 | 4 | # ====================
z = 0
def outer():
z = 1
def inner():
z = 2
print("inner:", z)
inner()
print("outer:", z)
outer()
print("global:", z)
# ====================
x = 0
def outer():
x = 1
def inner():
global x
x = 2
print("inner:", x)
inner()
p... |
03e33c70f91d20ffa2cdbdaa0442794dd80667b2 | navyad/python-labs | /default_args.py | 330 | 3.96875 | 4 | from datetime import datetime
from time import sleep
"""
example: 1
"""
def log(message, when=datetime.now()):
# when will always be same for each call
print(message, when)
log("hi")
#sleep(5)
log("bye")
"""
example: 2
"""
def add(x, items=[]):
items.append(x)
return items
print(add(12))
print... |
83290d04c83626d37d90b429e50af61457c92179 | navyad/python-labs | /decorators/decorator.py | 449 | 4 | 4 | def outer(some_func):
def inner(a, b):
if a > b :
fr = some_func(a, b)
else:
fr = -1
return fr
return inner
def add(x, y):
return x + y
def sub(x, y):
return x - y
if __name__ == '__main__':
func_inner_add = outer(add)
print func_inner_add(9, 2... |
17f6d6bc5987d0da6c5503d21445c259f58ed5c7 | martgil/get-aspect-ratio | /getratio.py | 521 | 4.03125 | 4 | #! /usr/bin/env python
# Author: Mart Gil
# Date: February 11. 2019
# Description: simple script to extract aspect ratio of an image
width = input('Enter Image width: ')
height = input('Enter image height: ')
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
d = gcd(width,height)
aspe... |
a917790916614cce844e1ac2bcd98149d50a6587 | KOYUBIN/OpenColleagePythonWebProject | /oc_0103/Car.py | 1,463 | 3.625 | 4 | class Car:
def __init__(self, 제조사, 모델, 색상):
self.제조사 = 제조사
self.모델 = 모델
self.색상 = 색상
self.fuel = 1000
def forward(self):
self.fuel = self.fuel - 50
print(self.제조사, self.모델, self.색상, "차량이 전진 중입니다! 현재 기름양은", self.fuel, "입니다.")
def reverse(self):
self.f... |
3e7da2be7f677e02fb90cba32a26369897290af6 | Villyli/Talent_Radar | /project/file_tools.py | 1,849 | 3.90625 | 4 | """
对文件操作的工具
"""
import os
import pandas as pd
class lists_processer:
"""
用于处理list的类
"""
def __init__(self, cols=[1, 6]):
self.cols = cols
self.lists = self.get_lists()
pass
def get_lists(self, dir_path="name_lists"):
'''
:param dims: 返回的读取csv中的列编号,默认为姓名、... |
3c3dd5ae3c031019f1e4c9daa76ce89c73527823 | viplash4/AmisHomework | /hometask/task3.py | 257 | 4.03125 | 4 | #wordList = input("Enter phrase: ")
#word = "help"
#def UpperList(string):
# up = string.split()
# for elem in up:
###print(newString)
#UpperList(word)
str = input("str")
s = ""
for ele in str.split():
s = s+" "+ele.title()
print(s[1:]) |
5c0ffbb0b1569ad40b85d03101ed790e574b9145 | Flor246/PythonFlor | /Modulo2/scripts/paso_por_valor2.py | 143 | 3.53125 | 4 |
def potencia_cuadrado(x):
x = x ** 2
return x
x = 2
print(x) # 2
print(potencia_cuadrado()) # 4
x = potencia_cuadrado()
print(x) # 2 |
7f7f6cc5e3489c7f84137f8e5c2a2b564c1c9744 | Flor246/PythonFlor | /Modulo1/scripts/ingreso_datos.py | 483 | 3.90625 | 4 | # control + n - > abro un nuevo file
# control + s -> guardar cambios
# Terminal: cls -> limpiar terminal
# ejecutar python : python nombre_archivo.py
# 1. Solicitando numero
x = int(input('Por favor ingrese un dato numerico: '))
# 2. elevando numero al cubo
potencia = x ** 3
# 3. Mostrando resultado
# print('El n... |
01a8f512a5660e81153add6d77d7d32b7720f46f | Flor246/PythonFlor | /Modulo2/scripts/funciones.py | 622 | 3.71875 | 4 | import math
def sumar_valores_lista(*args):
suma_lista = 0
for num in args:
suma_lista += num
return suma_lista
def potencia(x,y):
return math.pow(x,y)
def saludar(nombre='Juan'):
print(f'hola {nombre}')
def mostrar_triangulo(h):
for i in range(1,h+1):
print('#'*i)
def Mostr... |
ac937cf4ca1e5314a972486fe68848c62277e286 | MayankGuptaUF/SudokuSolver_backtracking | /Sudoku_Solver.py | 3,361 | 3.9375 | 4 | import sys
import math
class Solver():
def io(filenam):
global SIZE # SIZE 9 represented the no of row and column in 9x9 Sudoku
SIZE=9
file = open(filenam, 'r')
lise=[] # This loop is used to import the Sodoku as a List of Lists.
for i in range(SIZE):
line = file.readline().strip()
list1=list(lin... |
b139da9e7a8778d43353b2def52b91a8352ff223 | standbyme227/project_with_jtlim | /6th/workout.py | 2,635 | 3.640625 | 4 | from human import Human
class Workout:
"""
운동에 대한 추상화 클래스
Attributes :
# human (Human()) : Human 클래스의 인스턴스여야한다.
# intensity : 운동강도
"""
days = 0
def __init__(self, human, intensity):
self.human = human
self.intensity = intensity
# TODO 1811... |
57307eb0112c989051f9ff4b0e21ddce3978d4b2 | rguerreroayon/EmSys_Python | /Asignacion9/bisiestos2.py | 676 | 3.640625 | 4 | def esBisiesto(ano):
return ano%4 == 0 and ano%100 != 0 or ano%400 == 0
def leeAnhos(listaBisiestos):
anoInicial = listaBisiestos[0]
anoFinal = listaBisiestos[len(listaBisiestos) - 1]
anos = [anoInicial,anoFinal]
return tuple(anos)
def listaBisiestos(ano1,ano2):
anos = [ano1]
while(ano1 ... |
2078b356ef203378df48432b883a68dd14bab089 | rguerreroayon/EmSys_Python | /Asignacion5/comision.py | 669 | 3.8125 | 4 | def main():
sueldo = float(input('Ingresa tu sueldo: '))
if(sueldo<1000):
print('Comision: no hay comision')
if(sueldo>= 1000 and sueldo<=4999):
comision = float(sueldo * .025)
print('Comision: {0:.4f}.'.format(comision))
if(sueldo>= 5000 and sueldo<=... |
570a51ec5db91300b69ad21c6030cb35b914b1bf | roshanpiu/PythonOOP | /22_Core_Syntax.py | 1,099 | 3.625 | 4 | var1 = 'hello'
var2 = ' world!'
print var1 + var2
#the above line gets converted to this
print var1.__add__(var2)
var3 = 10
var4 = 20
print var3 + var4
#the above line gets converted to this
print var3.__add__(var4)
class SumList(object):
def __init__(self, this_list):
self.mylist = this_list
def ... |
182439b2b6788b01a954ce47777231ae3a53a0f2 | roshanpiu/PythonOOP | /12_Inheritance.py | 658 | 4.28125 | 4 | '''Inheritance example'''
class Animal(object):
'''Animal class'''
def __init__(self, name):
self.name = name
def eat(self, food):
'''eat method'''
print '%s is eating %s.' % (self.name, food)
class Dog(Animal):
'''Dog class'''
def fetch(self, thing):
'''eat metho... |
7bd12a9067e316bd042b7bf65d84423faa5f6b9b | roshanpiu/PythonOOP | /39_PyTest_1.py | 1,064 | 3.5625 | 4 | import pytest
#naming is very important in pytest
#when we initially run pytest it will look for any program that strats with word 'test'
#and the it will look for any function that starts with word 'test'
#run all the test programs with py.test
#use setup_class() method to do test prep
#use teardown_class() method t... |
c8269da6e73e3dfac23763142007c8b04b97faac | xaskasdf/baseGame | /boardEngine/board_logic.py | 2,076 | 4.0625 | 4 | from abc import ABC, abstractmethod
from layers.baseGame.gameError.game_error import GameError
class BoardLogic(ABC):
"""
Defines abstract class for making Game logic engines.
A game board should be designed to support anything you could imagine in a game, that's why LogicBoard is an
abstr... |
3699ca4d5220b66e612eb676019c223923f091fe | blader445/Inch-to-cm | /incm.py | 303 | 3.671875 | 4 | import sys
import time
ratio = 2.54
if len(sys.argv) > 1:
inch = float(' '.join(sys.argv[1:]))
b = inch * ratio
print(b, "cm")
input("Type enter to quit...")
else:
inch = float(input("How much inches ? "))
b = inch * ratio
print(b, "cm")
input("Type enter to quit...") |
38bf083f175227b6ef94c28c08c01df3d2ffadac | prieta1975/p2 | /p2.py | 666 | 3.65625 | 4 | # Ejemplos de uso de ficheros
import sys # Permite utilizar la variable __name__
if __name__ == "__main__": # Determina si estamos en el espacio de nombres principal
print("En main")
imprimir_parametros_entrada(*sys.argv) # Para lista con los argumentos de entrada
# Cuerpo de pro... |
d72e78500fecb21a96db88ff6217a13253667411 | hocht/Python | /4- Listas.py | 309 | 4 | 4 | milista = []
milista.append(1)
milista.append(2)
milista.append(3)
print (milista[0]) # imprime 1
print (milista[1]) # imprime 2
print (milista[2]) # imprime 3
mylist = [1,2,3,4,5,6,7,8,9,10]
# prints out 1,2,3
for x in mylist:
print (x)
cadenas = ['Hola','Tu mama']
print(cadenas[1])
print(cadenas[0]) |
50be5c69e6913df7e995c35cfd1e4e5fac608125 | maroberto/CursoPython | /ex003.py | 201 | 3.953125 | 4 | valor_um = int(input('Digite um Valor: '))
valor_dois = int(input('Digite outro valor: '))
soma = valor_um + valor_dois
print('A soma entre {} e {} é igual a: {}'.format(valor_um, valor_dois, soma))
|
ad325281a8b8963b6d301c8b0cb228bf8c35c81f | maroberto/CursoPython | /ex016.py | 107 | 3.5625 | 4 | from math import trunc
numero = float(input('Digite um número real: '))
real = trunc(numero)
print(real)
|
d9ac5b009fb517241efd41cd933795adbc5e20ed | maroberto/CursoPython | /ex010.py | 173 | 3.609375 | 4 | d = float(input('Quantp dinheiro você tem na carteira? R$ '))
dolar = float(5.10)
resultado = d / dolar
print('Com R${} você pode comprar US${:.2f}'.format(d, resultado))
|
f5469f7de6b7888f63b3bbc95c70682bbe5f27a0 | maroberto/CursoPython | /ex009.py | 223 | 3.9375 | 4 | n = int(input('Digite um número para ver sua tabuada: '))
print('____________')
i = 1
while (i <= 11):
print('{} X {:2} = {}'.format(n, i, (n * i)))
i = i + 1
if(i == 11):
break
print('____________')
|
0eeb88d27227ea8cbd67342e541905744df261bc | maroberto/CursoPython | /ex059.py | 765 | 4.0625 | 4 | num1 = float(input('Digite um número: '))
num2 = float(input('Digite mais um número: '))
print(10 * '__')
print('[1]Somar')
print('[2]Multiplicar')
print('[3]Maior')
print('[4]Novos números')
print('[5]Sair do programa')
print(10 * '__')
op = 0
while op != 5:
op = int(input('Qual é sua opção: '))
soma = num1... |
28f81dca1d8512672a6563b8d0ce33a89238ccac | maroberto/CursoPython | /ex050.py | 437 | 3.828125 | 4 | class Soma():
def __init__(self, numeros):
self.numeros = numeros
def Calculo(self):
s = 0
for i in range(0, 6):
self.numeros
if (self.numeros % 2) == 0:
s += self.numeros
print('Resultado é {}'.format(s))
else:
... |
b024737c383e9990ea898a749ec09a2ef3a42320 | samaroo/PythonForBeginners | /Ch7_Exercise.py | 1,064 | 4.3125 | 4 | # Notes
# Functions in "Math" Library
# use "import math" to import math library
# abs(x) will return the absolutw calue of x
# "math.ceil(x)" will round x up to the nearest integer greater than it
# "math.floor(x)" will round x down to the nearest integer less than it
# "pow(x, y)" will return x^y
#
# Functio... |
82c6d8cd880a187f741190d48c8b63a1d40581c4 | sid-7/Query_Processing_on_Image_Database | /phase_1/MyEncoder.py | 395 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 16:20:59 2019
@author: Siddharth
"""
#this file is used to encode the numpy object into python INT to dump in json
import numpy
import json
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, numpy.integer):
return in... |
0f0538ed519d055c299987135780bc82e6094277 | CleverAndWitty/CIS1501-Fall2018 | /FinalExamReview/Review.py | 2,148 | 3.875 | 4 | # source https://raw.githubusercontent.com/EricCharnesky/CIS1501-Fall2018/9a3d26277a3f166902618bc1a3af5fc1ed0a4a36/Week13/Week13.py
def better_fib_iterative(nth):
if nth <= 0:
return 0
elif nth == 1 or nth == 2:
return 1
else:
current = 1
previous = 1
currentNth = 2
... |
2ed33fc1c4faaa5fd3e53cc80ba7a5e904bbed17 | CanisMinor/Algorithms_Exercises | /change/change.py | 330 | 3.53125 | 4 | # Uses python3
import sys
def get_change(n):
coins = [10,5,1]
n_coins = 0
for coin in coins:
n_div = int(n // coin)
if n_div > 0:
n_coins += n_div
n -= n_div * coin
return n_coins
if __name__ == '__main__':
n = int(sys.stdin.read())
print(get_c... |
e899be90c73b3d1943c28c965d36d7b963500a92 | codrocker/algorithm | /python/sort/insert_sort.py | 530 | 3.78125 | 4 | # -*- encoding:utf-8 -*-
import random
data = []
data_len = 100
for x in range(1, data_len + 1):
data.append(random.randint(1, 100))
def insert_sort(data, start, end):
index = start + 1
while index <= end:
back = index
while back > start:
if data[back] < data[back - 1]:
... |
7af064248883d0664c130d24877a705c8d1f1c0a | jsvans/Computacional | /actividad 2/polar.py | 277 | 3.734375 | 4 |
# coding: utf-8
# In[3]:
from math import pi,atan,acos
x=float(input("Introduce x:"))
y=float(input("introduce y:"))
z=float(input("introduce z:"))
r= (x**2+y**2+z**2)**(1/2)
theta= atan(y/x)
phi= acos(z/r)
a=theta*180/pi
b=phi*180/pi
print("r=",r ,"theta=",a ,"phi=",b, )
|
60ad9d24e3afa5a670d871cbc174689d7148476d | CS6-IdeaventionsAcademy/more-control-ifelifelse-anacol | /game_showtake2.py | 817 | 4.03125 | 4 | #Alexander
#11/28/2017
#Game show thing
import random
import time
play_again = "Y"
doors = [1,2,3,4]
while play_again == "Y":
print("Welcome to the spectacular game show that has too long of a name and we don't know why i should really stop making this so long!")
prize_door = random.randint(1,4)
chosen_door... |
6cc60fd18982524eee763d536d3a992e0e25667c | azgrand/VIU_08GIIN_Orquideas | /bin/validador.py | 735 | 3.890625 | 4 | """
@author: Jon Lebrero Catalina
"""
# Este fichero contiene los validadores que usamos, creados asi para ahorrar tiempo a furuto
# Valida un ENTERO (INT)
def validar_entero(texto):
correcto = False
variable = 0
while(not correcto):
try:
variable = int(input(texto))
... |
9cfbb1535b15ead9940717aa4522481222497851 | shapworldup/furry-waffle | /untitled/hm1(2).py | 148 | 3.6875 | 4 | n = int(input('n = '))
array = []
for i in range(n):
x = int(input(f'x[{i}] = '))
array.append(x)
array.sort()
print(array[-2], array[-1]) |
94b114e34f9f94f1d7ff6393182a1aa82078e8ac | Archan2607/IT556_The-ERRORs_DAIICT | /201711014/Assignment 3/assign3_1.py | 847 | 3.515625 | 4 | #Noun Extraction Using Spacy
import spacy
import csv
import en_core_web_sm
import pandas as pd
nlp = en_core_web_sm.load()
#Uploading CSV File
df = pd.read_csv('C:/Anaconda/albums.csv')
print("\n")
#Noun Extraction on Album Names
print("Noun Extraction on Album Name")
df1 = df['album'].apply(nl... |
532e16ff1f1e3403e2d3c27bb22e058f11141dd2 | skalpanai7/arm | /arm.py | 139 | 3.59375 | 4 | n=int(raw_input())
temp=n
l=len(str(n))
sum=0
while (n>0):
x=n%10
sum=sum+(x**l)
n=n/10
if(sum==temp):
print("yes")
else:
print("no")
|
34fcd149b928fd3b0db4f8b5927aee6f20e09def | kemalik/simple_python_console_crud | /functions.py | 1,728 | 3.71875 | 4 | # coding:utf-8
from data import *
def get_spaces():
for record in cars:
for key, value in record.items():
value_length = len(value)
translit_length = len(translits[key])
if spaces[key] < value_length or spaces[key] < translit_length:
if value_length > ... |
2216153409f5216d46660430c76f8bea1d511e19 | jordanmasterson23/ExpenseTracker | /expensetracker.py | 5,145 | 3.671875 | 4 | import sqlite3, sys
## Connect to database
conn = sqlite3.connect('expenses.db')
c = conn.cursor()
def main():
try:
c.execute("""CREATE TABLE budgets (spending integer, creditcard integer, household integer, savings integer, rent integer, car integer, school integer)""")
c.execute("""CREATE TABLE ... |
7758e1f1d9b004b39796b6d20ed536166c8b1052 | LRenascence/AI-ML-DS | /Hands-onDSAndML/ch4PredictiveModels/linearRegression.py | 544 | 3.546875 | 4 | import numpy as np
from pylab import *
from scipy import stats
import matplotlib.pyplot as plt
def predict(x, slope, intercept):
return slope * x + intercept
pageSpeeds = np.random.normal(3.0, 1.0, 1000)
purchaseAmount = 100 - (pageSpeeds + np.random.normal(0, 1, 1000)) * 3
# ordinary least square
[slope, interc... |
7a7893d0d3136112aaf24ab886278ee660f82c55 | Faranheit15/Hacktoberfest-2020 | /Programs/Greedy/min_no_of_coins.py | 645 | 3.78125 | 4 | def findMin(V):
# All denominations of Indian Currency
deno = [2,1,5]
deno.sort()
n = len(deno)
# Initialize Result
ans = []
# Traverse through all denomination
i = n - 1
while(i >= 0):
# Find denominations
while (V >= deno[i]):
... |
d70cf05c5c87b9145b51f84e87aed8971c84d9ff | Faranheit15/Hacktoberfest-2020 | /line.py | 171 | 3.5625 | 4 | import matplotlib.pyplot as plot
x = [3,10,8,2,3]
y = [5,5,-5,9,1]
plot.plot(x, y)
plot.xlabel('X - Axis')
plot.ylabel('Y - Axis')
plot.title('graph')
plot.show()
|
a4cd49ed25235a6f9bd8c92baff65f7873a0971b | Faranheit15/Hacktoberfest-2020 | /Programs/folder_and_file.py | 361 | 3.890625 | 4 | #Creating a folder, a file inside it and writing something on it
import os
from csv import writer
from csv import reader
folder = input("Please, type the name of the folder: ")
file = input("Please, type the name of the file: ")
message = input("Please, type your text: ")
os.makedirs(folder)
f = open(folder+"/"+file... |
2b1af154ea7b93ae7bc57bbf6c9b0c79ef16012e | haikentcode/code | /collegeTime/pds/tree.py | 1,673 | 4.09375 | 4 | class Node:
def __init__(self,value=""):
self.value=value
self.left=""
self.right=""
def left(self):
return self.left
def right(self):
return self.right
def value(self):
return self.value
class bst:
def __init__(self):
self.root=""
def in... |
eccce954430ccdd6ace8e8db601ee734fd48ddfb | haikentcode/code | /cluesTime/python/matrixPath.py | 343 | 3.515625 | 4 | def numberOfPaths(m, n):
count = [[0 for x in range(m)] for y in range(n)]
for i in range(m):
count[i][0] = 1;
for j in range(n):
count[0][j] = 1;
for i in range(1, m):
for j in range(n):
count[i][j] = count[i-1][j] + count[i][j-1]
return count[m-1][n-1]
prin... |
63d1b84d5e4c1094070a8837935bfa62727de1b2 | Etery89/learn-homework-1 | /if2.py | 2,349 | 3.5625 | 4 | """
Домашнее задание №1
Условный оператор: Сравнение строк
* Написать функцию, которая принимает на вход две строки
* Проверить, является ли то, что передано функции, строками.
Если нет - вернуть 0
* Если строки одинаковые, вернуть 1
* Если строки разные и первая длиннее, вернуть 2
* Если строки разные и вторая стро... |
47a9a81a19167702406cdc447d564bcfbf27c94c | Yaco-Lee/Python | /Calculator/src/yacoapp.py | 1,602 | 4.1875 | 4 | # ACA ES DONDE VAMOS A DEFINIR LAS COSAS
def main():
operaciones = getOperaciones()
print("tenemos por ahora")
devuelveListaDeOperaciones(operaciones)
print("que deseas?")
accion = getAccion()
# print("poné el primer numero wacheen")
# primernumero = input()
# print("ahora el segundo")
# segundon... |
1fab4d1e621f4ae3e7b994fb82f8dca33e69eed8 | saidu941/Python-Programming | /Regression and Clustering/Source/Linear regression for Table data.py | 751 | 3.609375 | 4 | import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
import random
x=np.array([0,1,2,3,4,5,6,7,8,9])
y=np.array([1,3,2,5,7,8,8,9,10,12])
print('x mean is : ',(sum(x)/len(x)))
print('y mean is : ',(sum(y)/len(y)))
n=len(x)
sumx=x.sum()
sumy=y.sum()
sumxy = (x * y).sum()
sumxx = (x ** 2)... |
fc406bcf8f469edaf3291833c6fb6dc4f2e81624 | keyes-timothy/classes | /BIOMEDIN_214/Project_2/knn.py | 4,290 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
File name: knn.py
Author: tkeyes
Last Updated: 10/23/19
Description: Creates a class that runs the KNN classifier algorithm.
"""
import sys
import pandas as pd
import numpy as np
##global variables
k = 3
fn = 0.5
#Define my class
class KNN:
"""
Documentation
"""
de... |
8d6a0340a124b2db69e081981a944755990bde96 | aedoler/finalexam | /final_exam.py | 2,334 | 3.765625 | 4 | #!user/bin/env python
# -*- coding: utf-8 -*-
"""Fibonacci series"""
import json
import decimal
def loopschools(schooldata):
""" Finds school with lowest spending and highest grades in dataset.
Args:
schooldata (str, filepath): filepath containing dataset
Returns:
tuple containing school ... |
9863f3802e871464a25689280d7d165654eb0e52 | visor517/GeekBrains_python | /lesson3/task5.py | 1,583 | 3.765625 | 4 | # 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться
# сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь
# введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится сп... |
fc3c83902feb505756bcd45f29e054d1bd3765de | visor517/GeekBrains_python | /lesson4/task1.py | 631 | 3.609375 | 4 | # 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу:
# (выработка в часах * ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
from sys import argv
script_name... |
6e047bf678e6e04cde9ac54d6d54176c785daa15 | visor517/GeekBrains_python | /lesson8/task2.py | 905 | 3.84375 | 4 | # 2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных, вводимых пользователем. При вводе пользователем
# нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
class OwnError(Exception):
def __init__(self... |
5cb8d929e0d754bfca9a531dfedea219f3466270 | visor517/GeekBrains_python | /lesson4/task2.py | 369 | 3.9375 | 4 | # 2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
my_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55, 77]
print([my_list[i] for i in range(1,len(my_list)) if my_list[i] > my_list[i-1]]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.