blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e3a3f106c5eea5ae8d350f9171df0c9b98019172 | maximlt/guide_script_to_command_line | /minimal_effort/parsenote.py | 480 | 3.578125 | 4 | r"""Tool to parse an xml note and print it in a reable format.
Usage:
- Set the path of the input file in INPUTFILE
- Run `python myscript.py` from the directory of myscript.py
"""
from lxml import etree
INPUTFILE = r"..\inputdata\inputfile.xml"
tree = etree.parse(INPUTFILE)
root = tree.getroot()
parsed_xml = {child... |
d431a34f291b5e463349f3c16442593332d5f509 | zxj16152/PythonExercise | /com/suanfa/Sort.py | 4,233 | 3.71875 | 4 | import copy
import datetime
import random
def myInsertSort(a):
n=len(a)
if n<=1:
return a
for i in range(1,n):
j=i;
while j>0 and a[j]<a[j-1]:
a[j],a[j-1]=a[j-1],a[j]
j=j-1
def InsertSort2(lst):
n=len(lst)
if n<=1:
return lst
for i in ran... |
8ffd53365828daa41d25e0b89917b1a58590a57a | zxj16152/PythonExercise | /com/test/metaclass.py | 567 | 3.5625 | 4 | class Animal():
def __init__(self, name):
self.name1 = name
print("init")
print("%s" % (name))
# self.__init__()
def __new__(cls, *args, **kwargs):
print("new")
return object.__new__(cls)
def __getattribute__(self, item):
print("getattribute")
... |
0f01736712cbc996b7b18e5808a8cf4463661c42 | zxj16152/PythonExercise | /com/suanfa/ReverseList2.py | 3,808 | 3.578125 | 4 | class Lnode():
def __init__(self,x):
self.data=x
self.next=None
def findMidAndReverse(head):
if head is None or head.next is None:
return head
fast=head
slow=head
slowPre=head
while fast and fast.next:
slowPre=slow
slow=slow.next
fast=fast.next.ne... |
99b23d0a107f06316e4c1234e943719f24c52246 | zxj16152/PythonExercise | /com/suanfa/RemoveDup.py | 1,245 | 3.90625 | 4 | class LNode:
def __init__(self,x=None):
self.data=x;
self.next=None
def removeDup(head):
if head is None or head.next is None:
return
outerCur=head.next
innerCur=None
innerPre=None
while outerCur:
innerCur=outerCur.next
innerPre=outerCur
while inn... |
c591b57a9b61bb3d4bdd6782ac33634102349bfc | zxj16152/PythonExercise | /com/suanfa/BinarySearchTree.py | 3,242 | 3.828125 | 4 | class Node:
def __init__(self,data=None):
self.left=None
self.right=None
self.data=data
class BinarySearchTree:
def __init__(self,root=None):
self.root=root
def add(self,data):
node = Node(data)
if not self.root:
self.root=node
else:
... |
5eedacdd81fa37582f843684c1c7a06d538d7fa0 | zxj16152/PythonExercise | /TestRandomCharacter.py | 204 | 3.671875 | 4 | import RandomCharacter
NUMBER_OF_CHARS=175
CHARS_PRE_LINE=25
for i in range(NUMBER_OF_CHARS):
print(RandomCharacter.getRandomDigitCharacter(),end=' |')
if(i+1)%CHARS_PRE_LINE==0:
print() |
994f5de5850c7e17c4da47793771614d94719138 | zxj16152/PythonExercise | /exercise/MethodTypetest.py | 296 | 3.515625 | 4 | def test():
a,b=0,1
for i in range(10):
yield b
a,b=b,a+b
test=test();
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
|
5dea69ec5c7977574f9bfeba886bcec0bb90f898 | zxj16152/PythonExercise | /object/Person.py | 654 | 3.921875 | 4 | class Person(object):
def __init__(self, name, age):
self._name =name
self._age=age
@property
def name(self):
return self._name
@property
def age(self):
return self._age
@age.setter
def age(self,age):
self._age=age
def play(self):
if se... |
4e23ef18900e72102fd427a7f3167b76e715696e | EPCJC-LP10/12 | /Mod8/ex1.py | 175 | 3.515625 | 4 | nome = raw_input ("Como te chamas?")
idade = input ("Qual a tua idade?")
f = open ("nome.txt ","w")
f.write ("nome:" + nome + "\n")
f.write ("idade:" + str (idade))
f.close () |
7ec04432a7feacb5dcac14e110bcfb43a994efce | getLoyola/subnet | /subnet.py | 4,940 | 3.53125 | 4 | import sys
print("Welcome to Jack's Subnet Calc\n")
def subnet_calc():
try:
# Check for valid IP
while True:
ip_address = input("Enter an IP address: ")
# Split up octets
ip_octets = ip_address.split('.')
# Check octects
if (len(ip_... |
4c4edc385ca8ffb0f9246f29bb8ff2fb07da604a | DRC-AI/code-wars | /val_pin.py | 311 | 3.8125 | 4 | #ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true, else return false.
def validate_pin(pin):
return str(pin).isdigit() and len(pin) in (4, 6)
print(validate_pin('1234'))
|
f4b7a753145b29dc318f14bc3bd9f5000174d457 | DRC-AI/code-wars | /friend_or_foe.py | 403 | 4 | 4 | #Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...
def friend(x):
return [friend for friend in x if len(friend) == 4 and not friend.... |
64398d7756a60c4d7914533140f2ed9d9ca3a5ba | DRC-AI/code-wars | /mumbling.py | 432 | 3.765625 | 4 | #This time no story, no theory. The examples below show you how to write function accum:
Examples:
accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"
def accum(s):
output = []
increment = 1
for letter in s:
output.appen... |
2c3ee3c694127b19cd442656bf79bdd59661d2d6 | Zulko/moviepy | /moviepy/video/io/sliders.py | 2,049 | 3.609375 | 4 | """GUI matplotlib utility to tune the outputs of a function."""
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
def sliders(func, sliders_properties, wait_for_validation=False):
"""A light GUI to manually explore and tune the outputs of a function.
``slider_properties`` is a list of di... |
863f33340ed2b2f6d1bb344ca206eecf4f336201 | blubeck7/chess_neuralnetwork | /src/Chess.py | 1,536 | 3.59375 | 4 | import chess
import Computer
import random
if __name__ == '__main__':
board = chess.Board()
color = input('Please choose computer color:\nw = White\nb = Black\n--> ')
comp = Computer.ComputerPlayer.fromFile('../model/model_full_weights.npz', color)
comp.setDiff(4, 180, random.randint(1,100), 0, 0... |
5b28c0ff59ef18cf6fd26be42e496e42ff5904e6 | ruhsane/Technical-Interview-Practice | /SPD2.4/assignment1/findPair.py | 1,659 | 3.6875 | 4 | '''
Problem 1
Given an array a of n numbers and a target value t, find two numbers whose sum is t.
Example: a=[5, 3, 6, 8, 2, 4, 7], t=10 ⇒ [3, 7] or [6, 4] or [8, 2]
'''
# input: array(a) of numbers(n), target value(t)
# output: array of two numbers
# no duplicates. positive + negative. all int
# sort first
# have t... |
d58f2c9ed32bda96403690871d0a37ab7bb620ef | ruhsane/Technical-Interview-Practice | /two_sum.py | 810 | 3.53125 | 4 | class Solution:
def twoSum(self, nums, target) :
for i in nums:
complement = target - i
if complement in nums[nums.index(i)+1:]:
return [nums.index(i), nums.index(complement)]
solution = Solution().twoSum([3,3],6)
# print(solution)
class Haha:
def is_substring(... |
f59dfc2053d94f62946612230118dbcb16cd6f57 | Nikitos1409/RPGgame.vol | /monster.py | 671 | 3.609375 | 4 | import random "вызываем модуль рандом"
class Monster:
def __init__(self,name,type,strenght,hp): "сдесь то что состит в классе монстр"
self.x = 0
self.y = 0
self.name = name "имя"
self.type = type "тип"
self.strenght = strenght "сила"
self.hp = hp "здоровье"
def say(self,text): "функция ра... |
3bd2b5a3c7ff245dbb7864e0b6124cab8fdb8528 | Jiblet/PythonPractice | /percentage.py | 592 | 4.1875 | 4 | #percentage = input('What is the percentage?')
#print('The percentage is ', percentage,%)
def get_percentage():
while True:
try:
return float(input('What is the percentage? '))
except:
print('That isn\'t a number, please try again!')
percentage = get_percentage()
def get_v... |
e1eb105c07f5a526f9937dc63d7418dc845dba28 | woctezuma/puissance4 | /puissance4/env/grille.py | 5,549 | 3.859375 | 4 | from random import choice
class Grille:
"""Représentation du plateau de jeu"""
def __init__(self, grille_initiale=None):
"""Créer une grille vide, ou copier une grille existante"""
self.width = 7
self.height = 6
self.empty_space = '.'
self.top_row_no = 0
self.s... |
1c881ad6b27007859ba07af4ac2304e5ee4604ab | latavin243/dottable-dict | /example/try_dottable_dict.py | 320 | 3.671875 | 4 | from dottable_dict import DottableDict
def main():
raw_dict = {"a": "aa", "b": 2}
d = DottableDict(**raw_dict)
# same as: d = DottableDict(a="aa", b=2)
print(d) # {'a': 'aa', 'b': 2}
print(d.a) # aa
print(d.b) # 2
del d.a
print(d) # {'b': 2}
if __name__ == "__main__":
main()
|
9040c10e004ad7100b1d21efb4bc673ede409ec8 | mahik-p/minesweeper_440Pa2 | /main.py | 24,378 | 3.84375 | 4 | import pygame
import random
import os
import time
"""
Global Variables
dim = dimension of the minefield
num_mines = total number of mines
minefield = the actual minefield being modified
size = size of the pygame screen
time_sleep = time_sleep between each screen update
strat = which st... |
a91a8a73d9cdef43715a45bbcfda52bd5ed1bc15 | JamEnslaver/LearningPython | /NumberGuess.py | 546 | 4.125 | 4 | # Random number guessing game
import random
guesses = 0
print("I'm thinking of a number between 1 and 100.")
print("Try to guess the number in as few tries as possible.")
target = random.randint(1,100)
guess = 0
while guess != target:
guess = int(input("Enter your guess:"))
guesses +=1
if guess < target... |
63b6bb962fdb6a547cfbd018b5c9d02829f253cc | wrgsRay/matplots | /random_walk.py | 1,257 | 4.375 | 4 | """
Python 3.6
@Author: wrgsRay
"""
from random import choice
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
self.num_points = num_points
# All walk start at (0, 0)
self.x_values = [0]
... |
198c9c9bdc691a3be1255bfc877e8e9f00dc4b15 | RiccardoConti10/esercizi_10_11 | /esercizio1_scheda.py | 202 | 3.984375 | 4 | parola = input("inserisci una parola")
if parola == parola[::-1] :
print("la parola che hai scelto è palindroma")
elif parola != parola[::-1] :
print("la parola che hai scelto è palindroma")
|
d6b331713a1d99041006409acaffe4a35c851f52 | KanegaeGabriel/pathfinder | /Maze.py | 1,641 | 3.859375 | 4 | from math import sqrt
class Maze:
def __init__(self, filename=None, matrix=None):
if matrix and filename:
raise Exception("Please specify only a file OR a matrix.")
if matrix:
self.matrix = matrix
elif filename:
self.matrix = self.__loadFromFil... |
87ac289924683d12e5d5ebbf0f9c87edaed32afc | itsanjan/advent-of-code | /2018/day1/base.py | 497 | 3.6875 | 4 | with open('input.txt') as inputfile:
changes = list(map(int, inputfile.readlines()))
print(changes)
#---P1
current_frequency=0
for change in changes:
current_frequency += change
print(current_frequency)
#----P2
change=0
observed=set()
current_frequency=0
while True:
for change in changes:
... |
9d6a4b67056fd4d6576135ef09653e89d5f27477 | liwei-yeo/100days | /Day11 Capstone - Blackjack/Day11-Blackjack.py | 7,077 | 3.890625 | 4 | ############### Blackjack Project #####################
#Difficulty Normal 😎: Use all Hints below to complete the project.
#Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project.
#Difficulty Extra Hard 😭: Only use Hints 1 & 2 to complete the project.
#Difficulty Expert 🤯: Only use Hint 1 to complete th... |
7822e9a3cbb87a410f9e892a22539878ea912d8a | rahulsingh9878/Daily_Assignments | /assignment-sql.py | 2,497 | 4.4375 | 4 | #Q.1- Write a python script to create a database of students named Students.
import sqlite3
try:
con = sqlite3.connect('Students.db')
cursor = con.cursor()
query = 'create table students(name varchar(20),roll_no int(10), age int(2), marks int(3))'
cursor.execute(query)
print('Table created successfu... |
2fc4e038d5f85268bc2640f622634282b91883d1 | rahulsingh9878/Daily_Assignments | /assignment-14.py | 1,538 | 4.46875 | 4 | from functools import *
#Q.1- Write a python program to print the cube of each value of a list using list comprehension.
ls = [1,2,3,4,5,6,7,8,9]
ls1 = [x**3 for x in ls]
print(ls1)
#Q.2- Write a python program to get all the prime numbers in a specific range using list comprehension.
ls = [x for x in range(1, 20) ... |
4ded27705fb65a1d7f8c808deb5781a989e7adef | syladiana/basic-python-b3 | /for_loop.py | 302 | 3.90625 | 4 | fruits = ["apple", "banana", "cherry"]
# for x in fruits:
# print(x)
# banyak_data = len(fruits)
# for i in range(banyak_data):
# print(fruits[i])
# berapa_data = 3
for j in range(2):
fruits.append(input("Input data : "))
print(fruits[j])
print("=============")
print(fruits) |
241a2689528724fd96e6eba0ea57b4df067737cc | syladiana/basic-python-b3 | /input.py | 235 | 3.6875 | 4 | name = input("Masukkan nama :")
umur = input("Umur : ")
tinggi = input("Tinggi : ")
print("Nama saya adalah : " + name)
print("Umur saya : "+umur)
print("Tinggi saya : "+tinggi)
print(type(name))
print(type(umur))
print(type(tinggi)) |
34545645fe79ac0a5107d068e0cde56446598556 | syladiana/basic-python-b3 | /formating.py | 429 | 3.796875 | 4 | age = 36
tahun = "Tahun"
# txt = "Namaku adalah Nafi, dan aku berumur {} {}".format(age,tahun)
# print(txt)
# print(type(age))
# print(type(tahun))
print("Menghitung luas persegi panjang")
panjang = int(input("Masukkan panjang : "))
lebar = int(input("Masukkan lebar : "))
Luas_Persegi = panjang * lebar
output = "Di... |
153cc3061615243ab5b0574b5dd1ea3c9477a991 | syladiana/basic-python-b3 | /Final-Project/final_project_revisi.py | 893 | 3.65625 | 4 | # Source :
# - https://www.youtube.com/watch?v=sXjpkcF7rPQ
# - https://code.tutsplus.com/tutorials/sending-emails-in-python-with-smtp--cms-29975
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
file = open('e:\Indonesian AI\Basic-python-b3\Final-project/recei... |
66538f8b5a1cb25681cc8400fcd48a48192aee5f | Madhu-Kumar-S/Python_Basics | /Dictionary/append.py | 150 | 4.0625 | 4 | # Python – Append Dictionary Keys and Values ( In order ) in dictionary
d = {'a':1, 'b':2, 'c':3, 'd':4}
print(list(d.keys()) + list(d.values()))
|
30608b706d97a560effa35f0138a22418be44858 | Madhu-Kumar-S/Python_Basics | /OOPS/Inheritance/i4.py | 315 | 3.921875 | 4 | # accessing the super class constructor from sub class
class Father(object):
def __init__(self):
self.property = 80_00_000.00
def display(self):
print("Father\'s property =", self.property)
class Son(Father):
pass # since son doesnot have his own property
s = Son()
s.display()
|
a14004cfc6c8fe237154252a2611223aabe3e781 | Madhu-Kumar-S/Python_Basics | /Basic Programs/factorial.py | 311 | 4.21875 | 4 | # Python Program for factorial of a number
def factorial(no):
if no == 0:
return 1
else:
fact = 1
for i in range(1,no+1):
fact = fact * i
return fact
no = int(input("enter a no:"))
result = factorial(no)
print("factorial of {} is {}".format(no, result)) |
09cc51fdf601521a554e48733f74c234023f0ebc | Madhu-Kumar-S/Python_Basics | /File Handling/f1.py | 96 | 3.8125 | 4 | # writing a file
f = open("dog", "w")
str = input("Enter text to add:\n")
f.write(str)
f.close() |
bf8041f5287d563e76183fc68969e7ad6d40710b | Madhu-Kumar-S/Python_Basics | /List/remove_list.py | 309 | 4.03125 | 4 | # Remove multiple elements from a list in Python
lst = [1, 2, 3, 4, 5]
t = lst.copy()
print("enter elements to remove from the list")
r = [int(x) for x in input().split()]
for i in r:
for j in t:
if i == j:
t.remove(i)
print("new list after deleting elements is = {}".format(t))
|
e0a292e8246fd956c56af008254ae33c7a5d6e4b | Madhu-Kumar-S/Python_Basics | /Tuple/flatten_tuple.py | 127 | 3.90625 | 4 | # Python – Flatten tuple of List to tuple
t = ([5], [6], [3], [8])
print(tuple((j for i in t for j in i)))
l = [1, 2, 3]
|
21131443c553678503d7b562101258f6ad927b86 | Madhu-Kumar-S/Python_Basics | /List/remove empty list.py | 781 | 4.25 | 4 | # Python – Remove empty List from List
lst = [1, 2, [], 3, [], 4, 5]
print("original list is {}".format(lst))
print("method 1 using Naive method")
l1 = [1, 2, [], 3, [], 4, 5]
for i in l1:
if i == []:
l1.remove(i)
print("after removing empty list, new list is {}".format(l1))
print()
print("method 2 usin... |
910d6b2e5da8c0c2525990bc102f44510cf2f883 | Madhu-Kumar-S/Python_Basics | /Basic Programs/prime_check.py | 193 | 4.09375 | 4 | a = int(input("Enter a num to check if it is prime or not:"))
c = True
for i in range(2, a):
if a % i == 0:
c = False
if c == 0:
print("prime")
else:
print("not prime")
|
84cb999c724b3db9def08b0bffefcda7218a8262 | Madhu-Kumar-S/Python_Basics | /OOPS/demo 3.py | 526 | 4.40625 | 4 | # python program - an example for abstraction
class myclass:
def __init__(self):
self.__a = 10
self.b = 20
def display(self):
print(self.__a)
print(self.b)
m = myclass()
print("accessing variables through method:")
m.display()
print("accessing variables through instance(man... |
2ca5686a8f0c4d9632579977bd786920f189cfc6 | Madhu-Kumar-S/Python_Basics | /Core python/Set.py | 528 | 4.1875 | 4 | # program on set method
s = {1, 2, 2, 2.2, "hello"}
print(*s)
# add element
s.add(3)
print(s)
# remove 1st element
s.pop()
print(s)
s.pop()
print(s)
ss = {1, 2, 3}
# returns union of of two sets
ns = s.union(ss)
print(ns)
ss = {1, 2, 3}
# returns intersection of of two sets
ns = s.intersection(ss)
print(ns)
s1 = {... |
92041129d88d328121100b681ef72d6a4c9640e7 | Madhu-Kumar-S/Python_Basics | /Stringprograms/remove str.py | 832 | 4.15625 | 4 | # Ways to remove i’th character from string in Python
print("diff ways to remove ith char from given string")
st = input("enter a string:")
r = input("enter the character which need to be removed:")
print("method 1")
l = []
l.append(st[:st.find(r)])
l.append(st[((st.find(r))+1):])
ns = ''.join(l)
print("after remov... |
4c647ce097536c3fce87b1c6bedfc772c108d751 | Madhu-Kumar-S/Python_Basics | /Stringprograms/least_most_frequent_char.py | 1,049 | 3.984375 | 4 | # Python – Least and maximum Frequent Character in String
print("method 1")
s = input("enter a string:")
d = {}
for i in s:
k = i
v = s.count(i)
d.update({k:v})
nd =dict(sorted(d.items(), key=lambda x: x[1]))
for i,j in nd.items():
print("least frequent char in string is: '{:s}'".format(i))
bre... |
0fa2a383bf9f2a325654e4e7123489594c8ccc91 | Madhu-Kumar-S/Python_Basics | /OOPS/demo2.py | 303 | 4.03125 | 4 | # python program to show the example of encapsulation
class student:
def __init__(self): # to declare and initialize variables (or constructor)
self.name = "rahul"
self.age = 21
def display(self):
print(self.name)
print(self.age)
s = student()
s.display()
|
28ba7996ec1601f4b04e902a06ccb1a1777120a0 | Madhu-Kumar-S/Python_Basics | /Array programs/array_methods.py | 865 | 4.1875 | 4 | # array methods
import array
elements = [1, 2, 3, 4, 5] # iterable object
a = array.array('i', elements) # defining array
print(*a)
print(a.typecode) # returns the type code char of an array
print(a.itemsize) # returns the size of an items stored in array in bytes
a.append(6) # adds the element at end of an arra... |
7193e9f0af55394fc8ecc7ddb687a78e04ab7196 | Madhu-Kumar-S/Python_Basics | /Function/f9.py | 228 | 3.734375 | 4 | # passing a group of elements to a fun
def calculate(l):
sum = 0
for j in l:
sum = sum+j
print("sum of all values is:", sum)
lst = [int(i) for i in input("enter a list of numbers:").split()]
calculate(lst) |
ad21c78c0372ba83ca9059e36f084d053827f769 | Madhu-Kumar-S/Python_Basics | /List/Break.py | 416 | 4.28125 | 4 | # Break a list into chunks of size N in Python
ml = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print("original list is",ml)
nl = []
break_point = 3
if break_point > len(ml):
print("cant be break a list into chunks as break point is",break_point)
else:
for i in range(break_point + 1):
nl.append(ml[:break_poin... |
0e4acba5fa21f738958d8ceb019a8431fe6c0875 | Madhu-Kumar-S/Python_Basics | /Basic Programs/square and cubes.py | 482 | 4.25 | 4 | # Python Program for Sum of squares and cubes of first n natural numbers
import math as m
def square(n):
print("Square of 1st {} natural no is:".format(n))
sum = 0
for i in range(1,n+1):
sum = sum + m.pow(i,2)
print(int(sum))
def cube(n):
print("Cubee of 1st {} natural no is:".format(n))
... |
80f0eebd700184f6e01b9b6c9139647086d025df | Madhu-Kumar-S/Python_Basics | /OOPS/Polymorphism/p5.py | 542 | 4.125 | 4 | # example on magic methods --> * = object.__mul__(self, other)
class Employee(object):
def __init__(self, name, daily_sal):
self.name = name
self. daily_salary = daily_sal
def __mul__(self, other):
return self.daily_salary * other.attendance
class Attendance(object):
def __init__(... |
314d23e995fc95d08c0b1f6b2c9675459617725c | Madhu-Kumar-S/Python_Basics | /Stringprograms/reverse str.py | 159 | 4.3125 | 4 | # Reverse words in a given String in Python
st = input("enter a string to reverse:")
sr = st[::-1]
print("reversal of a string {:s} is {:s}".format(st, sr)) |
b04ed1ffb7e662288c953931a2ff38bc11801f21 | Madhu-Kumar-S/Python_Basics | /List/check element.py | 620 | 3.96875 | 4 | # Python | Ways to check if element exists in list
print("Diff ways to check if the element exists in list")
def m1(l, e):
print("method 1 using in operator")
if e in l:
print("{} is in list {}".format(e,l))
else:
print("{} is not in list {}".format(e, l))
def m2(l, e):
print("method ... |
b546a7a35a077d3f8f74e5ccd9dbbf0bf9b1a9e8 | pkrobinette/neural-nets | /src/network.py | 12,059 | 4.09375 | 4 | """
network.py
~~~~~~~~~~
A module to implement the stochastic gradient descent learning
algorithm for a feedforward neural network. Gradients are calculated
using backpropagation. Note that I have focused on making the code
simple, easily readable, and easily modifiable. It is not optimized,
and omits many... |
e7e95055417e0857840a6908189e830776edd8fb | victoray/P0 | /Task4.py | 1,188 | 3.96875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import time
import csv
start = time.time()
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)
"""
TASK 4... |
8b2a6dc8713a9ad8c1ef27be6c66ddf852c9cfe1 | hulaoan/homework-arch-5 | /1/longpengcheng/filter.py | 230 | 3.578125 | 4 | #!/usr/bin/env python
def cap(str):
return str[0].islower()
if __name__=="__main__":
a=["fda","Tdfd","dfsfd","Adfdf","lpc","Fe"]
b=filter(cap,a)
c=map(lambda x:len(x),b)
d=reduce(lambda x,y:x+y,c)
print b
print c
print d
|
db5dfc20489823e47a05d2633b2d08192d9e2133 | Theneaaaaaa/unit_four | /d3_unit_four_warmups.py | 213 | 4.28125 | 4 | grade = int(input("What grade are you in?"))
if grade <= 5:
print("You are in lower school.")
elif grade >= 6 and grade <= 8:
print("You are in middle school.")
else:
print("You are in upper school.") |
14dc96341e288fdfae76c8118603647c0e912e02 | LoveEmCoding/Wack-A-Mole | /wack a mole.py | 1,248 | 3.875 | 4 | import random
def prettyprintgrid(grid):
row = 0
print " 0 1 2 3 4"
for line in grid:
print row,
row +=1
for point in line:
print point,
print""
def straightdistance (r1, c1, r2, c2):
rdiff = r1 - r2
cdiff = c1 - c2
rdiff = abs(rdiff... |
c959f1405141593840ac7291d6eef65349f88a48 | vincentgong7/icwsm | /src/icwsm17/common/myio.py | 593 | 3.578125 | 4 | '''
Created on 14 Feb 2017
@author: vgong
'''
# common function: write line to a file from a list
def write_to_file(data_list, file):
with open(file, 'w') as f_w:
for line in data_list:
f_w.write("{0}".format(line))
print("done.")
def mywritelines2file(data_list, file):
with open(file... |
2f07be066365976cd622e256f41f6d0ef6ef8e55 | thephong45/student-practices | /7_Pham_Hoang_Trung/Bai2.5.py | 173 | 3.671875 | 4 | def total(lists):
array = []
sum = 0
for i in lists:
sum += i
array.append(sum)
return array
listss = [1,2,3,5,5,4]
print(total(listss))
|
749428e392a80dd7060513db84c092a18275cd58 | thephong45/student-practices | /7_Pham_Hoang_Trung/Bai2.7.py | 769 | 4.34375 | 4 | #Write three functions that compute the sum of the numbers in a list:
# using a for-loop,
# a while-loop and recursion.
# (Subject to availability of these constructs in your language of choice.)
def sum_for_loop(lists):
sum = 0
for i in lists:
sum += i
return sum
def sum_while_loop(lists):
su... |
e46c3ed9d8796cdf7c95814db48c6ef95217256c | thephong45/student-practices | /7_Pham_Hoang_Trung/Bai2.1.py | 156 | 4.03125 | 4 | #Write a function that returns the largest element in a list.
def list_return(lists):
return max(lists)
lists = [1, 5, 8, 4]
print(list_return(lists))
|
436e96a804a6ee537dc72057273fc101502e115e | thephong45/student-practices | /15_Nguyen_Tu_Giang/bai-1.4.py | 235 | 4.03125 | 4 | # Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
print('What is your number?')
value = input()
i = 1
result = 0
while i <= int(value):
result += i
i += 1
print(result)
|
164696e2f128c505cb37cf515d0f24b1b3d31cb0 | thephong45/student-practices | /15_Nguyen_Tu_Giang/bai-1.5.py | 363 | 4.0625 | 4 | # Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
print('What is your number?')
value = input()
i = 3
result = 0
while i <= int(value):
if i % 5 == 0:
result += int(i / 5)
elif i % 3 == 0:
result += ... |
50a6459a414375a076f75a9851ea77d23c4178fc | michalfoc/python | /python/ex5.py | 653 | 4.15625 | 4 | # Ex5 MORE VARABLES AND PRINTING
# Program using variables and printing, implementing format string using 'f'
#declaring variables
my_name = 'Michal Foc'
my_age = 30
my_height = 175 # cm
my_weight = 235 # lbs
my_eyes = 'brown'
my_teeth = 'white'
my_hair = 'brown'
print(f"Let's talk about {my_name}.")
print(f"He is {... |
d84f7dd5a0f87c1533276ec85ca2ac9025dc4b67 | michalfoc/python | /python/ex15.1.py | 402 | 4.125 | 4 | # Ex15. READING FILES
# script reading a file and printing its contents
# using 'argv' only
# import 'argv' from 'sys' module
from sys import argv
script, filename = argv
txt = open(filename) # 'open' opens the specified file to 'prepare' it for executing other commands, i.e reading, writing etc.
print(f"Here's You... |
22881bce8c33cfec0487d07b6a28a3884226882f | michalfoc/python | /python/ex18.py | 642 | 4.65625 | 5 | # Ex18 NAMES, VARIABLES, CODE, FUNCTIONS
# Introduction to functions
# this one is like scripts with 'argv'
def print_two(*args): # def - 'define', tells python that we are making a functiíon
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}.")
# ok, that *args is actually pointless, let's just do this
de... |
5ede7716350ab85895527220a0b3b09952d50a04 | michalfoc/python | /python/ex24.py | 1,384 | 4.0625 | 4 | # Ex.24 MORE PRACTICE
# A program re-caping on everything (almost) so far, and expanding a little bit on f-strings
# first some printing and escape sequencies
print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs.')
# ... some variables
poem =... |
7f6a0b9f5bd7623e43681ac00c4969ce7f5e9c3c | ayankelevich/misc-python-samples | /fbtraining.py | 3,496 | 3.6875 | 4 | #BASIC STRUCTURES
# Case
if 1 > 2 or 4 < 4:
print("Greater")
elif 5 == 5 and 7 != 7:
print("Equal")
elif 7 < 8 < 9:
print(not False)
else:
print("Less"[0])
# Iterator
my_iterator = iter('12345')
next(my_iterator)
next_item = next(my_iterator)
# Map, Filter, Reduce
l9 = ['blah', 'yadda']
l10 = list(... |
4a42869f077e4d108c5718cfa639b1b4338021c3 | nsunbury/E206_Labs | /Lab4/gym-e206-students-lab-04/traj_planner_SequentialPlanner.py | 9,498 | 4.0625 | 4 | # E206 Motion Planning
# Simple planner
# C Clark
import math
import dubins
import random
import matplotlib.pyplot as plt
from traj_planner_utils import *
import numpy as np
import time
from traj_planner_ExpPlanner import *
import sys
class Planning_Problem():
""" Class that holds a single motion planning problem... |
57dde2f79480275934cddec6fcc1693445534865 | dankpanda/flow-control | /9.py | 395 | 3.8125 | 4 | def get_score():
score = float(input("Enter score: "))
if score > 1:
return "Error, score cannot be more than 1.0"
elif score == 1 or score >= 0.9:
return "A"
elif score < 0.9 and score >= 0.8:
return "B"
elif score < 0.8 and score >= 0.7:
return "C"
elif score < ... |
350ad9433644928349cb6fca3380fb5b2def939d | dankpanda/flow-control | /8.py | 138 | 3.71875 | 4 | def generate_n_chars(n:int, c:str):
text = ""
for i in range(n):
text += c
return text
print(generate_n_chars(5,"X")) |
ee8d75c83f6b25d5fdf29f874d49858ecb65c958 | wjonesrhys/python | /learning_python/listcomp_dictionaries.py | 2,587 | 3.578125 | 4 | import math
# list_of_lists = [[1,2,3,4], [5,6,7,8], ['a','b','c','d']]
# for list in list_of_lists:
# for item in list:
# print(item)
# a = [x*x - 1 for x in range(9)]
# print("a: ", a)
# b = [(x,x*x) for x in range(9)]
# print("b: ", b)
# c = [a[x]+b[x][0] for x in range(9) if x % 2 == 0]
# print("c: ",... |
35e37f1b8ab3012af69e4eaa2eb82ba7e09f3f84 | wjonesrhys/python | /learning_python/sqlite.py | 3,951 | 3.75 | 4 | import csv
import sqlite3
import os
import calendar
def create_database(db_file):
db = sqlite3.connect(db_file)
cursor = db.cursor()
c_1 = "transaction_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL"
c_2 = "Organisation_Name TEXT NOT NULL"
c_3 = "Purchase_Order_Number INTEGER NOT NULL"
c... |
a5640ea2d8b9da161bf43facc8f75a7059bc93df | Faybeee/Session-1-homework | /session 1 task 5 homework.py | 1,273 | 4.4375 | 4 | #Write a program which will ask for two numbers from a user. Then
#offer a menu to the user giving them a choice of operator:
#e.g. – Enter “a” if you want to add
#“b” if you want to subtract
#Include +, -, /, *, **(to the power of) and square. Once the user has
#selected which operator they wish to use, perform t... |
69d8f411a37c4319d66d2f8c22bb47d1a54ad825 | alekseyfastovets/Python-2048-console-game | /main.py | 4,803 | 3.546875 | 4 | import random
import os
import time
def initField(filedLen):
if filedLen > 10 or filedLen <=2:
print(r'Размер поля не должен быть больше 10 и меньше 2\nЭто очевидно! В наказание, будет тебе маленькое поле, играй так.')
filedLen = 2
field = []
for i in range(0,filedLen):
elem = ... |
09a7c7184294cab8e80f474397fd82969b611c32 | bdanalytics/coursera-deeplearning-ai-med | /C2_W3_lecture_Kaplan_Meier_Survival.py | 3,458 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# # AI4M Course 2 Week 3 lecture notebook
# ## Outline
#
# [Count patients](#count-patients)
#
# [Kaplan-Meier](#kaplan-meier)
# <a name="count-patients"></a>
# ## Count patients
# In[1]:
import numpy as np
import pandas as pd
# We'll work with data where:
# - Time: days ... |
61d56db8085ae8bd989c322ba3d89d440f58ccf2 | Sharad702/BasicPythonCodes | /prime.py | 230 | 3.8125 | 4 | a=input("Enter the starting number :")
b=input("Enter the ending number :")
for i in range(int(a),int(b)+1):
if i>1:
for j in range(2,i):
if(i%j==0):
break
else:
print(i) |
39034e82f9634274372b972cbd81871ff0ddbb86 | Sharad702/BasicPythonCodes | /tupple1.py | 99 | 3.59375 | 4 | t1=(1,2,3)
#print(type(t))
t2=(1,5,6)
#print(t2)
#t=(3,4,5)
#print(t2)
t3=t2+t1
t3.sort()
print(t3) |
7bc16aa734073c6f2471e1ccb78e45a6ef480306 | Sharad702/BasicPythonCodes | /string6.py | 221 | 4.15625 | 4 | Name=input("Enter the name of student :")
Age=int(input("Enter the age of student :"))
University=input("Enter the university name :")
print(" HELLO,",Name,".You are studying in", University, "and your age is", Age,".") |
6c3f669ea328ff30570e6eff2a5560232dd74d8f | iamyup/applied_math | /a3/yup_hohu.py | 11,441 | 3.71875 | 4 | # Assignment 3: solves the Hodgkin-Huxley equations for the parameters shown in the ODE.pptx lecture.
import sys
import numpy as np
from matplotlib import pyplot as plt
# ordinary differential equation of Hodgkin-Huxley equation
def ode(i_ext, X, t):
V, n, m, h = X
# slide 66
gk = g[0]
Ek = E[0]
i... |
667dc326b7f592543f59b945e991aeebef81c518 | JimWeisman/PRG105 | /Practice 13.3 Miles Per Gallon Calculator.py | 1,696 | 3.796875 | 4 | """
jim weisman
spring2019
python
"""
import tkinter
class Gui:
def __init__(self):
self.main_window = tkinter.Tk()
self.top_frame = tkinter.Frame(self.main_window)
self.mid_frame = tkinter.Frame(self.main_window)
self.bottom_frame = tkinter.Frame(self.main_window)
self.... |
ed719a9fc0827583d072d3f93cadb4de36e8d224 | JimWeisman/PRG105 | /Practice 11.2 ProductionWorker/redo_11.2 Productionworker.py | 795 | 3.640625 | 4 | """
jim weisman
spring2018
python
redo
"""
import employee
def main():
name = input("Enter Employee Name: ")
num = int(input("Enter Employee Number: "))
hourly = float(input("Enter Hourly Pay Rate: "))
shift = int(input("Enter Shift Number: "))
if shift == 1:
shift = 'Day'
else:
... |
50f34510094837f764c907a1bc541c30a40ca0d1 | JimWeisman/PRG105 | /3.4_Age Classifier.py | 625 | 4.3125 | 4 | #jim weisman
# PRG105
# 3.4 Age Classifier
"""
If the person is 1 year old or less, he or she is an infant.
If the person is older than 1 year but younger than 13 years, he or she is a child.
If the person is at least 13 years old, but less than 20 years old, he or she is a teenager.
If the person is at... |
afecbc677c7306ce10b8c6e751298cf8213514fc | JimWeisman/PRG105 | /4.1 Calories Burned.py | 371 | 3.5 | 4 | """
jim weisman
spring 2019
PGR105
"""
# Running on a treadmill you burn 4.2 calories per minute.
# Write a program that uses a loop to display the number of calories burned after 10, 15, 20, 25 and 30 minutes.
cal_minute = 4.2
for minutes in range(10, 31, 5):
cal_burned = (minutes / 1) * cal_minute
print("... |
087bcbbc951f1f25c25e0f94ece4c459202d0480 | Haniehsadri/Python-Algorithms-and-Data-Structures | /Linkedlist.py | 1,539 | 3.9375 | 4 | from Node import Node
class Linkedlist:
def __init__(self):
self.head = None
# def is_empty(self):
# return self.head==None
# def size(self):
# current=self.head
# count=0
# while current != None:
# count+=1
# current=current.next_node
#... |
872a4916cdb72aabc36a667674dcfe05df7c8eca | Luweyh/Linked-List-and-various-ADTs | /cdll.py | 16,661 | 4.3125 | 4 | # Course: CS261 - Data Structures
# Student Name: Luwey Hon
# Assignment: Assignment 3 - CDLL
# Description: This program represent a circular
# double linked list which means that each node is connected
# to each other both way. It implements several ADT that is
# specific to the CDLL.
class CDLLException(Exception)... |
1c26e82557f38a56b341a2e80ee04152f1693295 | wangyuteng1997/learn_python | /type_of_data.py | 3,938 | 4.34375 | 4 | # Python有五个标准的数据类型:
# Numbers(数字)
# 四种不同的数字类型:
# int(有符号整型)
# long(长整型[也可以代表八进制和十六进制])
# float(浮点型) 8个字节
# complex(复数)
# String(字符串)
# List(列表)
# Tuple(元组)
# Dictionary(字典)
# 不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
# 可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。
'''
list
'''
# Python... |
86f0848397f7c01b2b12bbc029c535c422c56b31 | boatman223/aoc2020 | /day 11/11-1.py | 1,472 | 3.59375 | 4 | import functools
with open('input') as f:
grid = f.read().splitlines()
def parse_grid(grid):
empty = set()
occupied = set()
for y, row in enumerate(grid):
for x, tile in enumerate(row):
if tile == 'L':
empty.add((x,y))
return empty, occupied
def num_adjacent(s... |
4758a20d2ca9e2bb271049a3c30b460fe4d18874 | boatman223/aoc2020 | /day 17/17-1.py | 1,232 | 3.6875 | 4 | import itertools
with open('input') as f:
grid = f.read().splitlines()
def parse_input(grid):
active = set()
for y, row in enumerate(grid):
for x, column in enumerate(row):
if column == '#':
active.add((x, y, 0))
return active
def get_adjacent_cells(x, y, z):
... |
b6d50ba04d391c59f1ce18f46958c4563275e418 | chris123132/My-Document | /循环求平均数(改进版).py | 279 | 3.890625 | 4 | def main():
sum=0
count=0
xstr=input("please input the 1st number(enter to quit):")
while xstr!="":
sum+=eval(xstr)
count+=1
xstr=input("please input the next number:(enter to quit):")
print("the average number is:",sum/count)
main()
|
6e654868db57659e611a10e6cc5e6a8b5e7dac5a | alfonsoxw/Artificial-Intelligence-CS440 | /Pacman/Basic pathfinding/basicmaze.py | 2,719 | 3.5625 | 4 | '''
Basic path finding for Pacman assignment
Author: Litian Ma
'''
class Maze:
check_priority = ['u', 'r', 'd', 'l']
# initialize the maze by identifying the filename
def __init__(self, filename):
# width, height, startPos, dotsPos, mazeGraph
# maze represented by two dim list
s... |
5591b874468f5164274fb71d3e2cbdf4f603def1 | rutuja5544/Python_practice | /RPS.py | 805 | 3.9375 | 4 | import random
a = random.randint(0,2)
# 0 -> rock
# 1 -> paper
# 2 -> scissors
b = input("Player's chance: \n")
if b:
print("Invalid..")
if a == 0:
print("Computer: Rock")
elif a ==1:
print("Computer: Paper")
elif a ==2:
print("Computer: Scissors")
if a == 0 and b == "rock":
print("It'... |
0503d6f263957064498849e00632956b09fb4c0b | rutuja5544/Python_practice | /class.py | 1,246 | 3.84375 | 4 | # class student:
# def __init__(self, n,a):
# self.Full_Name = n
# self.Age = a
# def get_age(self):
# return self.Age
# stud1 = student("Rutuja" , 24)
# print(stud1.Full_Name)
class User:
active_users = 0
def __init__(self, fname, lname, age):
self.fname = fname
self.lname = lname... |
0b0c1256c3e02a96d0092d17f470490d3fe9489f | rutuja5544/Python_practice | /rs.py | 168 | 4 | 4 | b=int(input("How many times for print :"))
a=input("Enter any string\n\n")
# for i in range(b):
# print(f"\n{a}")
c=0
while c<b:
print(f"\n{a}")
c+=1 |
27e2dc0992d22480b2620b2a160a837839b20e04 | rutuja5544/Python_practice | /percentage.py | 142 | 3.828125 | 4 | a = int(input("Chem Marks"))
b = int(input("Phy Marks"))
c = int(input("Sci Marks"))
D = ((a+b+c)/300)*100
print(f"Percentage is {D}") |
919f3a66b391d0e767ebf895e5160066a4873e1a | rutuja5544/Python_practice | /listwithclass.py | 865 | 3.71875 | 4 |
class Pets :
allowed = ('dog','cat','pig','rat')
no_of_pets = 0
def __init__(self, species, pname, pcolor, pfood ):
if species not in Pets.allowed:
raise ValueError(f"You can't select {species} as Pet.")
self.species = species
self.pname = pname
self.pcolor = pcolor
self.pfood = pfood
P... |
d416b8612dbf294c112840f2bf8bf3ad2dec5429 | rutuja5544/Python_practice | /func_string.py | 236 | 3.8125 | 4 | c =input("Enter the string : ")
b=input("Letter : ")
def split(c):
a=[]
for i in range(len(c)):
a.extend(c[i])
print(a)
def string_count(c,b):
# a = []
split(c)
e = c.count(b)
print(e)
string_count(c,b) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.