blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
38e90a995c9a50cba7aac0df8362af1aac9e8809 | stephens-dev/afs-210 | /week2/linked.py | 921 | 3.640625 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class singlyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def iterateItem(self):
currentItem = self.head
while currentItem:
va... |
50bd2294b7a6c8c9363cf27c7bd7d88992bc9b37 | RomyNRug/pythonProject2 | /Week 3/MathWeek3part2.py | 1,691 | 4 | 4 | #8
def triangle_numbers(n):
for i in range(1, n + 1):
print("n = {0}, triangle = {1}".format(i, (i ** 2 + i)//2))
triangle_numbers(5)
#9 Write a program which prints True when n is a prime number and False otherwise
# Program to check if a number is prime or not
num = 407
# To take input from the user
... |
540d8b98398b360d505f3a1d3963772ad33d338e | AleksMaykov/GB | /lesson1_all.py | 6,232 | 4.0625 | 4 |
# Задача-1: поработайте с переменными, создайте несколько,
# выведите на экран, запросите от пользователя и сохраните в переменную, выведите на экран
a = 5
b = 7
c = 9
print(a,b,c)
z = input('Введите любое число:')
print('Вы ввели число: ' + z)
# Задача-2: Запросите от пользователя число, сохраните в переменную... |
b81da31ae5874696e23d4edd231797d78d776e7f | carlan/dailyprogrammer | /easy/3/python/app.py | 1,778 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""app.py: challenge #3"""
__author__ = "Carlan Calazans"
__copyright__ = "Copyright 2016, Carlan Calazans"
__credits__ = ["Carlan Calazans"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Carlan Calazans"
__email__ = "carlancalazans at gmail dot com"
__status... |
4136d9bae1896bdfdf3febcf4da3abf2bcdb83a9 | Jason101616/LeetCode_Solution | /Hash Table/249. Group Shifted Strings.py | 1,190 | 4 | 4 | # Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
#
# "abc" -> "bcd" -> ... -> "xyz"
# Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
#... |
507379e3d533e5d779859d5fb9bc93efae39384f | oliverhuangchao/python_study | /data_structure/worker_arrange.py | 276 | 3.90625 | 4 | x = {"a":["p1","p2","p3"],"b":["p2","p4"],"c":["p1","p3"]}
print x
y = dict()
for i in x:
for j in x[i]:
#print j
if j in y:
y[j].append(i)
else:
y[j] = list()
y[j].append(i)
for i in y:
print i + str(y[i]) |
ef0e43f1f337b4c2b8732cf18fcd9a0561f70c0f | RossMedvid/Pythone_core_tasks | /Classwork200919.py | 8,086 | 4.46875 | 4 | # 1. Написати функцію, яка знаходить середнє арифметичне значення довільної кількості чисел.
# def arifmetic_mean(*args):
# """This function calculate arifmetic mean of a non-empty arbitrary numbers"""
# return(sum(args))/len(args)
# print(arifmetic_mean(1,3,6))
# 2. Написати функцію, яка повертає абс... |
45a1b6f720d081594dfab848585a33ef8ed85ee3 | Ramsum123/Python | /baby_name.py | 1,957 | 3.796875 | 4 | from numpy import *
import numpy as np
import random2
from array import *
import os
## to run the loop
class Daughter(object):
def take_input(self):
h = input('What is your name?')
g = int(input('Enter the number of character you want to be in your baby name.'))
f = input("Enter your spouse... |
48dd3c57674205655db8eb66d1db9d25b8764e90 | Daiyunfeng/crawler | /thread.py | 424 | 3.53125 | 4 | import threading
import time
def target(n):
n = int(n)
num = [0 for x in range(0, n)]
for i in range(2,n):
if(num[i]==0):
print(i,end=" ")
for j in range(2,int(n/i)):
num[i*j]=1
print()
count = 100
while(count!=0):
# n = input("n:")
count-=1
n=10... |
3bb6b0a50bd328a2bc37903ba7fb5096c944bb0e | Shevah92/100doors | /doors.py | 223 | 3.578125 | 4 | #!/usr/bin/env python
# mathematical solution: we figured a doors will be open if
# the number of the divisors for that are odd. that's only true for square numbers
for i in range(1,11):
square= i*i
print(square)
|
7f05345f9896511c51cdef6dccc5f1eee5606483 | wxmsummer/algorithm | /leetcode/array/3_removeDuplicates.py | 455 | 3.65625 | 4 | class Solution:
def removeDuplicates(self, nums:list) -> int:
i, j = 0, 0
while j < len(nums):
print('j:', j)
if j+1 < len(nums) and nums[j+1] == nums[j]:
j += 1
else:
nums[i] = nums[j]
i += 1
j += 1
... |
1aa2380a01be4e7b08fabb3318a17d0c0c1daff2 | mikewarren02/PythonReview | /calculator.py | 506 | 4.15625 | 4 |
def calculator():
first_no = float(input("First number: "))
operation = input("Operation: ")
second_no = float(input("Second number: "))
if operation == "+":
total = first_no + second_no
print(total)
elif operation == "-":
total = first_no - second_no
print(total)
... |
3f519292eb2b7cfcda7e9bc86b35b80e6b693b44 | YadunathK/plab | /hw 18-22/rect_lessthan.py | 638 | 3.96875 | 4 | class rectangle():
def __init__(self,l,w):
self.__length=l
self.__width=w
self.ar=self.__length*self.__width
def __lt__(self,a2):
if self.ar<a2.ar:
print(self.ar,'is least area than',a2.ar)
else:
print(a2.ar ,'is the least area t... |
2792c80d790b766791224c50fcb896422b4e0a7a | bnitin92/coding_practice | /Graphs/Graph_BFS.py | 580 | 4.125 | 4 | # Traversing the graph using Breadth first search (BFS)
visited = set()
def bfs(visited, graph, node):
queue = []
queue.append(node)
while queue:
element = queue.pop(0)
if element not in visited:
print(element)
visited.add(element)
for neighbour in grap... |
44900a7540e41ea51de7f5c1950709effdc29962 | prasen7/python-examples | /student.py | 1,399 | 4.34375 | 4 | # program to evaluate students average score:
# an example to show how tuples and dictionaries can work together.
# create an empty dictionary for the input data; the student's name is used as a key,
# while all the associated scores are stored in a tuple.
school_class = {}
while True:
name = input("Enter... |
a3e545142aace399fcb025769414793c0d0e9212 | kchen36/fantastic-computing-machine | /db_builder.py | 801 | 3.546875 | 4 | import sqlite3 #enable control of an sqlite database
import csv #facilitates CSV I/O
f="discobandit.db"
db = sqlite3.connect(f) #open if f exists, otherwise create
c = db.cursor() #facilitate db ops
c.execute("CREATE TABLE courses(code TEXT, mark INTEGER, id INTEGER)" )
c.execute("CREATE TABLE peeps(name ... |
a4568ed78d9d88df89f2fd9e9354ab25738ec567 | sharonLuo/LeetCode_py | /two-sum-iii-data-structure-design.py | 1,823 | 4 | 4 | """
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
"""
### 580 ms... |
77f713c82dade421ce0aae5c11c7c9331dd41aa5 | huangxueqin/algorithm_exercise | /leetcode/python/reverseLinkedList.py | 564 | 4.125 | 4 | #!/usr/bin/env python3
#definition of single linked list
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
if head == None:
return head
currNode =... |
0975a3090017efdc6e236bcbb45fe692fcba9490 | linda-oranya/pypi_calculator | /src/calculator.py | 2,698 | 4.5 | 4 | from typing import Union
class Calculator:
"""
This class performs basic calculator functions such as:
- Addition / Subtraction
- Multiplication / Division
- Take (n) root of number
- Reset memory
"""
def __init__(self, start:int = 0)-> None:
"""
... |
4c4d341bfba2697aadb87389aa64844112650da3 | naeimnb/pythonexersices | /old/test3.py | 711 | 3.9375 | 4 | def standardName (name):
alphabet='abcdefghijklmnopqrstuvwxyz'
name=name.lower()
for alpha in alphabet:
startw=name.startswith(alpha)
if startw==True:
name = name[1:]
name= alpha.upper()+name
return name
name1= input('')
name2= input('')
name3= input('')
... |
975ec3a6f286288b9e838daf5d60afc2ac0f0bd8 | allyssnerd/Python-520 | /aula_2/exercicio_5.py | 1,201 | 3.65625 | 4 |
# Criar uma classe Usuario que tenha
# os atributos nome, idade, email
# e os metodos :
# - maior de idade
# - funcionario da 4linux
# - tem moto
class Usuario:
def __init__(self, nome, email, idade):
self.nome = nome
self.email = email
self.idade = idade
def maior_de_idade(self):
... |
4c769ca550d072e29a3eb1a87218c09127ed687c | Stella2019/study | /刷题/86.分隔链表.py | 2,978 | 3.5625 | 4 | #
# @lc app=leetcode.cn id=86 lang=python3
#
# [86] 分隔链表
#
# https://leetcode-cn.com/problems/partition-list/description/
#
# algorithms
# Medium (60.23%)
# Likes: 282
# Dislikes: 0
# Total Accepted: 60.8K
# Total Submissions: 100.9K
# Testcase Example: '[1,4,3,2,5,2]\n3'
#
# 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都... |
c24e3b74dcdef56986cdcbb4fe0bf085cddef022 | jaberg/nengo | /examples/squaring.py | 1,317 | 3.8125 | 4 | from .. import nengo as nengo
## This example demonstrates computing a nonlinear function (squaring) in neurons.
##
## Network diagram:
##
## [Input] ---> (A) ---> (B)
##
##
## Network behaviour:
## A = Input
## B = A * A
##
# Create the nengo model
model = nengo.Model('Squaring')
# Cr... |
8a274b169fef7b256062342ae10c0f4944d47ab8 | Abdilaziz/Collections-And-Algorithms-Notes | /Example Problems/Project Euler Problems/17. Number letter counts/problem.py | 1,147 | 3.734375 | 4 | # coding=utf-8
# If the numbers 1 to 5 are written out in words:
# one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
# how many letters would be used?
# NOTE: Do not count spaces or hyp... |
6d282abae3986fb0f697448372d87af7293e49e7 | avida/sandbox | /python/else.py | 347 | 3.875 | 4 | #!/usr/bin/env python3
import random
print("hi")
for i in range(3):
if i is random.randint(0,3):
print("Found random number")
break
else:
print("Random number not found")
try:
a = list(range(3))
b = a[3]
except:
print("except block")
else:
print("except else block")
finally:
... |
35c4dc56cc84d34e2a34babb5c4014d73fc8a099 | banchee/pirobot | /TankController/tank.py | 1,768 | 3.8125 | 4 | import motor
class tank(object):
def __init__(self):
self.left_motor = motor.motor(7,11)
self.right_motor = motor.motor(12,13)
self.actions = {'forward':False, 'reverse':False, 'left':False, 'right':False, 'stop':False}
def forward(self):
if not self.actions['forward']:
print 'Forward'
... |
12c84a54561d8c8d22ec6751d3f2258651c76b9b | mauriziokovacic/ACME | /ACME/math/barrier_function.py | 627 | 3.671875 | 4 | import torch
from .constant import *
def barrier_function(x, t):
"""
Returns the barrier function for a given value x and a threshold t
Parameters
----------
x : Tensor
the input value
t : scalar
the threshold value from which the barrier starts
Returns
-------
Te... |
e906bde00c901f2672d27fc92dafe5929ea387f2 | zeel1234/mypython | /ma007/Practical 9/class_static.py | 628 | 3.671875 | 4 | class Person:
count = 0
avg_age = 70
def __init__(self,name):
print("Constructor called !")
self.name = name
Person.count = Person.count + 1
def show(self):
print("Name of person : ",self.name)
@staticmethod
def showCount():
print("Total count :... |
81e34cd52e52cff387834da836fdd529529f9015 | AbandonBlue/Coding-Every-Day | /Data_Structure/RandomizedSet.py | 2,047 | 3.875 | 4 | import random
# Version 1
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = {} # use dict(hash table concept) to implement
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the... |
fa9c41ec83a61ec8e6762633b60b172e6d5d8b06 | pavanrao/bitesofpy | /pybites_bite132/vowels.py | 536 | 4.03125 | 4 | import re
from collections import Counter
# VOWELS = list('aeiou')
VOWELS = 'aeiou'
def get_word_max_vowels(text):
"""Get the case insensitive word in text that has most vowels.
Return a tuple of the matching word and the vowel count, e.g.
('object-oriented', 6)"""
vowel_count = {}
for ... |
080f63cb2c383acc73ebdb557adc3dbfb8b2d000 | AKondro/ITSE-1329-Python | /Chatbot Project/python3 chatbot-phase3-amykondro.py | 1,262 | 4.28125 | 4 | #chatbot-phase3-amykondro.py
def greeter(first_name, last_name, time_of_day) :
"""Returns a sentence containing first name, last name and the meal depending on the time of day"""
last_initial = last_name[0:1]
if time_of_day == 'Morning':
result = 'Have a good breakfast, '+' '+ first_name +' '+ last... |
e8f0572dc3d8bb7cbad002babd6b0a6a5f47e78c | tusharongit/Python | /pytraining/modules/sanitize.py | 426 | 3.5625 | 4 | # to ensure every data member is a capitalized string
def makeCaps (var):
return var.title()
def cleanup (data):
if type(data) != str:
data = str(data)
return makeCaps(data)
if __name__ == "__main__":
# print(makeCaps("a"))
# print(makeCaps("abcd"))
# x = "a"
# x = ... |
8df0ed2b0e792d9c8809d9b757db0404ad97640b | masnursalim/belajar-python | /08_strings/01_strings/cek_string.py | 241 | 4.09375 | 4 | txt = "Belajar Python sangat menyenangkan"
print("string : "+txt)
print()
print("Python" in txt)
kata = "PHP"
if kata not in txt:
print(kata + " tidak ditemukan dalam string")
else:
print(kata + " tidak ditemukan dalam string") |
47677782faa9ca5bd5f4cf711c0ea1c66b9b2c18 | Fortune-Adekogbe/python_algorithms | /graph.py | 4,201 | 4.125 | 4 | class Vertex:
"""A vertex that maintains a dict of (vertex -> weight)
key-value pairs of neighbors to which it is connected.
This avoids needing an extra data type, EDGE, to represent
connections between vertices."""
def __init__(self, node):
self.node = node
self.adjacent = {}
... |
d96ff8ffec7734d68ece2812afe0c1fe6fa219f4 | aduispace/EE232E_Graphs-and-Network-Flows | /Project2_Code-and-Report/Prob1-3_generate_graph.py | 3,574 | 3.75 | 4 | # In this script, we will generate three dicts:
# (1) id_name->{id:name} (finally abandon this thought, R cannot support this method to read graph)(2) id_movie->{id:movie1,2,3...} (3)movie_id->{movie:id1,id2,id3}
edgefile = open("/Users/lindu/Desktop/Spring 2017 Classes/EE232E Graphs Mining/Project2/project_2_data/... |
9d7975aa713d588285f37cab7c035f037274c11b | 2003sl500/functions_basic_2 | /countdown.py | 132 | 3.6875 | 4 | def countdown(num):
numList = []
for x in range(num,-1,-1):
numList.append(x)
return numList
print(countdown(5)) |
cf082f1c4010eb2d5557a7cedf2a6ada200d3391 | chunjiw/leetcode | /L525_findMaxLength.py | 1,447 | 3.84375 | 4 | # 525. Contiguous Array
# DescriptionHintsSubmissionsDiscussSolution
# Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
# Example 1:
# Input: [0,1]
# Output: 2
# Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
# Example 2:
# Input... |
e7dc80e234dbaab98a3b3f4853cf5ede556ea43d | TomiSar/ProgrammingMOOC2020 | /osa03-13c_osajonon_haku/src/osajonojen_haku.py | 145 | 3.84375 | 4 | sana = input("Sana: ")
merkki = input("Merkki: ")
kohta = sana.find(merkki)
if kohta + 3 <= len(sana):
print(sana[kohta:kohta + 3]) |
79aad048361d0147b727eeb5fb30007d778fad3f | dlefcoe/daily-questions | /directed_list_edge.py | 374 | 3.78125 | 4 | import pandas as pd
# read the data
df = pd.read_csv('test_csv.csv')
# build the new column
df['filter']='-'
for index, row in df.iterrows():
if row['from'] + '-' + row['to'] not in df['filter'].values:
if row['to'] + '-' + row['from'] not in df['filter'].values:
df.loc[index,'filter... |
75e7152f1c7e558273ffceca43d810237371e63a | deepakrajvenkat/dhilip | /sumofnnumber.py | 180 | 3.890625 | 4 | n=input()
if n.isdigit():
n=int(n)
if n < 0:
print ("enter the postive integer")
else:
sum=0
while(n > 0):
sum+= n
n-= 1
print (sum)
else:
print("invalid input")
|
f8114ec28447eee38a12cf5ac1de1c2782d617a8 | strint/pybind11_examples | /08_cpp-overload-eigen/test.py | 210 | 3.703125 | 4 | import numpy as np
import example
A = np.array([[1,2,1],
[2,1,0],
[-1,1,2]])
B = 10
print(example.mul(A.astype(np.int ),int (B)))
print(example.mul(A.astype(np.float),float(B)))
|
51a0c330f6d3d882daeb158e4f28b838368517b1 | amuchand47/Python | /tuple.py | 306 | 3.890625 | 4 | '''
MD Chand Alam
Aligarh Muslim University
'''
import sys
'''
# Tuple
y = [1, 2, 3]
x = ()
x = tuple(y)
print(x)
z = (1, 2, 3)
s = 4, 5, 6
print(z)
print(s)
# Immutable
l = (1, 2, 3)
#del(l[3]) # Error
a = ([1, 3], 2, 4)
del(a[0][1]) # But Inside tuple ,list can be deleted
print(a)
''' |
eda095a560aebf7b960be86f0fae2ac304f3f6a5 | layaxx/project_euler | /034_digit-factorials.py | 528 | 3.8125 | 4 | """ 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included. """
# max 7 digits
import math
def solve():
result = 0
for i in range(10, 1000000):
... |
bebb94edd53e0cbc01bb822c94c092d8f0eb256a | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/課後習題/Ex_02_6.py | 157 | 3.75 | 4 | #第二章,習題6
total = 1
number = int(input('輸入一個整數,計算階乘和->'))
for item in range(1, number+1):
total *= item
print(total) |
615105c7c76c12432b37c4ff596bf6df94c770ad | shafaypro/AndreBourque | /assignment1/example.py | 713 | 4.25 | 4 | '''
name = input("Enter any name here") # takes input of the name
if name == "Shafay":
print("Shafay") # this is optimal code or optimized code
elif name == "Andre": # elif --> else if --> elif condition:
print("Andre")
elif name == "Bob":
print("Bob")
else: # final Option
print("This is not Bob nor Andre nor Sh... |
05105a31d54dfef7a1a4ecaae3fe586f1aab526e | samantabueno/python | /GCD_geeksforgeeks.py | 379 | 3.828125 | 4 | # Greatest Common Divisor with n numbers
# GCD of more than two (or array) numbers
# This function implements the Euclidian
# algorithm to find H.C.F. of two number
def find_gcd(x, y):
while (y):
x, y = y, x % y
return x
l = [30, 35, 20, 5]
num1 = l[0]
num2 = l[1]
gcd = find_gcd(num1, num2)
for i in... |
6488b215997f68f766985eea50fdf717ab51e8a7 | Rakios/Alfa | /Proyectos_Python/norepetir.py | 648 | 3.984375 | 4 | # -*- coding: utf-8 -*-
def revisar(palabra,letra):
cont = 0
for letra2 in palabra:
if letra == letra2:
cont += 1
if cont == 1:
return letra
else:
return '_'
def main(palabra):
for letra in palabra:
resultado = revisar(palabra,letra)
if resultad... |
73df4ae97f94396f9dedda971555fcf89ccd6c38 | gunjan-madan/Python-Solution | /Module7/3.2.py | 3,887 | 4.34375 | 4 | # A set is a collection which is unordered and unindexed.
# Sets are written with curly brackets.
''' Task 1: Unique or Not '''
print("***** Task 1: *****")
print()
# In Python, you can use data structures called sets to perform operations like
# - Combining items
# - Finding common items
# - Identifying unique item... |
d96a17a49dea2e80bb62dd8f86c0e25bdd58edbc | loganetherton/quiz_exercise | /classes/School.py | 1,032 | 3.875 | 4 | from random import randrange
class School(object):
def __init__(self):
"""
The shool class will handle the entirety of the interactions between the students and teachers, as well as
determining the schoool year, assigning quizzes, grading quizzes, assigning final grades, and printing the
... |
cabc5411cdcf554d8f505e098e27a0c82aed00aa | larisamara/uri-programming-computers | /ur-desvio-de-fluxo/Elf-Time.py | 184 | 3.96875 | 4 | n = input()
a, b = input().split()
result = 0
if(int(a) + int(b) <= int(n)):
result = ("Farei hoje!")
if(int(a) + int(b) > int(n) ):
result = ("Deixa para amanha!")
print(result) |
dc957ddf7bd1aaf6a83563c950dbe7078e89c1db | AnonimousX1/coursepython | /Semana3/Calculo de Bhaskara.py | 578 | 4.09375 | 4 | print ("Extração de Raizes")
a= float(input("Qual o valor do quoficiente a?: "))
b= float(input("Qual o valor de quoficiente b?: "))
c= float(input("Qual o valor de quoficiente c?: "))
delta = b**2-4*a*c
if delta > 0:
x = (-b+(delta**0.5))/(2*a)
x2= (-b-(delta**0.5))/(2*a)
if x2<x:
print("as raízes ... |
4c0ed8f8a30e3801a82a3740545775a7087a3d26 | bitterengsci/algorithm | /九章算法/基础班LintCode/2.39.Recover Rotated Sorted Array.py | 533 | 4.0625 | 4 | #-*-coding:utf-8-*-
'''
Description
Given a rotated sorted array, recover it to sorted array in-place.
For example, the orginal array is [1,2,3,4], The rotated array of it can be [1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]
Example1:
[4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5]
Example2:
[6,8,9,1,2] -> [1,2,6,8,9]
C... |
6e85d72d245d8124cfd44b6af71cf30b5fe0230e | MarshalLeeeeee/myLeetCodes | /132-palindromePartition2.py | 1,165 | 3.703125 | 4 | '''
132. Palindrome Partitioning II
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
'''
class... |
399ea2fc3b1efe616bc22da1227fc42e1ece7d91 | YHLin19980714/week2 | /lesson_0205_list.py | 931 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 11:56:50 2021
@author: fennieliang
"""
#list [item1, item2,...]
a=['apple','melon','orange','pine apple']
a.append('tomato')# append single item
#print (a)
a.insert(3,'tomato')# insert into a certain position
#print (a)
a.remove('apple')# i... |
6d2750ca3776983cc81021089df4dc1c5ec627d9 | AbdelrahmanAhmed98/user-name-age | /Untitled9.py | 188 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
name = input('Enter your name: ')
name
age = int( input('Enter your age:'))
age
print('Hello', name+',','\nyour age is',age,'years old')
|
7f3fba9c5a8e76715c02927bbe10faf165053666 | lisamarieharrison/Py-machine-learning | /week_1_gradient_descent.py | 1,528 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
data = np.genfromtxt('C:/Users/Lisa/Documents/code/machine learning/ex1/ex1data1.txt', delimiter=',')
x = data[:,0]
y = data[:,1]
m = x.size
#Figure 1: Scatter plot of training data
plt.plot(x, y, 'o')
plt.xlabel('Population o... |
e4a5254b47d04eed47099bb1279ce8b3909263ec | santiago-quinga/Proyectos_Python | /Python Funtion #1.py | 881 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 13:36:15 2020
@author: Santiago Quinga
"""
def isYearLeap(year):
#
# Un año es bisiesto si cumple lo siguiente:
# es divisible por 4 y no lo es por 100 ó si es divisible por 400.
if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0):
retur... |
b00aae32ea1609546e35f30c85156e3761459c4b | usc-isi-i2/etk | /etk/crf_tokenizer.py | 16,897 | 3.75 | 4 | import string
import sys
class CrfTokenizer:
"""The tokenization rules take into account embedded HTML tags and
entities. HTML tags begin with "<" and end with ">". The contents of a
tag are treated as a single token, although internal spaces, tabs, and
newlines are stripped out so as not to confuse CRF++. HTML e... |
6a7bef04babf764c2accaaaa0ca10b40aa502582 | ycwang522/simpleEditor | /dict.py | 629 | 3.734375 | 4 | # coding: cp936
'''
Created on 20161025
@author: iPC
'''
print '-------------dict----------'
items={('Ruby','56'),('python','89')}
ite = dict(items)
print ite
print ite['Ruby']
d = dict(Ruby='56',python='89')
print d
print d['Ruby']
d.clear()
print d
print '-------------ֵ䷽----------'
x={'username':'admin','machines... |
4116a9dab8d3501204cfd87afa23d07dc990b44c | phipps980316/TCP-simulator | /14729831_server.py | 20,738 | 3.625 | 4 | from socket import socket # import for the TCP Socket object
from json import dumps, loads # import for turning the packet object into a json string
from random import randint # import to generate random number encrypting a packet
from sys import getsizeof # import to get the size of a packet object in bytes
... |
788bebf8e78dbd0600509c76eb9fdff81917a896 | Sophie-WH/exercises | /chapter-2/ex-2-3.py | 813 | 4.34375 | 4 | # Programming Exercise 2-3
#
# Program to convert area in square feet to acres.
# This program will prompt a user for the size of a tract in square feet,
# then use a constant ratio value to calculate it value in acres
# and display the result to the user.
# Variables to hold the size of the tract and number of acres.... |
97ef4410bde664fb094719fcb1338c02de6e2eef | ceddyzhang/demopython | /a7q2.py | 3,102 | 4.0625 | 4 | ##
##*************************************************************
##Assignment 7 Question 2
##Cedric Zhang
##Caesar Code
##*************************************************************
##
A = ['_','.','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#... |
72b71653a855aefbbde266a67363d0515954bd27 | wolf-tickets/pythonthehardway | /ex18.py | 346 | 3.59375 | 4 | def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r." % (arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r." % (arg1, arg2)
def print_one(arg1):
print "arg1: %r." % arg1
def print_name():
print "I got nothin."
print_two("Al", "Smith")
print_two_again("Al", "Smith")
print_... |
9b309f3747cc660d82b82371cf6b6d3c28b9ee73 | Vigyrious/python_fundamentals | /Functions-More-Exercises/Tribonacci-Sequence .py | 442 | 4.125 | 4 | number = int(input())
def tribonnacci(num):
tribbonacci_list = [1, 1, 2]
if num == 1:
print("1")
elif num == 2:
print("1 1")
elif num == 3:
print("1 1 2")
else:
print("1 1 2",end=" ")
for i in range(number-3):
result = sum(tribbonacci_list[len(tr... |
82bfa686b0ba2ad97c73982ea98d174e5df9658e | s3465535/s3465535 | /latlon_5.py | 3,330 | 3.5 | 4 | #!/usr/bin/python
#latlon_5.py
import re #do this to downoad the function regular expression
def decimalat(DegString): #functions must be defined before you can use it (def=define)
SearchStr='(\d+) ([\d\.]+) (\w)' #this requires that you open the InFile later, because they belong together
# Result=re.search(SearchSt... |
b928d90b98d705d89f462edfeb2b26e071ebc97b | balupabbi/Practice | /DS_and_ALG/DP_recusion_backtrack/BuySellStocks.py | 1,534 | 3.515625 | 4 | """
Buy Sell stocks: https://www.youtube.com/watch?v=mj7N8pLCJ6w
Buy Sell stockII: https://www.youtube.com/watch?v=blUwDD6JYaE
"""
def maxProfit(s):
"""
O(n^2) solution for only one transaction
:param s:
:return:
"""
#Brute Force
p = 0
days = []
for i in range(len(s)):
fo... |
a18a2e364c0bf61010546c0f09e8b5155cf4a951 | nerewarin/adventofcode2019 | /12.py | 4,673 | 3.828125 | 4 | """
--- Day 12: The N-Body Problem ---
https://adventofcode.com/2019/day/12
"""
import os
import re
import itertools
from dataclasses import dataclass
@dataclass()
class _Moon:
x: int
y: int
z: int
vx: int = 0
vy: int = 0
vz: int = 0
@property
def coords(self):
return sel... |
83ccd36e9c83fd3878b598b6ed246eeb6d1a4c9d | john-m-hanlon/Python | /Sentdex Tutorials/Intermediate Python 3 Tutorial [Sentdex]/09 - Writing our own Generator.py | 1,422 | 4 | 4 | """ This file contains code for use with "Intermediate Python Programming" by
Sentdex, available from https://www.youtube.com/user/sentdex/
Transcribed by: John Hanlon
Twitter: @hanlon_johnm
LinkedIn: http://bit.ly/2fcxlEw
Github: bit.ly/2fSDp4J
"""
def simple_gen():
'''
A simple generator that allows us to i... |
005bfaca231df5ef59675f62d3d7deed421435df | manojkumar-github/books | /professional-python/part-2-classes/metaclasses/writing_metaclasses.py | 3,498 | 4.0625 | 4 | """
Classes are just objects and metaclasses are just classes. Any class that subclasses "type" is capable of functioning
as a metaclass
"""
"""
Rule 1: Never attempt to declare or use a metaclass does not subclass "type". This will cause havoc in Python's multiple inheritence
Rule 2: Python's inheritence model require... |
1a7b7b02424aa20ee690275367e914da94dbca42 | WinrichSy/HackerRank-Solutions | /Python/SymmetricDifference.py | 328 | 3.53125 | 4 | #Symmetric Difference
#https://www.hackerrank.com/challenges/symmetric-difference/problem
first = int(input())
a = set([int(i) for i in input().split()])
second = int(input())
b = set([int(i) for i in input().split()])
diff = [i for i in a.difference(b)] + [i for i in b.difference(a)]
diff.sort()
for i in diff:
p... |
70c22d5a2eaeee3e37a9cdc242cf91b9bef66857 | Aman-Achotani/Python-Projects | /Snake_Water_gun.py | 2,929 | 3.96875 | 4 | import random
print("\t WELCOME TO SNAKE , WATER , GUN GAME")
p_name = input("Please enter your name :\n")
c_win = 0
c = ["Snake","Water","Gun"]
p_win = 0
rounds = 1
ties = 0
print("This game will have 5 rounds")
print("Lets start the game",p_name)
while (rounds!= 6):
c_choice = random.choice(c)
p_choi... |
558835d030e015d52e34552da8d649d72c9f2878 | TestowanieAutomatyczneUG/projekt-1-wiktormorawski | /tests/test_morse_asserpy.py | 1,898 | 3.515625 | 4 | from main import Main
import unittest
from assertpy import assert_that
'only unittest and assertpy morse'
class TestMain(unittest.TestCase):
def setUp(self):
self.temp = Main()
"""Morse coding tests"""
def test_morse_coding_value_equal_wiktor(self):
expected = '.-- .. -.- - --- .-. '
... |
9799a093125dba3bb7aa2a9730b5c5f33c3879bc | adgp97/NNandDL | /A2/perceptron.py | 1,335 | 3.515625 | 4 | import torch.nn as nn
import torch
import sys
class Perceptron(nn.Module):
"""
Simplest unit of Neural Networks
"""
def __init__(self, input_size, output_size, learning_rate, mode):
"""
Constructor
"""
super(Perceptron, self).__init__()
self.learning_rate = learning_rate
self.mode = mode
self.lay... |
8bc6794daea3dfc129912db2e274653d0a56b3d6 | MalliyawaduHemachandra/HacktomberfestHelloWorld | /Python/1first.py | 168 | 4.03125 | 4 | a=int(input("enter number 1;"))
b=int(input("enter number 2;"))
if(a==b):
print("both are equal")
elif a>b:
print(a,"is larger")
else:
print(b,"is larger")
|
a8793ebf8701d5df92f8c381aa188a5dcabf782f | Baoyx007/my_leetcode | /fullPermution.py | 283 | 3.65625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'PCPC'
def permution(prefix, str):
if len(str) <= 0:
print(prefix)
else:
for i in range(len(str)):
permution(prefix + str[i],str[0:i] + str[i + 1:] )
def combination(str):
pass
permution('', '12345')
|
01f5d29eb8c88ce7a0fa3840f56fad0701631725 | ZdenekPazdersky/python-academy | /Lesson6/6.36_chessboard.py | 1,079 | 4.1875 | 4 | # ###2DO
# # Write a program that prints a chessboard of given size to the terminal. The program will need:
# #
# # the length of board's edge and
# # character that will serve to fill in the black squares
# # Example of running the program for the edge length of 5 and fill character "#":
# # ######
# f_char = input('P... |
169fad274392b50f2ca3ea57f97788435b8c437c | sampathgoparaju/pythonpractice | /Exception3.py | 450 | 3.984375 | 4 | #!/usr/bin/python
# Exception handling
try:
x=input("Enter any number:")
y=input("Enter any number:")
print 'The values of x and y are', x,y
res=x/y
print 'The output of the division is', res
print "I have executed"
except ZeroDivisionError:
print 'Error encountered, trying to divide n... |
58e766413e8c7472c4f2b87b560845d2f6ebb7fd | mdh111/python | /pluralsight5.py | 196 | 3.8125 | 4 | shoppingList = []
shoppingList.append("Apples")
shoppingList.append("Milk")
print(shoppingList)
shoppingList[1] = "Bread"
print(shoppingList)
anotherList=list("characterlist")
print(anotherList) |
5a8415063edee44d834589481c6249e04cf8e7b8 | jordanvtskier12/Birthday-quiz | /birthday.py | 3,471 | 4.5625 | 5 | """
birthday.py
Author: Jordan
Credit: none
Assignment:
Your program will ask the user the following questions, in this order:
1. Their name.
2. The name of the month they were born in (e.g. "September").
3. The year they were born in (e.g. "1962").
4. The day they were born on (e.g. "11").
If the user's birthday fe... |
b5d6340b58fb122f620c16de020415bfe22f1247 | skailasa/practice | /ctc/ch01-arrays/8-zero-matrix.py | 682 | 3.96875 | 4 | """
Write an algorithm st if an element in an MxN matrix is zero, so are its
entire row and column
"""
def zero_matrix(M):
zero_cols = set()
zero_rows = set()
nvec = [0 for _ in range(len(M[0]))]
for idx, vector in enumerate(M):
for jdx, component in enumerate(vector):
if componen... |
68ed7679ae83be3946c2aa468c34b1f9e8e7dc19 | AdityaBelani/Learning-Python | /30.06.2018/1. Selection Sort.py | 289 | 3.9375 | 4 | def selsort(lst):
for i in range(0,len(lst)-1):
for j in range(i,len(lst)):
if lst[j]<lst[i]:
t=lst[j]
lst[j]=lst[i]
lst[i]=t
print('The new List')
print(lst)
lst=input("Enter List: ")
selsort(list(lst))
|
ed0341e7cb552ee351d31215d8d13eab982ba21c | jaycoskey/IntroToPythonCourse | /PythonSrc/Unit3_HW_src/banana.py | 95 | 3.65625 | 4 | #!/usr/bin/env python3
s = 'banana'
for k in range(0, len(s)):
print(s[0])
s = s[1::]
|
6ed4d624129ea68d75afd873c233444dd5e36e37 | charlie2104/PyGame_TicTacToe | /Button.py | 346 | 3.546875 | 4 | import pygame
class Button:
text = ""
def __init__(self, x, y, width, height, colour):
self.x = x
self.y = y
self.width = width
self.height = height
self.colour = colour
def displayButton(self, screen):
pygame.draw.rect(screen,self.colour,[self.x,self.y,self.... |
6af5b2309bba64405aa3b71161ddb577b7c61c7f | gittil/soulcode-datetime | /at_date.py | 367 | 3.84375 | 4 | from datetime import date # Importado a class date do modulo datetime (manipulação de datas).
# (ano, mes, dia) Padrão gregoriano.
data = date(2021, 2, 2)
print(data) # -> 2021-02-02 configurada
print('Data Atual: {}'.format(date.today()))
print('Dia: {}'.format(data.day))
print('Mês: {}'.format(data.mo... |
c0388d4a85d71c5ce73533ec001fdab84df57edc | taanh99ams/taanh-fundamental-c4e15 | /SS02/random_num.py | 93 | 3.546875 | 4 | from random import randint
x = randint(0, 100)
print("A random number from 0 to 100 is", x)
|
fce7f84b709fa91c6f62770714d5159578e9e187 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/cxxrog002/question2.py | 901 | 3.859375 | 4 | """change text to equal a correct format
Roger Cox
14 May 2014"""
text_im=input("Enter the input filename:\n")
f=open(text_im,"r")
#opens the correct file
text=f.read()
text_out=input("Enter the output filename:\n")
g=open(text_out,"w")
#n_text=text.replace("\n\n","chr(1)")
n1_text=text.replace("\n"... |
39dc935222f897a437010d11e07f2aac25c891f9 | ametthapa/python | /2Dlist_task.py | 246 | 3.90625 | 4 | #wap to remove the duplicates from the list
number=[1,4,6,8,5,3,2,1,3]
output=[]
for item in number:
if item not in output:
output.append(item)
output.sort()
print(output)
print(number)
set_2 = {1,2,3,3,4,5}
print(set_2) |
76b37fdad5dfc2650aa39e40b7662c4ccafc1d53 | fractal1729/CS_PRIMES_2016 | /utils.py | 765 | 3.75 | 4 | # Converts two-parent-list graph storage scheme to adjacency list
def tpl_to_adj(tpl):
# optional error-throwing mechanism in case the inputs are not of the same length; this really should need to be triggered in any case
# if(len(parent1) != len(parent2)):
# print("Error: input parent lists do not have same length... |
fbf618df66b4c255e8f7eaea3594c759f2874911 | shubhamrocks888/python_oops | /Methods.py | 1,402 | 4.5625 | 5 | ## Methods
Function that belongs to a class is called an Method.
All methods require ‘self’ parameter. If you have coded in other OOP language
you can think of ‘self’ as the ‘this’ keyword which is used for the current object.
It unhides the current instance variable.’self’ mostly wo... |
e181cfe4d13e92495911a6554d4f804e8d484466 | ljia2/leetcode.py | /solutions/dfs/079.Word.Search.py | 2,072 | 4.0625 | 4 | class DFSSolution:
def exist(self, board, word):
"""
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may no... |
0b4fbd675472f6f3bda5d3006a1bfa3aaed61207 | dely2p/Leetcode | /231.power-of-two.py | 460 | 3.65625 | 4 | #
# @lc app=leetcode id=231 lang=python3
#
# [231] Power of Two
#
# @lc code=start
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
result = False
power = 1
if n == 1:
return True
while True:
power = 2 * power
if power == n:
... |
ddf4d3bc999bcd93278baa93fbc48e2452e1b65d | ayivima/face_landmarks | /models.py | 4,421 | 3.8125 | 4 | """Implements a Convolutional Neural Network(CNN) for the detection of facial landmarks"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
__author__ = "Victor Mawusi Ayi <ayivima@hotmail.com>"
class Net(nn.Module):
def __init__(self):
"""Initializes ... |
600d9cb87e0f64d726f19e6893561eee03f1c516 | mukundoff07/age_predictor | /app.py | 1,110 | 3.53125 | 4 | # streamlit run app.py --server.port 9993
import streamlit as st
st.title("Age Predictor")
number = st.selectbox("Please Select Any Number", (2, 3, 4, 5, 6, 7, 8, 9, 10, ))
st.write("You Have Selected", number)
new_number = number * 2
new_number1 = new_number + 5
new_number2 = new_number1 * 50
# st.write(new_number... |
237ad1e96484abd542e84a08bbc471e7cf9b7922 | rafaelperazzo/programacao-web | /moodledata/vpl_data/425/usersdata/308/92288/submittedfiles/dec2bin.py | 119 | 3.96875 | 4 | # -*- coding: utf-8 -*-
p = input('Insira P: ')
q = input('Insira Q: ')
if p in q:
print('S')
else:
print('N')
|
11391e2aec7f64046ff18d6c77946402e5ccfc9c | zuxinlin/leetcode | /leetcode/editor/cn/[面试题 04.06]后继者-successor-lcci.py | 1,478 | 3.890625 | 4 | #! /usr/bin/env python
# coding: utf-8
# 设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
#
# 如果指定节点没有对应的“下一个”节点,则返回null。
#
# 示例 1:
#
# 输入: root = [2,1,3], p = 1
#
# 2
# / \
# 1 3
#
# 输出: 2
#
# 示例 2:
#
# 输入: root = [5,3,6,2,4,null,null,1], p = 6
#
# 5
# / \
# 3 6
# / \
# 2 4
# /
... |
894fae13639b2fe280766f34bb94740658bd92b1 | loosecanon/Project-Euler | /problem7.py | 317 | 3.734375 | 4 | import math
#compute 10001st prime number
i = 1 # first prime
num = 2 #number under examination storage variable
while i < 10001:
num+=1
for j in range(2,num):
#print("j = ", j, " num = ", num," i = ", i)
if num%j == 0:
break
else:
i+=1
print("100001st prime = ", num)
|
fafefdc67caef3de9a80a1f7d9f27bd61523ed85 | osanpozuki/competitive-programming | /competitive.py | 292 | 3.8125 | 4 | def is_prime(n):
if n < 2: return False
for k in range(2, int(n ** (1/2)) + 1):
if n % k == 0:
return False
return True
# using: 1 2 3 => [1, 2, 3]
def input_parse_int():
return [int(i) for i in input().split(' ')]
if __name__ == '__main__':
pass
|
87385a73f28d04e1f87cd59d0a67290a1daf0322 | bitbybitsth/automation_login | /bitbybit/interview_assignments/list_assignments.py | 624 | 3.96875 | 4 | l = ['(', '[', '{', '}', ']', ')']
def is_balanced(l):
stack = [] # -> [(,[,{,
opening_brackets = ('(', '{', '[')
closing_brackets = (')', '}', ']')
for i in l:
if i in opening_brackets:
stack.append(i)
if i in closing_brackets:
x = stack.pop() # x = '['
... |
db1218470a67df8234d8acc866f75e373b5baed4 | Ian84Be/Intro-Python-II | /src/player.py | 3,288 | 3.5625 | 4 | from gameObj import GameObj
from color import Color
class Player(GameObj):
def __init__(self, name, loc, desc='n/a', holding=[]):
super().__init__(name, desc, holding)
self.loc = loc
def startGame(self):
# DRAMATIC INTRO
print('\n')
self.crawlText('You awaken sudden... |
5cd6f6b504c23e5473b64c5093375d04e654c08d | alegalviz/RSA | /rsa | 2,687 | 3.796875 | 4 | #!/usr/bin/python3
import random
d = {1:'a',2:'b',3:'c',4:'d',5:'e',6:'f',7:'g',8:'h',9:'i',10:'j',11:'k',12:'l',13:'m',14:'n',15:'o',16:'p',17:'q',18:'r',19:'s',20:'t',21:'u',22:'v',23:'w',24:'x',25:'y',26:'z'}
# Función de Euler
def lcm(x, y):
# choose the greater number
if x > y:
greater = x
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.