blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fcfe98f9fda82e4872e7036298f956f60da316d5 | Vigneshg98/Guvi | /checkpnz.py | 151 | 3.921875 | 4 | inp = int(input())
if inp > 0 :
print("Positive")
elif inp < 0 :
print("Negative")
elif inp == 0:
print("Zero")
else :
print("Invalid Input")
|
8382180cf9b5c3fe6de91d0f08f9f296c85392d7 | rohaneden10/luminar_programs | /files/a2.py | 272 | 3.59375 | 4 | list=[]
f=open("messi","r")
sum=0
for lines in f:
list.append(int(lines.rstrip("\n")))#intilay read as astring and we convert it to integer
for i in list:
sum+=i
print(list)
print(sum)
#rstrip is used to remove end characters
#lstrip used to remove first character |
0fdcf381fa095c08c5fb678d5480ae8086a956c9 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4352/codes/1793_3141.py | 166 | 3.71875 | 4 | from numpy import*
v = array(eval(input("digite numeros: ")))
n = sum(v[0:])
m = (((v[0]**(1/6) + v[1]**(1/6) + v[2]**(1/6) + v[n-1]**(1/6))**6)/n)
print(round(m, 2)) |
7cc445b3f3b104c8f890455e80bb4ea11a805134 | velugotiss/Python-Deep-Learning | /ICP1/arithmetic.py | 339 | 3.890625 | 4 | var1 = input("Give the numbers to add")
var2 = input()
sum = float(var1)+float(var2)
subs = float(var1)-float(var2)
mult = float(var1)*float(var2)
div = float(var1)/float(var2)
mod = float(var1)%float(var2)
print("sum :{0} \nsubstraction :{1} \n multiplication : {2}\n division : {3}\n modulus : {4}" .format(sum,... |
13c2f8a6de4a0ec7544c903e53465b31572e8cb5 | josebummer/ugr_programacion_tecnica_y_cientifica | /Relacion Listas/ej1.py | 1,325 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 21 18:41:39 2018
@author: jose
"""
import numpy as np
from time import time
# =============================================================================
# Ejercicio 1
# Escribe una función sumNumLista(numeros) que sume todos los números de una
... |
86c034ba8ee4c6b30f3869d80d610b03b2955b8f | xukangjune/Leetcode | /solved/326. 3的幂.py | 398 | 3.71875 | 4 | """
此题不用循环或者递归来做,在整数范围最大的3的n次幂为3^19==1162261467。所以所有3的幂都可以整除它,其它的数则不能。
"""
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return 1162261467 % n == 0 if n > 0 else False
solve = Solution()
print(solve.isPowerOfThree(81)) |
00309f1a0478496f39abce568d00e03f39476df5 | woskar/automation | /files/files.py | 4,145 | 4.0625 | 4 | """
# Reading and Writing files
Folder names and filenames are not case sensitive on
Windows and macOS but they are on Linux.
Windows: root C:\ and backslashes \ as separators
Linux and Mac: root /. and forwardslashes / as separators
use os.path.join() function (import os)
os.path.sep returns the separator used on th... |
5a3391e392f90e7acfa3720323a6024e55109263 | thomasharms/exxcellent_challenge | /challenge_exsolutions.py | 5,831 | 3.5625 | 4 | import pandas as pd
import os.path
'''
Task Weather Challenge is solved by class Weather_Data
in order to run it use the predefined instantiation in line 137
Task Football Challenge is solved by class Football_Data
in order to run it use the predefined instantiation in line 139
just run the file to see both solutio... |
dd5ff5267967aad8ffe8386e4c53bc0a6967b116 | panditdandgule/DataScience | /NLP/Hands on Natural Language Processing/Python Basics/Dictionaries.py | 713 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 6 08:36:13 2019
@author: pandit
"""
#Key -Value Pairs
dict1={}
#Adding elements of the dictionary
dict1['Apple']='Apple is a fruit'
dict1['Orange']='Orange is a fruit'
dict1['Car']='Cars are fast'
dict1['Python']='Python is a snake'
#Printng d... |
0d27ec9567e71022e998d60597d5ac0f7e9ff88a | lalisnats/Proyecto-Programacion | /pro1.py | 3,347 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 18:23:58 2019
@author: lovelace
"""
# Librerias importadas
import time
##############################################################################
# Clases
class day:
""" Clase day:
Crea un objeto de tipo day cuyos atributos son... |
b5174e0b5e5c716b8d1ea136f627a6f67512a0aa | welchbj/almanac | /almanac/types/comparisons.py | 1,129 | 3.625 | 4 | from typing import Any, Type
from typing_inspect import is_union_type, get_args
def is_matching_type(
_type: Type,
annotation: Any
) -> bool:
"""Return whether a specified type matches an annotation.
This function does a bit more than a simple comparison, and performs the following
extra checks:... |
fabe2b9606c05bf757667397660e03440bd548a1 | jasmineagrawal/pythonprogram | /distance_between_2points.py | 292 | 3.890625 | 4 | x=(int(input(" entre the x coordinate of first point: ")))
y=(int(input(" entre the y coordinate of first point: ")))
p=(int(input(" entre the x coordinate of second point: ")))
q=(int(input(" entre the y coordinate of second point: ")))
d=((p-x)**2+(q-y)**2)**0.5
print("distance=" +str(d))
|
3e9a9d314525b8206363c470438e4f81088c6ea3 | VihaanVerma89/pythonCodes | /codingBat/string-1/left2.py | 173 | 3.8125 | 4 | def left2(string):
if len(string) < 2 :
return string
else:
return string[2:]+string[:2]
print left2('Hello')
print left2('java')
print left2('hi')
|
5f6f434b431bef2be907450dd288ad17542626f9 | nilbsongalindo/APA | /Heap Sort/heap_sort.py | 1,000 | 3.828125 | 4 | def root(i):
return int (i - 1) / 2
def left_child(i):
return 2 * i + 1
def right_child(i):
return 2 * i + 2
def max_heapfy(arr, n, i): #heapfy
biggest = i
left = left_child(i) #left_node
right = right_child(i) #right_node
#Checking if right node is greater than root
if right < n and arr[biggest] < arr[righ... |
d9390d50fa9f06b09508f8a7527a6ce8be4cbe63 | watsy0007/projecteuler | /p_7.py | 512 | 3.796875 | 4 | # https://zh.wikipedia.org/wiki/質數定理
from utils import is_prime
def prime_by_index(number, index):
prime_index = 0
for (idx, v) in enumerate(range(2, number)):
if is_prime(v):
prime_index += 1
print(v, prime_index)
if index == prime_index:
return v
... |
c0aaafa3173f369d4675e0dde6084c1ec4d51488 | mukoedo1993/Python_related | /python_official_tutorial/chap4_7/chap4_7_1.py | 851 | 4.6875 | 5 | """
The function can be called in several ways:
1: Similar to C++
"""
i = 5
def f(arg=i):
print(arg)
i = 6
f()
'''
Important warning: The default value is evaluated only once. This makes a
difference when the default is a mutable object such as a list, dictionary, or
instances of most classes. For example, the foll... |
29620b218318d8374396353802a5f2b78c2b8358 | driellevvieira/ProgISD20202 | /Dayalla_Marques/A4/ProgramasAula4.py | 3,378 | 3.953125 | 4 |
logicValue = int(input("Você está usando máscara?\n"))
if(logicValue):
print("Parabéns!\n")
print("Fim do programa!!")
###################################################################################
logicChocolate = int(input("Você gosta de chocolate?\n"))
logicCafe = int(input("Você gosta de café?\n")... |
7d12e596344bb2370d3e429eda917038a1538a66 | gnool/datastructure-algorithms | /graph/maxflow/maxflow.py | 5,070 | 4.25 | 4 | # python3
import queue
class Edge:
"""Edge of graph
Attributes:
start directed edge from start to end
end
capacity capacity
flow flow
"""
def __init__(self, start, end, capacity):
self.start = start
self.end = en... |
5757e7a9f4f46bc57ff9a93e4a5ab93db38f27ba | vaibhavumar/sudokuSolverOpenCV | /sudoku2.py | 2,698 | 3.515625 | 4 | from random import choice
import numpy as np
def is_eligible(sudoku, row_index, col_index, num):
if num in sudoku[row_index,:] or num in sudoku[:,col_index]:
return False
if within_box(sudoku, row_index, col_index, num):
return False
return True
def within_box(sudoku, row_index, ... |
9855f1c336267ece37f2858ce322811ab818997f | joselmjl19/pensamiento_computacional | /raiz_funciones.py | 1,609 | 3.953125 | 4 | def enumeracion():
objetivo = int(input('Escribe un entero: '))
respuesta = 0
while respuesta ** 2 < objetivo:
respuesta += 1
if respuesta ** 2 == objetivo:
print(f'La raiz cuadrada de {objetivo} es {respuesta}')
else:
print(f'{objetivo} no tiene una raiz cuadrada exacta')
... |
80898f9096ea030b2dfe1831f6aee90eba528d3e | CommanderCode/Daily-Problems | /Daily 364-dice roller.py | 669 | 4 | 4 | #I love playing D&D with my friends, and my favorite part is creating character sheets (my DM is notorious for
# killing us all off by level 3 or so). One major part of making character sheets is rolling the character's stats.
# Sadly, I have lost all my dice, so I'm asking for your help to make a dice roller for me to... |
1686261b21749f3a0de26e2317135029800b04e2 | JeremyBakker/Efficiency | /test.py | 2,682 | 3.546875 | 4 | import unittest
from learn import return_max_profit, binary_search, highest_product_of_three, \
is_unique, is_unique_without_addition, binary_gap, find_missing_element,\
integer_pairs, string_compression, check_permutation, isSubstring
class TestProblemSolving(unittest.TestCase):
def test_return_max_profit(self):... |
a9a16c2f4034342795d105e3dfeff73ed19795cd | nnaeueun/Python_RaspberryPi | /0909/if/practice05.py | 732 | 4.03125 | 4 | #3개의 양수중 가장 큰 값 출력
num1 = int(input("1. 양의 정수 입력 : "))#값을 받아서 int형변환
num2 = int(input("2. 양의 정수 입력 : "))
num3 = int(input("3. 양의 정수 입력 : "))
if num1>0 and num2>0 and num3>0:#양수 조건
if num1>num2:#num1이 num2보다 클 때
if num1>=num3:#num1이 num3보다 크거나 같을때
print(num1)#num1출력
else:#num1이 num3보다 작을... |
fdc11c48ff4bc889dca42c549fa98d697f027729 | N07070/Projects | /Solutions/Python/social_network_suite.py | 1,736 | 4.15625 | 4 | #!/usr/bin/python3.4
# -*- coding: utf-8 -*-
def days_limit():
jour = 1
jour_lim = int(input("Please input how many days you would like to cycle. >> "))
nbr_friends = 2
nbr_nvx_friends = 2
while jour <= jour_lim:
nbr_friends = nbr_nvx_friends*2
nbr_nvx_friends = nbr_nvx_friends*2
... |
155894ab25a35da332c800af1590a2e38f65f658 | dmytro-malyhin/University-Python | /HANGMAN.py | 1,236 | 4.03125 | 4 | print('You star to play')
word = list(str(input('Please, input the word for second player - ')))
massive_light = ['a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y']
Attempt = 5
letter = []
while True:
for element in word:
if element in massive_light:
letter.append(element)
... |
cb6f2f97ae7c5589ede4fa80f3fb2cd68cbd4965 | mscaudill/Tutorials | /sql_zoo/3_SELECT_from_Nobel.py | 3,345 | 3.578125 | 4 | # -- Matt Caudill
# nobel(yr, subject, winner)
#1. Write a query for the nobel table that displays prizes in 1950.
SELECT yr, subject, winner FROM nobel
WHERE yr = 1950
#2. Who won the the 1962 Prize for literature
SELECT winner FROM nobel
WHERE yr = 1962 AND subject = 'Literature'
#3. Find the year and subject of... |
b3b9b5dcaa4b4e0f715dcdb1298313aa6e425c6c | anuragseven/coding-problems | /online_practice_problems/Mathematical/Factorial.py | 333 | 3.765625 | 4 | # Given a positive integer, N. Find the factorial of N.
class Solution:
def factorial (self, N):
if N==0:
return 1
return N*self.factorial(N-1)
class Solution2:
def factorial (self, N):
fact=1
for i in range(N,0,-1):
fact=fact*i
... |
6878bb77a2c2ec31f86398ddd8d9795eb1f803c9 | 1Bitcoin/python-old | /TrashPython/подготовка/работа с массивами/create_kv_matrix_pascal_style.py | 304 | 3.734375 | 4 | '''
создать за 2 цикл кв. матрицу (выше гл. диаг = *, ниже #, на диаг. @)
'''
N = 5
a = [['@']*N for i in range(N)]
for i in range(N):
for j in range(N):
if i != j:
a[i][j] = '#'
a[j][i] = '*'
for row in a:
print(row)
|
1bf196ff878b635583e7d4b5427b6f334d96fc09 | minhntm/algorithm-in-python | /datastructures/list/challenge8_rearrange_positive_negative.py | 982 | 4.21875 | 4 | """
Problem Statement:
Implement a function rearrange(lst) which rearranges the elements such that
all the negative elements appear on the left and positive elements
appear at the right of the list.
Note that it is not necessary to maintain the order of the input list.
Generally zero is NOT positive or nega... |
a5aa6bc088eccd8b3d7685e314c89253ecaf4f5e | bigfatmouse9208/Algo_Study_Group | /Week8_Bit_Manipulation/leetcode_477.py | 610 | 3.546875 | 4 | """
Runtime: 476 ms, faster than 50.63% of Python3 online submissions for Total Hamming Distance.
Memory Usage: 15.4 MB, less than 7.23% of Python3 online submissions for Total Hamming Distance.
"""
class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
if not nums:
return 0
... |
a2726a4c0ceb34fa05aaab3d05df2603445f543b | Simonthesun/comp | /asst/1/asst1.py | 1,709 | 3.625 | 4 | def swapchars(string):
s = string.lower()
most = 0
least = 0
most_letter = ""
least_letter = ""
new_string = ""
letter_count = {}
for letter in s:
if letter in letter_count:
letter_count[letter] = letter_count[letter] + 1
else:
letter_count[letter] = 1
for key in letter_count:
count = letter_count[... |
76d937eb21ed906c9d725cc3090e2f27c91a6cca | duncanp11111/Year_End2017 | /OddsOn.py | 626 | 3.859375 | 4 | from random import randrange
import time
print ("Welcome to Odds On!")
odds_on = input("what will you do if you lose?: ")
odds = int(input("What are your odds?: "))
print ("Your odds are 1 to", odds)
print ("Please select a number between 1 and", odds, "when the counter hits zero.")
print ("Ready?")
print ("3")
time.... |
52e16e05b3945aad496426687a3fea6eb2c66f02 | patrickmn/euler-python | /020.py | 137 | 3.703125 | 4 | #!/usr/bin/env python3
n = 100
result = 100
while n > 0:
result = result * n
n = n - 1
print(sum(int(x) for x in str(result)))
|
bb8bd8849e97f50fbc528d2ddc6cbb844ec821fc | lucasggln/Info | /Exercices/5/Compteur d'événement.py | 141 | 3.515625 | 4 | #Wiaux Bastien
def count(events, i, j):
count = 0
for a,b in events:
if a == i and b == j:
count += 1
return count
|
72ea79ae2e1984b7eb809ae8e0d13930b9543a0a | ChristineKutka/Python-Files | /obamafy (2).py | 1,457 | 3.875 | 4 | # You have a pic
# You want to Obamafy it
# You want to take pixels in the image and change their colors
# [(0,1,74), (234, 123, 23)]
# def randomfunction(obamas_address, cherish_middle_name, biggest_number_ever):
# print(obamas_address)
# randomfunction(??????)
def obamafy (pixel_list):
# if our pixel_list looks... |
19655962651e5ae53b73b0b1c685586b37c93dbd | ErikLevander/erle | /jenbe.py | 818 | 3.5 | 4 | import math
# coding=utf-8
# print: investerat belopp
print('Hur mycket vill du investera?')
investment = float(input())
# print(investment)
# input för att ta årsavkastning som input från user
print('Hur många procent är årsavkastning?')
annualReturn = int(input())/100
print(annualReturn)
# print: antal år
print('... |
4fa6a5ee874c77ad1abf04db22e4732cb7daed2d | andyyang777/PY_LC | /448_FindAllNumbers.py | 859 | 3.703125 | 4 | # Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elemen
# ts appear twice and others appear once.
#
# Find all the elements of [1, n] inclusive that do not appear in this array.
#
# Could you do it without extra space and in O(n) runtime? You may assume the r
# eturned list does not count... |
6406fdcc7ed8b811dc8234e472a0c757885d58cc | hualazimi0425/squirrel | /88. Merge Sorted Array.py | 1,005 | 4.46875 | 4 | # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
#
# Note:
#
# The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has
# enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Examp... |
99424a4ba768939ff8a4877e9e05f5f0aae53428 | CeciliaMartins/-LingProg | /9-conteudoEtamanhoString.py | 896 | 4.09375 | 4 | ##9 Faça um programa que leia 2 strings e informe o conteúdo delas
##seguido do seu comprimento. Informe também se as duas strings
##possuem o mesmo comprimento e são iguais ou diferentes no
##conteúdo.
##Exemplo:
##String 1: Brasil Hexa 2018
##String 2: Brasil! Hexa 2018!
##Tamanho de "Brasil Hexa 2018": 16 caracteres... |
607fd2ee99eaf29df7a77e964eb0848f4cd4b3c9 | 8Raouf24/bbc_english_test | /crashfile.py | 883 | 3.8125 | 4 |
""" def test(corpus):
print("\nWelcome to your english level test!\n Please before starting, identify yourself\n#########\n")
# print("ID :")
# ID = input()
# print("Password:")
# password = input()
print(f"\n you are ready to start your test. Let's dive in !\n ")
cpt_tr = 0
cpt = 0
... |
7ab7b5f7b685e0292bd3dc6d44716e41122140eb | ashley0121/uband-python-s1 | /homeworks/B17333/B17333-Aro-交作业/week3/day17-homework.py | 528 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: xxx
import turtle
def main():
#设置一个画面
windows = turtle.Screen()
#设置背景
windows.bgcolor('blue')
#生成一个黄色乌龟
bran = turtle.Turtle()
bran.shape('turtle')
bran.color('yellow')
turtle.reset()
turtle.shape("circle")
turtle.shapesize(5,2)
turtle.settil... |
8eee8bad56bf54005002bfbb9b9ee5e4bffd1c1d | omnivaliant/High-School-Coding-Projects | /ICS3U1/Assignment #7 OOP 2/4-5-6 Class.py | 17,858 | 4.375 | 4 | #Author: Mohit Patel
#Date: Nov. 27, 2014.
#Purpose: To create a program that will roll and display 3 dice.
#------------------------------------------------------------------------#
import random
from tkinter import*
root = Tk()
root.title("4-5-6 Dice Game")
root.config(width=500,height=438,bg="sky blue")
menubar = ... |
b360ad9ff5bc8387434aff608b6f0c3390b9486a | pbarden/python-course | /Chapter 8/low_vals_out.py | 539 | 3.75 | 4 | def get_user_values():
list_len = int(input())
my_list = list()
for n in range(0, list_len):
my_list.append(int(input()))
# print(my_list)
my_max = int(input())
return my_list, my_max
def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):
for n in user_va... |
453ffcdcfb0c005137a7f6c250c57b6b38311cde | shiraz19-meet/y2s18-python_review | /exercises/for_loops.py | 116 | 3.546875 | 4 | # Write your solution for 1.1 here!
i=0
sum1=0
for i in range(101):
sum1 = sum1 + i
if i % 2 == 0:
print(sum1)
|
fb6a7c62cd1cf33f9051570782873558f3c1f7ab | devLorran/Python | /ex0103.py | 809 | 4.0625 | 4 | '''Faça um programa que tenha uma função receba dois
parametro opcionais: o nome de um jogador e quantos gols
ele marcou O programa deverá ser capaz de mostrar a
ficha do jogador, mesmo que algum dado não tenha sido informado corretamente
'''
def jgd(nome='<desconhecido>', gols=0):
if nome == '<desconhecido>'... |
c4704652cbf5e7f493df006bf4dfe844ad56406d | sylvioneto/python_games | /guessit.py | 1,636 | 4.1875 | 4 | # author: sylvio.pedroza@gmail.com
import random
def play():
print("*****************************")
print("Welcome to the guessing game!")
print("*****************************")
secret_number = random.randrange(1, 101);
no_tentatives = 0
print("What difficult level you want to play?")
pri... |
f84462b5fcb7de3e875640c5a5fd17669848d950 | jbobo/leetcode | /find_critical_nodes_iterative.py | 3,328 | 3.875 | 4 | #!/usr/bin/env python3
class Graph:
edges = dict()
def __init__(self):
"""Initialize a graph object with no edges.
'"""
self.edges = dict()
def add_edge(self, parent, child):
"""Add an edge between two nodes to the graph.
"""
self.edges.setdefault(parent,... |
3563a09eaa6272824069fcdf17699ca96a4a2fde | HighLvRiver/PythonLearning | /Study/python_basic_lambda_exp.py | 1,344 | 3.765625 | 4 |
# coding: utf-8
# In[1]:
t = lambda x:x*2+1
# In[2]:
t(6)
# In[3]:
t = lambda x: print("test")
# In[4]:
t = lambda x: print("test: {}".format(x+3))
# In[5]:
seq = [1,2,3,4,5]
# In[6]:
map(lambda num: num*3,seq)
# In[7]:
list(map(lambda num: num*3,seq))
# In[8]:
filter(lambda num: num%2 == 0, seq... |
57157e98bcf796474136142d17f243f634fa3c4c | RyanCliff/Lucky_Unicorn | /01.yesno_checker_v2.py | 536 | 4.09375 | 4 | # Make Function
def yes_no(question):
valid = False
while not valid:
answer = input(question).lower()
if answer == "yes" or answer == "y":
print("start game")
return answer
elif answer == "no" or answer == "n":
print("display instructions")
... |
33cf3217e2cad91dc9b65d2fb9edba95f3aa8f49 | xanderyzwich/Playground | /python/tools/display/staircase.py | 1,089 | 4.34375 | 4 | """
Staircase
This is a staircase of size :
#
##
###
####
Its base and height are both equal to .
It is drawn using # symbols and spaces.
The last line is not preceded by any spaces.
Write a program that prints a staircase of size .
Function Description
Complete the staircase function in the... |
fa932d0d62926cdd68c1631b82451fdb982d723d | MirsadHTX/GUI | /GUI6.py | 1,634 | 3.609375 | 4 | import tkinter
minVindue = tkinter.Tk()
frame1 = tkinter.Frame(minVindue, bg="black")
frame1.grid(row = 0, column = 0)
frame2 = tkinter.Frame(minVindue, bg="blue")
frame2.grid(row = 0, column = 1)
frame3 = tkinter.Frame(minVindue, bg="yellow")
frame3.grid(row = 0, column = 2)
greenButton = tkinter.Button(frame1,... |
55177357df2377ffe11ee7f08b9614689cb926a3 | zjwyx/python | /day06/05_深浅copy.py | 880 | 4.28125 | 4 | # 赋值运算
# l1 = [1,2,3,[22,33]]
# l2 = l1
# l1.append(666)
# print(l1)
# print(l2)
# 浅copy
# l1 = [1,2,3,[22,33]]
# l2 = l1.copy()
# l1.append(666)
# print(l1,id(l1))
# print(l2,id(l2))
l1 = [1,2,3,[22,33]]
l2 = l1.copy()
l1[-1].append(666);
print(id(l1[-1]))
print(id(l2[-1]))
print(l1,id(l1))
print(l2,id(l2))
# 深拷贝
... |
08b243ce35343dc5e97ee5ffcdcf2924ee4c23db | aldsouza4/Important-Questions | /Sorting Algorithms/scratchbook.py | 1,601 | 3.796875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def traverse(root: Node):
if root is None:
return
traverse(root.left)
print(root.data)
traverse(root.right)
# root = Node(4)
# root.left = Node(2)
# root.left.left = Node(1)... |
b2f21ec3ad9f7dff6802d56429b1e8221459ff26 | Eduflutter/EXE_python | /EX - 106.py | 1,053 | 3.859375 | 4 | '''Faça um mini-sistema que utilize o interactive Help do
Python. O usuário vai digitar o comonado e o manual vai
aparecer. Quando o usuário digitar a palavra 'Fim', o programa
se encerrará.
OBS:Use cores.'''
print('\33c')
from time import sleep
c = ('\33[m', # 0 - sem cor
'\33[0;30;41m', # 1 - vermelho
'... |
572b75b9c3b2badb1d141b9c47aff6c755b437ac | AgentZoy/sf_b3.13 | /htmlgen.py | 2,221 | 3.5 | 4 | class Tag:
def __init__(self, name='tag', is_single=False, output='', **attributes):
self.name = name
self.text = ''
self.children = []
self.is_child = False
self.attributes = attributes
self.is_single = is_single
self.output = output
def __enter__(self):... |
380ff0abb455a579e96f5f3d9c42dded770cc0a9 | rednur01/ProjectEuler | /003/main.py | 1,073 | 3.96875 | 4 | # Largest prime factor
### Helper function ###
from math import sqrt, ceil
def isPrime(n: int) -> bool:
if n < 2:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
for i in range(3, ceil(sqrt(n))+1, 2):
# Only check upto sqrt(n) since at least one prime root must b... |
4fb2c1c7a6a3e7ea3270d78d7f4a1328684aacdc | marimachine/sample_test | /src/features/FeatureSelector.py | 11,053 | 3.828125 | 4 | # numpy and pandas for data manipulation
import pandas as pd
import numpy as np
# visualizations
import matplotlib.pyplot as plt
import seaborn as sns
# utilities
from itertools import chain
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
class FeatureSelector(object):
... |
a154838a2239f2932d086500ff1637185c0c36a6 | dbgower/Project-3 | /Lesson 2/mindstorms2.py | 757 | 4.03125 | 4 | import turtle
def draw_square(some_turtle):
for i in range(1,5):
some_turtle.forward(100)
some_turtle.right(90)
def draw_shapes():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("triangle")
brad.color("blue","yellow")
brad.speed(3)
fo... |
07a122061847eea5e6b98b2e731ea5cb48b8dde1 | DorisBian/projectGit | /pythonPractice/FunctionalProgramming/Decorator2.py | 489 | 3.8125 | 4 | # 多个装饰器
# 定义函数:完成包裹数据
def make_bold(fn):
def wrapped():
return "<b>"+fn()+"<b>"
return wrapped
# 定义函数:完成包裹数据
def make_italic(fn):
def wrapped():
return "<i>"+fn()+"<i>"
return wrapped
@make_bold
def test1():
return "hello world-1"
@make_italic
def test2():
return "hello worl... |
557eb9ba0a7a3e1cd380a22a2342fe35d6076f9c | xiaoxiyouran/20171205python3Grammer | /08-面向对象编程/08.01 建立一个对象.py | 1,789 | 4.15625 | 4 | class Student(object):
'''
类描述...
'''
# 有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传
def __init__(self, name, score): # 第一个参数永远是self,表示创建的实例本身
self.__name = name # 把各种属性绑定到self,因为self就指向创建的实例本身
self.__score = score
def print_score(self): # 普通的函数相比... |
14fc625ff19ae994f2be8613e89c0920883d922d | radi84/Python | /Controle de estacionamento/controle_estacionamento_v2.py | 2,393 | 3.78125 | 4 | cadastro_rotativo = []
vaga_rotativo = []
print('==' * 20 + ' Controle de estacionamento ' + '==' * 20 + '\n')
# Inicialização do app
iniciar_app = str(input('Iniciar programa? s/n: '))
# Função de entrada de dados
def dados_cliente():
placa = str(input('Placa dados: '))
modelo = str(input('Modelo: '))
... |
c219900365a93dae7d226d2414b534cd75d3b92a | AndriiLatysh/ml_course | /python_4/main.py | 308 | 4.03125 | 4 | # unique_values = set([1, 2, 2, 3])
# print(unique_values)
capitals = {"Ukraine": "Kyiv", "Ireland": "Dublin"}
capitals["USA"] = "Washington DC"
print(capitals)
capitals.pop("Ireland")
print(capitals)
for key, value in capitals.items():
print("{} -> {}".format(key, value))
print(capitals.items())
|
fc7972e0960d2c21fa7bb372aacc065050bbfc69 | rishabhad/Python-Basics- | /practice11.py | 163 | 3.625 | 4 | #checkin the world count in sentence
count=0
item=[x for x in input().split(' ')]
for i in item :
count=count+1
print (count)
print(len(item))
|
fea30203d34abb48de06e05a6e5b261ec7919109 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/blcsau001/question2.py | 484 | 4.1875 | 4 | #Program that uses a recursive function to count the number of pairs of repeated characters in a string.
#Saul Bloch
#6 April 2014
user_string = input ("Enter a message:\n")
def pairs (user_sentence):
if len(user_sentence) == 0 or len(user_sentence) == 1:
return 0
elif user_sentence[0] == use... |
c1c6054b894de7aac468cd2290dee294f23475c8 | ed1rac/Estrutura-de-dados | /normal/Pilha.py | 1,587 | 3.828125 | 4 | import unittest
class Pilha:
class Noh:
def __init__(self, element, next):
self.elemento = element
self.next = next
def __init__(self):
self.cabeca = None
self.tamanho = 0
def __len__(self):
return self.tamanho
def vazia(self):
return ... |
8735a22a6a8bafc6b8a4ed152f2150bbcbf32c8b | MMingLeung/Python_Study | /chapter9/Tornado/tornado_study/part5/test1.py | 3,636 | 3.703125 | 4 | import re
import copy
# ############## 定制插件(HTML) ##############
class TextInput(object):
def __init__(self, attrs=None):
if attrs:
self.attrs = attrs
else:
self.attrs = {}
def __str__(self):
data_list = []
for k, v in self.attrs.items():
tpm ... |
1eccf57035082a2dc2e20273685fb9c2bd02c793 | AntonAroche/DataStructures-Algorithms | /arrays/deleting-items.py | 586 | 3.84375 | 4 | # Given an array nums and a value val, remove all instances of that value in-place and return the new length.
#
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#
# The order of elements can be changed. It doesn't matter what you leave beyon... |
d23aca102a1b280bf9192348be0740243495ac24 | zplchn/m_amzn | /reviewed/citadel.py | 10,459 | 3.640625 | 4 | from typing import List
import collections, heapq
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class HashTable:
def __init__(self, size):
self.hm = [[] for _ in range(size)]
def put(self, key, value):
hash_key = hash(key) % len(self.hm)
ke... |
8505415b05ed15e01410897e2a4d390515e616a1 | mifiamigahna/ANN | /01.py | 1,185 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 18 16:30:39 2019
@author: mifiamigahna
"""
import numpy as np
import matplotlib.pyplot as plt
#1
x = np.arange(-50, 51)
plt.subplot(121)
plt.plot(x, np.square(x))
plt.subplot(122)
plt.plot(x, np.sqrt(x))
plt.plot(x, -np.sqrt(x))
#2
x = np.arange(-10, 11)
def F... |
2c18fd04063321918302c56e207d84518b23f901 | HyeRRimm/Studying_Python | /CH4/4-1리스트와반복문/이론/aliase.py | 420 | 4.21875 | 4 | #1
x=5
y=x #주의: x=y 코드오류 왜냐면 y 정의X
y=3
print(x)
print(y)
#2 aliase(가명) : x,y 값 동시 변화(하니까 코드작성시 유의해라~요정도)
x=[1,2,3,4,5]
y=x # y=[1,2,3,4,5] x=[1,2,3,4,5]
y[2]=6 #y=[1,2,6,4,5] x=[1,2,3,4,5]
print(x)
print(y)
#3 y만 변화
x=[1,2,3,4,5]
y=list(x) #x 리스트를 복사해줌으로서 x리스트 건드리지 않고 y만 변화
y[2]=6
print(x)
print(y)
|
e94893a05eb5ab6c8f93a809461db504be6eba24 | jindtang/cs373 | /quizzes/Quiz5.py | 747 | 4.28125 | 4 | #!/usr/bin/env python3
"""
CS373: Quiz #5 (7 pts)
"""
""" ----------------------------------------------------------------------
1. What is the output of the following?
(6 pts)
g1 f1 f2 g2 else finally g3
g1 f1 except finally g3
g1 f1 finally
"""
def f (n) :
print("f1", end = " ")
if n == 1 :
r... |
e461ee40571936f59507237ce879b703c8e44f5b | rajan596/python-hacks | /matplotlib-tut.py | 510 | 3.734375 | 4 | # python 3
from matplotlib import pyplot as plt
from matplotlib import style
# styles
style.use('ggplot')
#style.use('dark_background')
#style.use('grayscale')
# points
x=[1,2,3,4]
y1=[2,5,6,7]
y2=[1,2,5,7]
y3=[1,2,3,4]
# chart/graph style
#plt.plot(x,y1,'b',linewidth=2,label='Y1')
#plt.scatter(x,y2,color='g',label... |
612bf63604c13eff1a4543cf0d26463f552a3c59 | dwbelliston/python_structures | /arrays/array.py | 5,690 | 4.0625 | 4 | #!/usr/bin/env python3
class Array(object):
'''
An array implementation that holds arbitrary objects.
'''
def __init__(self, initial_size=10, chunk_size=5):
'''Creates an array with an intial size.'''
self.content = alloc(initial_size)
self.size_alloc = initial_size
self... |
74ab48d2c5270f3ce54788b4a5a3d718c4d02ab0 | sergeiissaev/Kattis-solutions | /icpcawards.py | 478 | 3.6875 | 4 | class Award:
def __init__(self):
input()
self._print_winners()
def _print_winners(self):
awarded = 0
awarded_list = list()
while awarded < 12:
institution, team = list(map(str, input().rstrip().split()))
if institution not in awarded_list:
... |
dc8b7f536e3689fdba222cc8ed065d49ffa86768 | Arunabha97/bank | /main.py | 1,415 | 3.5625 | 4 | import functions
from os import system
import database
import cx_Oracle
from connection import con,cur
def main():
database.make_all_tables()
database.reset_withdrawals()
choice = 1
print("\n##### Welcome To ONLINE BANKING TERMINAL #####\n")
while choice != 0:
print("\t--- M... |
da4d636c1456dfcbc78759c9e57888e660aef0d2 | AL-8/ColorGuessGame | /app.py | 190 | 3.84375 | 4 |
secret_word = "orange"
guess = ""
while guess != secret_word:
guess = input("Guess Color: ")
print("You win!")
|
b7c81967ea9203becee8b3ec8b6974c97e75bc28 | ZSPASOV/softuni-python-fundamentals | /03-Lists-Basics-Lab/demo20-not-in.py | 238 | 4.28125 | 4 | # The "not in" keywords are used to check if an element is NOT in a list
#
my_list = [1, 2, 3, 4]
if 5 not in my_list:
print("The number 5 is not in the list")
# The "not in" keywords are also mainly used with if-else statements
|
663aaeb2cb602de8c13c88200e181d35944b8d05 | qbuch/python_szkolenie | /homework_4/string_int_counter.py | 517 | 3.890625 | 4 | #Napisz program, obliczający liczbę cyfr i liter w dowolnym ciągu znaków
# np.“Tomek123” - 5 liter, 3 cyfry. Dane wejściowe wprowadza użytkownik po uruchomieniu programu.
user_prompt = input("Hey, give me an input to count: ")
letters = 0
digits = 0
for i in user_prompt:
if(i.isalpha()):
letters+=1
e... |
543bbcde72b61692dfc61b9f8617d4b0e64dc008 | AlKoAl/-10 | /Hamming/Hamming.py | 3,250 | 4.03125 | 4 | string = input('Введите строку из 0 и 1') # Вводим последовательность 0 и 1
k = 0
while True:
if k <= 2**k - len(string) - 1:
break
else:
k += 1
string = ' ' + string[:]
for i in range(1, k):
string = string[: (2 ** i) - 1] + ' ' + string[(2 ** i) - 1:] # ставим пропуски на номера со степ... |
9edc10d077b8d049655d7ede5e9d76329ae8626a | rjtsg/StockExchangeAI | /StockSimPlay.py | 4,420 | 3.921875 | 4 | """
This file should let us choose a decision of buying, holding, selling a stock (if available).
It will load in the close data from the AXP stock data. The game will take us from 2000 to 20001.
Which means it simulates 1 year of stock trading. The user will start with an amount of cash of
$10,000. He will see the f... |
ffd8966e04d388308f112952e762ed31df699ed7 | Kapil1717/Python-Lab | /L8-DLL-All.py | 3,661 | 3.765625 | 4 | #121910313016
class Node:
def __init__(self, next=None, prev=None, data=None):
self.next = next
self.prev = prev
self.data = data
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, new_data):
new_node = Node(data = new_data) ... |
f8ec96f4ab42db27b7e3f4daefbcc772c36d1f30 | dsmith1974/edu-py-int | /ace/Challenge2.py | 1,288 | 4.1875 | 4 | # https://www.educative.io/module/lesson/data-structures-in-python/B137p8P75QW
# Problem Statement #
# Implement a function that merges two sorted lists of m and n elements respectively, into another sorted list.
# Name it merge_lists(lst1, lst2).
#
# Input #
# Two sorted lists.
#
# Output #
# A merged and sorted list... |
eb8490be3209b1f2467a2583b5b2c9c94a81416c | jO-Osko/Krozek-python | /srecanje3/fizzbuzz_obe.py | 828 | 3.796875 | 4 | # Uporabnik naj vpiše začetno število
# Uporabnik naj vpiše končno število
# Izpiši fizbuzz za števila med začetnim in končnim (lahko tudi padajoče)
# 1, 2, Fizz, .... , 11
# 22, fizz, buzz, ...., 14
# Najprej preberite samo začetek in konec in izpišite samo st (brez fizzbuzz)
zacetno = int(input("Vpiši začetek:"))
k... |
81045c32939f24b9aabc227325b73fe2c7ef3e5c | Kanupreet/Assignments | /task1/ques3.py | 365 | 3.859375 | 4 |
print("Ques3")
a = 25
b = 100
print("Original values of var1: " , a )
print("Original values of var2: " , b )
c=b
b=a
a=c
print("After swapping with 3rd var")
print("Final values of var1: " , a )
print("Final values of var2: " , b )
a , b = b, a
print("After swapping without any var")
print("Final values of var1: ... |
165d224ca10d42abb73d853f4f41dbb5be0a2abb | huigoing/algorithm | /程序员面试宝典/33.碰撞的蚂蚁.py | 868 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 15:26:53 2019
@author: Tang
"""
'''
题目描述
在n个顶点的多边形上有n只蚂蚁,这些蚂蚁同时开始沿着多边形的边爬行,请求出这些蚂蚁相撞的概率。
(这里的相撞是指存在任意两只蚂蚁会相撞)
给定一个int n(3<=n<=10000),代表n边形和n只蚂蚁,请返回一个double,为相撞的概率。
测试样例:
3
返回:0.75
思路:每个蚂蚁爬行的方向都有两个,即围绕多边形顺时针爬和逆时针爬,因此n个蚂蚁爬行的方法有2^n种。
只有当所有的蚂蚁按照同一个方向爬行才能保证所有的蚂蚁... |
d49ca944df7235d90072c5f37ad89fb72e24a7b1 | leizhen10000/learnPython | /python_improve/set_list.py | 993 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Zhen Lei on 2017/9/10
# set 是一个非常有用的数据接口。它与 list 的行为类似,区别在于 set 不能包含重复的值。
def show_repeat_key():
some_list = ['a', 'b', 'c', 'd', 'e', 'f', 'b', 'c', 'a']
duplicates = set([x for x in some_list if some_list.count(x) > 1])
print duplicates
# 交集
... |
f93d28e3e7c6b5e6ffe9f23020e48e3b32ebc8a3 | livetoworldlife/week01_pycodersnl | /3_Monthly_Expenses.py | 404 | 3.859375 | 4 |
mon_inc=int(input("Write your monthly income value: "))
mon_exp=int(input("Write your monthly kitchen expenses: "))+\
int(input("Write your monthly education expenses: "))+\
int(input("Write your monthly clothing expenses: "))+\
int(input("Write your monthly transportation expenses: "))
prin... |
1df38b315160f6a467527359a4c5306ac9595576 | eokeeffe/Python | /glob.py | 308 | 3.609375 | 4 | import os
#merge all files in a directory into a single file
path = 'Directory to read'
listing = os.listdir(path)
dictfile = open("somefile","w")
for infile in listing:
f = open(path+"\\"+infile,"r")
for i in f.read():
dictfile.write(i)
f.close()
print "file: " + infile + " finished"
dictfile.close() |
953369a75b3abeea397a1c2f17c2dcf1c0813509 | dinob0t/project_euler | /39.py | 571 | 3.734375 | 4 | import math
def return_triangle_solutions(num):
solns = 0
for a in range(1,num):
for b in range(a,num):
c = math.sqrt(a**2 + b**2)
if is_whole(num) and a + b + c == num:
solns += 1
return solns
def is_whole(x):
if x%1==0:
return True
return False
def find_most_solns(max_num):
current_max = 0
c... |
69e6b9c5d8ec1256c06d119ff6cb30cb179ff2a5 | zhlinh/leetcode | /0001.Two Sum/solution.py | 991 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-04
Last_modify: 2016-09-02
******************************************
'''
'''
Given an array of integers, return indices... |
ece65d366645fbccdaafcc2ecf0604f8c07755ee | ziyadalvi/PythonBook | /4Python Object Types/16MissingKeys(ifTests).py | 1,183 | 4.5625 | 5 | #as mappings, dictionaries support accessing items by key only. With sorts of
#operations we've just seen. In addition, though, they also support type-specific
#operations with method calls that are useful in variety of ocmmon usecases
# For example, although
#we can assign to a new key to expand a dictionary, fetchin... |
6b16adea684b855a79a9462d6593d54b6bc786f2 | pcowhill/Project-Euler-Python-Solutions | /Problem 12 Highly Divisible Triangle Number.py | 514 | 3.828125 | 4 | import math
def pearl(divisors):
current = 0
check = 0
adder = 1
track = 0
highest = 0
while check == 0:
current = current + adder
for i in range(1, int(math.sqrt(current))):
if (current % i) == 0:
track = track + 1
if track*2 > h... |
efe69eec4380f3041992e4b82eb1252f32876859 | Purushotamprasai/Python | /Rohith_Batch/Operator/Logical Operator/001_understand.py | 908 | 4.3125 | 4 | # this file is understand for logical operators
'''
Logical AND ---> and
---------------------
Defination :
-----------
if 1st input is false case then output is 1st input value
other wise 2nd input value is the output
Logical OR---> or
---------------------
Defination :
-----------
if 1st ... |
ea127dc6ef04f1bc38719cef24fe90a1d9c258c4 | psypig99/pyLec | /py3_tutorials/basic/037_lambda.py | 268 | 4.125 | 4 | """
lambda는 함수명이 존재하지 않으며 재활용성을 고려한 함수보다는
1회성으로 잠깐 사용하는 속성 함수라고 볼 수 있음
"""
answer = lambda x: x**3
print(answer(5))
power = list(map(lambda x: x**2, (range(1,6))))
print(power) |
e756bbf95d70e606d5e545e1918a1c386a1c7826 | Simo0o08/Python-Assignment | /Python assignment/Module 4/Pattern/pattern1_12.py | 285 | 3.765625 | 4 | #Left Arrow Star Pattern
n=int(input())
k=n
i=n
r=0
while(r<n):
k=i
while(k>=1):
print("*",end=" ")
k=k-1
i=i-1
print()
k=i
r=r+1
r=0
i=3
while(r<n-1):
k=i
while(k>1):
print("*",end=" ")
k=k-1
i=i+1
print()
k=i
r=r+1
|
5e3580db4235dd78feee73d89f447f2648c3ba12 | AnubhavMadhav/Learn-Python | /20 Multithreading/usingSubClass.py | 261 | 3.75 | 4 | '''Create a Thread using sub class or we can say by extending the 'Thread' class'''
from threading import Thread
class MyThread(Thread):
def run(self):
i = 0
while i <= 10:
print(i)
i += 1
t = MyThread()
t.start() |
ffe1b836559137f9fb6183f07b1149087e8826fe | CateGitau/Python_programming | /ace_python_interview/lists/challenge_9.py | 1,207 | 4.09375 | 4 | # Rearrange Positive and Negative values
'''
Implement a function which rearranges the elements such that all the negative elements appear on the left and positive elements appear on the right of the list.
Note that it tis not necessary to maintain the sorted order of the input list
NB: Zero in this case is trated as... |
5db59819e2e75cd876a7cedf170b5339a51f9bf0 | JayNemade/Python-Codes | /PProg2.py | 430 | 3.8125 | 4 | #Dealing with Strings
sent = "Jay is {} yrs old"
str = 'Hello, World'
str2 = ' Hello World '
age = 14
print(str[4:8])
#strip() method to remove any whitespaces
print(str2.strip())
#lower() and upper() method
print(str.lower(),str.upper())
#replace() method
print(str.replace("H","J"))
#split() method to split a str... |
f5fa16a4b2f3fc9f09f3b66c0b62bdfb8d8d2f01 | Alin0268/Functions_in_Python | /Select_the_ith_smallest_element.py | 1,208 | 3.78125 | 4 | def select(my_list, start, end, i):
"""Find ith smallest element in my_list[start... end-1]."""
if end - start <= 1:
return my_list[start]
pivot = partition(my_list, start, end)
# number of elements in my_list[start... pivot]
k = pivot - start + 1
if i < k:
return s... |
e8650be5da12d3b718f619ef95efbf3be2588ab6 | PythonXiaobai1/python_project_1 | /Task1.py | 830 | 4.15625 | 4 | """
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务1:
短信和通话记录中一共有多少电话号码?每个号码只统计一次。
输出信息:
"There are <count> different te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.