blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c6661f8b22fe588849d0b5df8b5d6cdde50c4c79 | InIronClad/python-project-4 | /crismon_robert_hw4.py | 1,378 | 4.3125 | 4 | #Assignment: (Homework 4)
#
#Description: (Square and Circle Generator)
# www
#Author: (Robert Crismon)
#
#Completion Time: (2-3 hours)
#
#In completing this program, I obtained help or worked with the following:
#(Help was acquired from the python.org website on turtle commands)
from turtle import ... |
a440f91737284eb99efd225d6b0351260f1f825f | rafaelcoding/simpleprojects | /timer(portuguese version).py | 301 | 3.828125 | 4 | from time import sleep
segundos = int(input('Digite quantos segundos você quer que eu espere: '))
print('Vou começar em')
sleep(1)
print('3')
sleep(1)
print('2')
sleep(1)
print('1')
sleep(1)
print('Esperando...')
for cont in range(segundos, -1, -1):
print(cont)
sleep(1)
print('Acabou')
|
6d18aaea396b23ea82f556075f6c85326de659a5 | brockn/learning-python-for-analysis | /lesson-1-json/problem.py | 2,766 | 3.515625 | 4 | #!/usr/bin/env python
import requests
import json
from pprint import pprint
print "######################################################"
print "######################################################"
print "#################### Example #########################"
print "##############################################... |
381593938ecc248a635640daba083e72fdd5df13 | jaredhusch/image_classifier_flowers | /predict.py | 7,649 | 3.578125 | 4 | '''
This programs predicts a flower name from an image with predict.py along with the probability of that name.
Pass in a single image and return the flower name and class probability.
Basic usage: python predict.py
Options:
Load checkpoin: python predict.py --checkpoint
Loading the image to be... |
397f013ab549bb048e512660203899f0660a596e | Pedromrv/Working_with_data | /Untitled.py | 122 | 3.671875 | 4 | print("Hello")
firstname= input("What is your first name? ")
print("Thanks.")
surname=input("And what is your surname? ")
|
177edcd83ba5b23f0e1d76d67917afe9be26b3bb | Pedromrv/Working_with_data | /Dictin.py | 108 | 3.65625 | 4 | phonebook= {}
name=input("Enter name: ")
number=int(input("Enter phone number: "))
phonebook[name]=number
|
a4cfc1419bd4584ecd2f0d54b5e5ec734f39b257 | WillowTotoro/Leecode-Answer | /728. Self Dividing Numbers.py | 555 | 3.546875 | 4 | class Solution:
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
Numbers = []
for i in range(left, right+1):
if '0' not in str(i):
count = 0
for num in str(i):
... |
33f212eb8ef2da8eeff515c491ed76738bb2fee8 | mykhailokoliadko/DevOps_online_-Lviv-_-2020-2020Q42021Q1- | /M9/task9.1/Python/testfizz_bazz.py | 286 | 3.953125 | 4 | from fizz_buzz import some_func
max = 100
count = 5
while count < max:
number = int(input("please give me a number: "))
result = some_func(number)
print("number is: " + result + ".")
if number > max:
print ("it's too much")
break
|
0124c5026fe132694c9902b360aa75844f2d3f7a | muditabysani/Design-3 | /Problem2.py | 2,650 | 4.125 | 4 | class LRUCache(object):
# Implemented using a dictionary(hashmap) and a list
# In the list, just storing the keys
# In the dictionary, storing the key, value pair
# Time Complexity : O(n) because we have to traverse through the entire list to delete a node in between
def __init__(self, capacity):
"""
:type cap... |
59d586840e5d82e2710531bc5b0301c363fc5d3f | mohdomama/AlgoDS | /Trees/vertical_order.py | 1,006 | 3.90625 | 4 | #User function Template for python3
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
def in_order(node, level, traversal):
if node == None:
return
# val = traversal.get(level, [])
# traversal[level] = val.append(node)
if... |
64076d4ba8b25462780503d3a46a345721951fd0 | Jonah3434/schoolcode1 | /main (3).py | 1,102 | 4.125 | 4 | #Jonah Belttari
'''
Nested ifs Notes
Monday, 1/6/2020
'''
school = str(input("What is your homeschool? "))
if school == "Salem" or school == "salem":
grade = int(input("What grade are you in ? "))
if grade == 9:
print("You are a freshman at Salem. ")
if grade == 10:
print("You are a sophemore at Salem. ")
if ... |
881654365b6892a9193c6a95fe8f45f93860ca82 | WPrendota/WC | /PycharmProjects/WC/venv/Functions.py | 1,332 | 3.578125 | 4 | import os
#Path to the script file:
script_path = os.path.dirname(os.path.realpath(__file__)) + "/"
#Function for lines counting:
def count_lines(arg):
countLines = 0
try:
file = open(script_path + arg)
print("Counting lines...")
file = open(script_path + arg, 'r')
file_data... |
8a055b5c6683b898281727a7d580120c02a0225b | jpsalviano/ATBSWP_exercises | /chapter9/backupFileExtensionToZip.py | 983 | 4.40625 | 4 | #! python3
# This code is part of the book Automate the Boring Stuff with Python by Al Sweigart
# backupFileExtensionToZip.py - Copies all files of same extension in a folder into a ZIP file.
import zipfile, os
def backupFileExtensionToZip(folder, extension):
# Create the ZIP file.
zipFilename = '{}Files.zip'... |
ee173a7e2b21e8aa89a60077bc05eee44a53ee25 | jpsalviano/ATBSWP_exercises | /chapter9/selectiveCopy.py | 1,681 | 4.25 | 4 | #! /usr/bin/python3
# This code is my solution to Practice Project: Selective Copy in the book Automate the Boring Stuff with Python by Al Sweigart
# selectiveCopy.py - Searches all files for an extension in a folder tree and copies them into a new folder.
# Usage: selectiveCopy.py <extension> <source> <destination>:
#... |
76556cd44bd04f51a574cd0c1de38a89ce591d6d | laukikpanse/Basic-Python-Programs | /findpairs.py | 350 | 4.03125 | 4 | my_list = [1,2,3,4,5,6,4,5,6,7,0,9]
target_value = 15
new_list = list(my_list)
print(my_list)
print(new_list)
for char in my_list:
if (target_value - char) in new_list:
print("The pairs are: ##Index :{0} ##Value : {2} and ##Index: {1} ##Value: {3}".format(my_list.index(char),new_list.index((target_value - char))... |
3d56b94ce683366aff4f1c97b45164e2f37d0c2d | azuluagavarios/Python | /conversor.py | 184 | 3.546875 | 4 | pesos = input("Ingres la cantidad COP$: ")
pesos = float(pesos)
valor_dolar = 3875
dollares = pesos/valor_dolar
aproximado = round(dollares, 2)
print("Tienes USD$ "+ str(aproximado)) |
89acbdc30d0e43f2d2eb08b55f316ac47aee919d | aming0518/PythonStudy | /查看字符串简介.py | 190 | 3.90625 | 4 | mylist=dir("")#dir返回的是一个列表
print(type(""))
print(mylist)#包含所有的函数 属性
for i in mylist:#遍历打印
print(i)
print(help("str."+i))#打印函数说明
|
19251211ee15fc23e04f8efaf221f447d82aa1d4 | aming0518/PythonStudy | /元组操作.py | 517 | 4.0625 | 4 | mydata=(1,2,3,4,5,6)
mydata2=(5,6,7,8)
print(mydata[-1])
print(mydata[:])
print(mydata[3:])
print(mydata[:-2])#默认从左到-2,不包含-2
print(mydata+mydata2)#拼接
print(mydata2*4)#复制4次
#del mydata2#内存清除,无法再调用
print(mydata2)
print(len(mydata2))#长度
print(5 in mydata2)#判断5是否在元组中
print(10 not in mydata2)
for data in mydata2:#副本
pri... |
4d77bf66a1057ab277911c6d64e5decb173f18e9 | aming0518/PythonStudy | /set集合简介.py | 277 | 3.9375 | 4 | mylist=[1,1,1]
myset={1,1,1}#元素不可重合
print(mylist)
print(myset)
set1={1,2,3,4}
set2={1,2,7,8}
print(set1-set2)#set1有set2没有的 差集
print(set1|set2)#set1和set2的并集
print(set1&set2)#set1和set2的交集
print(set1^set2)#set1和set2的并集减去交集 |
76d208c22cba1f1d49d2403f0d2419dc50de048e | aming0518/PythonStudy | /围棋格子.py | 333 | 3.75 | 4 | import turtle
turtle.showturtle()
step=20
for i in range(10):
turtle.penup()
turtle.goto(0,step*i)
turtle.pendown()
turtle.forward(step*10)
turtle.right(270)
for i in range(10):
turtle.penup()
turtle.goto(step*i,0)
turtle.pendown()
turtle.forward(step*10)
turtle.dot(10,"black")
t... |
c41df86c98902010ea09daa12837f9d99754e97b | aming0518/PythonStudy | /命令系统.py | 177 | 3.5625 | 4 | import os
cmd=input("cmd")
while(cmd!="退出"):
if cmd=="记事本":
os.system("notepad")
elif cmd=="计算器":
os.system("calc")
cmd=input("cmd") |
106ae48dda851b30c8174f0c106ccbde742d345c | aming0518/PythonStudy | /字符串编码 问题.py | 972 | 4.15625 | 4 |
#utf-8一个汉字两个字节
a=bytes("你好abc","utf-8")
print(a)
a=bytes("你好中国abc","gbk")
print(a)
#不同编码大小不一样 内容不一样
print(b'\xe4\xbd\xa0\xe5\xa5\xbdabc'.decode("utf-8"))#解码,不同类型不可转换
#encode 和 decode
print(type("hello".encode("utf-8")))#字符串转换为二进制编码
print(type(b'\xe4\xbd\xa0\xe5\xa5\xbdabc'.decode("utf-8")))#二进制编码转化为字符串
mystr... |
d93a7520c2bb21407673a2011ac10b8c96d46d0c | shaojun93/LeetCode | /twoSum.py | 935 | 3.515625 | 4 | # 1. 两数之和
#
# 题目描述:
#
# 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
#
# 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
a =set()
... |
a249d1b89aeb11db6bf2d4cc9ecbb0668e7927ce | chutki-25/python_ws | /OOP/empmgr.py | 1,330 | 3.6875 | 4 | from employee import Employee
lst_emp = []
def load_emp():
with open("empdata.txt")as f:
fdata=f.readlines()
for data in fdata:
edata=data.strip("\n").split(",")
empno=int(edata[0])
ename=edata[1]
qualification=edata[2]
salary=edata[3]
... |
877fb6700a465cb4abf2e8c5726053e10e6366d2 | chutki-25/python_ws | /M1_Q/q2.py | 246 | 4 | 4 | """Write a program to accept a number “n” from the user; then display the sum of the following series:1 + 1/2 + 1/3 + ……. + 1/n"""
n=int(input("Enter n:"))
sum=0
for i in range(1,n+1):
sum=sum+(1/i)
print(f"Sum of the series: {sum}")
|
e2a217d4831cbd16a54be704dcf58e18acd36683 | dglo/dash | /utils/ip.py | 3,503 | 3.9375 | 4 | import socket
def get_hostname_no_domain():
"""Get the host name of the calling machine.
Will not return the domain name with the host name
Args:
None
Returns:
A string containing the host name of the calling machine
"""
host_name = socket.gethostname().split('.')
retur... |
5311846a4e9e928c16c2d8ce86750d85f3fa51fa | YogeshKapila/Algo | /Searching/InterpolationSearch.py | 1,349 | 4.03125 | 4 | """
Given a sorted array of n elements, write a function to search a given element x in it.
Algorithm: Interpolation Search
"""
def interpolation_search(input_list, to_find):
"""
Interpolation Search Implementation
:param input_list: Input List
:param to_find: Element to be searched for
... |
775751f9d77962dd8cbdeccf67cae2f0544e686c | YogeshKapila/Algo | /DP/LIS.py | 747 | 4.15625 | 4 | """
Find the length of the longest sub sequence of a given sequence such that all elements of the
sub sequence are sorted in increasing order.
Paradigm: Dynamic Programming
"""
def lis_util(input_list, n, result):
for i in range(1, n):
for j in range(i):
if input_list[i] > input_li... |
1b00f2167ffcbb9008e51ecb83e7554da8832d00 | soikkea/airportgame | /airportgame/textinput.py | 4,123 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""Implementation of the TextInput class."""
from pygame.locals import *
from airportgame.colors import BLACK
class TextInput():
"""
Class for interpreting text input from keyboard.
"""
def __init__(self, pgtext, max_length = 0, color=BLACK):
self.active = False
... |
4602de88f30415b81febba9f1e35e2f6bf3e505d | matsumon/Graph-Algorithim | /rivals.py | 3,379 | 3.71875 | 4 | import sys
#creates the groups by flipping back and forth between groups depending on what
#layer of the "tree" the search is in. IE 0 goes in group 0 and then its children
#go in group 1 and the children of the children go in group 0
def CreateGroups(array,parentIndex,toggle):
if len(queue)==0:
retur... |
f0605da7cefeff2a24153d719559cc48b54cff92 | victor-oliveira1/metodista_login | /metodista_login.py | 1,804 | 3.5 | 4 | #!/bin/python3
#Esta é uma biblioteca simples, criada para uso pessoal com o alvo de
#simplesmente automatizar o processo de logon na rede wifi da Metodista.
#Feito por Victor Oliveira
from urllib.request import urlopen
from urllib.parse import urlencode
from ssl import SSLContext
def _request(url, headers):
'''F... |
8b74b53bd1bae8faca665920743c0dee16c41311 | LeetCodeMio/LeetCodeProblems | /AcRate/039. 540. Single Element in a Sorted Array .py | 258 | 3.5625 | 4 | # 时间O(n) 空间O(0)
# 利用 异或 运算的 交换律 结合律 有
# a^b^d^c^b^a^c = a^a ^ b^b ^ c^c ^ d = 0^0^0^d = d
from functools import reduce
class Solution(object) :
def singleNonDuplicate(self, nums) :
return reduce(int.__xor__, nums) |
ef1a2544f6c9c78274eb3001478769fa4c091c2b | LeetCodeMio/LeetCodeProblems | /AcRate/091. 676. Implement Magic Dictionary .py | 412 | 3.578125 | 4 | class MagicDictionary :
def buildDict(self, words) :
self.words = {}
for i in words :
self.words.setdefault(len(i), []).append(i)
def search(self, word) :
if len(word) not in self.words : return False
for i in self.words[len(word)] :
num = 0
for index,char in enumerate(word) :
if i[inde... |
fddba51bf91758dc3df09d39e771540e7decc35d | LeetCodeMio/LeetCodeProblems | /AcRate/179. 778. Swim in Rising Water .py | 834 | 3.578125 | 4 | # 模拟下雨 用并查集表示水坑
# 格点由低到高进入并查集 起终点进入同一水坑即可
class Solution :
def swimInWater(self, grid) :
N = len(grid)
connect = lambda i,j : ((i+di, j+dj)
for di,dj in zip([1,-1,0,0], [0,0,1,-1])
if 0 <= i+di < N and 0 <= j+dj < N)
uset = {}
def find(node) :
root = node
while uset[root] != root :
... |
9ecfb2541d7953a15754e1172aef4ec96612deef | LeetCodeMio/LeetCodeProblems | /AcRate/070. 796. Rotate String .py | 275 | 3.53125 | 4 | class Solution :
def rotateString(self, A, B) :
if len(A) != len(B) : return False
if A == B == '' : return True
for a in range(len(A)) :
if A[a] != B[0] : continue
if all(A[(a+b) % len(A)] == B[b]
for b in range(len(B))) : return True
return False |
b272f58e746b3f62fac18cf88574e92287718f29 | AjayKrish24/Assessment | /Python Practice/Group C.py | 1,256 | 3.828125 | 4 | class destination:
__count=0
li = ["cost","distance","rating","description"]
places = ["ooty","shimla","yelagiri"]
costs = [5000,10000,4000]
ratings =[3.5,4.2,3]
descriptions = ["abc","xyz","lmn"]
distance = [400,1500,200]
def __new__(cls, *args, **kwargs):
if cls.__c... |
937289a9dc841f9ab21f39f12c0ca21a993d0f79 | AjayKrish24/Assessment | /Python Practice/Assessment-2 Country_details.py | 4,529 | 3.578125 | 4 | import datetime
from datetime import timedelta
def countries(country_name,country_details,inr):
'''
Parameters
country_name : string
country_details : Dictionary (Key : country_name, value : tuple(time_zone, time, currency, language, currency_rate))
inr : int
... |
b7ae15e02c6009f059047a513418d8edd7ee507b | indrapermana/sudoku-evaluator-code-in-javascript | /suduku.py | 2,471 | 4.15625 | 4 | """
this is a program to check if the given sudoko solution is valid
"""
print("hello")
valid_grid = [
[2, 7, 5, 1, 9, 8, 3, 6, 4],
[1, 4, 3, 5, 7, 6, 9, 2, 8],
[8, 9, 6, 2, 4, 3, 1, 7, 5],
[3, 2, 8, 4, 6, 1, 7, 5, 9],
[4, 5, 7, 9, 8, 2, 6, 1, 3],
[6, 1, 9, 7, 3, 5, 4, 8, 2],
[7, 8, 1, 3,... |
d850213f2fd6df3384e30eb42092aecba3ef81f0 | russo588/russo588.github.io | /old/teaching/samplescripts/montecarlo.py | 428 | 3.578125 | 4 |
import random
import math
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return math.exp(x)
n = 100 #number of samples
x = np.linspace(0,1,50)
Domain = [i for i in x]
Range = [f(i) for i in x]
Sample = [random.random() for i in range(n)]
FSample = [f(i) for i in Sample]
Average = sum(FSample) /... |
c227956550936c1218154fd65be0aa0eb5041072 | boragungoren-portakalteknoloji/METU-BUS232-Spring-2021 | /Week 4 - Branching/Week 4 - FX Tax Deduction.py | 2,165 | 4.15625 | 4 | # License : Simplified 2-Clause BSD
# Developer(s) : Bora Güngören
# In Turkey when you buy Foreign currency there is a very small (0.2 percent) tax.
# When you sell foreign currency there is
# When you buy at a certain rate. Say 1 USD is 8 TL. And you buy 1.000 USD.
# You pay 8.000 TL to the bank for the 1.000... |
0982884843e511a768eb5f3fc558e3999fdf77c2 | boragungoren-portakalteknoloji/METU-BUS232-Spring-2021 | /Week 11 - Networks and File Downloads/Simple file download.py | 9,859 | 4.09375 | 4 | # We will demonstrate simple ways of file downloads from the web
# A URL is the unique identifier for the location of a networked resource
# Most URL's are web URL's, they start with http:// or https://
metu_homepage_url="https://www.metu.edu.tr"
metu_logo_url="https://www.metu.edu.tr/sites/all/themes/odtu/images/odtu... |
b168cfaa32e8d5da00cfed892d61f102d8f62ed2 | boragungoren-portakalteknoloji/METU-BUS232-Spring-2021 | /Week 14 - Review and Discussion/Set example.py | 2,037 | 4.53125 | 5 | # Sets in Python
# A set is a collection which is both unordered and unindexed.
simple_cart = {"yoghurt", "apples", "bananas", "cherry tomatoes", "lettuce", "jalapeno pepper", "mineral water"}
size = len(simple_cart)
print("Here is my shopping cart today:", simple_cart)
print("It contains", size, "items")
# Items in ... |
b4c5d794843a77a4447dc10e20c8d828d913c3b7 | PavelGorbal/DZ | /3.py | 454 | 4.25 | 4 | # Напишите программу, которая принимает текст и выводит два слова: наиболее часто встречающееся и самое длинное.
string_a = 'Meet my family There are five of us my parents my elder brother my baby sister and me'
string_a = string_a.split()
print(max(string_a, key=len))
for el in string_a:
count = string_a.count... |
1260b1239c0b3e4bce4350f8aeffcb14b6b1dbc6 | shilpapantula/python_programming_tutorials | /reverse_string.py | 650 | 4.25 | 4 | def reverse_string(string):
"""
reverses a string and returns it
"""
if len(string) < 1:
return ''
length = len(string)
new_str = ''
for l in range(length):
new_str += string[length-l-1]
return new_str
from nose.tools import assert_equal
class testing(object):
def test(self, function):
assert_equal(... |
08ca0a48df98b646e313e86c0a7e6760fc35ec33 | DoumanAsh/collectionScripts | /python/art/fs.py | 1,758 | 3.5625 | 4 | """ File system module """
from os import path as os_path
from os import walk as os_walk
from shutil import copy2 as copy
def copy_files(source_dir, dest_dir, dest_only=False, ext_only=None):
""" Copy files from @source_dir to @dest_dir.
@param source_dir Directory from where to take files.
... |
63ddf6d94852c0a482284f651c3900164e8ffb04 | eduardolimabra/Computer-Vision---Object-Detection-with-OpenCV-and-Python | /01_face_detection.py | 884 | 3.578125 | 4 | #Import Libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#Create Classifier
face_classifier = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')
#Open Image
image = cv2.imread('Images/eye_face.jpg')
fix_img = cv2.cv2.cvtColor(image, cv2.COL... |
a67ce77ffd3afc8298d477dfa7ffe73a9decbfca | Jennyying/CSC-148 | /a1/Superclass.py | 1,540 | 3.921875 | 4 | from typing import Any
class Game:
"""
The game the players are playing.
"""
def __init__(self, status: bool) -> None:
self.current_state = State()
self.status = status
def __str__(self) -> str:
return str(self.status)
def __eq__(self, other: 'Game') -> bool:
r... |
836eaf430d1d963e5276541597acdf7b6b9585ea | Jennyying/CSC-148 | /term_test_2.py | 1,903 | 3.9375 | 4 | class Tree:
"""
A bare-bones Tree ADT that identifies the root with the entire tree.
"""
def __init__(self, value=None, children=None) -> None:
"""
Create Tree self with content value and 0 or more children
"""
self.value = value
# copy children if not None
... |
aebd7ccdffa197bf86e1b25eef6858406b48e02c | RutvikMori18/Python-Program-Practice | /fibonacci.py | 228 | 3.6875 | 4 | def fib(n):
a=0
b=1
if (n == 1):
print(a)
else:
print(a)
print(b)
for i in range (1,n-1):
x=a+b
a=b
b=x
print(x)
fib(10) |
e0ed092b979e1c0ce218bc8a3caae32a113391a0 | RutvikMori18/Python-Program-Practice | /keword length variablee.py | 144 | 3.671875 | 4 | def person(name,**data):
print(name)
for i,j in data.items():
print(i,j)
person('rutvik',age=20,city='gujrat',mob=7878787878)
|
b3e7c8ed2058a8cada26b2fc5e21d86c5b4529c4 | RutvikMori18/Python-Program-Practice | /paas list to a function.py | 263 | 4.03125 | 4 | def even_odd(lst):
even=0
odd=0
for i in lst:
if i%2 == 0:
even+=1
else:
odd+=1
return even,odd
list=(12,15,14,16,11,13,26,23,27,28,56,54,55,53)
even,odd=even_odd(list)
print("even",even)
print("odd",odd)
|
5b0a174be5cb3d492dec77df8aeb5dc0a4eb0532 | NicholasTD07/nick-learns | /python/year-week-markdown.py | 792 | 3.5625 | 4 | import datetime
def t(year):
"""
t(2017) ->
```
## Year 2017
### Jan Week 0
### Jan Week 1
.
.
.
### Dec Week 51
### Dec Week 52
### Dec Week 53
```
"""
month_format = "%b" # Jan, Feb, ...
week_format = "%W" # Monday as the first day
month_we... |
8bcff43d3f34fd62f1835def78432e6e1d0bee0f | NicholasTD07/nick-learns | /exercises/codewars/square_digits.py | 517 | 4.28125 | 4 | """
https://www.codewars.com/kata/546e2562b03326a88e000020/train/python
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.
Note: The function accepts an integer and returns an integer
"""
def square_digits(num):
x = str... |
1784e719486bd915239ef59a97f6f719267e0f72 | 4SchoolZero/-F1M1PYT | /fucntionsshit.py | 157 | 3.578125 | 4 | def add(getal1, getal2):
sum = getal1 + getal2
print(sum)
#add(1, 3)
#add(34, 45)
def multiply(x, y):
som = x * y
print(som)
multiply(2, 5) |
34b50ba6d21f375d146ab4a4da3dc8141bc6e54c | FritzHeider/Tweet2 | /second_order_markov_chain.py | 1,361 | 3.78125 | 4 | import random
text = "i like cats and you like cats i like dogs but you hate dogs"
words_list = text.split(" ")
class Queue():
def __init__(self):
self.items = []
def is_empty(self, size):
return self.items == []
def add(self, item):
self.items.insert(1,item)
def remove(self):
self.items.pop(0)
def... |
6a1d8c957129e3feaa119356babcc906ad205000 | youinmelin/practice2020 | /turtle_work_10_flowers.py | 330 | 3.953125 | 4 | import turtle as tt
tt.penup()
tt.setposition(0,0)
tt.pendown()
tt.color('red')
tt.pensize(3)
tt.speed(3)
petals_num = 8
width = 100
for i in range(petals_num):
# draw a petal
tt.circle(width,180)
if petals_num%2==0:
tt.left(360/petals_num)
else:
tt.left(180/petals_num)
#tt.hideturtle()
... |
5977e30776f36211e7dfaeb1765797875f374316 | youinmelin/practice2020 | /data_wrangling/deal_excel/sort_excel/find_files.py | 1,229 | 3.96875 | 4 | import os
"""
os.walk(top, topdown=True, onerror=None, followlinks=False)
我们一般只使用第一个参数。(topdown指明遍历的顺序)
该方法对于每个目录返回一个三元组,(dirpath, dirnames, filenames)。
第一个是路径,第二个是路径下面的目录,
第三个是路径下面的非目录(对于windows来说也就是文件)
"""
def pick_file(key_word=''):
"""
find files in current path(includes subfolde... |
16ff2159a91aead5200ea43890bec68a271dd1d3 | youinmelin/practice2020 | /turtle_work_08_red_cross.py | 272 | 3.578125 | 4 | import turtle as tu
tu.color('red',"red")
i=0
tu.hideturtle()
tu.begin_fill()
times = 8
while i<times:
tu.forward(100)
tu.right(90)
tu.forward(20)
tu.right(90)
tu.forward(100)
tu.left(180-360/times)
i+=1
tu.end_fill()
tu.hideturtle()
tu.done()
|
097b41cdc87914a22c4f3635465c2d4f8e49198a | youinmelin/practice2020 | /closure_practice_02.py | 353 | 4.03125 | 4 | def circle(radius):
def circumference():
c = 3.14*radius*2
print (f'circumference is {c}')
return c
def area():
a = 3.14*radius**2
print (f'area is {a}')
return a
return circumference,area
print(circle(3))
cir,are = circle(3)
print(cir(),are())
for i in cir... |
f05dfb9081f123fe53179db0dc430c5b29deb569 | youinmelin/practice2020 | /oo_practice.py | 539 | 3.8125 | 4 | class Add:
def __init__(self,a,b):
self.a = a
self.b = b
def add(self):
print(f'{self.a} + {self.b} = {self.a + self.b}')
return self.a + self.b
addlist = []
for i in range(10):
j = i*2
ab_add = Add(i,j)
addlist.append(ab_add)
for i in range(10):
j = i*3
lo... |
f68989b5f9ac65dd3ac7d5c6dd03207be9e8e6b9 | youinmelin/practice2020 | /read_and_analyze_file.py | 580 | 4.09375 | 4 | #Write a program that prompts the user to enter a text file, reads words from the file, and displays all the non-duplicate words in ascending order.
path = 'files'
file_name = 'Integration tests.txt'
words_dict = {}
words_set=set()
with open('%s\\%s'%(path,file_name),'r') as f:
for content in f.readlines():
... |
059ea17a7e21619b63c526db214d0476d88fbb79 | youinmelin/practice2020 | /sum_matrixes.py | 265 | 3.53125 | 4 | # sum two matrixes
matrixa=matrixb=[[0,1,2],[3,4,5],[6,7,8]]
sum_matrix=[]
for i,a in enumerate(matrixa):
sum_matrix.append([])
for j,b in enumerate(a):
sum_matrix[i].append(0)
sum_matrix[i][j]=matrixa[i][j]+matrixb[i][j]
print (sum_matrix)
|
35580dd17947221b20186fee52ee387c3423e2bc | youinmelin/practice2020 | /fibonacci_01_for_loop.py | 391 | 3.953125 | 4 | # create a Fibonacci sequence
# use for loop
class NormalFibonacci():
def __init__(self,num):
self.num = num
def creator(self):
fi = [0,1]
for i in range(2,self.num):
fi.append(fi[i-1]+fi[i-2])
print(fi)
def main():
num = 15
created_list = NormalFibonacci(... |
562a65c73c1ab49af1cdd838e74f0592f31196b2 | youinmelin/practice2020 | /transposed_matrix.py | 364 | 3.625 | 4 | matrixa=[[1,2],[3,4],[5,6]]
matrixb=[]
arow = len(matrixa)
acolumn= len(matrixa[0])
# build a new matrix
for i in range(acolumn):
matrixb.append([])
for j in range(arow):
matrixb[i].append(0)
# transposed matrix
for i,a in enumerate(matrixa):
for j,b in enumerate(a):
matrixb[j][i]=b
... |
70a33bcc5bcc0dabd0c2281f2457536b25d1956d | filipkny/SmartBots | /src/NeuralNetwork.py | 1,326 | 3.859375 | 4 | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class Neural_net:
def __init__(self,w1,w2, input = 2, hidden = 6):#1 hidden layer NN; w1,w2 - weight matricies, rows indicate the amount of neurons in next layer
self.w1 = np.reshape(w1,(hidden,input)) #numpy array
self.w2 = np.arr... |
62c93ea97fb50652dab5a033a65ae34ecc9496fd | bjmarsh/insight-coding-practice | /daily_coding_problem/2020-09-11.py | 698 | 4.1875 | 4 |
"""
Given an array of numbers, find the maximum sum of any contiguous subarray of the array.
For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137,
since we would take elements 42, 14, -5, and 86.
Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take an... |
ef598b006895710fc80a653442c54568f47a2ba8 | bjmarsh/insight-coding-practice | /algorithms/sorting_functions.py | 2,477 | 4.03125 | 4 |
def bubble_sort(vals, inplace=False):
if not inplace:
vals = list(vals)
size = len(vals)
nflips = 1
iter = 0
while nflips > 0:
nflips = 0
iter += 1
for i in range(size-iter):
if vals[i+1] < vals[i]:
vals[i], vals[i+1] = vals[i+1], val... |
20c4ddba0ab22d154fb4da7dab588c51fd00ace2 | bjmarsh/insight-coding-practice | /daily_coding_problem/2020-09-07.py | 552 | 4.03125 | 4 | """
Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability,
implement a function rand7() that returns an integer from 1 to 7 (inclusive).
"""
import random
def rand5():
return random.randint(1,5)
def rand7():
r = 8
while r > 7:
x1, x2 = rand5(), r... |
90d305cfb53c74f227247ec44316e6c7533a40d6 | bjmarsh/insight-coding-practice | /daily_coding_problem/2020-09-09.py | 722 | 4.15625 | 4 | """
Given a array of numbers representing the stock prices of a company in chronological order,
write a function that calculates the maximum profit you could have made from buying and
selling that stock once. You must buy before you can sell it.
For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you... |
74a229e1318829b81454ae6f59d2ba2aded43f35 | bjmarsh/insight-coding-practice | /daily_coding_problem/2020-08-09.py | 542 | 3.6875 | 4 | """
You run an e-commerce website and want to record the last N order IDs in a log.
Implement a data structure to accomplish this, with the following API:
"""
class OrderLog:
def __init__(self, N):
self.ids = [None] * N
self.cur_idx = 0 # index pointing to the next element to be filled
def r... |
c07b20c34dce8e12b40d20317048a5d7c7f6565d | bjmarsh/insight-coding-practice | /daily_coding_problem/2020-08-30.py | 804 | 4.46875 | 4 | """
The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set.
For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}
"""
def generate_power_set(vals, used=None):
if not isinstance(vals, set):
va... |
df02775c95e7573d60da7422022f703f719e7dba | bjmarsh/insight-coding-practice | /daily_coding_problem/2020-08-02.py | 751 | 4.03125 | 4 | """
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
Follow-up: Can you do this in O(N) time and constant space?... |
dd0736bea2ceeeccf76f7d847173930526207cde | simon-suuk/ContactManager | /contact_manager.py | 5,866 | 3.5625 | 4 | import csv
import os
def capture_input():
nm = input("enter name: ")
ph = input("enter phone number: ")
em = input("enter email: ")
g = input("enter gender: ")
p_adr = input("enter post_address: ")
return dict(name=nm, phone_no=ph, email=em,
gender=g, post_address=p_adr)
def ... |
9d6279664852937f3e2b7683382220e3f2bed760 | amkotsar-prog/HomeworkPython | /Lesson2Task3.py | 366 | 4 | 4 | month = int(input('Введите месяц в виде целого числа: '))
my_list = ["winter", "spring", "summer", "autumn", "winter"]
my_dict = {1: 'winter', 2: 'spring', 3: 'summer', 4: 'autumn', 5: 'winter'}
print(f'This month is {my_list [month // 3]} (from the list)!')
print(f'This month is {my_dict [month // 3 + 1]} (from the ... |
b6fc26358563a88338c2f44a482a5c5c76387091 | leosbelpoll/data-science-machine-learning-starting | /introduccion_al_pensamiento_computacional_con_python/busqueda_binaria.py | 526 | 3.953125 | 4 | # cuando la respuesta se encuentra en un conjunto ordenado, podemos utilizar búsqueda binaria
# es altamente eficiente, pues corta el espacio de búsqueda en dos por cada iteración
goal = int(input('Ingrese un número'))
epsilon = 0.01
min_limit = 0.0
max_limit = max(1.0, goal)
result = (max_limit + min_limit) / 2
whil... |
ed3f7b023500bfba686b14e3d23ab56907c3311e | leosbelpoll/data-science-machine-learning-starting | /introduccion_al_pensamiento_computacional_con_python/afirmaciones.py | 348 | 3.625 | 4 | def divide_elementos_de_lista(lista, divisor):
assert divisor != 0, 'El divisor no puede ser cero'
return [i / divisor for i in lista]
lista = list(range(10))
lista2 = divide_elementos_de_lista(lista, 2)
print(lista2)
try:
lista3 = divide_elementos_de_lista(lista, 0)
print(lista3)
except AssertionEr... |
573f4c626e99c5a32b3282e56d4c04450ef0df2f | rmulder/coding_sandbox | /hackerrank/diagonal_difference.py | 1,117 | 4.4375 | 4 | """ Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3
4 5 6
9 8 9
The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is .
Function description
Complete the function in the editor b... |
1e3355829d7a544a94f4e4dd8afde7c50bc7f299 | erikperillo/ps2016_vision_challenge | /comments/grupo_1.py | 3,021 | 3.578125 | 4 | import math # uso do método atan
def main():
#lendo a imagem de um dispositivo
M = read_image()
#você tem que dar o valor correto às duas variáveis abaixo.
#cone_x e cone_y são os pontos x e y, respectivamente, do centro
#do retângulo que encobre completamente o cone.
cone_x, cone_y = 0, 0
... |
e1ebbd44d34c935bed984eb3b7facf39a0356b77 | sqeekypotato/kids_clock | /weather_API.py | 3,502 | 3.765625 | 4 | from weather import Weather
from settings import my_location, weather_words, weather_symbols, highlight_temperature
from error_logging import LogFile
class GetWeather:
print("getting weather!")
weather = Weather()
lookup = ''
forcasts = ''
todays_forcast = ''
celcius = ''
temperature_scal... |
e085e52e401f3296958ccb33367e935efea758ea | winterfellding/algorithms-note | /src/sort/insertion_sort.py | 583 | 3.6875 | 4 | import random
def insertion_sort(arr):
for i in range(1, len(arr)):
j = i - 1
tmp = arr[i]
while tmp < arr[j] and j >= 0:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = tmp
if __name__ == '__main__':
for i in range(10000):
arr = []
for _ in range(10... |
1855ee2439e7cf735aa6f6cd443eed6cd8fe5db1 | LeonardoGCF/Python_exe-eval- | /连续质数问题.py | 566 | 3.578125 | 4 | def prime(m):
for i in range(2,m):
if m%i == 0:
return False
else:
return True
n = eval(input())
num = int(n)
num=num+1 if num<n else num
count = 5
while count >0 :
if prime(num):
if count >1:
print(num,end=',')
else:
print(num,end='')
... |
4063847fe8ed812b598cad7874fa60b843180b0d | die-zwei-Freunde/extrem-epic-excessive-enthusiastic-elf-elevator | /classes/enemy/enemy.py | 1,616 | 3.6875 | 4 | '''
Introducing: the enemy.
It is ... not your friend, I guess.
'''
class Enemy():
'''
Enemy (short: NME)
base class for future enemies which will be clubbed to death for entertainment.
Maybe they should scream a bit?
'''
def __init__(self, name):
self.name = name
self.HP, sel... |
407f8f0ea05918c72c1e030c1d54436a4084b167 | die-zwei-Freunde/extrem-epic-excessive-enthusiastic-elf-elevator | /classes/item/use/useable.py | 739 | 3.703125 | 4 | from classes.item import item
class Useable(item.Item):
"""Base class for creating an useable object."""
def __init__(self, name, race, alignment):
super().__init__(name, race, alignment)
self.designation = 'useable'
self.effect = self.use()
def use(self):
"""Specify the e... |
97733669e9ef89d65ea6cbb555d8a8e856657241 | moonblade/smith | /upper.py | 143 | 3.671875 | 4 | import os, sys
def toUpper(fileName):
with open(fileName, "r+b") as file:
content = file.read()
file.seek(0)
file.write(content.upper()) |
abc23bc5d4723b0edf114dfbc99bbfd2d7348e3d | igor-reis/lp-unis-ead | /Ciclo2Atv1.py | 323 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: latin1 -*-
"""
1) Faa um programa que leia a idade de uma pessoa expressa em dias e mostre-a expressa em anos, meses e dias.
"""
idade = input('Digite sua idade em dias: ')
a = idade/365
m = idade/30
d = idade
print "Sua idade em anos:", a, "- meses:", m, "- dias:", d
... |
2aece8d89a3b11e924eb0bbbe5905f7e5b36b4b2 | igor-reis/lp-unis-ead | /Ciclo4Atv1/Banco.py | 535 | 3.765625 | 4 | import sqlite3
class Banco():
def __init__(self):
self.conexao = sqlite3.connect('banco.db')
self.createTable()
def createTable(self):
c = self.conexao.cursor()
c.execute("""create table if not exists pacientes (
cpf text primary key,
... |
35a085e4e695fb1162af825000b294986409f4a0 | nguyenhuyhoang010709/python-projects | /day-19 Motivational Quote Generator/main.py | 421 | 3.53125 | 4 | from tkinter import *
import pandas as pd
import random
window = Tk()
window.minsize(width=200, height=200)
window.title("Quotes")
quotess = pd.read_csv("quotes.csv").to_dict(orient="records")
rand = random.choice(quotess)
auth = Label(text=f"By:{rand['AUTHOR']}")
auth.grid(row=0,column=0)
text = Text(height=5, wid... |
4b27567c567dc1446b2128bdd03acf0ff66832f3 | priye-1/Simple-Bank-Management-Model | /bank_management_script.py | 7,782 | 4.3125 | 4 | """ A Bank Mangement Program """
import random
import sys
class User():
"""This class is to register and store user details"""
# class attribute
BankName = "Reimnet Bank"
# instance attributes
def __init__(self, name, phone_no, location):
self.name = name
self.phone_no = phon... |
91f8a575fe48df1dab860130464397858a052e65 | CountessCherry/ShevaLabs | /laboratory_work_10.py | 1,552 | 3.6875 | 4 | # 1
s = input('введіть прізвище та ім\'я: ')
print(s[2])
y = len(s)
print(s[y - 2])
print(s[0:5])
print(s[0:y - 2])
print(s[0::2])
print(s[1::2])
print(s[y::-1])
print(s[y::-2])
print(y)
# 2
s = input('введіть символьний рядок: ')
whitespace = 1
for i in range(len(s) - 1):
if s[i] == ' ' and s[i + 1] != ' ' and s[i... |
540bbbd37a239bb2cc361163fa56161a5315af5f | Marcus-Jon/common_algroithms_python | /selection_sort.py | 696 | 4.09375 | 4 | import sys
students = ['ted', 'steve', 'dave', 'dan', 'jack', 'jon', 'will', 'rick', 'adam', 'james', 'bruce']
# Selection sort
print students
for x in range(len(students)):
# set minimum value and the index of it
min_index = x
min_value = students[x]
for y in range(x + 1, len(students)):
... |
75f908df6ce7569a94a3b26c6026b76a8bcb78ed | Marcus-Jon/common_algroithms_python | /insertion_sort.py | 401 | 3.828125 | 4 | import sys
students = ['ted', 'steve', 'dave', 'dan', 'jack', 'jon', 'will', 'rick', 'adam', 'james', 'bruce']
# Insertion sort
print students
for x in range(0, len(students)):
value = students[x]
index = x
while index > 0 and students[index - 1] > value:
students[index] = students[ind... |
31217d34675795acc9bb938e41a129600c64dab7 | rishjain-iitr/Learning_Data_Structures | /linked_list/multiple_functions.py | 4,674 | 4.15625 | 4 | # A program with mutliple function in linked list
# Node class
class Node:
# Function to initialize node object
def __init__(self, data):
self.data = data # assigns data
self.next = None # Inotialize next as null
#Linked List class
class LinkedList:
def __init__(self):
self.head = None
# Inserts new node ... |
c5ebf62441ff188ce1fe63b26af377fd45507dce | NataFediy/MyPythonProject | /hackerrank/itertools_permutations.py | 1,119 | 4.3125 | 4 | #! itertools.permutations(iterable[, r])
#
# This tool returns successive r length permutations of elements
# in an iterable.
# If r is not specified or is None, then r defaults to the length of
# the iterable, and all possible full length permutations are generated.
#
# Permutations are printed in a lexicographic sort... |
1a0038d74f6c7bfbaac65cef1e5df809d5908089 | NataFediy/MyPythonProject | /hackerrank/closures_and_decorators_Mobile_number.py | 1,265 | 4.46875 | 4 | # The given mobile numbers may have +91, 91 or 0 written before
# the actual 10 digit number.
# Alternatively, there may not be any prefix at all.
#
# Input Format:
# The first line of input contains an integer N,
# the number of mobile phone numbers.
# N lines follow each containing a mobile number.
#
# Output Format:... |
3e2c2743ba830adc06f845a4ca3540b6dca51e95 | NataFediy/MyPythonProject | /hackerrank/math_triangle_quest.py | 840 | 4.1875 | 4 | # You are given a positive integer N.
# Print a numerical triangle of height like the one below:
#
# 1
# 22
# 333
# 4444
# 55555
# ......
#
# Can you do it using only arithmetic operations,
# a single for loop and print statement?
#
# Use no more than two lines.
# The first line (the for statement) is already written ... |
c00a8231290e9ff593c000e4c0f716f8ebbbfb68 | NataFediy/MyPythonProject | /other_resources/index_of.py | 435 | 4.3125 | 4 | #! Find the first index of item in array
def index_of(arr, item):
if item not in arr:
return f"{item} is not in {arr}"
else:
for i in range(len(arr)):
if arr[i] == item:
return i
print(index_of('abcdcba', 'Z'))
print(index_of('abcd', 'A'))
print(index_of('abcd', 'a'... |
ca30d8db8162a3290815bd55a8d10a1173a21673 | NataFediy/MyPythonProject | /codingbat/make_bricks.py | 1,035 | 4.34375 | 4 | #! Task from http://codingbat.com:
# We want to make a row of bricks that is goal inches long.
# We have a number of small bricks (1 inch each) and big bricks
# (5 inches each). Return True if it is possible to make the goal
# by choosing from the given bricks. This is a little harder than
# it looks and can be done wi... |
dfb1963f502ec1fa7eaac7bb731cb7b0bdc4a4a4 | NataFediy/MyPythonProject | /hackerrank/regExp_email_validation.py | 1,746 | 4.28125 | 4 | # A valid email address meets the following criteria:
#
# It's composed of a username, domain name, and extension assembled in this
# format: username@domain.extension
# The username starts with an English alphabetical character, and any
# subsequent characters consist of one or more of the following:
# alphanumeric ch... |
d60f320c456fd441ef9a6f738b0e3e9cedb92a60 | NataFediy/MyPythonProject | /hackerrank/class_complex_numbers.py | 3,091 | 4.46875 | 4 | #! You are given two complex numbers,
# and you have to print the result of their
# addition, subtraction, multiplication, division and modulus operations.
# The real and imaginary precision part should be correct up to two decimal
# places.
#
# Input Format:
# One line of input: The real and imaginary part of a number... |
6fb70785d3f3eeaa2f8f133ba70b427429919c9e | NataFediy/MyPythonProject | /hackerrank/set_exec_methods.py | 1,476 | 3.890625 | 4 | # Task:
# You have a non-empty set s, and you have to execute N commands given in N lines.
# The commands will be pop, remove and discard.
#
# Input Format:
# The first line contains integer n, the number of elements in the set s.
# The second line contains n space separated elements of set s.
# All of the elements are... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.